From 32ce0b841c7226837052d87c806005ae1aa66dee Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 20:24:43 +0100 Subject: [PATCH] fix(store): publish a push's trees after the trees they hold A push wrote its blobs and trees in one batch, renamed into place in parallel, so a crash or a failed rename could publish a tree without a subtree. Later pushes check only that a tree they need is stored, so they would build on the incomplete one. A durable write now stages files in layers, publishing each once the layers before it are durable, still with one batch sync, and a push writes blobs and attachments first, then each tree after the trees it holds. --- apps/origin-src/src/service.rs | 108 ++++++++++++++++-- apps/origin-src/src/store/mod.rs | 46 +++++++- crates/origin-platform/src/durability.rs | 133 +++++++++++++++++++---- 3 files changed, 252 insertions(+), 35 deletions(-) diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index e450950c..4595a678 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -611,7 +611,9 @@ impl OriginService { /// may only change what they write, as /// [`permissions`](crate::permissions) explains. Records are read from /// the pack before the repository, so a pack may hold a stack. The blobs and trees - /// are durable before the records that refer to them, statements before + /// are durable before the records that refer to them, each tree once + /// the trees it holds are, so the repository never has a tree without + /// what it holds, which a later pack may rely on, statements before /// the revisions they're about, and promotions come last, each checked /// against its original by [`Store::claim`], /// once the original and both subjects are stored. Issues @@ -666,7 +668,7 @@ impl OriginService { // The dependencies the repository has, whose kinds are read once // every object is checked otherwise. let mut stored: HashMap = HashMap::new(); - let mut snapshots = Vec::new(); + let mut snapshots = SnapshotLayers::default(); let mut statements = Vec::new(); let mut revisions = Vec::new(); let mut promotions = Vec::new(); @@ -709,7 +711,9 @@ impl OriginService { })?; match record { Object::Acceptance(_) => return Err(ServiceError::Acceptance(id.into())), - Object::Blob(_) | Object::Tree(_) | Object::Attachment(_) => snapshots.push(object), + Object::Blob(_) | Object::Tree(_) | Object::Attachment(_) => { + snapshots.add(object, &record); + } Object::Revision(ref revision) => { if !revision.predecessors.is_empty() { changes.insert(revision.change); @@ -731,10 +735,7 @@ impl OriginService { } self.check_kinds(&stored)?; dependencies.commit()?; - let mut new = 0; - if !snapshots.is_empty() { - new += self.store.write_all(&snapshots)?; - } + let mut new = self.store.write_layers(&snapshots.layers())?; self.check_writes(caller, &held, &decoded)?; let pushing = self.lock_heads(caller, !revisions.is_empty(), expect)?; // In layers, each durable before the next, as a workspace writes @@ -1303,6 +1304,67 @@ impl OriginService { } } +/// The blobs, trees and attachments of a pack, which +/// [`OriginService::push`] writes in layers: blobs and attachments first, +/// then each tree after the trees of the pack it holds. So neither a crash +/// nor a failed write leaves the repository a tree without what it holds, +/// which a later pack needing the tree would rely on. +#[derive(Debug, Default)] +struct SnapshotLayers { + objects: Vec, + /// The subtrees of each tree of `objects`. + subtrees: HashMap>, +} + +impl SnapshotLayers { + /// Adds `object`, which decodes as `record`. + fn add(&mut self, object: EncodedObject, record: &Object) { + if let Object::Tree(tree) = record { + let subtrees = tree + .iter() + .filter_map(|(_, entry)| entry.subtree()) + .map(ObjectId::from) + .collect(); + self.subtrees.insert(object.id(), subtrees); + } + self.objects.push(object); + } + + /// The objects by layer: a tree's is one past the highest of its + /// subtrees the pack holds, and a blob's or an attachment's, the first. + fn layers(self) -> Vec> { + let mut heights: HashMap = HashMap::new(); + // Depth first, without recursing: a pack may nest trees deeply. + let mut stack: Vec = self.subtrees.keys().copied().collect(); + while let Some(&id) = stack.last() { + if heights.contains_key(&id) { + stack.pop(); + continue; + } + let subtrees = &self.subtrees[&id]; + let before = stack.len(); + stack.extend(subtrees.iter().filter(|&subtree| { + self.subtrees.contains_key(subtree) && !heights.contains_key(subtree) + })); + if stack.len() == before { + let highest = subtrees + .iter() + .filter_map(|subtree| heights.get(subtree)) + .max(); + heights.insert(id, highest.map_or(1, |height| height + 1)); + stack.pop(); + } + } + let mut layers: Vec> = iter::repeat_with(Vec::new) + .take(heights.values().max().map_or(1, |height| height + 1)) + .collect(); + for object in self.objects { + layers[heights.get(&object.id()).copied().unwrap_or(0)].push(object); + } + layers + } +} + /// What an object needs the repository to have for it to be usable, as /// [`OriginService::put_records`] lists, and the kind each must be: the /// records it refers to, and the content, snapshots and blobs. A @@ -1563,8 +1625,8 @@ impl ServiceError { #[cfg(test)] mod tests { - use origin_shared::Record; use origin_shared::landing::Landing; + use origin_shared::{EntryKind, Record, Tree}; use super::*; use crate::permissions::Scope; @@ -1652,6 +1714,36 @@ mod tests { assert!(repo.store.contains(conflict.id()).unwrap()); } + #[test] + fn trees_are_written_after_the_trees_they_hold() { + let tree = |entries: &[(&str, EntryKind, ObjectId)]| { + let mut tree = Tree::default(); + for &(name, kind, id) in entries { + tree.insert(name.parse().unwrap(), TreeEntry { kind, id }); + } + tree.encode() + }; + let blob = EncodedObject::blob(b"file"); + let leaf = tree(&[("file", EntryKind::File, blob.id())]); + let middle = tree(&[("leaf", EntryKind::Tree, leaf.id())]); + let stored = Tree::default().encode(); + // The root holds the leaf too, and a tree the pack doesn't. + let root = tree(&[ + ("leaf", EntryKind::Tree, leaf.id()), + ("middle", EntryKind::Tree, middle.id()), + ("stored", EntryKind::Tree, stored.id()), + ]); + + let mut snapshots = SnapshotLayers::default(); + for object in [&root, &blob, &middle, &leaf] { + snapshots.add(object.clone(), &object.decode().unwrap()); + } + assert_eq!( + snapshots.layers(), + [vec![blob], vec![leaf], vec![middle], vec![root]] + ); + } + #[test] fn calls_using_the_index_do_not_wait_for_each_other() { let dir = tempfile::tempdir().unwrap(); diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 511f1d8e..b98246c7 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -264,8 +264,27 @@ impl Store

{ /// Fails if an object cannot be written. Objects written before the /// failure may not be durable. pub fn write_all(&self, objects: &[EncodedObject]) -> Result { + self.write_layers(&[objects]) + } + + /// Writes `layers` like [`Store::write_all`], in one batch that + /// publishes each layer once those before it are durable: so a crash or + /// a failed write never leaves an object without one of an earlier + /// layer. + /// + /// # Errors + /// + /// Fails like [`Store::write_all`]. Only objects of the layer that + /// failed, and the layers before it, may have been written. + pub fn write_layers( + &self, + layers: &[impl AsRef<[EncodedObject]>], + ) -> Result { let batch = self.batch(); - let written = batch.stage_all(objects)?; + let mut written = 0; + for (layer, objects) in layers.iter().enumerate() { + written += batch.stage_in(layer, objects.as_ref())?; + } batch.commit()?; Ok(written) } @@ -653,6 +672,16 @@ impl Batch<'_, P> { /// Fails if the object is a record that doesn't decode, or if it cannot /// be compressed or written. pub fn write(&self, object: &EncodedObject) -> Result { + self.write_in(0, object) + } + + /// Stages an object like [`Batch::write`], in `layer`: it is published + /// once the objects of the layers before it are durable. + /// + /// # Errors + /// + /// Fails like [`Batch::write`]. + pub fn write_in(&self, layer: usize, object: &EncodedObject) -> Result { let id = object.id(); let path = self.store.path(id); if self.hold(&path, || self.packed(id))? { @@ -661,7 +690,8 @@ impl Batch<'_, P> { let entry = Entry::of(object).map_err(|source| StoreError::Decode { id, source })?; let compressed = zstd::bulk::compress(object.bytes(), Store::

::COMPRESSION_LEVEL) .map_err(|source| StoreError::io(&path, source))?; - self.write.stage(path, &compressed)?; + self.write + .stage_in(layer, path, |file| file.write_all(&compressed))?; if let Some(entry) = entry { self.entries .lock() @@ -741,9 +771,19 @@ impl Batch<'_, P> { /// /// Fails like [`Batch::write`]. pub fn stage_all(&self, objects: &[EncodedObject]) -> Result { + self.stage_in(0, objects) + } + + /// Stages `objects` like [`Batch::stage_all`], in `layer`, as + /// [`Batch::write_in`] does. + /// + /// # Errors + /// + /// Fails like [`Batch::write`]. + pub fn stage_in(&self, layer: usize, objects: &[EncodedObject]) -> Result { Store::

::on_every_core(objects, |chunk| { chunk.iter().try_fold(0, |written, object| { - Ok(written + usize::from(self.write(object)?)) + Ok(written + usize::from(self.write_in(layer, object)?)) }) }) .into_iter() diff --git a/crates/origin-platform/src/durability.rs b/crates/origin-platform/src/durability.rs index befef1ad..6804691c 100644 --- a/crates/origin-platform/src/durability.rs +++ b/crates/origin-platform/src/durability.rs @@ -68,6 +68,13 @@ pub trait Durability { /// append-only log, to the batch sync, so it becomes durable no later than /// the batch is published, at no extra sync. /// +/// Files staged with [`DurableWrite::stage_in`] are published in layers: +/// `commit` renames each layer's files and syncs their directories before it +/// renames any of the next, so a crash or a failed rename never leaves a +/// file published without those of the layers before it, such as an object +/// without the objects it refers to. Each layer costs its directories' +/// syncs, but the batch is still synced once. +/// /// Files can be staged from several threads at once. #[derive(Debug)] pub struct DurableWrite<'a, P> { @@ -78,13 +85,21 @@ pub struct DurableWrite<'a, P> { /// The files staged so far. #[derive(Debug, Default)] struct Staged { + /// The files of each layer, in the order they're published. + layers: Vec, + /// Files written in place, synced with the batch but never renamed. + in_place: Vec, +} + +/// The files of one layer of a [`DurableWrite`]. +#[derive(Debug, Default)] +struct Layer { /// Each temporary file and the path it's published to. files: Vec<(PathBuf, PathBuf)>, - /// The directories whose entries must be durable: the published files' - /// parents, and those added with [`DurableWrite::sync_dir_with`]. + /// The directories whose entries must be durable before the next layer + /// is published: the published files' parents, and for the first + /// layer, those added with [`DurableWrite::sync_dir_with`]. dirs: BTreeSet, - /// Files written in place, synced with the batch but never renamed. - in_place: Vec, } /// Distinguishes the temporary files of one process. @@ -147,6 +162,21 @@ impl<'a, P: Durability> DurableWrite<'a, P> { &self, path: impl Into, write: impl FnOnce(&mut StagedFile) -> Result<(), E>, + ) -> Result<(), E> { + self.stage_in(0, path, write) + } + + /// Stages `path` like [`DurableWrite::stage_with`], in `layer`: it is + /// published once every file of the layers before it is durable. + /// + /// # Errors + /// + /// Fails like [`DurableWrite::stage_with`]. + pub fn stage_in>( + &self, + layer: usize, + path: impl Into, + write: impl FnOnce(&mut StagedFile) -> Result<(), E>, ) -> Result<(), E> { let path = path.into(); let relied_on = self.create_parents(&path)?; @@ -162,18 +192,19 @@ impl<'a, P: Durability> DurableWrite<'a, P> { return Err(error); } let mut staged = self.staged.lock().unwrap_or_else(PoisonError::into_inner); - staged.dirs.insert(Self::parent(&path).to_owned()); - staged.dirs.extend(relied_on); - staged.files.push((temp, path)); + let layer = staged.layer(layer); + layer.dirs.insert(Self::parent(&path).to_owned()); + layer.dirs.extend(relied_on); + layer.files.push((temp, path)); Ok(()) } - /// Makes the entries of `dir` durable with the batch, as for a file - /// staged in it: for a file another write published, which this one - /// relies on, and may not have synced yet. + /// Makes the entries of `dir` durable with the batch's first layer, as + /// for a file staged in it: for a file another write published, which + /// this one relies on, and may not have synced yet. pub fn sync_dir_with(&self, dir: impl Into) { let mut staged = self.staged.lock().unwrap_or_else(PoisonError::into_inner); - staged.dirs.insert(dir.into()); + staged.layer(0).dirs.insert(dir.into()); } /// Makes `path`, a file already written in place, durable with the @@ -239,29 +270,36 @@ impl<'a, P: Durability> DurableWrite<'a, P> { } /// Syncs every staged file and every file added with - /// [`DurableWrite::sync_with`], renames the staged files into place, then - /// syncs each directory involved once. + /// [`DurableWrite::sync_with`], then, a layer at a time, renames the + /// layer's files into place and syncs each directory involved once. /// /// # Errors /// /// Fails if the files cannot be synced, in which case none is published, - /// or if a file cannot be renamed or a directory cannot be synced. Files - /// renamed before such a failure are visible but may not be durable. + /// or if a file cannot be renamed or a directory cannot be synced, in + /// which case none of the later layers is. Files of the failed layer + /// renamed before the failure are visible but may not be durable. pub fn commit(mut self) -> Result<(), Error> { let staged = self .staged .get_mut() .unwrap_or_else(PoisonError::into_inner); - let temps = staged.files.iter().map(|(temp, _)| temp.as_path()); + let temps = staged + .layers + .iter() + .flat_map(|layer| &layer.files) + .map(|(temp, _)| temp.as_path()); self.platform .sync_batch(temps.chain(staged.in_place.iter().map(PathBuf::as_path)))?; - Self::rename_all(&staged.files)?; - // Every file is published, so dropping the write removes none. - staged.files.clear(); - for dir in &staged.dirs { - self.platform - .sync_dir(dir) - .map_err(|source| Error::new(Op::Sync, dir, source))?; + for layer in &mut staged.layers { + Self::rename_all(&layer.files)?; + // Every file is published, so dropping the write removes none. + layer.files.clear(); + for dir in &layer.dirs { + self.platform + .sync_dir(dir) + .map_err(|source| Error::new(Op::Sync, dir, source))?; + } } Ok(()) } @@ -304,7 +342,7 @@ impl

Drop for DurableWrite<'_, P> { .staged .get_mut() .unwrap_or_else(PoisonError::into_inner); - for (temp, _) in &staged.files { + for (temp, _) in staged.layers.iter().flat_map(|layer| &layer.files) { // Best effort: a leftover is garbage that readers skip. After a // failed rename, some of these are already published. let _ = fs::remove_file(temp); @@ -312,6 +350,16 @@ impl

Drop for DurableWrite<'_, P> { } } +impl Staged { + /// The layer numbered `layer`, with those before it. + fn layer(&mut self, layer: usize) -> &mut Layer { + if self.layers.len() <= layer { + self.layers.resize_with(layer + 1, Layer::default); + } + &mut self.layers[layer] + } +} + /// A temporary file being written by [`DurableWrite::stage_with`]. #[derive(Debug)] pub struct StagedFile { @@ -541,6 +589,43 @@ mod tests { assert_eq!(recorder.take(), [], "no directory is synced"); } + #[test] + fn layers_are_published_in_order() { + let root = tempfile::tempdir().unwrap(); + let root = root.path(); + for dir in ["a", "b", "c"] { + fs::create_dir(root.join(dir)).unwrap(); + } + let recorder = Recorder::default(); + let write = DurableWrite::new(&recorder); + write + .stage_in(1, root.join("b/2"), |file| file.write_all(b"two")) + .unwrap(); + write.stage(root.join("a/1"), b"one").unwrap(); + write.commit().unwrap(); + assert_eq!( + recorder.take(), + [ + Call::Batch(2), + Call::Dir(root.to_owned()), + Call::Dir(root.join("a")), + Call::Dir(root.to_owned()), + Call::Dir(root.join("b")), + ], + "the batch is synced once, then each layer's directories" + ); + + // A rename that fails leaves the later layers unpublished. + let write = DurableWrite::new(&recorder); + write.stage(root.join("a/blocked"), b"one").unwrap(); + write + .stage_in(1, root.join("c/after"), |file| file.write_all(b"two")) + .unwrap(); + fs::create_dir_all(root.join("a/blocked/full")).unwrap(); + assert_eq!(write.commit().unwrap_err().op, Op::Publish); + assert_eq!(names(&root.join("c")), Vec::::new()); + } + #[test] fn files_written_in_place_are_synced_with_the_batch() { let root = tempfile::tempdir().unwrap();