diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index 3df09924c9..26fb102327 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -251,7 +251,7 @@ pub(crate) enum WorldCommand { reply: oneshot::Sender< Result<( String, - JournalSnapshot, + JournalSnapshotSource, broadcast::Receiver, )>, >, @@ -1622,8 +1622,8 @@ impl WorldActor { self.journal .as_mut() .ok_or_else(|| anyhow::anyhow!("world has no durable journal")) - .and_then(|journal| journal.replication_snapshot()) - .map(|snapshot| (world_id, snapshot, updates)) + .and_then(|journal| journal.replication_snapshot_source()) + .map(|snapshot_source| (world_id, snapshot_source, updates)) }; let _ = reply.send(result); } diff --git a/pkgs/id/src/world/handle.rs b/pkgs/id/src/world/handle.rs index b80c515086..89299f7e51 100644 --- a/pkgs/id/src/world/handle.rs +++ b/pkgs/id/src/world/handle.rs @@ -146,7 +146,7 @@ impl WorldHandle { &self, ) -> Result<( String, - JournalSnapshot, + JournalSnapshotSource, broadcast::Receiver, )> { let (reply, response) = oneshot::channel(); diff --git a/pkgs/id/src/world/mod.rs b/pkgs/id/src/world/mod.rs index a52971fb32..b2e0fdd8e5 100644 --- a/pkgs/id/src/world/mod.rs +++ b/pkgs/id/src/world/mod.rs @@ -17,6 +17,7 @@ //! counts are local to the hosting node and need not converge across partitions. use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::io::Read; use anyhow::{Context, Result, bail, ensure}; use rand::RngExt as _; @@ -1074,6 +1075,15 @@ pub trait WorldJournal: Send + 'static { bail!("this journal cannot provide a replication snapshot") } + /// Capture a lightweight, readable source for the initial replication + /// feed. Durable file journals should pin the file and its current length + /// here, then defer reading the bytes until the network layer requests it. + /// Journals that cannot provide a deferred source should leave this + /// unsupported rather than materializing the full image in the actor. + fn replication_snapshot_source(&mut self) -> Result { + bail!("this journal cannot provide a deferred replication snapshot source") + } + /// Current journal header version, when the implementation can report it. fn replication_header_version(&self) -> Option { None @@ -1101,6 +1111,68 @@ pub struct JournalSnapshot { pub bytes: Vec, } +/// A captured snapshot reader. File-backed journals keep only a pinned file +/// handle and the captured byte length in the actor; the network layer reads +/// the bytes after the actor has resumed handling commands. +pub struct JournalSnapshotSource { + /// Version in the journal's `Created` header. + pub header_version: u32, + /// Number of bytes belonging to this captured image. + pub byte_len: u64, + reader: Box, +} + +impl std::fmt::Debug for JournalSnapshotSource { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("JournalSnapshotSource") + .field("header_version", &self.header_version) + .field("byte_len", &self.byte_len) + .finish_non_exhaustive() + } +} + +impl JournalSnapshotSource { + pub(crate) fn from_reader(header_version: u32, byte_len: u64, reader: R) -> Self + where + R: Read + Send + 'static, + { + Self { + header_version, + byte_len, + reader: Box::new(reader), + } + } + + /// Read exactly the captured image. This consumes the source, so its file + /// handle and the resulting byte buffer have one clear owner at a time. + /// + /// # Errors + /// + /// If the source cannot be read completely, is too large for this target, + /// or does not end at a journal-entry boundary. + pub fn read(self) -> Result { + let capacity = usize::try_from(self.byte_len).context("journal snapshot is too large")?; + let mut bytes = Vec::with_capacity(capacity); + self.reader + .take(self.byte_len) + .read_to_end(&mut bytes) + .context("read captured journal snapshot")?; + ensure!( + bytes.len() == capacity, + "captured journal snapshot changed while reading" + ); + ensure!( + bytes.is_empty() || bytes.ends_with(b"\n"), + "captured journal snapshot has an unterminated final entry" + ); + Ok(JournalSnapshot { + header_version: self.header_version, + bytes, + }) + } +} + /// A durable change delivered to replication subscribers. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ReplicationUpdate { diff --git a/pkgs/id/src/world_replication_net.rs b/pkgs/id/src/world_replication_net.rs index e33de5b647..12868a1ea5 100644 --- a/pkgs/id/src/world_replication_net.rs +++ b/pkgs/id/src/world_replication_net.rs @@ -117,18 +117,28 @@ async fn serve_stream( .lease(request.world.as_deref(), None) .await .map_err(|error| anyhow::anyhow!("open replication world: {}", error.message()))?; - let (world_id, snapshot, mut updates) = lease.service().world().replication_feed().await?; + let (world_id, snapshot_source, mut updates) = + lease.service().world().replication_feed().await?; let source = *signing_key.verifying_key().as_bytes(); - let (mut cursor, mut header_version, mut prev_frame_digest) = send_snapshot( - &mut send, - signing_key, - &world_id, - source, - request.session_nonce, - &snapshot, - [0; 32], - ) - .await?; + // Only the pinned file handle and captured length crossed the actor + // boundary. Read the initial image on the blocking pool, then confine its + // owned bytes to this transfer so they are dropped before following + // updates for the lifetime of the stream. + let (mut cursor, mut header_version, mut prev_frame_digest) = { + let snapshot = tokio::task::spawn_blocking(move || snapshot_source.read()) + .await + .context("initial replication snapshot read task")??; + send_snapshot( + &mut send, + signing_key, + &world_id, + source, + request.session_nonce, + snapshot, + [0; 32], + ) + .await? + }; loop { match updates.recv().await { @@ -161,7 +171,7 @@ async fn serve_stream( &world_id, source, request.session_nonce, - &reset, + reset, prev_frame_digest, ) .await?; @@ -191,13 +201,15 @@ fn ensure_nonce(nonce: &[u8; 16]) -> Result<()> { Ok(()) } +// Take ownership of each snapshot so its journal buffer cannot escape into +// the long-lived update loop after the transfer has been sent. async fn send_snapshot( send: &mut SendStream, signing_key: &SigningKey, world_id: &str, source: [u8; 32], nonce: [u8; 16], - snapshot: &JournalSnapshot, + snapshot: JournalSnapshot, mut prev_frame_digest: [u8; 32], ) -> Result<(ReplicationCursor, u32, [u8; 32])> { let chunks = split_entry_payload(&snapshot.bytes).context("split journal snapshot")?; diff --git a/pkgs/id/src/world_store.rs b/pkgs/id/src/world_store.rs index 555a64d8ca..c5359e90f7 100644 --- a/pkgs/id/src/world_store.rs +++ b/pkgs/id/src/world_store.rs @@ -217,6 +217,23 @@ impl WorldJournal for FileJournal { }) } + fn replication_snapshot_source(&mut self) -> Result { + // Open a separate descriptor while the actor still owns the journal. + // It pins the current inode across compaction, and the captured length + // excludes appends that happen after the actor returns to its loop. + let file = File::open(&self.path) + .with_context(|| format!("open world journal snapshot {}", self.path.display()))?; + let byte_len = file + .metadata() + .with_context(|| format!("stat world journal snapshot {}", self.path.display()))? + .len(); + Ok(crate::world::JournalSnapshotSource::from_reader( + self.version, + byte_len, + file, + )) + } + fn replication_header_version(&self) -> Option { Some(self.version) } @@ -689,19 +706,26 @@ mod tests { .await .unwrap(); let world = service.world(); - let (world_id, first, mut first_updates) = world.replication_feed().await.unwrap(); - let (second_world_id, second, mut second_updates) = world.replication_feed().await.unwrap(); + let (world_id, first_source, mut first_updates) = world.replication_feed().await.unwrap(); + let (second_world_id, second_source, mut second_updates) = + world.replication_feed().await.unwrap(); let durable_bytes = std::fs::read(dir.path().join("journal.jsonl")).unwrap(); assert_eq!(world_id, "lobby"); assert_eq!(second_world_id, world_id); - assert_eq!(first, second); - assert_eq!(first.bytes, durable_bytes); - assert!(first.bytes.ends_with(b"\n")); + assert_eq!(first_source.header_version, second_source.header_version); + assert_eq!(first_source.byte_len, durable_bytes.len() as u64); + // The actor is free to append before the network materializes either + // source. The captured length still bounds both snapshots to this cut. world .set_isolation(Authority::Admin, Isolation::Unisolated) .await .unwrap(); + let first = first_source.read().unwrap(); + let second = second_source.read().unwrap(); + assert_eq!(first, second); + assert_eq!(first.bytes, durable_bytes); + assert!(first.bytes.ends_with(b"\n")); for update in [ first_updates.recv().await.unwrap(), second_updates.recv().await.unwrap(), @@ -748,6 +772,29 @@ mod tests { assert_eq!(std::fs::read(&path).unwrap(), expected); } + #[test] + fn replication_snapshot_source_is_pinned_and_reads_only_its_captured_length() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("journal.jsonl"); + let (mut journal, entries) = FileJournal::open(&path, "lobby").unwrap(); + journal + .append(&JournalEntry::Isolation { + isolation: Isolation::Unisolated, + }) + .unwrap(); + let expected = std::fs::read(&path).unwrap(); + let source = journal.replication_snapshot_source().unwrap(); + assert_eq!(source.byte_len, expected.len() as u64); + + // Replacing the path after capture must not redirect the reader to a + // compacted image; the source owns the old inode and captured length. + journal.compact(&entries).unwrap(); + let snapshot = source.read().unwrap(); + assert_eq!(snapshot.bytes, expected); + assert!(snapshot.bytes.ends_with(b"\n")); + assert_ne!(std::fs::read(&path).unwrap(), snapshot.bytes); + } + #[tokio::test] async fn isolation_survives_a_restart() { let dir = TempDir::new().unwrap();