From e3b67c48647ad9a8c3088971aaeba98f8604eaba Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 10 Nov 2026 23:08:14 -0600 Subject: [PATCH 1/7] feat(id): destination import for region-seam handoff (#3902) #3870 phase 3 (design #2818 section 8.3), gated on phase 2 (#3901, landed via PR #8375). Mirrors the source-export path: WorldHandle::import_entity / WorldCommand::ImportEntity validate the envelope before any mutation (program module hash must match the destination program, payload schema bounded, payload digest must equal BLAKE3 of the payload, payload capped at MAX_ENTITY_TRANSFER_PAYLOAD_BYTES), the program prepares the import event purely, the actor persists one EntityImported journal entry, records the dedupe receipt, and only then applies - the receipt is returned only after apply succeeds, and a post-append apply failure withholds it and fails closed for replay recovery. An exact retry by handoff_id returns the stored receipt without re-journalling or re-applying; the same ID with different fields, or a second import for the same entity, fails closed. WorldCore gains validate_entity_import/record_entity_import, and restore now validates journaled imports (entity ref, duplicate entity import, and the destination event envelope: payload_hex inside the versioned system event must hash to the recorded digest). No coordinator route changes. Tests: journaled-before-apply + replay, exact retry without reapply, conflicting ID fails closed, dedupe after checkpoint compaction, envelope validation before mutation (bad digest / module mismatch / unsupported schema / oversized), failed post-append apply withholds receipt and keeps the dedupe record. World suite: 683 + 82 passed. --- pkgs/id/src/world/actor.rs | 229 +++++++++++++++++++++++++++++++ pkgs/id/src/world/core.rs | 105 ++++++++++++++- pkgs/id/src/world/handle.rs | 40 ++++++ pkgs/id/src/world/mod.rs | 2 +- pkgs/id/src/world/tests.rs | 260 ++++++++++++++++++++++++++++++++++-- 5 files changed, 620 insertions(+), 16 deletions(-) diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index f0b7edb713..0be42e64f9 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -54,6 +54,7 @@ impl WorldCommand { Self::Input { .. } => "Input", Self::EntityInput { .. } => "EntityInput", Self::ExportEntity { .. } => "ExportEntity", + Self::ImportEntity { .. } => "ImportEntity", Self::Snapshot { .. } => "Snapshot", Self::HostView { .. } => "HostView", Self::EventsAfter { .. } => "EventsAfter", @@ -175,6 +176,18 @@ pub(crate) enum WorldCommand { prior_owner_epoch: u64, reply: oneshot::Sender>, }, + ImportEntity { + handoff_id: String, + entity_ref: String, + source_region: String, + target_region: String, + prior_owner_epoch: u64, + program_module_hash: String, + payload_schema: String, + payload: Vec, + payload_digest: String, + reply: oneshot::Sender>, + }, Snapshot { token: JoinCapability, reply: oneshot::Sender>, @@ -822,6 +835,197 @@ impl WorldActor { Ok(transfer) } + fn import_entity( + &mut self, + handoff_id: String, + entity_ref: String, + source_region: String, + target_region: String, + prior_owner_epoch: u64, + program_module_hash: String, + payload_schema: String, + payload: Vec, + payload_digest: String, + ) -> Result { + self.check_storage()?; + ensure!(self.program_healthy, "world program is unavailable"); + ensure!( + self.journal.is_some(), + "entity import requires a durable world journal" + ); + ensure!( + self.core.limits.region_sharded, + "entity import requires a region-sharded world" + ); + ensure!( + handoff_id.len() == 32 && handoff_id.bytes().all(|b| b.is_ascii_hexdigit()), + "handoff ID must be 128-bit hexadecimal" + ); + core::validate_entity_ref(&entity_ref)?; + for (name, value) in [ + ("source region", source_region.as_str()), + ("target region", target_region.as_str()), + ] { + ensure!(!value.trim().is_empty(), "{name} must not be empty"); + ensure!(value.len() <= 256, "{name} exceeds 256 bytes"); + ensure!( + !value.chars().any(char::is_control), + "{name} contains a control character" + ); + } + ensure!( + source_region != target_region, + "source and target regions match" + ); + // Validate the envelope before any mutation (design #2818 \§3): + // the module hash and payload schema must be ones this destination + // runs, and the payload must hash to the digest the source recorded. + let active_module_hash = self + .core + .active_module_hash + .clone() + .context("world has no installed program for entity import")?; + ensure!( + program_module_hash == active_module_hash, + "entity import program module hash does not match the destination program" + ); + ensure!( + !payload_schema.trim().is_empty() && payload_schema.len() <= 128, + "entity transfer payload schema must be 1..=128 bytes" + ); + ensure!( + !payload_schema.chars().any(char::is_control), + "entity transfer payload schema contains a control character" + ); + ensure!( + payload.len() <= MAX_ENTITY_TRANSFER_PAYLOAD_BYTES, + "entity transfer payload exceeds {MAX_ENTITY_TRANSFER_PAYLOAD_BYTES} bytes" + ); + ensure!( + payload_digest == hex_encode(blake3::hash(&payload).as_bytes()), + "entity transfer payload digest does not match" + ); + let new_owner_epoch = prior_owner_epoch + .checked_add(1) + .context("entity import owner epoch overflow")?; + // Exact-retry recovery: if this import already committed (its reply + // was lost, or the actor restarted and replayed it), return the + // stored receipt instead of applying the entity twice. A stored + // import whose fields differ from the request is not a retry \— it + // falls through and validate_entity_import rejects the conflicting + // handoff ID / entity, failing closed, never overwriting. + if let Some(existing) = self.core.handoff_transfers.iter().find(|transfer| { + transfer.direction == HandoffDirection::Import && transfer.handoff_id == handoff_id + }) && existing.entity_ref == entity_ref + && existing.source_region == source_region + && existing.target_region == target_region + && existing.prior_owner_epoch == prior_owner_epoch + && existing.new_owner_epoch == Some(new_owner_epoch) + && existing.program_module_hash == program_module_hash + && existing.payload_schema == payload_schema + && existing.payload_digest == payload_digest + { + return Ok(existing.clone()); + } + let request = EntityTransferRequest::Import { + handoff_id: handoff_id.clone(), + entity_ref: entity_ref.clone(), + source_region: source_region.clone(), + target_region: target_region.clone(), + prior_owner_epoch, + program_module_hash: program_module_hash.clone(), + payload_schema: payload_schema.clone(), + payload: payload.clone(), + payload_digest: payload_digest.clone(), + }; + let EntityTransferPlan::Import { app_event } = + self.program.prepare_entity_transfer(&request)? + else { + bail!("world program returned an export plan for an import request"); + }; + let event_text = serde_json::json!({ + "protocol": "world.entity-transfer.v1", + "direction": "import", + "handoff_id": handoff_id, + "entity_ref": entity_ref, + "source_region": source_region, + "target_region": target_region, + "prior_owner_epoch": prior_owner_epoch, + "new_owner_epoch": new_owner_epoch, + "module_hash": program_module_hash, + "payload_schema": payload_schema, + "payload_digest": payload_digest, + "payload_hex": hex_encode(&payload), + "app_event": app_event, + }) + .to_string(); + ensure!( + event_text.len() <= crate::world_caps::MAX_EVENT_BYTES, + "entity transfer event exceeds {} bytes", + crate::world_caps::MAX_EVENT_BYTES + ); + let destination_event = WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { event: event_text }, + }; + let transfer = HandoffTransferState { + handoff_id: handoff_id.clone(), + entity_ref: entity_ref.clone(), + source_region: source_region.clone(), + target_region: target_region.clone(), + direction: HandoffDirection::Import, + prior_owner_epoch, + new_owner_epoch: Some(new_owner_epoch), + program_module_hash: program_module_hash.clone(), + payload_schema: payload_schema.clone(), + payload_digest: payload_digest.clone(), + payload: None, + event: destination_event.clone(), + }; + self.core.validate_entity_import(&transfer)?; + + // Persist-before-apply: the durable entry is the import receipt. + // Record it in the dedupe ledger before applying the prepared + // event, so a retry after a crash observes the receipt instead of + // applying the entity twice. The receipt is returned only after + // the program applies the event; a post-append failure withholds + // it and recovery replays the durable entry. + self.persist(JournalEntry::EntityImported { + handoff_id, + entity_ref, + source_region, + target_region, + prior_owner_epoch, + new_owner_epoch, + program_module_hash, + payload_schema, + payload_digest, + destination_event: destination_event.clone(), + })?; + self.core.record_entity_import(transfer.clone()); + if let Err(error) = self.program.update(&destination_event) { + self.program_healthy = false; + tracing::error!("world program rejected a durable entity import: {error:#}"); + return Err( + error.context("world program rejected a durable entity import; replay required") + ); + } + let records = match program_records(self.program.as_mut()) { + Ok(records) => records.unwrap_or_default(), + Err(error) => { + self.program_healthy = false; + tracing::error!("world program records failed after entity import: {error:#}"); + return Err(error.context( + "world program failed after a durable entity import; replay required", + )); + } + }; + self.republished(records, self.core.sequence); + let _ = self.view_changed.send(self.core.sequence); + Ok(transfer) + } + /// Publish freshly recomputed records. Participant events push their own /// view frame right after the event; host events signal the views watch. fn republished(&mut self, records: Records, sequence: u64) { @@ -1893,6 +2097,31 @@ impl WorldActor { ); let _ = reply.send(result); } + WorldCommand::ImportEntity { + handoff_id, + entity_ref, + source_region, + target_region, + prior_owner_epoch, + program_module_hash, + payload_schema, + payload, + payload_digest, + reply, + } => { + let result = self.import_entity( + handoff_id, + entity_ref, + source_region, + target_region, + prior_owner_epoch, + program_module_hash, + payload_schema, + payload, + payload_digest, + ); + let _ = reply.send(result); + } WorldCommand::Snapshot { token, reply } => { let _ = reply.send(self.core.snapshot(&token)); } diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs index b7d9dcc6d6..4100f35dd6 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -299,6 +299,53 @@ fn validate_handoff_transfer( Ok(()) } +/// Verify a journaled destination event carries the import envelope for +/// `payload_digest` (#3870 phase 3, design #2818 \§3): the payload rides +/// hex-encoded inside the versioned system event, and its BLAKE3 digest +/// must match the digest the journal entry records \— a tampered or +/// mismatched envelope is refused at restore, never applied. +fn validate_import_envelope(event: &WorldEvent, payload_digest: &str) -> Result<()> { + let text = match &event.kind { + WorldEventKind::System { event } => event, + _ => { + return Err(anyhow::anyhow!( + "journal import event is not a host system event" + )); + } + }; + let envelope: serde_json::Value = serde_json::from_str(text) + .map_err(|_| anyhow::anyhow!("journal import event is not a transfer envelope"))?; + ensure!( + envelope["protocol"] == "world.entity-transfer.v1" && envelope["direction"] == "import", + "journal import event is not an import envelope" + ); + ensure!( + envelope["payload_digest"] == payload_digest, + "journal import envelope digest does not match the journal entry" + ); + let payload_hex = envelope["payload_hex"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("journal import envelope carries no payload"))?; + ensure!( + payload_hex.len() % 2 == 0 && payload_hex.bytes().all(|b| b.is_ascii_hexdigit()), + "journal import envelope payload is not hex" + ); + let payload: Vec = (0..payload_hex.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&payload_hex[i..i + 2], 16)) + .collect::>() + .map_err(|_| anyhow::anyhow!("journal import envelope payload is not hex"))?; + ensure!( + payload.len() <= MAX_ENTITY_TRANSFER_PAYLOAD_BYTES, + "journal import payload exceeds {MAX_ENTITY_TRANSFER_PAYLOAD_BYTES} bytes" + ); + ensure!( + hex_encode(blake3::hash(&payload).as_bytes()) == payload_digest, + "journal import payload digest does not match" + ); + Ok(()) +} + impl WorldCore { /// Create an empty in-memory world on the real [`SystemClock`]. pub fn new(world_id: impl Into, limits: WorldLimits) -> Result { @@ -846,8 +893,8 @@ impl WorldCore { destination_event, } => { let transfer = HandoffTransferState { - handoff_id, - entity_ref, + handoff_id: handoff_id.clone(), + entity_ref: entity_ref.clone(), source_region, target_region, direction: HandoffDirection::Import, @@ -855,11 +902,19 @@ impl WorldCore { new_owner_epoch: Some(new_owner_epoch), program_module_hash, payload_schema, - payload_digest, + payload_digest: payload_digest.clone(), payload: None, event: destination_event.clone(), }; validate_handoff_transfer(&transfer, &core.handoff_transfers)?; + validate_entity_ref(&entity_ref)?; + ensure!( + !core.handoff_transfers.iter().any(|t| { + t.entity_ref == entity_ref && t.direction == HandoffDirection::Import + }), + "journal imports entity {entity_ref:?} twice" + ); + validate_import_envelope(&destination_event, &payload_digest)?; core.handoff_transfers.push(transfer); replay.push(destination_event); core.since_checkpoint = core.since_checkpoint.saturating_add(1); @@ -2278,6 +2333,50 @@ impl WorldCore { self.since_checkpoint = self.since_checkpoint.saturating_add(1); } + /// Validate a destination import against the dedupe ledger (#3870 + /// phase 3). The actor has already verified the envelope's module + /// hash, schema and payload digest before mutation; this checks the + /// durable-state invariants: direction, owner-epoch advance, no + /// duplicate payload copy, and that neither the handoff ID nor the + /// entity already carries an import. + pub(crate) fn validate_entity_import(&self, transfer: &HandoffTransferState) -> Result<()> { + ensure!( + self.limits.region_sharded, + "entity import requires a region-sharded world" + ); + ensure!( + transfer.direction == HandoffDirection::Import, + "destination import has the wrong transfer direction" + ); + validate_entity_ref(&transfer.entity_ref)?; + ensure!( + transfer.new_owner_epoch.is_some_and(|new_owner_epoch| { + transfer.prior_owner_epoch.checked_add(1) == Some(new_owner_epoch) + }), + "destination import does not advance the owner epoch" + ); + ensure!( + transfer.payload.is_none(), + "destination import carries a duplicate payload outside its event" + ); + ensure!( + !self.handoff_transfers.iter().any(|existing| { + existing.handoff_id == transfer.handoff_id + || (existing.direction == HandoffDirection::Import + && existing.entity_ref == transfer.entity_ref) + }), + "entity already has an active import or handoff ID is duplicated" + ); + Ok(()) + } + + /// Install an import receipt after its matching journal record is durable. + pub(crate) fn record_entity_import(&mut self, transfer: HandoffTransferState) { + debug_assert!(self.validate_entity_import(&transfer).is_ok()); + self.handoff_transfers.push(transfer); + self.since_checkpoint = self.since_checkpoint.saturating_add(1); + } + pub(crate) fn commit_prepared(&mut self, event: WorldEvent) -> Result { ensure!( event.sequence == self.sequence.saturating_add(1), diff --git a/pkgs/id/src/world/handle.rs b/pkgs/id/src/world/handle.rs index cf48bf4038..4ee8a01db5 100644 --- a/pkgs/id/src/world/handle.rs +++ b/pkgs/id/src/world/handle.rs @@ -963,6 +963,46 @@ impl WorldHandle { .context("world actor dropped entity export response")? } + /// Import an entity into this destination shard. The envelope is + /// validated (module hash, payload schema, payload digest) before any + /// mutation; the actor journals the import event in one + /// `EntityImported` entry before applying it and returns the durable + /// receipt only after application succeeds. An exact retry returns + /// the existing receipt; a conflicting reuse of the handoff ID fails + /// closed. + pub async fn import_entity( + &self, + handoff_id: impl Into, + entity_ref: impl Into, + source_region: impl Into, + target_region: impl Into, + prior_owner_epoch: u64, + program_module_hash: impl Into, + payload_schema: impl Into, + payload: Vec, + payload_digest: impl Into, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::ImportEntity { + handoff_id: handoff_id.into(), + entity_ref: entity_ref.into(), + source_region: source_region.into(), + target_region: target_region.into(), + prior_owner_epoch, + program_module_hash: program_module_hash.into(), + payload_schema: payload_schema.into(), + payload, + payload_digest: payload_digest.into(), + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped entity import response")? + } + /// Read a world snapshot. pub async fn snapshot(&self, token: JoinCapability) -> Result { let (reply, response) = oneshot::channel(); diff --git a/pkgs/id/src/world/mod.rs b/pkgs/id/src/world/mod.rs index 00a88cb96c..09f6dabd94 100644 --- a/pkgs/id/src/world/mod.rs +++ b/pkgs/id/src/world/mod.rs @@ -1444,7 +1444,7 @@ pub enum JournalEntry { /// (#3870 phase 1, design #2818 §3). Written persist-before-apply; the /// durable receipt for `handoff_id`. An exact retry returns the /// existing receipt; the same ID with a different digest is a hard - /// conflict (enforced from phase 3 of #3870). + /// conflict (phase 3 of #3870). EntityImported { /// Coordinator-generated handoff ID (hex); the dedupe key. handoff_id: String, diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index 7358b223bf..7687ca5587 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -85,15 +85,17 @@ mod tests { .unwrap_or_default() .to_owned(), ); - let durable = self - .journal - .entries() - .iter() - .any(|entry| matches!(entry, JournalEntry::EntityExported { .. })); + let durable = self.journal.entries().iter().any(|entry| { + if envelope["direction"] == "import" { + matches!(entry, JournalEntry::EntityImported { .. }) + } else { + matches!(entry, JournalEntry::EntityExported { .. }) + } + }); *self.saw_durable_export_before_apply.lock().unwrap() = durable; - ensure!(durable, "export event applied before it was journaled"); + ensure!(durable, "transfer event applied before it was journaled"); if self.fail_apply { - bail!("injected export-apply failure"); + bail!("injected transfer-apply failure"); } } Ok(()) @@ -109,9 +111,24 @@ mod tests { payload: self.payload.clone(), app_event: "remove-entity".to_owned(), }), - EntityTransferRequest::Import { .. } => Ok(EntityTransferPlan::Import { - app_event: "add-entity".to_owned(), - }), + EntityTransferRequest::Import { + payload_schema, + payload, + payload_digest, + .. + } => { + ensure!( + payload_schema == "test/v1", + "unsupported payload schema {payload_schema:?}" + ); + ensure!( + *payload_digest == hex_encode(blake3::hash(payload).as_bytes()), + "import payload digest does not match" + ); + Ok(EntityTransferPlan::Import { + app_event: "add-entity".to_owned(), + }) + } } } } @@ -273,6 +290,211 @@ mod tests { assert!(response.await.unwrap().is_err()); } + async fn import(actor: &mut WorldActor) -> Result { + import_payload(actor, b"entity".to_vec()).await + } + + async fn import_payload( + actor: &mut WorldActor, + payload: Vec, + ) -> Result { + let payload_digest = hex_encode(blake3::hash(&payload).as_bytes()); + import_with(actor, "module-hash", "test/v1", payload, payload_digest).await + } + + async fn import_with( + actor: &mut WorldActor, + program_module_hash: &str, + payload_schema: &str, + payload: Vec, + payload_digest: String, + ) -> Result { + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::ImportEntity { + handoff_id: "cd".repeat(16), + entity_ref: "entity-1".to_owned(), + source_region: "region-a".to_owned(), + target_region: "region-b".to_owned(), + prior_owner_epoch: 7, + program_module_hash: program_module_hash.to_owned(), + payload_schema: payload_schema.to_owned(), + payload, + payload_digest, + reply, + }) + .await; + response.await.unwrap() + } + + #[tokio::test] + async fn import_is_journaled_before_apply_and_replayed() { + let (mut actor, _, journal, saw_durable, applied) = + transfer_actor(b"entity".to_vec(), false); + let receipt = import(&mut actor).await.unwrap(); + assert_eq!(receipt.direction, HandoffDirection::Import); + assert_eq!(receipt.new_owner_epoch, Some(8)); + assert_eq!(receipt.payload, None); + assert!(*saw_durable.lock().unwrap()); + assert_eq!(*applied.lock().unwrap(), vec!["add-entity".to_owned()]); + assert!(matches!( + journal.entries().last(), + Some(JournalEntry::EntityImported { .. }) + )); + + let restored = WorldCore::restore( + "source", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + journal.entries(), + ) + .unwrap(); + assert_eq!(restored.core.handoff_transfers(), &[receipt.clone()]); + assert_eq!(restored.replay, vec![receipt.event.clone()]); + } + + #[tokio::test] + async fn import_exact_retry_returns_the_stored_receipt_without_reapplying() { + let (mut actor, _, journal, _, applied) = transfer_actor(b"entity".to_vec(), false); + let receipt = import(&mut actor).await.unwrap(); + let entries_after_first = journal.entries().len(); + let retry = import(&mut actor).await.unwrap(); + assert_eq!(retry, receipt); + assert_eq!(journal.entries().len(), entries_after_first); + assert_eq!(applied.lock().unwrap().len(), 1); + + // A conflicting reuse of the handoff ID is not a retry: it fails + // closed and the stored receipt is never overwritten. + assert!( + import_payload(&mut actor, b"different".to_vec()) + .await + .is_err() + ); + assert_eq!(journal.entries().len(), entries_after_first); + assert_eq!(actor.core.handoff_transfers(), &[receipt]); + } + + #[tokio::test] + async fn import_dedupes_after_checkpoint_compaction() { + let (mut actor, _, journal, _, _) = transfer_actor(b"entity".to_vec(), false); + let receipt = import(&mut actor).await.unwrap(); + let restored = WorldCore::restore( + "source", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + journal.entries(), + ) + .unwrap(); + let mut core = restored.core; + core.active_module_hash = Some("module-hash".to_owned()); + let compacted = core.checkpoint_entries("state".to_owned()).unwrap(); + let restored = WorldCore::restore( + "source", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + compacted.clone(), + ) + .unwrap(); + assert_eq!(restored.core.handoff_transfers(), &[receipt.clone()]); + + // A retry after compaction observes the receipt: it neither + // journals nor applies a second import. + let compacted_journal = TransferJournal(Arc::new(std::sync::Mutex::new(compacted))); + let applied = Arc::new(std::sync::Mutex::new(Vec::new())); + let program = TransferProgram { + payload: b"entity".to_vec(), + fail_apply: false, + journal: compacted_journal.clone(), + saw_durable_export_before_apply: Arc::new(std::sync::Mutex::new(false)), + applied_events: applied.clone(), + }; + let mut actor = WorldActor::for_test( + restored.core, + Box::new(program), + Some(Box::new(compacted_journal.clone())), + ); + let retry = import(&mut actor).await.unwrap(); + assert_eq!(retry, receipt); + assert!(applied.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn import_validates_the_envelope_before_any_mutation() { + let (mut actor, _, journal, _, applied) = transfer_actor(b"entity".to_vec(), false); + let before = journal.entries().len(); + let good_digest = hex_encode(blake3::hash(b"entity").as_bytes()); + + // A digest that does not match the payload. + assert!( + import_with( + &mut actor, + "module-hash", + "test/v1", + b"entity".to_vec(), + "00".repeat(32), + ) + .await + .is_err() + ); + // A module hash the destination does not run. + assert!( + import_with( + &mut actor, + "other-module", + "test/v1", + b"entity".to_vec(), + good_digest.clone(), + ) + .await + .is_err() + ); + // An unsupported payload schema (the program refuses in prepare). + assert!( + import_with( + &mut actor, + "module-hash", + "test/v2", + b"entity".to_vec(), + good_digest, + ) + .await + .is_err() + ); + // An oversized payload. + assert!( + import_payload(&mut actor, vec![0; MAX_ENTITY_TRANSFER_PAYLOAD_BYTES + 1]) + .await + .is_err() + ); + + assert_eq!(journal.entries().len(), before); + assert!(actor.core.handoff_transfers().is_empty()); + assert!(applied.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn failed_post_append_import_apply_withholds_receipt_and_keeps_the_dedupe_record() { + let (mut actor, _, journal, saw_durable, _) = transfer_actor(b"entity".to_vec(), true); + assert!(import(&mut actor).await.is_err()); + assert!(*saw_durable.lock().unwrap()); + assert!(!actor.program_healthy); + assert!(matches!( + journal.entries().last(), + Some(JournalEntry::EntityImported { .. }) + )); + assert_eq!(actor.core.handoff_transfers().len(), 1); + assert_eq!( + actor.core.handoff_transfers()[0].direction, + HandoffDirection::Import + ); + } + #[tokio::test] async fn entity_input_on_a_read_only_replica_never_reaches_the_program() { let (mut actor, token, _, _, applied) = transfer_actor(b"entity".to_vec(), false); @@ -819,8 +1041,22 @@ mod tests { new_owner_epoch: 2, program_module_hash: "module".to_owned(), payload_schema: "entity/v1".to_owned(), - payload_digest: "digest-2".to_owned(), - destination_event: handoff_event(), + payload_digest: hex_encode(blake3::hash(&[1, 2, 3]).as_bytes()), + destination_event: WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: serde_json::json!({ + "protocol": "world.entity-transfer.v1", + "direction": "import", + "handoff_id": "cd".repeat(16), + "entity_ref": "entity-2", + "payload_digest": hex_encode(blake3::hash(&[1, 2, 3]).as_bytes()), + "payload_hex": "010203", + }) + .to_string(), + }, + }, }, ]; let restored = WorldCore::restore("w", WorldLimits::default(), entries).unwrap(); From 7e94069f7b4630fb0e186ba668adde8f0bb7c2c0 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 00:35:04 -0600 Subject: [PATCH 2/7] fix(id): import-back lifts the export fence; pending transfer replay survives program replacement (#3902) --- pkgs/id/src/world/actor.rs | 49 +++++++++++++- pkgs/id/src/world/core.rs | 83 ++++++++++++++++------- pkgs/id/src/world/handle.rs | 1 + pkgs/id/src/world/tests.rs | 129 ++++++++++++++++++++++++++++++++++++ 4 files changed, 238 insertions(+), 24 deletions(-) diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index 0be42e64f9..b9ed0b16e7 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -383,6 +383,13 @@ pub(crate) struct WorldActor { /// by the replica open path; a writer never runs this way. pub(crate) read_only: bool, pub(crate) program_healthy: bool, + /// Durable transfers whose journal append succeeded but whose program + /// apply failed (#3902): their receipts sit in the core dedupe ledger + /// yet no live program has applied their events. The requirement is + /// tracked independently of `program_healthy`: an exact retry must not + /// acknowledge one of these receipts until a program — the current + /// one or an installed replacement — has actually applied the event. + pub(crate) pending_transfer_replays: Vec, /// Times a `view` or `layout` call trapped. Counted for `id world stats` /// (F11.17): a trapping view degrades to an error screen, not a poisoned /// world, so this counter is the only place the failure is recorded. @@ -726,6 +733,10 @@ impl WorldActor { && existing.prior_owner_epoch == prior_owner_epoch && existing.program_module_hash == program_module_hash { + ensure!( + !self.transfer_replay_pending(HandoffDirection::Export, &handoff_id), + "entity export {handoff_id:?} is durably recorded but has not been applied; replay required" + ); return Ok(existing.clone()); } let request = EntityTransferRequest::Export { @@ -814,6 +825,7 @@ impl WorldActor { })?; self.core.record_entity_export(transfer.clone()); if let Err(error) = self.program.update(&source_event) { + self.pending_transfer_replays.push(transfer); self.program_healthy = false; tracing::error!("world program rejected a durable entity export: {error:#}"); return Err( @@ -835,6 +847,15 @@ impl WorldActor { Ok(transfer) } + /// Whether a durably recorded transfer is still waiting for a program + /// to apply it (#3902): while it is, its stored receipt is withheld + /// from exact retries instead of being acknowledged. + fn transfer_replay_pending(&self, direction: HandoffDirection, handoff_id: &str) -> bool { + self.pending_transfer_replays + .iter() + .any(|pending| pending.direction == direction && pending.handoff_id == handoff_id) + } + fn import_entity( &mut self, handoff_id: String, @@ -925,6 +946,10 @@ impl WorldActor { && existing.payload_schema == payload_schema && existing.payload_digest == payload_digest { + ensure!( + !self.transfer_replay_pending(HandoffDirection::Import, &handoff_id), + "entity import {handoff_id:?} is durably recorded but has not been applied; replay required" + ); return Ok(existing.clone()); } let request = EntityTransferRequest::Import { @@ -1005,6 +1030,7 @@ impl WorldActor { })?; self.core.record_entity_import(transfer.clone()); if let Err(error) = self.program.update(&destination_event) { + self.pending_transfer_replays.push(transfer); self.program_healthy = false; tracing::error!("world program rejected a durable entity import: {error:#}"); return Err( @@ -2356,7 +2382,27 @@ impl WorldActor { self.core.active_module_provenance = provenance; self.core.active_seed = seed; self.program = replacement; - self.program_healthy = true; + // A program replacement does not discharge the + // replay requirement of transfers the previous + // program never applied (#3902): replay them into + // the replacement now, and declare health only + // once every pending transfer has been applied. + // Receipts for any that still fail stay withheld + // (see `transfer_replay_pending`). + let mut still_pending = Vec::new(); + for pending in std::mem::take(&mut self.pending_transfer_replays) { + match self.program.update(&pending.event) { + Ok(()) => {} + Err(error) => { + tracing::error!( + "world program rejected a pending transfer replay after install: {error:#}" + ); + still_pending.push(pending); + } + } + } + self.pending_transfer_replays = still_pending; + self.program_healthy = self.pending_transfer_replays.is_empty(); self.compaction_off = false; // A new program starts with a clean slate. self.handled_requests.clear(); @@ -3078,6 +3124,7 @@ impl WorldActor { storage_failed: false, read_only: false, program_healthy, + pending_transfer_replays: Vec::new(), view_failures: 0, compaction_off: false, event_sender: events, diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs index 4100f35dd6..1f65ef1305 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -853,11 +853,12 @@ impl WorldCore { ); ensure!( !core.handoff_transfers.iter().any(|t| { - (t.handoff_id == handoff_id && t.direction == HandoffDirection::Export) - || (t.entity_ref == entity_ref - && t.direction == HandoffDirection::Export) - }), - "journal exports handoff {handoff_id:?} or entity {entity_ref:?} twice" + t.handoff_id == handoff_id && t.direction == HandoffDirection::Export + }) && !matches!( + core.latest_transfer(&entity_ref), + Some(latest) if latest.direction == HandoffDirection::Export + ), + "journal exports handoff {handoff_id:?} twice or entity {entity_ref:?} while an export is active" ); let transfer = HandoffTransferState { handoff_id, @@ -909,10 +910,11 @@ impl WorldCore { validate_handoff_transfer(&transfer, &core.handoff_transfers)?; validate_entity_ref(&entity_ref)?; ensure!( - !core.handoff_transfers.iter().any(|t| { - t.entity_ref == entity_ref && t.direction == HandoffDirection::Import - }), - "journal imports entity {entity_ref:?} twice" + !matches!( + core.latest_transfer(&entity_ref), + Some(latest) if latest.direction == HandoffDirection::Import + ), + "journal imports entity {entity_ref:?} while an import is active" ); validate_import_envelope(&destination_event, &payload_digest)?; core.handoff_transfers.push(transfer); @@ -1056,7 +1058,19 @@ impl WorldCore { snapshot: None, provenance: provenance.clone(), }); - replay.clear(); + // Transfer receipts outlive the install (the + // dedupe ledger is retained whole), so their + // events survive the slate wipe too: the + // replacement program has not applied them, + // and dropping them would leave a stored + // receipt acknowledgable for a transfer the + // current program never saw (#3902). + let transfer_events: Vec<&WorldEvent> = core + .handoff_transfers + .iter() + .map(|transfer| &transfer.event) + .collect(); + replay.retain(|event| transfer_events.contains(&event)); } WorldEventKind::Input(_) => replay.push(event.clone()), WorldEventKind::EntityInput { entity_ref, .. } => { @@ -2285,10 +2299,27 @@ impl WorldCore { }) } + /// The most recent ownership transfer recorded for `entity_ref`, if + /// any. The ledger is append-only and chronological, so the last entry + /// for an entity is its current ownership state; earlier entries are + /// history, retained for handoff-ID deduplication. + pub(crate) fn latest_transfer(&self, entity_ref: &str) -> Option<&HandoffTransferState> { + self.handoff_transfers + .iter() + .rev() + .find(|transfer| transfer.entity_ref == entity_ref) + } + + /// An entity is fenced while its latest ownership transfer is an + /// export: the fence derives from the current ownership state, not + /// from any historical export. An entity imported back (design #2818 + /// §3 permits later crossings) is writable again; every historical + /// receipt stays in the ledger for deduplication. pub(crate) fn entity_is_fenced(&self, entity_ref: &str) -> bool { - self.handoff_transfers.iter().any(|transfer| { - transfer.direction == HandoffDirection::Export && transfer.entity_ref == entity_ref - }) + matches!( + self.latest_transfer(entity_ref), + Some(transfer) if transfer.direction == HandoffDirection::Export + ) } /// Install a durable source export in the in-memory transfer ledger. The @@ -2316,11 +2347,14 @@ impl WorldCore { "entity transfer payload digest does not match" ); ensure!( - !self.handoff_transfers.iter().any(|existing| { - existing.handoff_id == transfer.handoff_id - || (existing.direction == HandoffDirection::Export - && existing.entity_ref == transfer.entity_ref) - }), + !self + .handoff_transfers + .iter() + .any(|existing| existing.handoff_id == transfer.handoff_id) + && !matches!( + self.latest_transfer(&transfer.entity_ref), + Some(latest) if latest.direction == HandoffDirection::Export + ), "entity already has an active export or handoff ID is duplicated" ); Ok(()) @@ -2360,11 +2394,14 @@ impl WorldCore { "destination import carries a duplicate payload outside its event" ); ensure!( - !self.handoff_transfers.iter().any(|existing| { - existing.handoff_id == transfer.handoff_id - || (existing.direction == HandoffDirection::Import - && existing.entity_ref == transfer.entity_ref) - }), + !self + .handoff_transfers + .iter() + .any(|existing| existing.handoff_id == transfer.handoff_id) + && !matches!( + self.latest_transfer(&transfer.entity_ref), + Some(latest) if latest.direction == HandoffDirection::Import + ), "entity already has an active import or handoff ID is duplicated" ); Ok(()) diff --git a/pkgs/id/src/world/handle.rs b/pkgs/id/src/world/handle.rs index 4ee8a01db5..09af47329f 100644 --- a/pkgs/id/src/world/handle.rs +++ b/pkgs/id/src/world/handle.rs @@ -234,6 +234,7 @@ impl WorldHandle { storage_failed: false, read_only, program_healthy, + pending_transfer_replays: Vec::new(), view_failures: 0, compaction_off: false, event_sender: events.clone(), diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index 7687ca5587..24fd2e05a0 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -495,6 +495,135 @@ mod tests { ); } + #[tokio::test] + async fn imported_back_entity_loses_its_fence_and_can_cross_again() { + let (mut actor, token, journal, _, _) = transfer_actor(b"entity".to_vec(), false); + let exported = export(&mut actor).await.unwrap(); + assert!(actor.core.entity_is_fenced("entity-1")); + + // The entity crosses back B -> A under a fresh handoff ID with the + // owner epoch advanced (design #2818 §3 permits later crossings). + let payload = b"entity".to_vec(); + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::ImportEntity { + handoff_id: "ef".repeat(16), + entity_ref: "entity-1".to_owned(), + source_region: "region-b".to_owned(), + target_region: "region-a".to_owned(), + prior_owner_epoch: 7, + program_module_hash: "module-hash".to_owned(), + payload_schema: "test/v1".to_owned(), + payload_digest: hex_encode(blake3::hash(&payload).as_bytes()), + payload, + reply, + }) + .await; + let imported = response.await.unwrap().unwrap(); + assert_eq!(imported.direction, HandoffDirection::Import); + + // The historical export receipt stays in the ledger for dedupe, + // but the fence derives from the latest transfer: the entity is + // writable again. + assert_eq!(actor.core.handoff_transfers().len(), 2); + assert!(!actor.core.entity_is_fenced("entity-1")); + // The fence gate itself accepts writes again (checked at prepare + // level so the test journal keeps only transfer entries, like the + // restore-based tests above). + assert!( + actor + .core + .prepare_entity_input(&token, "entity-1", b"mutate") + .is_ok() + ); + + // And it can cross out again under another fresh handoff ID. + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::ExportEntity { + handoff_id: "12".repeat(16), + entity_ref: "entity-1".to_owned(), + source_region: "region-a".to_owned(), + target_region: "region-b".to_owned(), + prior_owner_epoch: 8, + reply, + }) + .await; + let re_exported = response.await.unwrap().unwrap(); + assert!(actor.core.entity_is_fenced("entity-1")); + + // The whole round trip restores: both crossings replay in order + // and the restored fence follows the latest transfer. + let restored = WorldCore::restore( + "source", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + journal.entries(), + ) + .unwrap(); + assert_eq!(restored.core.handoff_transfers().len(), 3); + assert_eq!( + restored.replay, + vec![ + exported.event.clone(), + imported.event.clone(), + re_exported.event.clone() + ] + ); + assert!(restored.core.entity_is_fenced("entity-1")); + } + + #[tokio::test] + async fn failed_import_replay_requirement_survives_program_replacement() { + let (mut actor, _, journal, _, _) = transfer_actor(b"entity".to_vec(), true); + assert!(import(&mut actor).await.is_err()); + assert!(!actor.program_healthy); + assert_eq!(actor.pending_transfer_replays.len(), 1); + + // Reinstalling the same module must not clear the requirement: + // the replacement program replays the pending import as part of + // the install, and only then is the world healthy again. + let applied_after_install = Arc::new(std::sync::Mutex::new(Vec::new())); + let replacement = TransferProgram { + payload: b"entity".to_vec(), + fail_apply: false, + journal: journal.clone(), + saw_durable_export_before_apply: Arc::new(std::sync::Mutex::new(false)), + applied_events: applied_after_install.clone(), + }; + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::InstallProgram { + module_hash: "module-hash".to_owned(), + seed: 0, + provenance: None, + installed_by: None, + trust: None, + program: Box::new(replacement), + reply, + }) + .await; + assert!(response.await.unwrap().is_ok()); + assert!(actor.pending_transfer_replays.is_empty()); + assert!(actor.program_healthy); + assert_eq!( + *applied_after_install.lock().unwrap(), + vec!["add-entity".to_owned()], + "the replacement program applied the pending import exactly once" + ); + + // Now the exact retry may return the stored receipt — and it must + // not apply the import a second time. + let receipt = import(&mut actor).await.unwrap(); + assert_eq!(receipt.direction, HandoffDirection::Import); + assert_eq!( + *applied_after_install.lock().unwrap(), + vec!["add-entity".to_owned()] + ); + } + #[tokio::test] async fn entity_input_on_a_read_only_replica_never_reaches_the_program() { let (mut actor, token, _, _, applied) = transfer_actor(b"entity".to_vec(), false); From 564cca48dbcf3594343fef78591a4cac91001932 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 02:05:51 -0600 Subject: [PATCH 3/7] id: replay full transfer history on live install; publish post-replay records (#3902) Codex P2 (PR #8542): live InstallProgram replayed only never-applied transfers while journal restore retains the whole handoff history across an install, so a successful import vanished from the live replacement and resurrected on restart. The live install now replays the full retained handoff_transfers history in order; failures stay pending with receipts withheld. Codex P2: the install published records computed before the replay; records are now recomputed from the replayed program before publishing, and a records failure marks the world unhealthy instead of acknowledging recovery. Tests: successful_import_replays_into_replacement_on_live_install, install_publishes_records_recomputed_after_transfer_replay; world::tests 217 passed. --- pkgs/id/src/world/actor.rs | 51 +++++++++++++----- pkgs/id/src/world/tests.rs | 105 +++++++++++++++++++++++++++++++++++++ 2 files changed, 142 insertions(+), 14 deletions(-) diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index b9ed0b16e7..916d73f42e 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -2382,22 +2382,26 @@ impl WorldActor { self.core.active_module_provenance = provenance; self.core.active_seed = seed; self.program = replacement; - // A program replacement does not discharge the - // replay requirement of transfers the previous - // program never applied (#3902): replay them into - // the replacement now, and declare health only - // once every pending transfer has been applied. - // Receipts for any that still fail stay withheld - // (see `transfer_replay_pending`). + // The replacement starts from the same transfer + // history a journal restore would apply to it + // (#3902): restore retains every handoff transfer + // event across an install, so the live install + // replays the full retained history here too - + // not only the transfers the previous program + // never applied. Anything less would let a + // restart change application state. Transfers + // whose replay fails stay pending, their receipts + // stay withheld (see transfer_replay_pending), + // and health is declared only once none remain. let mut still_pending = Vec::new(); - for pending in std::mem::take(&mut self.pending_transfer_replays) { - match self.program.update(&pending.event) { + for transfer in self.core.handoff_transfers.clone() { + match self.program.update(&transfer.event) { Ok(()) => {} Err(error) => { tracing::error!( - "world program rejected a pending transfer replay after install: {error:#}" + "world program rejected a transfer replay after install: {error:#}" ); - still_pending.push(pending); + still_pending.push(transfer); } } } @@ -2409,9 +2413,28 @@ impl WorldActor { self.denied_subs.clear(); self.active_subs.clear(); self.ticks.clear(); - self.republished(new_records, event.sequence); - let _ = self.event_sender.send(event.clone()); - Ok(event) + // The records computed before the replay describe + // the replacement without the transfers it just + // applied; recompute them from the replayed state + // before publishing, so an imported entity is + // visible in records() as soon as the install is + // acknowledged. + match program_records(self.program.as_mut()) { + Ok(records) => { + self.republished(records.unwrap_or_default(), event.sequence); + let _ = self.event_sender.send(event.clone()); + Ok(event) + } + Err(error) => { + self.program_healthy = false; + tracing::error!( + "world program records failed after transfer replay on install: {error:#}" + ); + Err(error.context( + "world program records failed after transfer replay on install", + )) + } + } } Err(error) => Err(error), }; diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index 24fd2e05a0..ca8de9da11 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -101,6 +101,11 @@ mod tests { Ok(()) } + fn records(&mut self) -> Result> { + let applied = self.applied_events.lock().unwrap().clone(); + Ok(Some(serde_json::json!({ "applied": applied }).to_string())) + } + fn prepare_entity_transfer( &self, request: &EntityTransferRequest, @@ -624,6 +629,106 @@ mod tests { ); } + #[tokio::test] + async fn successful_import_replays_into_replacement_on_live_install() { + let (mut actor, _, journal, _, applied_first) = transfer_actor(b"entity".to_vec(), false); + let receipt = import(&mut actor).await.unwrap(); + assert_eq!(receipt.direction, HandoffDirection::Import); + assert_eq!( + *applied_first.lock().unwrap(), + vec!["add-entity".to_owned()] + ); + assert!(actor.pending_transfer_replays.is_empty()); + assert!(actor.program_healthy); + + // A live reinstall of the same module must hand the replacement + // the same transfer history a journal restore would: restore + // retains the successful import across the install, so the live + // replacement applies it too - exactly once - instead of losing + // the entity until a restart resurrects it (#3902). + let applied_after_install = Arc::new(std::sync::Mutex::new(Vec::new())); + let replacement = TransferProgram { + payload: b"entity".to_vec(), + fail_apply: false, + journal: journal.clone(), + saw_durable_export_before_apply: Arc::new(std::sync::Mutex::new(false)), + applied_events: applied_after_install.clone(), + }; + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::InstallProgram { + module_hash: "module-hash".to_owned(), + seed: 0, + provenance: None, + installed_by: None, + trust: None, + program: Box::new(replacement), + reply, + }) + .await; + assert!(response.await.unwrap().is_ok()); + assert!(actor.program_healthy); + assert!(actor.pending_transfer_replays.is_empty()); + assert_eq!( + *applied_after_install.lock().unwrap(), + vec!["add-entity".to_owned()], + "the replacement program applied the retained import exactly once" + ); + + // The restore path agrees: the same journal replays the import + // into a restored program as well. + let restored = WorldCore::restore( + "source", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + journal.entries(), + ) + .unwrap(); + assert_eq!(restored.replay, vec![receipt.event.clone()]); + } + + #[tokio::test] + async fn install_publishes_records_recomputed_after_transfer_replay() { + let (mut actor, _, journal, _, _) = transfer_actor(b"entity".to_vec(), true); + assert!(import(&mut actor).await.is_err()); + assert_eq!(actor.pending_transfer_replays.len(), 1); + + // The replacement recovers the pending import during install; + // the records published for the install must describe the + // replacement AFTER that replay, not the empty pre-replay state + // computed before it (#3902). + let applied_after_install = Arc::new(std::sync::Mutex::new(Vec::new())); + let replacement = TransferProgram { + payload: b"entity".to_vec(), + fail_apply: false, + journal: journal.clone(), + saw_durable_export_before_apply: Arc::new(std::sync::Mutex::new(false)), + applied_events: applied_after_install.clone(), + }; + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::InstallProgram { + module_hash: "module-hash".to_owned(), + seed: 0, + provenance: None, + installed_by: None, + trust: None, + program: Box::new(replacement), + reply, + }) + .await; + assert!(response.await.unwrap().is_ok()); + assert!(actor.program_healthy); + let published = actor.records_sender.borrow().1.clone(); + assert_eq!( + published["applied"], + serde_json::json!(["add-entity"]), + "published records reflect the import the replacement just applied" + ); + } + #[tokio::test] async fn entity_input_on_a_read_only_replica_never_reaches_the_program() { let (mut actor, token, _, _, applied) = transfer_actor(b"entity".to_vec(), false); From 93e2c270eeed4c0b96f63610e5fe2ff0290e3de0 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 02:16:36 -0600 Subject: [PATCH 4/7] id: rebuild post-install replay from the transfer ledger on restore (#3902) Codex P2 (PR #8542): a transfer compacted into a checkpoint sits in core.handoff_transfers without ever entering the restore replay, so the install arm's retain-filter could not recover it and a restart after an install lost the checkpoint-carried import while its receipt stayed acknowledgable. The install arm now rebuilds the replay from the retained ledger. Regression test: checkpoint_carried_transfer_replays_after_install_on_restore; world::tests 218 passed. --- pkgs/id/src/world/core.rs | 12 +++++--- pkgs/id/src/world/tests.rs | 58 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs index 1f65ef1305..f2ba8923db 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -1064,13 +1064,17 @@ impl WorldCore { // replacement program has not applied them, // and dropping them would leave a stored // receipt acknowledgable for a transfer the - // current program never saw (#3902). - let transfer_events: Vec<&WorldEvent> = core + // current program never saw (#3902). Rebuild + // the replay from the ledger instead of + // filtering the events already replayed: a + // transfer compacted into a checkpoint sits + // in the ledger without ever entering the + // replay, and filtering would lose it here. + replay = core .handoff_transfers .iter() - .map(|transfer| &transfer.event) + .map(|transfer| transfer.event.clone()) .collect(); - replay.retain(|event| transfer_events.contains(&event)); } WorldEventKind::Input(_) => replay.push(event.clone()), WorldEventKind::EntityInput { entity_ref, .. } => { diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index ca8de9da11..46a0192817 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -689,6 +689,64 @@ mod tests { assert_eq!(restored.replay, vec![receipt.event.clone()]); } + #[tokio::test] + async fn checkpoint_carried_transfer_replays_after_install_on_restore() { + let (mut actor, _, _, _, _) = transfer_actor(b"entity".to_vec(), false); + let receipt = import(&mut actor).await.unwrap(); + + // Compact the import into a checkpoint: the transfer now sits in + // the checkpoint ledger (transfers), and its event never enters a + // restored replay on its own. A program install journaled after + // the checkpoint must still hand the transfer to the replacement + // when the journal is restored (#3902). + let install = WorldEvent { + sequence: receipt.event.sequence + 1, + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash: "module-hash".to_owned(), + seed: 0, + provenance: None, + trust: None, + }, + }; + let restored = WorldCore::restore( + "source", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + [ + JournalEntry::Created { + world_id: "source".to_owned(), + version: JOURNAL_VERSION_REGION_HANDOFF, + }, + JournalEntry::Checkpoint { + sequence: receipt.event.sequence, + module_hash: "module-hash".to_owned(), + seed: 0, + provenance: None, + execution_profile: None, + caps_ceiling: None, + schedules: None, + transfers: Some(vec![receipt.clone()]), + lease: None, + snapshot: "snapshot".to_owned(), + events: Vec::new(), + admin_history: None, + open_presence: None, + }, + JournalEntry::Committed { event: install }, + ], + ) + .unwrap(); + assert_eq!(restored.core.handoff_transfers().len(), 1); + assert_eq!( + restored.replay, + vec![receipt.event.clone()], + "the checkpoint-carried import replays into the replacement after restore" + ); + } + #[tokio::test] async fn install_publishes_records_recomputed_after_transfer_replay() { let (mut actor, _, journal, _, _) = transfer_actor(b"entity".to_vec(), true); From d8f24d74832899e388b57547bdff7bee2b69fce2 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 02:26:33 -0600 Subject: [PATCH 5/7] id: install result reports a failed transfer replay (#3902) Codex P2 (PR #8542): when the replacement rejected a retained transfer but records() succeeded, InstallProgram returned success (and audited success) while the world stayed unhealthy with receipts withheld. The first replay error is now propagated as the install result; the install event remains journaled and recovery stays possible. Regression test: install_reports_failure_when_transfer_replay_still_fails; world::tests 219 passed. --- pkgs/id/src/world/actor.rs | 19 +++++++++-- pkgs/id/src/world/tests.rs | 64 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index 916d73f42e..82ade35dd1 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -2394,6 +2394,7 @@ impl WorldActor { // stay withheld (see transfer_replay_pending), // and health is declared only once none remain. let mut still_pending = Vec::new(); + let mut first_replay_error = None; for transfer in self.core.handoff_transfers.clone() { match self.program.update(&transfer.event) { Ok(()) => {} @@ -2401,6 +2402,9 @@ impl WorldActor { tracing::error!( "world program rejected a transfer replay after install: {error:#}" ); + if first_replay_error.is_none() { + first_replay_error = Some(error); + } still_pending.push(transfer); } } @@ -2422,8 +2426,19 @@ impl WorldActor { match program_records(self.program.as_mut()) { Ok(records) => { self.republished(records.unwrap_or_default(), event.sequence); - let _ = self.event_sender.send(event.clone()); - Ok(event) + if let Some(error) = first_replay_error { + // The install stands (it is journaled), + // but recovery is incomplete: report the + // replay failure as the install result + // instead of acknowledging success while + // the world stays unhealthy (#3902). + Err(error.context( + "world program rejected a retained transfer replay after install", + )) + } else { + let _ = self.event_sender.send(event.clone()); + Ok(event) + } } Err(error) => { self.program_healthy = false; diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index 46a0192817..6ba2973930 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -787,6 +787,70 @@ mod tests { ); } + #[tokio::test] + async fn install_reports_failure_when_transfer_replay_still_fails() { + let (mut actor, _, journal, _, _) = transfer_actor(b"entity".to_vec(), true); + assert!(import(&mut actor).await.is_err()); + assert_eq!(actor.pending_transfer_replays.len(), 1); + + // A replacement that also rejects the pending import must not be + // acknowledged as a successful install: the world is still + // unhealthy and the receipt still withheld, so the install + // result (and its audit record) reports the replay failure + // (#3902). + let failing_replacement = TransferProgram { + payload: b"entity".to_vec(), + fail_apply: true, + journal: journal.clone(), + saw_durable_export_before_apply: Arc::new(std::sync::Mutex::new(false)), + applied_events: Arc::new(std::sync::Mutex::new(Vec::new())), + }; + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::InstallProgram { + module_hash: "module-hash".to_owned(), + seed: 0, + provenance: None, + installed_by: None, + trust: None, + program: Box::new(failing_replacement), + reply, + }) + .await; + let error = response.await.unwrap().unwrap_err(); + assert!( + format!("{error:#}").contains("rejected a retained transfer replay"), + "the install result names the replay failure: {error:#}" + ); + assert!(!actor.program_healthy); + assert_eq!(actor.pending_transfer_replays.len(), 1); + + // Recovery is still possible: a program that accepts the replay + // installs successfully and drains the requirement. + let good_replacement = TransferProgram { + payload: b"entity".to_vec(), + fail_apply: false, + journal: journal.clone(), + saw_durable_export_before_apply: Arc::new(std::sync::Mutex::new(false)), + applied_events: Arc::new(std::sync::Mutex::new(Vec::new())), + }; + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::InstallProgram { + module_hash: "module-hash".to_owned(), + seed: 0, + provenance: None, + installed_by: None, + trust: None, + program: Box::new(good_replacement), + reply, + }) + .await; + assert!(response.await.unwrap().is_ok()); + assert!(actor.program_healthy); + assert!(actor.pending_transfer_replays.is_empty()); + } + #[tokio::test] async fn entity_input_on_a_read_only_replica_never_reaches_the_program() { let (mut actor, token, _, _, applied) = transfer_actor(b"entity".to_vec(), false); From 6b34323360073a328131d72a03cae116966776d4 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 02:36:58 -0600 Subject: [PATCH 6/7] id: chain handoff epochs so a stale import cannot supersede an export fence (#3902) Codex P2 (PR #8542): an import under a fresh handoff ID with a stale prior_owner_epoch passed validation (only prior+1=new was checked), became the latest transfer, and cleared the export fence. Crossings now chain epochs: a transfer prior epoch must equal the epoch the entity latest recorded transfer leaves it at (export: its prior epoch; import: its new epoch), enforced in validate_entity_import/validate_entity_export and in journal restore via validate_handoff_transfer. Regression test: stale_epoch_import_cannot_supersede_an_export_fence (live rejection + restore rejection); world::tests 220 passed. --- pkgs/id/src/world/core.rs | 42 +++++++++++++++++++++ pkgs/id/src/world/tests.rs | 75 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+) diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs index f2ba8923db..b793963a77 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -262,6 +262,45 @@ fn chat_endpoint(participant_id: u64) -> crate::abuse::EndpointId { /// Validate the invariants shared by standalone handoff entries and /// checkpoint-carried transfer state. `prior_transfers` are the already /// admitted records, so callers validate a checkpoint's list in list order. +/// The owner epoch an entity sits at after a transfer: an export leaves +/// at the epoch it records as prior (ownership departs at that epoch), an +/// import lands at its new epoch. A subsequent crossing for the same +/// entity must chain from exactly this epoch; anything else is a stale +/// ownership claim and must never supersede the recorded state (#3902). +fn owner_epoch_after(transfer: &HandoffTransferState) -> u64 { + match transfer.direction { + HandoffDirection::Export => transfer.prior_owner_epoch, + HandoffDirection::Import => transfer + .new_owner_epoch + .unwrap_or(transfer.prior_owner_epoch), + } +} + +/// Enforce the epoch chain against the transfers already recorded for +/// the entity, if any: the new transfer's prior epoch must continue the +/// latest recorded transfer. First crossings are unconstrained (the +/// epoch originates with the caller's ownership claim). +fn ensure_epoch_chains( + transfer: &HandoffTransferState, + prior_transfers: &[HandoffTransferState], +) -> Result<()> { + if let Some(latest) = prior_transfers + .iter() + .rev() + .find(|prior| prior.entity_ref == transfer.entity_ref) + { + ensure!( + transfer.prior_owner_epoch == owner_epoch_after(latest), + "handoff {:?} claims prior owner epoch {} for entity {:?}, but the latest recorded transfer leaves it at epoch {}", + transfer.handoff_id, + transfer.prior_owner_epoch, + transfer.entity_ref, + owner_epoch_after(latest) + ); + } + Ok(()) +} + fn validate_handoff_transfer( transfer: &HandoffTransferState, prior_transfers: &[HandoffTransferState], @@ -296,6 +335,7 @@ fn validate_handoff_transfer( "journal {name}s handoff {:?} twice", transfer.handoff_id ); + ensure_epoch_chains(transfer, prior_transfers)?; Ok(()) } @@ -2361,6 +2401,7 @@ impl WorldCore { ), "entity already has an active export or handoff ID is duplicated" ); + ensure_epoch_chains(transfer, &self.handoff_transfers)?; Ok(()) } @@ -2408,6 +2449,7 @@ impl WorldCore { ), "entity already has an active import or handoff ID is duplicated" ); + ensure_epoch_chains(transfer, &self.handoff_transfers)?; Ok(()) } diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index 6ba2973930..1428b60785 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -851,6 +851,81 @@ mod tests { assert!(actor.pending_transfer_replays.is_empty()); } + #[tokio::test] + async fn stale_epoch_import_cannot_supersede_an_export_fence() { + let (mut actor, _, journal, _, _) = transfer_actor(b"entity".to_vec(), false); + let exported = export(&mut actor).await.unwrap(); + assert!(actor.core.entity_is_fenced("entity-1")); + + // A returning import under a fresh handoff ID but a STALE prior + // epoch (6, while the export left ownership at 7) must be + // rejected: recording it would make it the latest transfer and + // silently clear the fence (#3902). + let payload = b"entity".to_vec(); + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::ImportEntity { + handoff_id: "34".repeat(16), + entity_ref: "entity-1".to_owned(), + source_region: "region-b".to_owned(), + target_region: "region-a".to_owned(), + prior_owner_epoch: 6, + program_module_hash: "module-hash".to_owned(), + payload_schema: "test/v1".to_owned(), + payload_digest: hex_encode(blake3::hash(&payload).as_bytes()), + payload, + reply, + }) + .await; + assert!(response.await.unwrap().is_err()); + assert!(actor.core.entity_is_fenced("entity-1")); + assert_eq!(actor.core.handoff_transfers().len(), 1); + + // The same invariant holds at journal restoration: a journal + // carrying the stale import after the export is refused. + let stale_event = { + let payload = b"entity".to_vec(); + let envelope = serde_json::json!({ + "protocol": "world.entity-transfer.v1", + "direction": "import", + "app_event": "add-entity", + "payload_hex": hex_encode(&payload), + "payload_digest": hex_encode(blake3::hash(&payload).as_bytes()), + }); + WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: envelope.to_string(), + }, + } + }; + let mut entries = journal.entries(); + entries.push(JournalEntry::EntityImported { + handoff_id: "34".repeat(16), + entity_ref: "entity-1".to_owned(), + source_region: "region-b".to_owned(), + target_region: "region-a".to_owned(), + prior_owner_epoch: 6, + new_owner_epoch: 7, + program_module_hash: "module-hash".to_owned(), + payload_schema: "test/v1".to_owned(), + payload_digest: exported.payload_digest.clone(), + destination_event: stale_event, + }); + assert!( + WorldCore::restore( + "source", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + entries, + ) + .is_err() + ); + } + #[tokio::test] async fn entity_input_on_a_read_only_replica_never_reaches_the_program() { let (mut actor, token, _, _, applied) = transfer_actor(b"entity".to_vec(), false); From 3068bf38718d60047d1d4ac8d10838518de9311f Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 02:45:08 -0600 Subject: [PATCH 7/7] id: allow returning imports to chain from epochs advanced abroad (#3902) Codex P2 (PR #8542): strict epoch equality rejected the legitimate A->B->A return - ownership advances one step per crossing on other shards, so a return import chains from an epoch beyond the last local export. Rule corrected: after a local export, a crossing must chain from at least the export epoch (older is stale and rejected); after a local import, it must chain from exactly the landed epoch. Regression test: advanced_epoch_return_import_is_accepted; world::tests 221 passed. --- pkgs/id/src/world/core.rs | 18 ++++++++++++++---- pkgs/id/src/world/tests.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs index b793963a77..4db42698be 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -277,9 +277,15 @@ fn owner_epoch_after(transfer: &HandoffTransferState) -> u64 { } /// Enforce the epoch chain against the transfers already recorded for -/// the entity, if any: the new transfer's prior epoch must continue the -/// latest recorded transfer. First crossings are unconstrained (the -/// epoch originates with the caller's ownership claim). +/// the entity, if any. While the entity is local (its latest transfer is +/// an import), the next crossing must depart from exactly the epoch the +/// import landed at. While it is away (its latest transfer is an +/// export), ownership advances abroad - one step per crossing on other +/// shards - so a returning transfer may chain from any epoch at or +/// beyond the one the export left at, but never an older one: a stale +/// epoch would supersede the fence with an outdated ownership claim. +/// First crossings are unconstrained (the epoch originates with the +/// caller's ownership claim). fn ensure_epoch_chains( transfer: &HandoffTransferState, prior_transfers: &[HandoffTransferState], @@ -289,8 +295,12 @@ fn ensure_epoch_chains( .rev() .find(|prior| prior.entity_ref == transfer.entity_ref) { + let chained = match latest.direction { + HandoffDirection::Export => transfer.prior_owner_epoch >= latest.prior_owner_epoch, + HandoffDirection::Import => transfer.prior_owner_epoch == owner_epoch_after(latest), + }; ensure!( - transfer.prior_owner_epoch == owner_epoch_after(latest), + chained, "handoff {:?} claims prior owner epoch {} for entity {:?}, but the latest recorded transfer leaves it at epoch {}", transfer.handoff_id, transfer.prior_owner_epoch, diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index 1428b60785..a44bd00e9a 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -926,6 +926,38 @@ mod tests { ); } + #[tokio::test] + async fn advanced_epoch_return_import_is_accepted() { + let (mut actor, _, _, _, _) = transfer_actor(b"entity".to_vec(), false); + export(&mut actor).await.unwrap(); + assert!(actor.core.entity_is_fenced("entity-1")); + + // The real round trip: the entity was imported on the other shard + // (advancing ownership 7 -> 8) and exported back from there, so + // the return import chains from epoch 8 even though this shard + // last saw it at 7. That is a legitimate advance, not staleness + // (#3902). + let payload = b"entity".to_vec(); + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::ImportEntity { + handoff_id: "56".repeat(16), + entity_ref: "entity-1".to_owned(), + source_region: "region-b".to_owned(), + target_region: "region-a".to_owned(), + prior_owner_epoch: 8, + program_module_hash: "module-hash".to_owned(), + payload_schema: "test/v1".to_owned(), + payload_digest: hex_encode(blake3::hash(&payload).as_bytes()), + payload, + reply, + }) + .await; + let imported = response.await.unwrap().unwrap(); + assert_eq!(imported.new_owner_epoch, Some(9)); + assert!(!actor.core.entity_is_fenced("entity-1")); + } + #[tokio::test] async fn entity_input_on_a_read_only_replica_never_reaches_the_program() { let (mut actor, token, _, _, applied) = transfer_actor(b"entity".to_vec(), false);