M9: open a full snapshot without copying it first (#2041)

Replica::from_snapshot borrowed the changes and cloned the whole
Vec<Change> before applying it, because the review-settings clamp
rewrites some of them in place. Every caller already owns the snapshot
(Client::join, the rejoin path, Server::restore), so it now takes the
Vec by value: a large file's snapshot is no longer copied and then
dropped twice on the way in. The server's publish path still borrows
and copies explicitly.

In a wasm32 build joining a 120k-layer file through the full-snapshot
catch-up (what an older server sends), this cut peak memory from 722 MiB
to 455 MiB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bryton CooperandClaude Opus 5.5 committed 2026-11-28 02:54:44 -07:00
1 parent 745fe1aae7
commit b33b75275c
11 files changed
+21 -20

No files matched your search

+1 -1
View File
@@ -90,7 +90,7 @@ impl Store {
if let Some(why) = self.low_disk() {
return Err(why);
}
let replica = Replica::from_snapshot(snapshot).map_err(|e| format!("the file couldn't be read: {e}"))?;
let replica = Replica::from_snapshot(snapshot.to_vec()).map_err(|e| format!("the file couldn't be read: {e}"))?;
if replica.document().node_count() > self.cfg.core.max_nodes {
return Err(format!("the file has more than {} layers", self.cfg.core.max_nodes));
}
+1 -1
View File
@@ -687,7 +687,7 @@ fn welcomes_are_packed_only_for_clients_that_read_them() {
};
message::unpack(&mut delta_welcome, 64 << 20).unwrap();
let delta_doc = Client::join(delta_welcome).unwrap().document().clone();
let plain_doc = figcraft_collab::Replica::from_snapshot(&plain).unwrap().document().clone();
let plain_doc = figcraft_collab::Replica::from_snapshot(plain).unwrap().document().clone();
assert_eq!(delta_doc, plain_doc, "delta snapshot opens the exact same document");
host.stop();
}
+1 -1
View File
@@ -18,7 +18,7 @@ fn a_boards_kind_and_its_objects_metadata_sync() {
// A joiner's copy, built from the snapshot, is a board with the sticky's metadata.
let snap = host.snapshot().unwrap();
assert!(snap.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Kind, .. })));
let joiner = Replica::from_snapshot(&snap).unwrap();
let joiner = Replica::from_snapshot(snap).unwrap();
assert_eq!(joiner.document().kind, FileKind::Board);
assert_eq!(joiner.document().node(a).unwrap().board, host.document().node(a).unwrap().board);
// Re-attaching a connector's end is one property write, the same after the wire.
+2 -2
View File
@@ -90,7 +90,7 @@ impl Client {
return Err(Error::Protocol("expected a welcome with the document".into()));
};
let mut confirmed = match catch_up {
CatchUp::Snapshot(snapshot) => Replica::from_snapshot(&snapshot)?,
CatchUp::Snapshot(snapshot) => Replica::from_snapshot(snapshot)?,
CatchUp::DeltaSnapshot(bytes) => {
let limits = crate::Limits::default();
crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)?
@@ -604,7 +604,7 @@ impl Client {
}
}
CatchUp::Snapshot(snapshot) => {
let mut confirmed = Replica::from_snapshot(&snapshot)?;
let mut confirmed = Replica::from_snapshot(snapshot)?;
confirmed.document_mut().set_client_id(self.id);
self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?;
}
+2 -2
View File
@@ -163,7 +163,7 @@ fn mirror_delta_preserves_paint_color_alpha_and_signed_zero() {
let replica = Replica::new(doc);
let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 16 << 20, Limits::default().max_nodes).unwrap();
let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
let legacy = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap();
assert_docs_json_eq(replica.document(), decoded.document(), "exact structural equality");
assert_docs_json_eq(legacy.document(), decoded.document(), "legacy parity");
}
@@ -311,7 +311,7 @@ fn full_metadata_and_design_review_roundtrip_matches_legacy_json() {
doc.take_dirty();
let replica = Replica::new(doc);
let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
let legacy = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap();
let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap();
assert_eq!(decoded.document().design_review.radii.len(), figcraft_doc::MAX_RADII);
assert_docs_json_eq(legacy.document(), decoded.document(), "full metadata parity");
+4 -4
View File
@@ -77,7 +77,7 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() {
// A snapshot holding settings over the limits (an old file's) opens clamped to what fits:
// the preset, grid and disabled rules exactly as saved, the lists to the limit.
let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes;
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap();
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(snap).unwrap();
assert!(clamped, "the settings needed clamping, and the caller is told");
assert_eq!(left_out, 0, "nothing needed leaving out");
let cfg = &r2.document().design_review;
@@ -99,7 +99,7 @@ fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them
assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}");
// A snapshot with a longer list opens with the ones that fit, not without the settings.
let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes;
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap();
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(snap).unwrap();
assert!(clamped);
assert_eq!(left_out, 0, "nothing needed leaving out");
let cfg = &r2.document().design_review;
@@ -232,9 +232,9 @@ fn snapshots_rebuild_the_same_state() {
b.styles.push(style("s"));
let r = diff(&a, &b).unwrap().replica;
let snap = r.snapshot().unwrap();
let back = Replica::from_snapshot(&snap).unwrap();
let back = Replica::from_snapshot(snap).unwrap();
assert_eq!(back, r);
assert!(Replica::from_snapshot(&[]).is_err(), "a snapshot needs a page");
assert!(Replica::from_snapshot(Vec::new()).is_err(), "a snapshot needs a page");
}
#[test]
+2 -2
View File
@@ -169,7 +169,7 @@ fn a_snapshot_holding_an_image_the_checks_refuse_still_opens_without_it() {
let mut snapshot = crate::Replica::new(crate::sim_tests::base()).snapshot().unwrap();
let (key, bytes) = forged();
snapshot.push(put(&key, 2, 1, bytes));
let r = crate::Replica::from_snapshot(&snapshot).expect("the snapshot opens");
let r = crate::Replica::from_snapshot(snapshot).expect("the snapshot opens");
assert!(!r.document().images.contains_key(&key));
}
@@ -254,5 +254,5 @@ fn a_snapshot_with_a_broken_layer_change_still_fails_to_open() {
// A property of a layer that isn't there: an error when applied (unlike deleting it).
let missing = figcraft_doc::NodeId(u64::MAX);
snapshot.push(Change::Set { id: missing, prop: crate::change::Prop::Name, value: Json(json!("x")) });
assert!(crate::Replica::from_snapshot(&snapshot).is_err());
assert!(crate::Replica::from_snapshot(snapshot).is_err());
}
+1 -1
View File
@@ -57,7 +57,7 @@ fn a_packed_welcome_is_much_smaller_and_reads_back_the_same() {
assert_eq!(back, plain);
// The client opens the same document from it.
let ServerMsg::Welcome { catch_up: CatchUp::Snapshot(changes), .. } = &plain else { panic!("not a snapshot") };
assert_eq!(Client::join(back).unwrap().document(), Replica::from_snapshot(changes).unwrap().document());
assert_eq!(Client::join(back).unwrap().document(), Replica::from_snapshot(changes.clone()).unwrap().document());
}
#[test]
+5 -4
View File
@@ -70,8 +70,10 @@ impl Replica {
Replica { doc, positions }
}
/// Rebuild a replica from a [`snapshot`](Self::snapshot).
pub fn from_snapshot(changes: &[Change]) -> Result<Replica, Error> {
/// Rebuild a replica from a [`snapshot`](Self::snapshot). It takes the changes, so a large
/// file's snapshot isn't copied on the way in (#2041): the few that need it (review settings
/// past the limits) are rewritten in place.
pub fn from_snapshot(changes: Vec<Change>) -> Result<Replica, Error> {
Self::from_snapshot_leaving_out(changes).map(|(r, _, _)| r)
}
@@ -81,9 +83,8 @@ impl Replica {
/// [`docprops::clamp_snapshot_design_review`]); the last value says whether that happened,
/// because a session whose settings had to be clamped can no longer replay its saved batches
/// for clients that resume (they hold the value past the limits).
pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize, bool), Error> {
pub(crate) fn from_snapshot_leaving_out(mut changes: Vec<Change>) -> Result<(Replica, usize, bool), Error> {
let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() };
let mut changes = changes.to_vec();
let clamped = docprops::clamp_snapshot_design_review(&mut changes);
let left_out = r.apply_kept(&mut changes, Change::is_image)?;
if r.doc.pages.is_empty() {
+1 -1
View File
@@ -214,7 +214,7 @@ impl Server {
/// reconnect with their ids). A log that doesn't lead up to the sequence number is dropped
/// (clients then catch up with a snapshot).
pub fn restore(state: SessionState, token: impl Into<String>, limits: Limits) -> Result<Server, Error> {
let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(&state.snapshot)?;
let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(state.snapshot)?;
let mut server = Server::new(replica.document().clone(), token, limits);
server.state = replica;
server.session = state.session;
+1 -1
View File
@@ -114,7 +114,7 @@ fn every_command_edit_round_trips_through_its_changes() {
replica = d.replica;
}
assert!(edits > 50, "seed {seed}: only {edits} edits");
let back = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
let back = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap();
assert_eq!(back, replica, "seed {seed}: snapshot");
}
}