diff --git a/pkgs/id/crates/id-worlds/src/world/actor.rs b/pkgs/id/crates/id-worlds/src/world/actor.rs index 54ea5ce753..886b72e3dd 100644 --- a/pkgs/id/crates/id-worlds/src/world/actor.rs +++ b/pkgs/id/crates/id-worlds/src/world/actor.rs @@ -989,13 +989,21 @@ impl WorldActor { ); } + // The handoff's journal position is the ownership boundary + // (#13711): stamp the next position on the entry and on the + // lease history in the same step, before the durable append. + // If the append fails, `next_lease` is dropped and the + // counter — derived from the history — never advanced, so + // the retry reuses the same position. + let position = self.core.next_lease_position(); let mut next_lease = self.core.write_lease().clone(); - next_lease.apply_handoff(&from, &to, epoch, expires_at_ms)?; + next_lease.apply_handoff(&from, &to, epoch, expires_at_ms, position)?; self.persist(JournalEntry::LeaseHandedOff { from, to, epoch, expires_at_ms, + position, })?; self.core.write_lease = next_lease; self.core.since_checkpoint = self.core.since_checkpoint.saturating_add(1); diff --git a/pkgs/id/crates/id-worlds/src/world/core.rs b/pkgs/id/crates/id-worlds/src/world/core.rs index 6795d062ec..2972fda23f 100644 --- a/pkgs/id/crates/id-worlds/src/world/core.rs +++ b/pkgs/id/crates/id-worlds/src/world/core.rs @@ -1228,18 +1228,20 @@ impl WorldCore { holder, epoch, expires_at_ms, + position, } => { core.write_lease - .apply_grant(&holder, epoch, expires_at_ms)?; + .apply_grant(&holder, epoch, expires_at_ms, position)?; core.since_checkpoint = core.since_checkpoint.saturating_add(1); } JournalEntry::LeaseRenewed { holder, epoch, expires_at_ms, + position, } => { core.write_lease - .apply_renew(&holder, epoch, expires_at_ms)?; + .apply_renew(&holder, epoch, expires_at_ms, position)?; core.since_checkpoint = core.since_checkpoint.saturating_add(1); } JournalEntry::LeaseHandedOff { @@ -1247,18 +1249,20 @@ impl WorldCore { to, epoch, expires_at_ms, + position, } => { core.write_lease - .apply_handoff(&from, &to, epoch, expires_at_ms)?; + .apply_handoff(&from, &to, epoch, expires_at_ms, position)?; core.since_checkpoint = core.since_checkpoint.saturating_add(1); } JournalEntry::LeaseRevoked { former_holder, epoch, reason, + position, } => { core.write_lease - .apply_revoke(&former_holder, epoch, &reason)?; + .apply_revoke(&former_holder, epoch, &reason, position)?; core.since_checkpoint = core.since_checkpoint.saturating_add(1); } JournalEntry::LeaseWriteRejected { @@ -1268,6 +1272,7 @@ impl WorldCore { observed_epoch, reason, received_at_ms, + position, } => { core.write_lease.apply_rejection(LeaseWriteRejection { writer, @@ -1276,6 +1281,7 @@ impl WorldCore { observed_epoch, reason, received_at_ms, + position, })?; core.since_checkpoint = core.since_checkpoint.saturating_add(1); } diff --git a/pkgs/id/crates/id-worlds/src/world/core/operations.rs b/pkgs/id/crates/id-worlds/src/world/core/operations.rs index a321097d6e..72e5a4d696 100644 --- a/pkgs/id/crates/id-worlds/src/world/core/operations.rs +++ b/pkgs/id/crates/id-worlds/src/world/core/operations.rs @@ -477,6 +477,29 @@ impl WorldCore { &self.write_lease } + /// The replay watermark (#13711): the highest stamped lease + /// position this world has replayed — `0` when no lease record + /// in the journal carries a position. A successor that reports + /// this value has replayed through the grant at that position; + /// the failover barrier (#7572) admits writes only once the + /// watermark reaches the grant's position. History is + /// append-only, so the watermark never decreases within a + /// journal, and a checkpoint carries the whole history, so it + /// survives compaction. + #[must_use] + pub(crate) fn lease_position_watermark(&self) -> u64 { + self.write_lease.last_position() + } + + /// The position the next live lease record must carry (#13711): + /// one past the watermark. The append authority stamps it in + /// the same serialized operation as the append; callers never + /// choose a position. + #[must_use] + pub(crate) fn next_lease_position(&self) -> u64 { + self.write_lease.last_position().saturating_add(1) + } + /// The per-world resource requests, independent of current server ceilings. /// The world's total-memory budget ledger (#557): the effective /// limit, the logical charge measured at restore, its high-water diff --git a/pkgs/id/crates/id-worlds/src/world/journal.rs b/pkgs/id/crates/id-worlds/src/world/journal.rs index 522f637306..40ab4f7dc7 100644 --- a/pkgs/id/crates/id-worlds/src/world/journal.rs +++ b/pkgs/id/crates/id-worlds/src/world/journal.rs @@ -535,6 +535,12 @@ pub enum JournalEntry { /// authority's clock; absent for an untermed holder. #[serde(default, skip_serializing_if = "Option::is_none")] expires_at_ms: Option, + /// The entry's durable per-world journal position (#13711): + /// strictly increasing across lease entries in journal order, + /// assigned by the append authority. `0` means unstamped: a + /// lease entry written before positions existed. + #[serde(default)] + position: u64, }, /// The current holder's lease term was renewed by the authority /// (design #2819). The epoch is unchanged. @@ -545,6 +551,10 @@ pub enum JournalEntry { epoch: u64, /// The new term expiry, in unix milliseconds. expires_at_ms: u64, + /// The entry's durable per-world journal position (#13711); + /// `0` means unstamped (pre-positions entry). + #[serde(default)] + position: u64, }, /// The write lease was handed from one holder to another /// (design #2819). This entry's journal position is the ownership @@ -561,6 +571,10 @@ pub enum JournalEntry { /// absent for an untermed holder. #[serde(default, skip_serializing_if = "Option::is_none")] expires_at_ms: Option, + /// The entry's durable per-world journal position (#13711); + /// `0` means unstamped (pre-positions entry). + #[serde(default)] + position: u64, }, /// The write lease was revoked by the authority (design #2819): /// the former holder is fenced at the resulting epoch and no @@ -572,6 +586,10 @@ pub enum JournalEntry { epoch: u64, /// Why the lease was revoked. reason: String, + /// The entry's durable per-world journal position (#13711); + /// `0` means unstamped (pre-positions entry). + #[serde(default)] + position: u64, }, /// An authenticated append attempt was refused by the append gate /// and the authority journaled the attempt as an audit record @@ -591,6 +609,10 @@ pub enum JournalEntry { /// When the authority received the attempt, in unix /// milliseconds on the authority's clock. received_at_ms: u64, + /// The entry's durable per-world journal position (#13711); + /// `0` means unstamped (pre-positions entry). + #[serde(default)] + position: u64, }, /// One UTF-8-safe part of a compacted program snapshot. The complete set /// immediately precedes its checkpoint and is keyed by that checkpoint's @@ -862,17 +884,30 @@ pub const JOURNAL_VERSION_BLOB: u32 = 14; /// containing one must be refused at the header check instead. pub const JOURNAL_VERSION_NOTIFY: u32 = 15; +/// Journal version 16 (#13711): a lease entry +/// ([`JournalEntry::LeaseGranted`] and its siblings) carrying a +/// stamped journal `position`, or a checkpoint carrying a lease +/// history with stamped positions. The field is optional, so a +/// version-15 binary would parse such an entry yet drop the +/// position at its next checkpoint — silently unmooring the +/// replay barrier the position names — so a journal containing a +/// stamped position must be refused at the header check instead. +/// Unstamped (position 0) lease entries keep version 7. +pub const JOURNAL_VERSION_LEASE_POSITION: u32 = 16; + /// Newest journal version this binary can read. Journals with a higher /// header version are refused at the header check, before any entry is /// applied. -pub const MAX_JOURNAL_VERSION: u32 = JOURNAL_VERSION_NOTIFY; +pub const MAX_JOURNAL_VERSION: u32 = JOURNAL_VERSION_LEASE_POSITION; /// The header version a journal must carry once it contains `entry`: version 2 /// for execution-profile entries, version 3 for region-handoff entries, /// version 4 for entries persisting a per-world total memory budget, version 5 /// for checkpoints with open-presence metadata, and version 6 for checkpoint /// part entries. Checkpoints combine the requirements of their transfers, -/// retained events, profile and presence field. +/// retained events, profile and presence field. A lease entry carrying a +/// stamped journal position requires version 16, as does a checkpoint whose +/// lease history carries one; unstamped lease entries keep version 7. /// /// Any entry that records a program-bundle install additionally requires /// [`JOURNAL_VERSION_PROGRAM_BUNDLE`]. @@ -940,11 +975,17 @@ fn entry_kind_version(entry: &JournalEntry) -> u32 { JournalEntry::EntityExported { .. } | JournalEntry::EntityImported { .. } => { JOURNAL_VERSION_REGION_HANDOFF } - JournalEntry::LeaseGranted { .. } - | JournalEntry::LeaseRenewed { .. } - | JournalEntry::LeaseHandedOff { .. } - | JournalEntry::LeaseRevoked { .. } - | JournalEntry::LeaseWriteRejected { .. } => JOURNAL_VERSION_WRITE_LEASE, + JournalEntry::LeaseGranted { position, .. } + | JournalEntry::LeaseRenewed { position, .. } + | JournalEntry::LeaseHandedOff { position, .. } + | JournalEntry::LeaseRevoked { position, .. } + | JournalEntry::LeaseWriteRejected { position, .. } => { + if *position == 0 { + JOURNAL_VERSION_WRITE_LEASE + } else { + JOURNAL_VERSION_LEASE_POSITION + } + } JournalEntry::AuthorKeyBound { .. } | JournalEntry::SignedMoveAccepted { .. } => { JOURNAL_VERSION_SIGNED_PLAY } @@ -987,11 +1028,20 @@ fn entry_kind_version(entry: &JournalEntry) -> u32 { admin_history, .. } => { + // A checkpoint with a stamped lease history requires + // version 16, above every other content version: the + // check is ordered highest-first, so this arm comes + // before the notify/blob/kv arms below. + let base = if lease + .as_ref() + .is_some_and(|lease| lease.last_position() > 0) + { + JOURNAL_VERSION_LEASE_POSITION // A retained `Notification` event is a version-15 kind // wherever the checkpoint carries it — the retained // events or the admin history (the both-places check // the bundle-provenance rule uses). - let base = if events + } else if events .iter() .any(|event| matches!(event.kind, WorldEventKind::Notification { .. })) || admin_history.as_ref().is_some_and(|history| { diff --git a/pkgs/id/crates/id-worlds/src/world/mod.rs b/pkgs/id/crates/id-worlds/src/world/mod.rs index 8459ce5e2c..c9faa31510 100644 --- a/pkgs/id/crates/id-worlds/src/world/mod.rs +++ b/pkgs/id/crates/id-worlds/src/world/mod.rs @@ -83,13 +83,13 @@ pub use id_caps::portal::{PortalGrantState, PortalGrants, PortalRefusal}; pub use journal::{ CoordinatorJournalEntry, JOURNAL_VERSION, JOURNAL_VERSION_BLOB, JOURNAL_VERSION_CHECKPOINT_PARTS, JOURNAL_VERSION_EXECUTION_PROFILE, - JOURNAL_VERSION_JOIN_TIMES, JOURNAL_VERSION_KV, JOURNAL_VERSION_NOTIFY, - JOURNAL_VERSION_OPEN_PRESENCE, JOURNAL_VERSION_PORTALS, JOURNAL_VERSION_PROGRAM_BUNDLE, - JOURNAL_VERSION_REGION_HANDOFF, JOURNAL_VERSION_SCHEDULE_RECURRENCE, - JOURNAL_VERSION_SIGNED_PLAY, JOURNAL_VERSION_WORLD_BUDGET, JOURNAL_VERSION_WRITE_LEASE, - JournalAckMode, JournalAdminHistory, JournalEntry, JournalSignedMove, JournalSnapshot, - JournalSnapshotSource, MAX_JOURNAL_VERSION, TrustBasis, TrustDecision, WorldJournal, - journal_version_required_by, + JOURNAL_VERSION_JOIN_TIMES, JOURNAL_VERSION_KV, JOURNAL_VERSION_LEASE_POSITION, + JOURNAL_VERSION_NOTIFY, JOURNAL_VERSION_OPEN_PRESENCE, JOURNAL_VERSION_PORTALS, + JOURNAL_VERSION_PROGRAM_BUNDLE, JOURNAL_VERSION_REGION_HANDOFF, + JOURNAL_VERSION_SCHEDULE_RECURRENCE, JOURNAL_VERSION_SIGNED_PLAY, + JOURNAL_VERSION_WORLD_BUDGET, JOURNAL_VERSION_WRITE_LEASE, JournalAckMode, + JournalAdminHistory, JournalEntry, JournalSignedMove, JournalSnapshot, JournalSnapshotSource, + MAX_JOURNAL_VERSION, TrustBasis, TrustDecision, WorldJournal, journal_version_required_by, }; pub use metrics::{ HistogramSnapshot, MetricsSnapshot, RegionWrites, WorldMetrics, WriteLocalitySnapshot, @@ -740,6 +740,13 @@ pub struct WriteLeaseTransition { /// Why a revocation happened; absent for other kinds. #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option, + /// The transition's durable per-world journal position (#13711): + /// strictly increasing across the lease history in journal order. + /// `0` means unstamped: a transition recorded before positions + /// existed. A checkpoint carries this whole history, so a + /// position survives compaction exactly when its transition does. + #[serde(default)] + pub position: u64, } /// One rejected stale append attempt, as the append authority audited @@ -762,6 +769,10 @@ pub struct LeaseWriteRejection { /// When the authority received the attempt, in unix milliseconds /// on the authority's clock. pub received_at_ms: u64, + /// The audit's durable per-world journal position (#13711); + /// `0` means unstamped (pre-positions entry). + #[serde(default)] + pub position: u64, } /// One entry in a [`WriteLease`]'s audit history, in journal order. @@ -849,6 +860,27 @@ impl WriteLease { *self == Self::bootstrap() } + /// The highest stamped journal position in the lease history + /// (#13711): the replay watermark — a successor that has + /// replayed this history has replayed through this position. + /// `0` when no transition or audit in the history carries a + /// stamped position (a world that never spilled, or a legacy + /// journal whose lease entries predate positions). History is + /// append-only and positions strictly increase in journal order, + /// so this is also the position the next live lease record + /// must exceed. + #[must_use] + pub fn last_position(&self) -> u64 { + self.history + .iter() + .map(|entry| match entry { + WriteLeaseHistory::Transition(transition) => transition.position, + WriteLeaseHistory::Rejection(rejection) => rejection.position, + }) + .max() + .unwrap_or(0) + } + /// Whether `now_ms` is past the current term. An untermed holder /// never expires; a world with no holder has nothing to expire. #[must_use] @@ -884,6 +916,20 @@ impl WriteLease { Ok(()) } + /// A stamped journal position must advance past every stamped + /// position already in the history (#13711); `0` is the + /// unstamped legacy marker and neither advances the order nor + /// violates it. Checked after the domain validation, so a bad + /// epoch or holder reports its own error first. + fn ensure_position_advances(&self, position: u64) -> Result<()> { + ensure!( + position == 0 || position > self.last_position(), + "journal lease position {position} does not advance past {}", + self.last_position() + ); + Ok(()) + } + /// Apply a `LeaseGranted` record: legal only while no holder /// stands, and the granted epoch must be exactly the next epoch. /// @@ -896,6 +942,7 @@ impl WriteLease { holder: &str, epoch: u64, expires_at_ms: Option, + position: u64, ) -> Result<()> { ensure!( self.holder.is_none(), @@ -903,6 +950,7 @@ impl WriteLease { self.holder ); self.advance_epoch(epoch, "grant")?; + self.ensure_position_advances(position)?; self.holder = Some(holder.to_owned()); self.expires_at_ms = expires_at_ms; self.history @@ -913,6 +961,7 @@ impl WriteLease { epoch, expires_at_ms, reason: None, + position, })); Ok(()) } @@ -924,7 +973,13 @@ impl WriteLease { /// /// A renewal by a non-holder, under a different epoch, or moving /// the expiry backwards. - pub fn apply_renew(&mut self, holder: &str, epoch: u64, expires_at_ms: u64) -> Result<()> { + pub fn apply_renew( + &mut self, + holder: &str, + epoch: u64, + expires_at_ms: u64, + position: u64, + ) -> Result<()> { ensure!( self.holder.as_deref() == Some(holder), "journal renews the write lease for {holder:?}, held by {:?}", @@ -940,6 +995,7 @@ impl WriteLease { .is_none_or(|current| expires_at_ms >= current), "journal renewal moves the write lease expiry backwards" ); + self.ensure_position_advances(position)?; self.expires_at_ms = Some(expires_at_ms); self.history .push(WriteLeaseHistory::Transition(WriteLeaseTransition { @@ -949,6 +1005,7 @@ impl WriteLease { epoch, expires_at_ms: Some(expires_at_ms), reason: None, + position, })); Ok(()) } @@ -967,6 +1024,7 @@ impl WriteLease { to: &str, epoch: u64, expires_at_ms: Option, + position: u64, ) -> Result<()> { ensure!( self.holder.as_deref() == Some(from), @@ -974,6 +1032,7 @@ impl WriteLease { self.holder ); self.advance_epoch(epoch, "handoff")?; + self.ensure_position_advances(position)?; self.holder = Some(to.to_owned()); self.expires_at_ms = expires_at_ms; self.history @@ -984,6 +1043,7 @@ impl WriteLease { epoch, expires_at_ms, reason: None, + position, })); Ok(()) } @@ -996,13 +1056,20 @@ impl WriteLease { /// /// A revocation of a non-holder, or an epoch that is not /// `current + 1`. - pub fn apply_revoke(&mut self, former_holder: &str, epoch: u64, reason: &str) -> Result<()> { + pub fn apply_revoke( + &mut self, + former_holder: &str, + epoch: u64, + reason: &str, + position: u64, + ) -> Result<()> { ensure!( self.holder.as_deref() == Some(former_holder), "journal revokes the write lease from {former_holder:?}, held by {:?}", self.holder ); self.advance_epoch(epoch, "revocation")?; + self.ensure_position_advances(position)?; self.holder = None; self.expires_at_ms = None; self.history @@ -1013,6 +1080,7 @@ impl WriteLease { epoch, expires_at_ms: None, reason: Some(reason.to_owned()), + position, })); Ok(()) } @@ -1056,6 +1124,7 @@ impl WriteLease { "journal audits rejected write {:?} twice", rejection.operation_id ); + self.ensure_position_advances(rejection.position)?; self.history.push(WriteLeaseHistory::Rejection(rejection)); Ok(()) } @@ -1081,6 +1150,7 @@ impl WriteLease { .context("lease grant transition names no holder")?, transition.epoch, transition.expires_at_ms, + transition.position, )?, LeaseTransitionKind::Renewed => replayed.apply_renew( transition @@ -1091,6 +1161,7 @@ impl WriteLease { transition .expires_at_ms .context("lease renewal transition names no expiry")?, + transition.position, )?, LeaseTransitionKind::HandedOff => replayed.apply_handoff( transition @@ -1103,6 +1174,7 @@ impl WriteLease { .context("lease handoff transition names no target")?, transition.epoch, transition.expires_at_ms, + transition.position, )?, LeaseTransitionKind::Revoked => replayed.apply_revoke( transition @@ -1114,6 +1186,7 @@ impl WriteLease { .reason .as_deref() .context("lease revocation transition names no reason")?, + transition.position, )?, }, WriteLeaseHistory::Rejection(rejection) => { diff --git a/pkgs/id/crates/id-worlds/src/world/tests.rs b/pkgs/id/crates/id-worlds/src/world/tests.rs index a8ee0141a7..ac61666244 100644 --- a/pkgs/id/crates/id-worlds/src/world/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world/tests.rs @@ -1633,9 +1633,12 @@ mod tests { } fn lease_header() -> JournalEntry { + // Stamped lease entries (#13711) require version 16; the + // unstamped legacy header (version 7) is covered by + // `unstamped_lease_entries_still_restore_at_version_7`. JournalEntry::Created { world_id: "w".to_owned(), - version: JOURNAL_VERSION_WRITE_LEASE, + version: JOURNAL_VERSION_LEASE_POSITION, } } @@ -1645,6 +1648,7 @@ mod tests { to: "native-1".to_owned(), epoch: 1, expires_at_ms: Some(30_000), + position: 1, } } @@ -1653,6 +1657,7 @@ mod tests { holder: "native-1".to_owned(), epoch: 1, expires_at_ms: 40_000, + position: 2, } } @@ -1666,6 +1671,7 @@ mod tests { observed_epoch: 1, reason: LeaseRejectionReason::StaleEpoch, received_at_ms: 35_000, + position: 3, } } @@ -1674,21 +1680,43 @@ mod tests { // Design #2819 phase 2 (#3804): lease kinds are the first // entries a version-6 binary cannot read, so they pin the // header to version 7 under the #227 bump-on-first-write - // contract. + // contract. Unstamped (position 0) entries still require + // exactly 7; a stamped position (#13711) requires 16. for entry in [ JournalEntry::LeaseGranted { holder: "native-1".to_owned(), epoch: 1, expires_at_ms: Some(30_000), + position: 0, + }, + JournalEntry::LeaseRenewed { + holder: "native-1".to_owned(), + epoch: 1, + expires_at_ms: 40_000, + position: 0, + }, + JournalEntry::LeaseHandedOff { + from: DO_WRITE_LEASE_HOLDER.to_owned(), + to: "native-1".to_owned(), + epoch: 1, + expires_at_ms: Some(30_000), + position: 0, }, - spill_renewal(), - spill_handoff(), JournalEntry::LeaseRevoked { former_holder: "native-1".to_owned(), epoch: 2, reason: "expired".to_owned(), + position: 0, + }, + JournalEntry::LeaseWriteRejected { + writer: "native-1".to_owned(), + presented_epoch: 0, + operation_id: "op-1".to_owned(), + observed_epoch: 1, + reason: LeaseRejectionReason::StaleEpoch, + received_at_ms: 35_000, + position: 0, }, - stale_rejection(), ] { assert_eq!( journal_version_required_by(&entry), @@ -1696,6 +1724,13 @@ mod tests { "{entry:?}" ); } + for entry in [spill_handoff(), spill_renewal(), stale_rejection()] { + assert_eq!( + journal_version_required_by(&entry), + JOURNAL_VERSION_LEASE_POSITION, + "{entry:?}" + ); + } // The max-version pin moved to version 11 with program-bundle // installs (#8280), after version 10 for portal grants (F12.14 // wiring, code#1068), version 9 for signed play (#4346) and @@ -1704,13 +1739,19 @@ mod tests { // Version 12 (#11960) records join and revoke times, version // 13 the kv store entries, version 14 the blob store entries, // and version 15 the notify provider's `Notification` events - // (all #1062). - assert_eq!(MAX_JOURNAL_VERSION, JOURNAL_VERSION_NOTIFY); + // (all #1062). Version 16 (#13711) stamps lease positions. + assert_eq!(MAX_JOURNAL_VERSION, JOURNAL_VERSION_LEASE_POSITION); // A checkpoint carrying a non-bootstrap lease also requires // version 7; one without a lease keeps its existing version. + // A checkpoint whose lease history carries stamped positions + // requires version 16. let mut lease = WriteLease::bootstrap(); lease - .apply_handoff(DO_WRITE_LEASE_HOLDER, "native-1", 1, Some(30_000)) + .apply_handoff(DO_WRITE_LEASE_HOLDER, "native-1", 1, Some(30_000), 0) + .unwrap(); + let mut stamped = WriteLease::bootstrap(); + stamped + .apply_handoff(DO_WRITE_LEASE_HOLDER, "native-1", 1, Some(30_000), 1) .unwrap(); let checkpoint = |lease: Option| JournalEntry::Checkpoint { sequence: 0, @@ -1733,6 +1774,10 @@ mod tests { journal_version_required_by(&checkpoint(Some(lease))), JOURNAL_VERSION_WRITE_LEASE ); + assert_eq!( + journal_version_required_by(&checkpoint(Some(stamped))), + JOURNAL_VERSION_LEASE_POSITION + ); assert_eq!( journal_version_required_by(&checkpoint(None)), JOURNAL_VERSION @@ -1749,8 +1794,10 @@ mod tests { "{json}" ); } - // A lease entry in a journal whose header predates version 7 is - // refused at restore, never applied mid-read. + // A lease entry in a journal whose header predates the + // version it requires is refused at restore, never applied + // mid-read. The handoff helper carries a stamped position + // (#13711), so it requires version 16. let error = WorldCore::restore( "w", WorldLimits::default(), @@ -1764,7 +1811,7 @@ mod tests { ) .unwrap_err(); assert!( - error.to_string().contains("requires version 7"), + error.to_string().contains("requires version 16"), "{error:#}" ); } @@ -1801,11 +1848,13 @@ mod tests { former_holder: "native-1".to_owned(), epoch: 2, reason: "term expired without renewal".to_owned(), + position: 3, }, JournalEntry::LeaseGranted { holder: DO_WRITE_LEASE_HOLDER.to_owned(), epoch: 3, expires_at_ms: None, + position: 4, }, ], ) @@ -1827,6 +1876,14 @@ mod tests { LeaseTransitionKind::Granted, ] ); + // Positions ride the history in journal order (#13711), and + // the watermark is the highest position replayed. + let positions: Vec = lease + .transitions() + .map(|transition| transition.position) + .collect(); + assert_eq!(positions, [1, 2, 3, 4]); + assert_eq!(restored.core.lease_position_watermark(), 4); // The ex-holder is fenced at the new epoch, and the returned // holder presenting an old epoch is stale. assert_eq!( @@ -1905,6 +1962,7 @@ mod tests { observed_epoch: 1, reason: LeaseRejectionReason::Expired, received_at_ms: 35_000, + position: 2, }; let error = WorldCore::restore( "w", @@ -1928,6 +1986,7 @@ mod tests { to: "native-1".to_owned(), epoch: 2, expires_at_ms: Some(30_000), + position: 1, }], "advances the write lease epoch from 0 to 2", ), @@ -1937,6 +1996,7 @@ mod tests { holder: "native-1".to_owned(), epoch: 1, expires_at_ms: None, + position: 1, }], "while", ), @@ -1948,6 +2008,7 @@ mod tests { holder: DO_WRITE_LEASE_HOLDER.to_owned(), epoch: 1, expires_at_ms: 50_000, + position: 2, }, ], "held by", @@ -1961,6 +2022,7 @@ mod tests { holder: "native-1".to_owned(), epoch: 1, expires_at_ms: 35_000, + position: 3, }, ], "backwards", @@ -1973,6 +2035,7 @@ mod tests { former_holder: DO_WRITE_LEASE_HOLDER.to_owned(), epoch: 2, reason: "operator".to_owned(), + position: 2, }, ], "held by", @@ -1984,6 +2047,7 @@ mod tests { to: "native-1".to_owned(), epoch: 1, expires_at_ms: None, + position: 1, }], "held by", ), @@ -2017,11 +2081,13 @@ mod tests { former_holder: "native-1".to_owned(), epoch: 2, reason: "term expired without renewal".to_owned(), + position: 4, }, JournalEntry::LeaseGranted { holder: DO_WRITE_LEASE_HOLDER.to_owned(), epoch: 3, expires_at_ms: None, + position: 5, }, ], ) @@ -2054,16 +2120,17 @@ mod tests { let lease = restored.core.write_lease().clone(); // Compaction carries the lease whole on the checkpoint: the - // header rises to version 7 and a restore of the compacted - // journal rebuilds the identical lease — epoch, holder, term, - // transition history and rejection audit all preserved. + // header rises to version 16 (stamped positions, #13711) and + // a restore of the compacted journal rebuilds the identical + // lease — epoch, holder, term, transition history and + // rejection audit all preserved. let mut core = restored.core; core.active_module_hash = Some("h".to_owned()); let compacted = core.checkpoint_entries("state".to_owned()).unwrap(); assert!(matches!( compacted[0], JournalEntry::Created { - version: JOURNAL_VERSION_WRITE_LEASE, + version: JOURNAL_VERSION_LEASE_POSITION, .. } )); @@ -2091,6 +2158,253 @@ mod tests { assert!(error.to_string().contains("write lease"), "{error:#}"); } + #[test] + fn lease_position_watermark_reports_the_grant_position_after_replay() { + // #13711 oracle: a successor replaying a journal with a + // grant at position P reports watermark >= P before it may + // accept writes. Bootstrap has no stamped position. + let bootstrap = WorldCore::restore( + "w", + WorldLimits::default(), + [JournalEntry::Created { + world_id: "w".to_owned(), + version: JOURNAL_VERSION, + }], + ) + .unwrap(); + assert_eq!(bootstrap.core.lease_position_watermark(), 0); + + let restored = WorldCore::restore( + "w", + WorldLimits::default(), + [ + lease_header(), + spill_handoff(), + JournalEntry::LeaseRevoked { + former_holder: "native-1".to_owned(), + epoch: 2, + reason: "term expired without renewal".to_owned(), + position: 2, + }, + JournalEntry::LeaseGranted { + holder: DO_WRITE_LEASE_HOLDER.to_owned(), + epoch: 3, + expires_at_ms: None, + position: 3, + }, + ], + ) + .unwrap(); + assert_eq!(restored.core.lease_position_watermark(), 3); + assert_eq!(restored.core.write_lease().last_position(), 3); + + // Compaction preserves the watermark: the checkpoint carries + // the whole lease history, positions included. + let mut core = restored.core; + core.active_module_hash = Some("h".to_owned()); + let compacted = core.checkpoint_entries("state".to_owned()).unwrap(); + let restored = WorldCore::restore("w", WorldLimits::default(), compacted).unwrap(); + assert_eq!(restored.core.lease_position_watermark(), 3); + } + + #[test] + fn unstamped_lease_entries_still_restore_at_version_7() { + // #13711 back-compat: lease entries written before positions + // existed parse with position 0, restore under a version-7 + // header, and report watermark 0 — the barrier simply has + // no stamped grant to name yet. + let restored = WorldCore::restore( + "w", + WorldLimits::default(), + [ + JournalEntry::Created { + world_id: "w".to_owned(), + version: JOURNAL_VERSION_WRITE_LEASE, + }, + JournalEntry::LeaseHandedOff { + from: DO_WRITE_LEASE_HOLDER.to_owned(), + to: "native-1".to_owned(), + epoch: 1, + expires_at_ms: Some(30_000), + position: 0, + }, + JournalEntry::LeaseRenewed { + holder: "native-1".to_owned(), + epoch: 1, + expires_at_ms: 40_000, + position: 0, + }, + ], + ) + .unwrap(); + let lease = restored.core.write_lease(); + assert_eq!(lease.holder.as_deref(), Some("native-1")); + assert_eq!(lease.epoch, 1); + assert_eq!(restored.core.lease_position_watermark(), 0); + assert!( + lease + .transitions() + .all(|transition| transition.position == 0) + ); + } + + #[test] + fn lease_positions_that_do_not_advance_are_refused() { + // #13711: a stamped position that does not advance past the + // highest stamped position already replayed is a corrupt + // journal, refused at restore — not silently reordered. + let error = WorldCore::restore( + "w", + WorldLimits::default(), + [ + lease_header(), + spill_handoff(), + JournalEntry::LeaseRenewed { + holder: "native-1".to_owned(), + epoch: 1, + expires_at_ms: 40_000, + position: 1, + }, + ], + ) + .unwrap_err(); + assert!( + error.to_string().contains("does not advance past"), + "{error:#}" + ); + } + + #[test] + fn lease_positions_are_strictly_increasing_across_appends_and_compaction() { + // #13711 property test. Oracle: the lease history after + // restore (and after compaction + restore) carries exactly + // the positions the appends stamped, in order — one per + // lease record, strictly increasing. The generator folds + // op bytes through the lease state machine (holder, epoch, + // expiry), so every sequence is one the append authority + // could legally have written: handoff/renew/revoke while a + // holder stands, grant only while none does. + use proptest::prelude::*; + proptest!(|(ops in proptest::collection::vec(0u8..=255, 1..=12))| { + #[derive(Clone, Copy, PartialEq, Eq)] + enum ModelHolder { + Do, + Native, + } + let mut holder = Some(ModelHolder::Do); + let mut epoch = 0u64; + let mut expiry: Option = None; + let mut entries = vec![lease_header()]; + let mut position = 0u64; + for op in ops { + position += 1; + match holder { + Some(current) => match op % 3 { + 0 => { + let (from, to) = match current { + ModelHolder::Do => (DO_WRITE_LEASE_HOLDER, "native-1"), + ModelHolder::Native => ("native-1", DO_WRITE_LEASE_HOLDER), + }; + epoch += 1; + let next_expiry = if current == ModelHolder::Do { + Some(30_000 + epoch * 1_000) + } else { + None + }; + entries.push(JournalEntry::LeaseHandedOff { + from: from.to_owned(), + to: to.to_owned(), + epoch, + expires_at_ms: next_expiry, + position, + }); + holder = Some(if current == ModelHolder::Do { + ModelHolder::Native + } else { + ModelHolder::Do + }); + expiry = next_expiry; + } + 1 => { + let next_expiry = expiry.map_or(40_000, |e| e + 1_000); + let holder_name = match current { + ModelHolder::Do => DO_WRITE_LEASE_HOLDER, + ModelHolder::Native => "native-1", + }; + entries.push(JournalEntry::LeaseRenewed { + holder: holder_name.to_owned(), + epoch, + expires_at_ms: next_expiry, + position, + }); + expiry = Some(next_expiry); + } + _ => { + let former = match current { + ModelHolder::Do => DO_WRITE_LEASE_HOLDER, + ModelHolder::Native => "native-1", + }; + epoch += 1; + entries.push(JournalEntry::LeaseRevoked { + former_holder: former.to_owned(), + epoch, + reason: "term expired without renewal".to_owned(), + position, + }); + holder = None; + expiry = None; + } + }, + None => { + epoch += 1; + if op % 2 == 0 { + entries.push(JournalEntry::LeaseGranted { + holder: DO_WRITE_LEASE_HOLDER.to_owned(), + epoch, + expires_at_ms: None, + position, + }); + holder = Some(ModelHolder::Do); + expiry = None; + } else { + entries.push(JournalEntry::LeaseGranted { + holder: "native-1".to_owned(), + epoch, + expires_at_ms: Some(30_000 + epoch * 1_000), + position, + }); + holder = Some(ModelHolder::Native); + expiry = Some(30_000 + epoch * 1_000); + } + } + } + } + let expected: Vec = (1..=position).collect(); + let restored = WorldCore::restore("w", WorldLimits::default(), entries).unwrap(); + let positions: Vec = restored + .core + .write_lease() + .transitions() + .map(|transition| transition.position) + .collect(); + prop_assert_eq!(positions, expected.clone()); + prop_assert_eq!(restored.core.lease_position_watermark(), position); + + let mut core = restored.core; + core.active_module_hash = Some("h".to_owned()); + let compacted = core.checkpoint_entries("state".to_owned()).unwrap(); + let restored = WorldCore::restore("w", WorldLimits::default(), compacted).unwrap(); + let positions: Vec = restored + .core + .write_lease() + .transitions() + .map(|transition| transition.position) + .collect(); + prop_assert_eq!(positions, expected); + prop_assert_eq!(restored.core.lease_position_watermark(), position); + }); + } + #[test] fn checkpoint_handoff_transfers_validate_duplicates_epochs_and_events() { for (first, second) in [ @@ -8772,8 +9086,13 @@ mod tests { let entries = w.journal.entries(); assert!(matches!( entries.last(), - Some(JournalEntry::LeaseHandedOff { from, to, epoch: 1, .. }) - if from == DO_WRITE_LEASE_HOLDER && to == "native-1" + Some(JournalEntry::LeaseHandedOff { + from, + to, + epoch: 1, + position: 1, + .. + }) if from == DO_WRITE_LEASE_HOLDER && to == "native-1" )); assert!( !entries @@ -8839,6 +9158,14 @@ mod tests { LeaseTransitionKind::HandedOff ] ); + // Live handoffs stamp successive positions (#13711): the + // first handoff is position 1, the handback position 2, and + // the successor's watermark is 2. + assert_eq!( + lease.transitions().map(|t| t.position).collect::>(), + [1, 2] + ); + assert_eq!(restored.core.lease_position_watermark(), 2); } #[tokio::test] @@ -11642,8 +11969,7 @@ mod schedule_tests { }), JOURNAL_VERSION_NOTIFY ); - // A checkpoint retaining one requires it too, and it is - // the newest version this binary reads. + // A checkpoint retaining one requires it too. let checkpoint = JournalEntry::Checkpoint { sequence: 1, module_hash: "h".to_owned(), @@ -11665,7 +11991,9 @@ mod schedule_tests { journal_version_required_by(&checkpoint), JOURNAL_VERSION_NOTIFY ); - assert_eq!(MAX_JOURNAL_VERSION, JOURNAL_VERSION_NOTIFY); + // Version 16 (#13711, stamped lease positions) is the newest + // version this binary reads. + assert_eq!(MAX_JOURNAL_VERSION, JOURNAL_VERSION_LEASE_POSITION); } #[tokio::test] diff --git a/pkgs/id/crates/id-worlds/src/world_store.rs b/pkgs/id/crates/id-worlds/src/world_store.rs index 54d1813b95..69cc279da4 100644 --- a/pkgs/id/crates/id-worlds/src/world_store.rs +++ b/pkgs/id/crates/id-worlds/src/world_store.rs @@ -2656,11 +2656,12 @@ mod tests { #[test] fn write_lease_entries_survive_jsonl_reopen_with_epoch_intact() { // Design #2819 phase 2 (#3804): lease entries appended to a - // fresh (version 1) journal bump its header to version 7 on - // first write, and a reopen + replay rebuilds the same lease: - // holder, monotonic epoch, term, and transition history. + // fresh (version 1) journal bump its header to version 16 on + // first write (#13711: stamped positions), and a reopen + + // replay rebuilds the same lease: holder, monotonic epoch, + // term, and transition history. use crate::world::{ - JOURNAL_VERSION_WRITE_LEASE, JournalEntry as Entry, WorldCore, WorldJournal, + JOURNAL_VERSION_LEASE_POSITION, JournalEntry as Entry, WorldCore, WorldJournal, WorldLimits, }; let dir = TempDir::new().unwrap(); @@ -2672,6 +2673,7 @@ mod tests { to: "native-1".to_owned(), epoch: 1, expires_at_ms: Some(30_000), + position: 1, }) .unwrap(); journal @@ -2679,6 +2681,7 @@ mod tests { holder: "native-1".to_owned(), epoch: 1, expires_at_ms: 40_000, + position: 2, }) .unwrap(); drop(journal); @@ -2687,7 +2690,7 @@ mod tests { assert!(matches!( entries[0], Entry::Created { - version: JOURNAL_VERSION_WRITE_LEASE, + version: JOURNAL_VERSION_LEASE_POSITION, .. } ));