From c8ab72c76fae2898fe0ad23a8ef4840206b01ce3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 13:04:07 -0600 Subject: [PATCH 1/2] feat(id): add region-seam source export --- pkgs/id/src/world/actor.rs | 226 ++++++++++++++++++++++++++++++++++- pkgs/id/src/world/core.rs | 135 ++++++++++++++++++++- pkgs/id/src/world/handle.rs | 50 ++++++++ pkgs/id/src/world/mod.rs | 87 ++++++++++++++ pkgs/id/src/world/tests.rs | 227 +++++++++++++++++++++++++++++++++++- 5 files changed, 721 insertions(+), 4 deletions(-) diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index ac9b3f9c5c..01b5f7120a 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -3,7 +3,7 @@ use super::*; use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; -use anyhow::{Result, ensure}; +use anyhow::{Result, bail, ensure}; use tokio::sync::{broadcast, mpsc, oneshot, watch}; use tracing::Instrument; @@ -52,6 +52,8 @@ impl WorldCommand { Self::BindAuthorKey { .. } => "BindAuthorKey", Self::Chat { .. } => "Chat", Self::Input { .. } => "Input", + Self::EntityInput { .. } => "EntityInput", + Self::ExportEntity { .. } => "ExportEntity", Self::Snapshot { .. } => "Snapshot", Self::HostView { .. } => "HostView", Self::EventsAfter { .. } => "EventsAfter", @@ -159,6 +161,20 @@ pub(crate) enum WorldCommand { author_key: [u8; 32], reply: oneshot::Sender>, }, + EntityInput { + token: JoinCapability, + entity_ref: String, + input: Vec, + reply: oneshot::Sender>, + }, + ExportEntity { + handoff_id: String, + entity_ref: String, + source_region: String, + target_region: String, + prior_owner_epoch: u64, + reply: oneshot::Sender>, + }, Snapshot { token: JoinCapability, reply: oneshot::Sender>, @@ -640,6 +656,156 @@ impl WorldActor { Ok(()) } + fn export_entity( + &mut self, + handoff_id: String, + entity_ref: String, + source_region: String, + target_region: String, + prior_owner_epoch: u64, + ) -> Result { + self.check_storage()?; + ensure!(self.program_healthy, "world program is unavailable"); + ensure!( + self.journal.is_some(), + "entity export requires a durable world journal" + ); + ensure!( + self.core.limits.region_sharded, + "entity export 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" + ); + let program_module_hash = self + .core + .active_module_hash + .clone() + .context("world has no installed program for entity export")?; + let request = EntityTransferRequest::Export { + 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(), + }; + let EntityTransferPlan::Export { + payload_schema, + payload, + app_event, + } = self.program.prepare_entity_transfer(&request)? + else { + bail!("world program returned an import plan for an export request"); + }; + 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" + ); + let payload_digest = hex_encode(blake3::hash(&payload).as_bytes()); + let event_text = serde_json::json!({ + "protocol": "world.entity-transfer.v1", + "direction": "export", + "handoff_id": handoff_id, + "entity_ref": entity_ref, + "source_region": source_region, + "target_region": target_region, + "prior_owner_epoch": prior_owner_epoch, + "module_hash": program_module_hash, + "payload_schema": payload_schema, + "payload_digest": payload_digest, + "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 source_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::Export, + prior_owner_epoch, + new_owner_epoch: None, + program_module_hash: program_module_hash.clone(), + payload_schema: payload_schema.clone(), + payload_digest: payload_digest.clone(), + payload: Some(payload.clone()), + event: source_event.clone(), + }; + self.core.validate_entity_export(&transfer)?; + + // The durable entry is the source-side fence. Install it before + // applying the prepared event so no subsequent command can mutate + // this entity, even when the program rejects the post-append update. + self.persist(JournalEntry::EntityExported { + handoff_id, + entity_ref, + source_region, + target_region, + prior_owner_epoch, + source_event: source_event.clone(), + payload_schema, + program_module_hash, + payload, + payload_digest, + })?; + self.core.record_entity_export(transfer.clone()); + if let Err(error) = self.program.update(&source_event) { + self.program_healthy = false; + tracing::error!("world program rejected a durable entity export: {error:#}"); + return Err( + error.context("world program rejected a durable entity export; 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 export: {error:#}"); + return Err(error.context( + "world program failed after a durable entity export; 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) { @@ -1647,6 +1813,64 @@ impl WorldActor { } let _ = reply.send(result); } + WorldCommand::EntityInput { + token, + entity_ref, + input, + reply, + } => { + let result = match self.core.prepare_entity_input(&token, &entity_ref, &input) { + Ok(_) if self.storage_failed => Err(anyhow::anyhow!( + "world storage failed; the world is read-only" + )), + Ok(candidate) if self.program_healthy => { + self.acting = Some(candidate.participant_id); + match self + .program + .update(&candidate) + .and_then(|()| program_records(self.program.as_mut())) + { + Ok(records) => self + .persist(JournalEntry::Committed { + event: candidate.clone(), + }) + .and_then(|()| self.core.commit_prepared(candidate)) + .inspect(|event| { + self.republished(records.unwrap_or_default(), event.sequence); + }), + Err(error) => { + self.program_healthy = false; + Err(error.context("world program rejected entity input")) + } + } + } + Ok(_) => Err(anyhow::anyhow!( + "world program is unavailable after a previous failure" + )), + Err(error) => Err(error), + }; + if let Ok(event) = &result { + let _ = self.event_sender.send(event.clone()); + } + let _ = reply.send(result); + } + WorldCommand::ExportEntity { + handoff_id, + entity_ref, + source_region, + target_region, + prior_owner_epoch, + reply, + } => { + let result = self.export_entity( + handoff_id, + entity_ref, + source_region, + target_region, + prior_owner_epoch, + ); + 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 035949d1f7..593208e8c1 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -134,6 +134,22 @@ pub(super) fn check_journal_version(version: u32, max_supported: u32) -> Result< Ok(()) } +pub(super) fn validate_entity_ref(entity_ref: &str) -> Result<()> { + ensure!( + !entity_ref.trim().is_empty(), + "entity reference must not be empty" + ); + ensure!( + entity_ref.len() <= 256, + "entity reference exceeds 256 bytes" + ); + ensure!( + !entity_ref.chars().any(char::is_control), + "entity reference contains a control character" + ); + Ok(()) +} + /// Mutable world state. Keep it behind one actor/mutex so event sequencing is serialized. #[derive(Debug)] pub struct WorldCore { @@ -771,6 +787,31 @@ impl WorldCore { payload, payload_digest, } => { + ensure!( + source_event.sequence == 0 && source_event.participant_id == 0, + "journal export event claims a sequence" + ); + ensure!( + matches!(&source_event.kind, WorldEventKind::System { .. }), + "journal export event is not a host system event" + ); + validate_entity_ref(&entity_ref)?; + ensure!( + payload.len() <= MAX_ENTITY_TRANSFER_PAYLOAD_BYTES, + "journal export payload exceeds {MAX_ENTITY_TRANSFER_PAYLOAD_BYTES} bytes" + ); + ensure!( + payload_digest == hex_encode(blake3::hash(&payload).as_bytes()), + "journal export payload digest does not match" + ); + 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" + ); let transfer = HandoffTransferState { handoff_id, entity_ref, @@ -962,8 +1003,13 @@ impl WorldCore { }); replay.clear(); } - WorldEventKind::Input(_) | WorldEventKind::EntityInput { .. } => { - replay.push(event.clone()) + WorldEventKind::Input(_) => replay.push(event.clone()), + WorldEventKind::EntityInput { entity_ref, .. } => { + ensure!( + !core.entity_is_fenced(entity_ref), + "journal accepts input for fenced entity {entity_ref:?}" + ); + replay.push(event.clone()); } WorldEventKind::System { .. } => anyhow::bail!( "host system events must use the unsequenced system journal entry" @@ -2121,6 +2167,10 @@ impl WorldCore { !self.author_keys.contains_key(&participant_id), "participant {participant_id} has a bound author key; inputs must be player-signed (#2814)" ); + ensure!( + !self.limits.region_sharded, + "region-sharded worlds require entity-addressed input" + ); self.ensure_uses_left(participant_id)?; ensure!( input.len() <= self.limits.input_bytes, @@ -2139,6 +2189,87 @@ impl WorldCore { }) } + pub(crate) fn prepare_entity_input( + &self, + token: &JoinCapability, + entity_ref: &str, + input: &[u8], + ) -> Result { + validate_entity_ref(entity_ref)?; + let participant_id = self.authorize(token, WorldScopes::INPUT)?; + self.ensure_uses_left(participant_id)?; + ensure!( + input.len() <= self.limits.input_bytes, + "world input exceeds {} bytes", + self.limits.input_bytes + ); + ensure!(!input.is_empty(), "world input must not be empty"); + ensure!( + !self.entity_is_fenced(entity_ref), + "entity {entity_ref:?} is fenced after export" + ); + let sequence = self + .sequence + .checked_add(1) + .context("world event sequence exhausted")?; + Ok(WorldEvent { + sequence, + participant_id, + kind: WorldEventKind::EntityInput { + entity_ref: entity_ref.to_owned(), + input: input.to_vec(), + }, + }) + } + + 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 + }) + } + + /// Install a durable source export in the in-memory transfer ledger. The + /// caller must append the matching journal entry first. + pub(crate) fn validate_entity_export(&self, transfer: &HandoffTransferState) -> Result<()> { + ensure!( + self.limits.region_sharded, + "entity export requires a region-sharded world" + ); + ensure!( + transfer.direction == HandoffDirection::Export, + "source export has the wrong transfer direction" + ); + validate_entity_ref(&transfer.entity_ref)?; + ensure!( + transfer + .payload + .as_ref() + .is_some_and(|payload| payload.len() <= MAX_ENTITY_TRANSFER_PAYLOAD_BYTES), + "entity transfer payload exceeds {MAX_ENTITY_TRANSFER_PAYLOAD_BYTES} bytes" + ); + let payload = transfer.payload.as_deref().unwrap_or_default(); + ensure!( + transfer.payload_digest == hex_encode(blake3::hash(payload).as_bytes()), + "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) + }), + "entity already has an active export or handoff ID is duplicated" + ); + Ok(()) + } + + /// Install a source fence after its matching journal record is durable. + pub(crate) fn record_entity_export(&mut self, transfer: HandoffTransferState) { + debug_assert!(self.validate_entity_export(&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 2e8a82cecc..cf48bf4038 100644 --- a/pkgs/id/src/world/handle.rs +++ b/pkgs/id/src/world/handle.rs @@ -913,6 +913,56 @@ impl WorldHandle { .context("world actor dropped input response")? } + /// Submit bounded input addressed to one application-owned entity. + pub async fn entity_input( + &self, + token: JoinCapability, + entity_ref: impl Into, + input: Vec, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::EntityInput { + token, + entity_ref: entity_ref.into(), + input, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped entity input response")? + } + + /// Export an entity from this source shard. The actor journals the + /// complete bounded payload and source event before applying the event and + /// returns the durable source receipt only after application succeeds. + pub async fn export_entity( + &self, + handoff_id: impl Into, + entity_ref: impl Into, + source_region: impl Into, + target_region: impl Into, + prior_owner_epoch: u64, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::ExportEntity { + handoff_id: handoff_id.into(), + entity_ref: entity_ref.into(), + source_region: source_region.into(), + target_region: target_region.into(), + prior_owner_epoch, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped entity export 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 ef790646b3..00a88cb96c 100644 --- a/pkgs/id/src/world/mod.rs +++ b/pkgs/id/src/world/mod.rs @@ -120,6 +120,9 @@ pub struct WorldLimits { pub chat_bytes: usize, /// Maximum opaque game input size in bytes. pub input_bytes: usize, + /// Require entity-addressed application inputs instead of legacy opaque + /// inputs. Enable for region-sharded worlds; defaults off for compatibility. + pub region_sharded: bool, /// Number of recent events kept for reconnect catch-up. pub retained_events: usize, /// Maximum presentation text returned by a world program, in bytes. @@ -147,6 +150,7 @@ impl Default for WorldLimits { participants: 256, chat_bytes: 2048, input_bytes: 16 * 1024, + region_sharded: false, retained_events: 1024, presentation_bytes: 8192, snapshot_bytes: 512 * 1024, @@ -580,6 +584,74 @@ pub enum HandoffDirection { Import, } +/// Maximum complete entity snapshot accepted by a v1 region-seam export. +pub const MAX_ENTITY_TRANSFER_PAYLOAD_BYTES: usize = 16 * 1024; + +/// Request passed to a world program to prepare one side of an entity transfer. +/// The hook must be pure: it validates and describes the event but must not +/// mutate program state. The actor persists the resulting event before applying +/// it, so replay observes the same state transition. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EntityTransferRequest { + /// Prepare the source-side removal and complete entity snapshot. + Export { + /// Coordinator-generated 128-bit handoff ID, encoded as hex. + handoff_id: String, + /// Application-defined stable identifier for the entity. + entity_ref: String, + /// Region currently owning the entity. + source_region: String, + /// Region that will receive the entity. + target_region: String, + /// Current owner epoch at the source. + prior_owner_epoch: u64, + /// Hash of the program module preparing the transfer. + program_module_hash: String, + }, + /// Validate a destination-side envelope and prepare its import event. + Import { + /// Coordinator-generated 128-bit handoff ID, encoded as hex. + handoff_id: String, + /// Application-defined stable identifier for the entity. + entity_ref: String, + /// Region that exported the entity. + source_region: String, + /// Region currently importing the entity. + target_region: String, + /// Owner epoch at the source before this transfer. + prior_owner_epoch: u64, + /// Hash of the program module expected by the envelope. + program_module_hash: String, + /// Versioned identifier for the entity payload format. + payload_schema: String, + /// Complete source snapshot to validate and import. + payload: Vec, + /// BLAKE3 digest of `payload`, encoded as lowercase hex. + payload_digest: String, + }, +} + +/// Pure, validated application work returned by +/// [`WorldProgram::prepare_entity_transfer`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EntityTransferPlan { + /// The source's complete snapshot and deterministic removal event. + Export { + /// Versioned identifier for the entity payload format. + payload_schema: String, + /// Complete source snapshot; limited to + /// [`MAX_ENTITY_TRANSFER_PAYLOAD_BYTES`]. + payload: Vec, + /// Deterministic program event that removes the entity at the source. + app_event: String, + }, + /// The deterministic destination insertion event. + Import { + /// Deterministic program event that adds the entity at the destination. + app_event: String, + }, +} + /// One active region-seam handoff as a world journal records it (#3870 /// phase 1, design #2818 §3). Carried in [`JournalEntry::Checkpoint`] so /// compaction preserves active export fences/payloads, import receipts and @@ -2031,6 +2103,21 @@ pub trait WorldProgram: Send + 'static { Ok(()) } + /// Purely validate and prepare one side of an application-owned entity + /// transfer. Implementations return the complete entity snapshot and a + /// deterministic removal event for [`EntityTransferRequest::Export`], or + /// validate the supplied envelope and return a deterministic insertion + /// event for [`EntityTransferRequest::Import`]. This hook must not mutate + /// program state; the actor journals the returned event before calling + /// [`Self::update`]. Programs without a transfer adapter remain supported + /// and reject transfer requests by default. + fn prepare_entity_transfer( + &self, + _request: &EntityTransferRequest, + ) -> Result { + bail!("world program does not support entity transfer") + } + /// Return this participant's presentation, or `None` for a chat-only /// world. The presentation must be UTF-8 and fit `presentation_bytes`. fn view(&mut self, _viewer: &Participant) -> Result> { diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index d0276ad613..e6101798fa 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -42,6 +42,231 @@ mod tests { .unwrap() } + #[derive(Clone, Default)] + struct TransferJournal(Arc>>); + + impl TransferJournal { + fn for_world(world_id: &str) -> Self { + Self(Arc::new(std::sync::Mutex::new(vec![ + JournalEntry::Created { + world_id: world_id.to_owned(), + version: JOURNAL_VERSION_REGION_HANDOFF, + }, + ]))) + } + + fn entries(&self) -> Vec { + self.0.lock().unwrap().clone() + } + } + + impl WorldJournal for TransferJournal { + fn append(&mut self, entry: &JournalEntry) -> Result<()> { + self.0.lock().unwrap().push(entry.clone()); + Ok(()) + } + } + + struct TransferProgram { + payload: Vec, + fail_apply: bool, + journal: TransferJournal, + saw_durable_export_before_apply: Arc>, + applied_events: Arc>>, + } + + impl WorldProgram for TransferProgram { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + if let WorldEventKind::System { event } = &event.kind { + let envelope: serde_json::Value = serde_json::from_str(event)?; + self.applied_events.lock().unwrap().push( + envelope["app_event"] + .as_str() + .unwrap_or_default() + .to_owned(), + ); + let durable = self + .journal + .entries() + .iter() + .any(|entry| matches!(entry, JournalEntry::EntityExported { .. })); + *self.saw_durable_export_before_apply.lock().unwrap() = durable; + ensure!(durable, "export event applied before it was journaled"); + if self.fail_apply { + bail!("injected export-apply failure"); + } + } + Ok(()) + } + + fn prepare_entity_transfer( + &self, + request: &EntityTransferRequest, + ) -> Result { + match request { + EntityTransferRequest::Export { .. } => Ok(EntityTransferPlan::Export { + payload_schema: "test/v1".to_owned(), + payload: self.payload.clone(), + app_event: "remove-entity".to_owned(), + }), + EntityTransferRequest::Import { .. } => Ok(EntityTransferPlan::Import { + app_event: "add-entity".to_owned(), + }), + } + } + } + + fn transfer_actor( + payload: Vec, + fail_apply: bool, + ) -> ( + WorldActor, + JoinCapability, + TransferJournal, + Arc>, + Arc>>, + ) { + let mut core = WorldCore::new( + "source", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + ) + .unwrap(); + core.active_module_hash = Some("module-hash".to_owned()); + let (_, token) = join(&mut core, "source-user"); + let journal = TransferJournal::for_world("source"); + let saw_durable_export_before_apply = Arc::new(std::sync::Mutex::new(false)); + let applied_events = Arc::new(std::sync::Mutex::new(Vec::new())); + let program = TransferProgram { + payload, + fail_apply, + journal: journal.clone(), + saw_durable_export_before_apply: saw_durable_export_before_apply.clone(), + applied_events: applied_events.clone(), + }; + let actor = WorldActor::for_test(core, Box::new(program), Some(Box::new(journal.clone()))); + ( + actor, + token, + journal, + saw_durable_export_before_apply, + applied_events, + ) + } + + async fn export(actor: &mut WorldActor) -> Result { + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::ExportEntity { + handoff_id: "ab".repeat(16), + entity_ref: "entity-1".to_owned(), + source_region: "region-a".to_owned(), + target_region: "region-b".to_owned(), + prior_owner_epoch: 7, + reply, + }) + .await; + response.await.unwrap() + } + + #[tokio::test] + async fn export_is_journaled_before_apply_replayed_and_fences_later_writes() { + let (mut actor, token, journal, saw_durable, applied) = + transfer_actor(b"entity".to_vec(), false); + let receipt = export(&mut actor).await.unwrap(); + assert_eq!(receipt.payload.as_deref(), Some(b"entity".as_slice())); + assert!(*saw_durable.lock().unwrap()); + assert!(actor.core.entity_is_fenced("entity-1")); + + let entries = journal.entries(); + assert!(matches!( + entries.last(), + Some(JournalEntry::EntityExported { .. }) + )); + let restored = WorldCore::restore( + "source", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + entries, + ) + .unwrap(); + assert_eq!(restored.core.handoff_transfers(), &[receipt.clone()]); + assert!(restored.core.entity_is_fenced("entity-1")); + assert_eq!(restored.replay, vec![receipt.event.clone()]); + let replayed = Arc::new(std::sync::Mutex::new(Vec::new())); + let mut replay_program = 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: replayed.clone(), + }; + replay_program.update(&restored.replay[0]).unwrap(); + assert_eq!(*replayed.lock().unwrap(), *applied.lock().unwrap()); + + let before = journal.entries().len(); + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::EntityInput { + token, + entity_ref: "entity-1".to_owned(), + input: b"mutate".to_vec(), + reply, + }) + .await; + assert!(response.await.unwrap().is_err()); + assert_eq!(journal.entries().len(), before); + } + + #[tokio::test] + async fn oversized_export_is_refused_before_a_durable_fence() { + let payload = vec![0; MAX_ENTITY_TRANSFER_PAYLOAD_BYTES + 1]; + let (mut actor, _, journal, _, _) = transfer_actor(payload, false); + assert!(export(&mut actor).await.is_err()); + assert!(actor.core.handoff_transfers().is_empty()); + assert!( + !journal + .entries() + .iter() + .any(|entry| matches!(entry, JournalEntry::EntityExported { .. })) + ); + } + + #[tokio::test] + async fn failed_post_append_apply_withholds_receipt_and_keeps_fence() { + let (mut actor, _, journal, saw_durable, _) = transfer_actor(b"entity".to_vec(), true); + assert!(export(&mut actor).await.is_err()); + assert!(*saw_durable.lock().unwrap()); + assert!(actor.core.entity_is_fenced("entity-1")); + assert!(!actor.program_healthy); + assert!(matches!( + journal.entries().last(), + Some(JournalEntry::EntityExported { .. }) + )); + } + + #[test] + fn region_sharded_world_rejects_unscoped_input() { + let mut core = WorldCore::new( + "sharded", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + ) + .unwrap(); + let (_, token) = join(&mut core, "user"); + assert!(core.prepare_input(&token, b"legacy").is_err()); + assert!( + core.prepare_entity_input(&token, "entity-1", b"scoped") + .is_ok() + ); + } + fn sample_source_provenance() -> ModuleProvenance { ModuleProvenance::SourceBuild(SourceBuildProvenance { schema_version: 1, @@ -284,7 +509,7 @@ mod tests { payload_schema: "entity/v1".to_owned(), program_module_hash: "module".to_owned(), payload: vec![1, 2, 3], - payload_digest: "digest".to_owned(), + payload_digest: hex_encode(blake3::hash(&[1, 2, 3]).as_bytes()), } } From de9299b16119aa055d0c649551a4bf6da4ac6d6a Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 21:29:24 -0600 Subject: [PATCH 2/2] fix(id/world): address Codex P1 findings on the transfer port (#3901) Four P1 findings on PR #8375, one fix each: (1) entity input now refuses participants with a bound author key, who must player-sign (#2814); (2) the region-sharded entity-addressed gate also applies to signed unscoped input; (3) the actor refuses entity input on a read-only replica before prepare touches the program; (4) an exact export retry returns the stored handoff receipt instead of preparing a duplicate the core would refuse. Each fix carries a regression test: world suite 147/147 pass, cargo check -p id clean. --- pkgs/id/src/world/actor.rs | 22 ++++++++++ pkgs/id/src/world/core.rs | 8 ++++ pkgs/id/src/world/tests.rs | 82 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 112 insertions(+) diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index 01b5f7120a..f98facdf57 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -699,6 +699,22 @@ impl WorldActor { .active_module_hash .clone() .context("world has no installed program for entity export")?; + // Exact-retry recovery: if this export already committed (its reply + // was lost, or the actor restarted and replayed it), return the + // stored receipt instead of preparing a duplicate the core would + // refuse. A stored export whose fields differ from the request is + // not a retry — it falls through and validate_entity_export + // rejects the conflicting handoff ID / entity. + if let Some(existing) = self.core.handoff_transfers.iter().find(|transfer| { + transfer.direction == HandoffDirection::Export && 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.program_module_hash == program_module_hash + { + return Ok(existing.clone()); + } let request = EntityTransferRequest::Export { handoff_id: handoff_id.clone(), entity_ref: entity_ref.clone(), @@ -1819,6 +1835,12 @@ impl WorldActor { input, reply, } => { + // Refuse before touching the program: a replica must not + // run entity inputs through its program instance. + if let Err(error) = self.check_writable() { + let _ = reply.send(Err(error)); + return; + } let result = match self.core.prepare_entity_input(&token, &entity_ref, &input) { Ok(_) if self.storage_failed => Err(anyhow::anyhow!( "world storage failed; the world is read-only" diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs index 593208e8c1..3a556985a3 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -2063,6 +2063,10 @@ impl WorldCore { signed_move: &[u8], ) -> Result<(WorldEvent, crate::chain::Event)> { let participant_id = self.authorize(token, WorldScopes::INPUT)?; + ensure!( + !self.limits.region_sharded, + "region-sharded worlds require entity-addressed input" + ); self.ensure_uses_left(participant_id)?; ensure!( input.len() <= self.limits.input_bytes, @@ -2197,6 +2201,10 @@ impl WorldCore { ) -> Result { validate_entity_ref(entity_ref)?; let participant_id = self.authorize(token, WorldScopes::INPUT)?; + ensure!( + !self.author_keys.contains_key(&participant_id), + "participant {participant_id} has a bound author key; inputs must be player-signed (#2814)" + ); self.ensure_uses_left(participant_id)?; ensure!( input.len() <= self.limits.input_bytes, diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index e6101798fa..de9b2c9439 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -249,6 +249,88 @@ mod tests { )); } + #[tokio::test] + async fn export_exact_retry_returns_the_stored_receipt() { + let (mut actor, _, journal, _, _) = transfer_actor(b"entity".to_vec(), false); + let receipt = export(&mut actor).await.unwrap(); + let entries_after_first = journal.entries().len(); + let retry = export(&mut actor).await.unwrap(); + assert_eq!(retry, receipt); + assert_eq!(journal.entries().len(), entries_after_first); + + // A conflicting reuse of the handoff ID is not a retry. + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::ExportEntity { + handoff_id: "ab".repeat(16), + entity_ref: "entity-1".to_owned(), + source_region: "region-a".to_owned(), + target_region: "region-c".to_owned(), + prior_owner_epoch: 7, + reply, + }) + .await; + assert!(response.await.unwrap().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); + actor.read_only = true; + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::EntityInput { + token, + entity_ref: "entity-1".to_owned(), + input: b"mutate".to_vec(), + reply, + }) + .await; + assert!(response.await.unwrap().is_err()); + assert!(applied.lock().unwrap().is_empty()); + } + + #[test] + fn bound_author_participant_cannot_use_unsigned_entity_input() { + use p2panda_core::{Hash, SigningKey}; + + let mut core = WorldCore::new( + "sharded-bound", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + ) + .unwrap(); + let (_, token) = join(&mut core, "bound-user"); + let key = SigningKey::from_bytes(Hash::digest(b"bound user").as_bytes()); + core.bind_author_key(&token, *key.verifying_key().as_bytes()) + .unwrap(); + assert!( + core.prepare_entity_input(&token, "entity-1", b"scoped") + .is_err() + ); + } + + #[test] + fn region_sharded_world_rejects_signed_unscoped_input() { + let mut core = WorldCore::new( + "sharded-signed", + WorldLimits { + region_sharded: true, + ..WorldLimits::default() + }, + ) + .unwrap(); + let (_, token) = join(&mut core, "user"); + let result = core.prepare_input_signed(&token, b"legacy", b"not-a-signed-move"); + let error = result.err().expect("signed unscoped input must be refused"); + assert!( + format!("{error:#}").contains("entity-addressed"), + "unexpected refusal: {error:#}" + ); + } + #[test] fn region_sharded_world_rejects_unscoped_input() { let mut core = WorldCore::new(