From 37c0a8b14990f2f7d222db54ca42a7335eb076e9 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 14:21:25 +0800 Subject: [PATCH 1/6] Commit: settle pre-publish failures by phase; conflicts take no lane Finding #4 (V-CC-2): settle_failure kept custody whenever CommitError::uncertain() held, whatever the phase. Content failures with no provider cause (merge-stage Save reads, logical counts, binding hints, removals) and unknown Storage errors from Save::finish happen before the Publish phase, when nothing in history can have changed, yet they locked the Workspace in Uncertain until a force unmount discarded its work. CommitFailure::uncertain() now depends on the phase: before Publish only local uncertainty counts (CommitError::locally_uncertain(): an uncertain or quarantined overlay, an uncertain owner job, a poisoned binding or port); from Publish until the answer is known CommitError::uncertain() decides. settle_failure and the daemon's reply code use it, so such a failure folds the capture back and answers Failed, not Unknown. The merge stage reports the Save's own failure (Save::take_failure) as its first cause. Finding #6 (V-CC-4): a conflicted merge publishes nothing but held the publication lane (Session turn and directory flock) through validation and its local install. A conflict found before the lane no longer takes it; one found by the in-lane step releases it before validation and install. The lane is dropped right after commit_branch on the publish path. Docs (engine/commit, engine/store, flows/commit) now agree. Tests (new engine/crates/layerfs-store-service/tests/commit_settle.rs): a pre-publish Content failure folds back and the next Commit publishes the change; local uncertainty keeps custody; a conflicted merge never enters the lane phase. No test deleted. Changed to the new contract: layerfs-daemon tests/store_commit.rs nested_storage_unknown_keeps_original_capture_and_blocks_another_commit is now nested_storage_unknown_before_publication_folds_back: a Construct-phase Storage failure with a nested unknown outcome publishes nothing, so every case folds back and a later Commit publishes. Production LOC: 206,537 -> 206,583 (delta +46) core 40,988 -> 40,988 (0) engine 95,899 -> 95,945 (+46) layerfs-daemon +3, layerfs-store-service +43 control 59,325 -> 59,325 (0) api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent 343c59b2ca and the staged tree Co-Authored-By: Claude Opus 5.5 --- docs/architecture/engine/commit/README.md | 22 +- docs/architecture/engine/store/README.md | 4 +- docs/architecture/flows/commit.md | 3 +- .../layerfs-daemon/src/control/failure.rs | 5 + .../layerfs-daemon/tests/store_commit.rs | 55 ++--- .../layerfs-store-service/src/store/commit.rs | 26 ++- .../src/store/commit_merge.rs | 9 +- .../src/store/commit_types.rs | 40 ++++ .../layerfs-store-service/src/store/settle.rs | 5 +- .../tests/commit_settle.rs | 141 +++++++++++++ .../tests/support/live.rs | 197 ++++++++++++++++++ 11 files changed, 455 insertions(+), 52 deletions(-) create mode 100644 engine/crates/layerfs-store-service/tests/commit_settle.rs create mode 100644 engine/crates/layerfs-store-service/tests/support/live.rs diff --git a/docs/architecture/engine/commit/README.md b/docs/architecture/engine/commit/README.md index 3df4c2df85..d0d1e5c6b2 100644 --- a/docs/architecture/engine/commit/README.md +++ b/docs/architecture/engine/commit/README.md @@ -64,7 +64,7 @@ phase is a telemetry child (`uptodate.state`, `capture`, `producer`, `begin`, | Head unchanged | `Committed` against the head the Workspace bound | [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs) | | Head moved, `force` false | `merge_candidate`: `merge_roots(base, ours, theirs)` in the Commit's own Save, before the lane; published against the head it merged with (`MergeReport`) | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs) | | Head moved again before the lane | `merge_in_lane`: only what landed in between, with its own Save, at most `LANE_MERGE_PATHS` serials | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs) | -| Merge conflict | Nothing published; the merge with marker blocks becomes the local base, `PendingMerge` is kept and the history binding moves to the head. The lane is released when the Commit returns | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs), [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs) | +| Merge conflict | Nothing published; the merge with marker blocks becomes the local base, `PendingMerge` is kept and the history binding moves to the head. A conflict found before the lane never takes it; one found by the in-lane step releases it before validation and install. Only a publication holds the lane | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs), [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs) | | `force` with a moved head | No merge; published over the head, the displaced head recorded | [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs), [`history/commit.rs`](../../../../engine/crates/layerfs-persistence/src/history/commit.rs) | | Relink (unlink and re-create with equal bytes) | A fresh chunked file whose overlay digest names an already saved root reuses it (`files_reused`); others are built and `record_file_digests` stores their digest. Files below the Store's `small_file_threshold_bytes` are rebuilt to the same object id | [`digests.rs`](../../../../engine/crates/layerfs-store-service/src/store/digests.rs), [`digest.rs`](../../../../engine/crates/layerfs-overlay/src/payload/digest.rs) | | Install | `prepare_base_install` rebinds the base to the new root without a tree walk; after publish, `install_prepared_base` waits for `base_readers == 0`, then `Overlay::install` sets `base_root`, `installed := G`, `captured := None` and queues `RETIRE` of G, in one SQL transaction | [`install.rs`](../../../../engine/crates/layerfs-workspace/src/workspace/install.rs), [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs) | @@ -91,8 +91,8 @@ is a different install, placing a sealed Store file into a project volume; see --> acquire_operation(request) --> construct ... outcome known --> release reader, then operation owner --> answer --> reclaim - failure --> published or uncertain? --yes--> keep all custody - | no + failure --> published, or CommitFailure::uncertain()? --yes--> keep all custody + | no (before Publish only local uncertainty counts) capture taken? --no--> locally_settled | yes resolve_failed(capture) --ok--> locally_settled @@ -116,7 +116,19 @@ the work counted and the release error that stopped the sequence | --- | --- | --- | --- | | Definite, settled, owners released | `Idle` | Admitted | [`operations.rs`](../../../../engine/crates/layerfs-daemon/src/control/operations.rs) | | Published, then install or a release failed | `LocalFailure` | Refused: code `Unknown`, phase `admission`; the daemon keeps `published`, the SDK refusal does not carry it | [`registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs) | -| Uncertain (`CommitError::uncertain()`) | `Uncertain` | Refused as above | [`commit_types.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_types.rs), [`registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs) | +| Uncertain (`CommitFailure::uncertain()`) | `Uncertain` | Refused as above | [`commit_types.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_types.rs), [`registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs) | + +`CommitFailure::uncertain()` depends on the phase. `commit_branch` is the +only write that publishes, so before the `Publish` phase nothing in history +can have changed: a Store, Content or History failure there (a merge-stage +Save read, a logical count, binding hints, removals, an unknown Storage +error from `Save::finish`) is a definite nonpublication, folded back with +`resolve_failed`, and the reply's code is `Failed`, not `Unknown`. Only local +uncertainty keeps custody there (`CommitError::locally_uncertain()`: an +uncertain or quarantined overlay, an uncertain owner job, a poisoned binding +or port). From the `Publish` phase until the answer is known, +`CommitError::uncertain()` decides. A merge-stage failure reports the Save's +own failure (`Save::take_failure`) as its first cause when there is one. ## Invariants @@ -146,7 +158,7 @@ the work counted and the release error that stopped the sequence | Moved head without merge | `HeadMoved` from `commit_branch` unless `force` | [`history/commit.rs`](../../../../engine/crates/layerfs-persistence/src/history/commit.rs) | | Base sources still open at install | Install waits; `OverlayError::BaseSourcesPending` if called unready | [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs) | | Install failed after publish | `OwnerError::Install` with the `PreparedBase`, never replayed; `CommitFailure.published` is `Some`; activity `LocalFailure` | [`owner.rs`](../../../../engine/crates/layerfs-store-service/src/overlay/owner.rs), [`operations.rs`](../../../../engine/crates/layerfs-daemon/src/control/operations.rs) | -| Uncertain outcome | `CommitError::uncertain()` true, code `Unknown`; custody kept | [`commit_types.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_types.rs) | +| Uncertain outcome | `CommitFailure::uncertain()` true, code `Unknown`; custody kept | [`commit_types.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_types.rs) | | Concurrent Commits on other Workspaces | Correct, serialized by the publication lane; not the optimized case | [Store](../store/README.md) | No total file, edit or Commit size cap exists: captured input is paged and diff --git a/docs/architecture/engine/store/README.md b/docs/architecture/engine/store/README.md index 09b94d8232..d67ec1e953 100644 --- a/docs/architecture/engine/store/README.md +++ b/docs/architecture/engine/store/README.md @@ -118,7 +118,9 @@ open, filled once by `backfill_lineage` install the new base ``` -`branch_snapshot` reads a Branch with its stack, base root and head Commit in +A merge that conflicted publishes nothing and so takes no lane; when the +in-lane step is what conflicts, the lane is released before validation and +the local install. `branch_snapshot` reads a Branch with its stack, base root and head Commit in one statement. Work that grows with the Commit runs before the lane ([`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs)). `fork`, `merge_branch` and `add_layer` check their expected heads inside their diff --git a/docs/architecture/flows/commit.md b/docs/architecture/flows/commit.md index e1bb646003..747191057e 100644 --- a/docs/architecture/flows/commit.md +++ b/docs/architecture/flows/commit.md @@ -37,7 +37,8 @@ ``` The publish lane is held only for the head re-check and the publish; all -work that grows with the Commit runs before it. Publication is one history +work that grows with the Commit runs before it, and a conflicted merge, +which publishes nothing, never holds it through validation or install. Publication is one history write transaction: once it commits, the Commit exists whether or not the reply arrives, and nothing guesses or resends. diff --git a/engine/crates/layerfs-daemon/src/control/failure.rs b/engine/crates/layerfs-daemon/src/control/failure.rs index c6b2a3a11d..2cc6aac760 100644 --- a/engine/crates/layerfs-daemon/src/control/failure.rs +++ b/engine/crates/layerfs-daemon/src/control/failure.rs @@ -99,6 +99,11 @@ impl Failure { } Self::Commit(failed) => { let (mut code, moved, mut detail) = commit(&failed.error); + // Before publication only local uncertainty is unknown: a + // Store or Content failure there is a definite refusal. + if code == ControlCode::Unknown && !failed.uncertain() { + code = ControlCode::Failed; + } // A settled failure whose reader or owner was not released // still leaves custody; the reply must not read as settled. if code != ControlCode::Unknown diff --git a/engine/crates/layerfs-daemon/tests/store_commit.rs b/engine/crates/layerfs-daemon/tests/store_commit.rs index 1048bd1845..3685972d69 100644 --- a/engine/crates/layerfs-daemon/tests/store_commit.rs +++ b/engine/crates/layerfs-daemon/tests/store_commit.rs @@ -714,8 +714,12 @@ fn unknown_history_acknowledgement_retains_original_intent_and_capture() { f.cleanup(); } +/// A Storage outcome before publication, nested unknowns included, is +/// definite: nothing was published, so the capture folds back and a later +/// explicit Commit runs (finding #4; an unknown before the publication's +/// own attempt cannot have published). #[test] -fn nested_storage_unknown_keeps_original_capture_and_blocks_another_commit() { +fn nested_storage_unknown_before_publication_folds_back() { let (f, store, owner) = setup("nested-unknown"); let missing = || StorageError::ObjectMissing(ObjectId::for_bytes(b"nested unknown dependency")); let unknown = || StorageError::UnknownOutcome { @@ -742,7 +746,6 @@ fn nested_storage_unknown_keeps_original_capture_and_blocks_another_commit() { cleanup: Box::new(StorageError::Busy), }, ]; - let mut retained = Vec::new(); for (index, error) in cases.into_iter().enumerate() { let workspace = bind(&store, &owner, &f, 61 + index as u8); let original = workspace.snapshot().unwrap(); @@ -758,42 +761,24 @@ fn nested_storage_unknown_keeps_original_capture_and_blocks_another_commit() { &failed.error, CommitError::Storage(StorageError::CleanupFailed { .. }) )); + assert!(!failed.uncertain(), "case {index}"); + assert!(failed.locally_settled, "case {index}: {failed:?}"); assert_eq!(workspace.snapshot().unwrap(), original); assert_eq!(read(&workspace), value); - if index < 3 { - assert!( - !failed.locally_settled, - "nested original unknown must not resolve capture: case {index}" - ); - assert!(!failed.locally_settled && failed.local_error.is_none()); - assert!(matches!( - workspace - .commit(|_, _, _| unreachable!()) - .unwrap_err() - .error, - CommitError::InFlight - )); - retained.push((workspace, failed)); - } else { - assert!(failed.locally_settled); - drop(failed); - let later = workspace - .commit(|save, _, snapshot| { - construct(save, snapshot, &value, store.policy().construction()) - }) - .unwrap(); - assert!(matches!( - later.history, - Some(CommitOutcome::Committed { .. }) - )); - drop(later); - close(&owner, &workspace); - } + drop(failed); + let later = workspace + .commit(|save, _, snapshot| { + construct(save, snapshot, &value, store.policy().construction()) + }) + .unwrap(); + assert!(matches!( + later.history, + Some(CommitOutcome::Committed { .. }) + )); + drop(later); + close(&owner, &workspace); } - println!("NESTED_UNKNOWN original_and_cleanup_and_nested=retained definite_control=resolved later_explicit_commit=passed no_stage=true terminal_unknowns=3"); - // These are deliberately supplied original producer outcomes. The proof - // does not execute a kernel SQLite I/O failure or settle the three unknowns. owner.stop().unwrap(); - drop((retained, store)); + drop(store); f.cleanup(); } diff --git a/engine/crates/layerfs-store-service/src/store/commit.rs b/engine/crates/layerfs-store-service/src/store/commit.rs index 2016337e8f..a3cfdffdde 100644 --- a/engine/crates/layerfs-store-service/src/store/commit.rs +++ b/engine/crates/layerfs-store-service/src/store/commit.rs @@ -263,15 +263,21 @@ impl BoundWorkspace { })?; let early = (Self::target_key(early_target, root), early); retained.phase = CommitPhase::Finish; - let lane = phase(timing, "lane", || { - self.store - .history - .publish_lane() - .map_err(CommitError::History) - })?; + // A conflicted merge publishes nothing, so it never takes the + // lane. let conflicted = merge .as_ref() .is_some_and(|report: &MergeReport| !report.conflicts.is_empty()); + let lane = if conflicted { + None + } else { + Some(phase(timing, "lane", || { + self.store + .history + .publish_lane() + .map_err(CommitError::History) + })?) + }; let (current, root, moved, logical) = if force || conflicted { (current, root, moved, logical) } else { @@ -336,6 +342,9 @@ impl BoundWorkspace { let conflicted = merge .as_ref() .is_some_and(|report: &MergeReport| !report.conflicts.is_empty()); + // Only a publication holds the lane: an in-lane step that + // conflicted releases it before validation and install. + let lane = lane.filter(|_| !conflicted); // A merge is published against the head it merged with; a forced // or unmoved Commit against the head the Workspace bound. let target = if merge.is_some() { ¤t } else { &snapshot }; @@ -414,12 +423,13 @@ impl BoundWorkspace { .history .commit_branch(intent) .map_err(CommitError::History) - })?; + }); + drop(lane); + let outcome = outcome?; let (head, root) = match &outcome { CommitOutcome::Committed { record, .. } => (Some(record.id), record.root), CommitOutcome::UpToDate { head, root } => (*head, *root), }; - drop(lane); retained.published = Some(outcome); if root != candidate.0 { return Err(CommitError::Context( diff --git a/engine/crates/layerfs-store-service/src/store/commit_merge.rs b/engine/crates/layerfs-store-service/src/store/commit_merge.rs index 56957e8181..8dad7cd41c 100644 --- a/engine/crates/layerfs-store-service/src/store/commit_merge.rs +++ b/engine/crates/layerfs-store-service/src/store/commit_merge.rs @@ -245,7 +245,14 @@ impl BoundWorkspace { limit, }) } - (Err(error), None) => return Err(content(error)), + // A Save write or read the merge depended on failed: that is + // the first cause, as for construction. + (Err(error), None) => { + return Err(match save.take_failure() { + Some(storage) => CommitError::Storage(storage), + None => content(error), + }) + } }; let (written, written_truncated) = if merged.clean() { (Vec::new(), false) diff --git a/engine/crates/layerfs-store-service/src/store/commit_types.rs b/engine/crates/layerfs-store-service/src/store/commit_types.rs index 014b1ded39..9a6e67bef9 100644 --- a/engine/crates/layerfs-store-service/src/store/commit_types.rs +++ b/engine/crates/layerfs-store-service/src/store/commit_types.rs @@ -174,6 +174,19 @@ impl CommitFailure { } } } +impl CommitFailure { + /// Whether this failure leaves its outcome unknown. Before the Publish + /// phase nothing in history can have changed (`commit_branch` is the + /// only write that publishes), so only local uncertainty counts there, + /// as it does after a known publication; an unanswered publication is + /// uncertain on any unknown outcome. + pub fn uncertain(&self) -> bool { + match self.phase { + CommitPhase::Publish if self.published.is_none() => self.error.uncertain(), + _ => self.error.locally_uncertain(), + } + } +} impl fmt::Display for CommitFailure { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Store Commit at {:?}: {:?}", self.phase, self.error) @@ -219,6 +232,33 @@ impl CommitError { } } } +impl CommitError { + /// Uncertainty about local state alone: the overlay engine, an owner job + /// or the Workspace binding. A Store, Content or History failure is not + /// here: before publication it cannot have changed history. + pub fn locally_uncertain(&self) -> bool { + match self { + Self::Construction { original, .. } => original.locally_uncertain(), + Self::Content { + provider: Some(provider), + .. + } => matches!( + provider.as_ref(), + PortError::Poisoned | PortError::ReadAdmission(super::ReadAdmissionError::Poisoned) + ), + Self::Owner(error) => owner_uncertain(error), + Self::Workspace( + WorkspaceError::BindingPoisoned + | WorkspaceError::Service(_) + | WorkspaceError::Overlay( + layerfs_overlay::OverlayError::Uncertain { .. } + | layerfs_overlay::OverlayError::Quarantined, + ), + ) => true, + _ => false, + } + } +} impl From for CommitError { fn from(error: ContentError) -> Self { Self::Content { diff --git a/engine/crates/layerfs-store-service/src/store/settle.rs b/engine/crates/layerfs-store-service/src/store/settle.rs index c95c0d2c13..f6917b7573 100644 --- a/engine/crates/layerfs-store-service/src/store/settle.rs +++ b/engine/crates/layerfs-store-service/src/store/settle.rs @@ -13,8 +13,11 @@ impl BoundWorkspace { ) -> Result { command(&self.owner, self.route()) } + /// Keeps custody of a known publication or an uncertain outcome + /// ([`CommitFailure::uncertain`]: before the Publish phase only local + /// uncertainty counts); folds a definite nonpublication's capture back. pub(super) fn settle_failure(&self, mut failure: CommitFailure) -> Box { - if failure.published.is_some() || failure.error.uncertain() { + if failure.published.is_some() || failure.uncertain() { return Box::new(failure); } let Some(capture) = failure.capture else { diff --git a/engine/crates/layerfs-store-service/tests/commit_settle.rs b/engine/crates/layerfs-store-service/tests/commit_settle.rs new file mode 100644 index 0000000000..0a1cb9946b --- /dev/null +++ b/engine/crates/layerfs-store-service/tests/commit_settle.rs @@ -0,0 +1,141 @@ +//! How a failed Commit settles. Before the Publish phase nothing in history +//! can have changed, so a Store, Content or History failure there is a +//! definite nonpublication: the capture folds back and the Workspace takes +//! the next Commit. Only local uncertainty (the overlay, an owner job, the +//! binding) keeps custody. A conflicted merge publishes nothing and takes no +//! publication lane. +#[path = "support/installed_store.rs"] +#[allow(dead_code)] +mod installed; +#[path = "support/live.rs"] +#[allow(dead_code)] +mod live; +#[path = "support/sdk.rs"] +#[allow(dead_code)] +mod support; + +use layerfs_content::ContentError; +use layerfs_history::CommitOutcome; +use layerfs_store_service::store::{CommitError, CommitOptions, CommitPhase}; +use layerfs_store_service::telemetry::{mark_phases, Recording}; +use layerfs_workspace::WorkspaceError; +use std::{cell::RefCell, rc::Rc, sync::Once}; +use support::Change; + +fn tmp() { + static SET: Once = Once::new(); + SET.call_once(|| std::env::set_var("TMPDIR", env!("CARGO_TARGET_TMPDIR"))); +} + +fn base(source: &std::path::Path) -> usize { + std::fs::write(source.join("a.txt"), b"alpha\n").unwrap(); + std::fs::write(source.join("b.txt"), b"bravo\n").unwrap(); + 2 +} + +fn options() -> CommitOptions { + CommitOptions { + force: false, + message: Some("settle".into()), + ..CommitOptions::default() + } +} + +/// A read failure after construction, of the class merge, count and hint +/// reads report (`Content` with no provider cause), is definite before the +/// Publish phase: the capture folds back, nothing is lost, and the next +/// Commit publishes the same change. +#[test] +fn content_failure_before_publication_folds_back() { + tmp(); + let fixture = support::Fixture::new("settle-content", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 51, "lane"); + live::change(&workspace, &[Change::Write("/a.txt", b"ALPHA\n")]); + let failure = workspace + .commit(|_, _, _| { + Err(CommitError::Content { + error: ContentError::OutputRejected, + provider: None, + }) + }) + .expect_err("refused construction"); + assert_eq!(failure.phase, CommitPhase::Construct, "{failure:?}"); + assert!( + failure.error.uncertain(), + "the class alone reads as unknown" + ); + assert!(!failure.uncertain(), "nothing could publish: {failure:?}"); + assert!(failure.locally_settled, "capture folded back: {failure:?}"); + assert_eq!(live::live(&workspace, "/a.txt").unwrap(), b"ALPHA\n"); + let committed = workspace.commit_captured(&options()).unwrap(); + assert!( + matches!(committed.history, Some(CommitOutcome::Committed { .. })), + "{:?}", + committed.history + ); + assert_eq!( + live::committed(&fixture, "lane", "/a.txt").as_deref(), + Some("ALPHA\n") + ); + workspace.close().unwrap(); + fixture.cleanup(); +} + +/// Local uncertainty keeps custody whatever the phase. +#[test] +fn local_uncertainty_keeps_custody() { + tmp(); + let fixture = support::Fixture::new("settle-local", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 52, "lane"); + live::change(&workspace, &[Change::Write("/a.txt", b"ALPHA\n")]); + let failure = workspace + .commit(|_, _, _| Err(CommitError::Workspace(WorkspaceError::BindingPoisoned))) + .expect_err("refused construction"); + assert!(failure.uncertain(), "{failure:?}"); + assert!(!failure.locally_settled, "custody kept: {failure:?}"); + let next = workspace + .commit_captured(&options()) + .expect_err("admission still held"); + assert!(matches!(next.error, CommitError::InFlight), "{next:?}"); + fixture.cleanup(); +} + +/// A conflicted merge publishes nothing and never takes the lane; the +/// merge with markers is installed and nothing is lost. +#[test] +fn conflicted_merge_takes_no_lane() { + tmp(); + let fixture = support::Fixture::new("settle-conflict-lane", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 53, "lane"); + live::change(&workspace, &[Change::Write("/a.txt", b"ours\n")]); + fixture.workspace_commit("lane", &[Change::Write("/a.txt", b"theirs\n")], 54, || {}); + let phases = Rc::new(RefCell::new(Vec::new())); + let seen = phases.clone(); + let recording = Recording::start(); + mark_phases(Some(Box::new(move |name, end| { + if !end { + seen.borrow_mut().push(name); + } + }))); + let committed = workspace.commit_captured(&options()); + mark_phases(None); + drop(recording); + let committed = committed.unwrap_or_else(|failure| panic!("{failure:?}")); + assert!(committed.history.is_none(), "nothing published"); + let merge = committed.merge.expect("merged"); + assert_eq!(merge.conflicts.len(), 1, "{merge:?}"); + let phases = phases.borrow(); + assert!(phases.contains(&"merge"), "{phases:?}"); + assert!(!phases.contains(&"lane"), "lane taken: {phases:?}"); + assert!(!phases.contains(&"publish"), "{phases:?}"); + let shown = String::from_utf8(live::live(&workspace, "/a.txt").unwrap()).unwrap(); + assert!( + shown.contains("ours") && shown.contains("theirs"), + "{shown}" + ); + workspace.close().unwrap(); + fixture.cleanup(); +} diff --git a/engine/crates/layerfs-store-service/tests/support/live.rs b/engine/crates/layerfs-store-service/tests/support/live.rs new file mode 100644 index 0000000000..3f46bb9542 --- /dev/null +++ b/engine/crates/layerfs-store-service/tests/support/live.rs @@ -0,0 +1,197 @@ +//! A bound Workspace changed in place and read back through its live view, +//! for Commit tests that change a Workspace between and during Commits. +use super::support::{Change, Fixture}; +use layerfs_content::filesystem::PathName; +use layerfs_history::{BranchId, HistoryName, LayerStackId, WorkspaceId}; +use layerfs_store_service::store::{BindRequest, BoundWorkspace}; +use layerfs_workspace::{Operation, Outcome, Position, Time}; + +/// The test Store's project. +pub fn branch(name: &str) -> BranchId { + BranchId::named( + LayerStackId::from_authority([23; 16]), + &HistoryName::new(name).unwrap(), + ) +} + +/// Binds Workspace `id` on `name`. +pub fn bind(fixture: &Fixture, id: u8, name: &str) -> BoundWorkspace { + fixture + .service + .store + .bind( + fixture.owner.client(), + BindRequest { + workspace: WorkspaceId::from_authority([id; 32]).unwrap(), + branch: branch(name), + }, + ) + .unwrap() + .workspace +} + +/// Applies `changes` in turn to the Workspace's live view, at time 123 s, +/// with each reply attempt recorded. A refused change panics. +pub fn change(workspace: &BoundWorkspace, changes: &[Change<'_>]) { + for change in changes { + try_change(workspace, *change).unwrap_or_else(|error| panic!("change: {error}")); + } +} + +/// One change; its refusal is returned as text. +pub fn try_change(workspace: &BoundWorkspace, change: Change<'_>) -> Result<(), String> { + let operation = workspace.operation().unwrap(); + let route = operation.workspace().route(); + let source = operation + .overlay() + .acquire_base_source(route, 9101) + .unwrap(); + let view = operation.workspace().view_for_source(source).unwrap(); + let lookup = |path: &str| -> Result { + let mut serial = view.root_serial(); + for name in path.split('/').filter(|part| !part.is_empty()) { + serial = view + .lookup(operation.overlay(), serial, &PathName::new(name).unwrap()) + .map_err(|error| format!("{path}: {error:?}"))? + .serial; + } + Ok(serial) + }; + let split = |path: &str| -> Result<(u64, PathName), String> { + let (parent, name) = path.rsplit_once('/').unwrap(); + Ok((lookup(parent)?, PathName::new(name).unwrap())) + }; + let apply = |op: Operation| -> Result<(), String> { + let applied = operation + .workspace() + .mutate( + operation.overlay(), + operation.ports(), + &view, + op, + Time { + seconds: 123, + nanoseconds: 0, + }, + ) + .map_err(|error| format!("{error:?}"))?; + let Outcome::Applied { publication, .. } = applied else { + return Err(format!("{applied:?}")); + }; + operation.overlay().reply_attempted(publication).unwrap(); + Ok(()) + }; + let done = (|| match change { + Change::Mode(path, mode) => apply(Operation::SetAttributes { + serial: lookup(path)?, + mode: Some(mode), + mtime: None, + size: None, + }), + Change::Mtime(path, seconds) => apply(Operation::SetAttributes { + serial: lookup(path)?, + mode: None, + mtime: Some(Time { + seconds, + nanoseconds: 0, + }), + size: None, + }), + Change::Write(path, bytes) => apply(Operation::Write { + serial: lookup(path)?, + position: Position::At(0), + data: bytes.to_vec().into(), + }), + Change::Create(path, bytes) => { + let (parent, name) = split(path)?; + apply(Operation::Create { + parent, + name, + mode: 0o644, + })?; + apply(Operation::Write { + serial: lookup(path)?, + position: Position::At(0), + data: bytes.to_vec().into(), + }) + } + Change::Mkdir(path) => { + let (parent, name) = split(path)?; + apply(Operation::Mkdir { + parent, + name, + mode: 0o755, + }) + } + Change::Unlink(path) => { + let (parent, name) = split(path)?; + apply(Operation::Unlink { parent, name }) + } + Change::Rmdir(path) => { + let (parent, name) = split(path)?; + apply(Operation::Rmdir { parent, name }) + } + _ => Err("change not used by these tests".into()), + })(); + drop(view); + operation + .overlay() + .release_base_source(route, source) + .unwrap(); + done +} + +/// The bytes the Workspace's live view shows at `path`, or why not. +pub fn live(workspace: &BoundWorkspace, path: &str) -> Result, String> { + let operation = workspace.operation().unwrap(); + let route = operation.workspace().route(); + let source = operation + .overlay() + .acquire_base_source(route, 9102) + .unwrap(); + let view = operation.workspace().view_for_source(source).unwrap(); + let read = (|| { + let mut serial = view.root_serial(); + for name in path.split('/').filter(|part| !part.is_empty()) { + serial = view + .lookup(operation.overlay(), serial, &PathName::new(name).unwrap()) + .map_err(|error| format!("{path}: {error:?}"))? + .serial; + } + let mut bytes = Vec::new(); + loop { + let read = view + .read( + operation.overlay(), + serial, + bytes.len() as u64, + 64 * 1024, + &mut bytes, + ) + .map_err(|error| format!("{path}: {error:?}"))?; + if read == 0 { + return Ok(bytes); + } + } + })(); + drop(view); + operation + .overlay() + .release_base_source(route, source) + .unwrap(); + read +} + +/// The text `branch` holds at `path` in the Store, or `None` when absent. +pub fn committed(fixture: &Fixture, name: &str, path: &str) -> Option { + fixture + .try_call( + "fs.read", + vec![ + ("branch", layerfs_bridge::control::SdkValue::text(name)), + ("path", layerfs_bridge::control::SdkValue::text(path)), + ], + ) + .ok() + .map(|value| value.get_text("text").unwrap_or_default().to_owned()) +} From c7eb6ac1f652133949d2d93faf68c46f1099c0dc Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 14:40:25 +0800 Subject: [PATCH 2/6] Commit: --expected inside the publication; force reads the head in the lane Finding #14 (V-CC-6): --expected was one read in the Sandbox before the Commit was sent, so a head that moved after it was merged with, and --force --expected C displaced whatever head the publication found. - CommitRequest gains required_head: the node the Branch must answer as its head (its head Commit, else its base Layer). commit_branch refuses another head HeadMoved inside its own transaction, forced or not. - The Workspace Commit carries it end to end: the Sandbox parses the resolved --expected id into CommitControl.expected (bridge record field), the daemon passes it as CommitOptions::expected, the Commit checks it when it reads the head (HeadMoved before any merge), does not merge in the lane with a head that moved again, and sends it as required_head. A daemon HeadMoved for a Commit sent with --expected is answered as the Sandbox's own check answers: Conflict naming the head as commit. - commit_advance_branch (shared by SQLite and PostgreSQL) gains a head_commit_id predicate on the head the transaction read; zero rows is HeadMoved, not Integrity (finding #10's missing predicate: a PostgreSQL lane connection lost inside the lane can no longer let one Commit overwrite another). CC-8: a forced Commit sent force && moved, with moved read before the lane, so a head that moved inside the lane was refused HeadMoved. It now sends force and lets the publication's own in-lane read decide, displacing the head it reads. Re-confirmed and not changed: "only the newest displaced head is recorded" loses nothing. The Commits between the forced Commit's parent and the displaced head are that head's first-parent ancestors, and the history closure follows displaced_id and parent edges, so all stay reachable and kept. The docs now say so. Tests: persistence commit_required_head.rs (another head refused forced or not; force over the required head displaces only it; force decides on the head its transaction reads), each on SQLite and on PostgreSQL when LAYERFS_TEST_POSTGRES_URL is set; store-service commit_expected.rs (moved expected head refused before the merge and the change kept; a head landing just before the lane refused forced or not; force publishes over the head read in the lane; force --expected displaces that head). CommitRequest, CommitOptions and CommitControl literals in tests and examples gain the new field as None (including three NFS test/example literals). No test deleted. Docs: core/history, engine/store, engine/commit, api/sdk/workspace. Production LOC: 206,583 -> 206,681 (delta +98) core 40,988 -> 40,989 (+1) layerfs-history +1 engine 95,945 -> 96,001 (+56) layerfs-bridge +5, layerfs-daemon +1, layerfs-persistence +20, layerfs-store-service +30 control 59,325 -> 59,366 (+41) layerfs-sandbox +41 api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent 37c0a8b149 (377c64dd92 before a test-only fixup) and the staged tree Co-Authored-By: Claude Opus 5.5 --- .../tests/kernel_application.rs | 2 +- .../layerfs-control/tests/mount_control.rs | 14 +- .../src/daemon/workspace/commit.rs | 1 + .../layerfs-sandbox/src/workspace/serve.rs | 54 +++- .../tests/daemon_unreadable_reply.rs | 1 + .../layerfs-history/src/contract/records.rs | 5 + docs/architecture/api/sdk/workspace.md | 7 +- docs/architecture/core/history/README.md | 4 +- docs/architecture/engine/commit/README.md | 3 +- docs/architecture/engine/store/README.md | 2 +- .../layerfs-bridge/src/control_merge.rs | 14 +- .../layerfs-bridge/tests/control_records.rs | 1 + .../layerfs-bridge/tests/observed_records.rs | 1 + .../layerfs-daemon/src/control/operations.rs | 1 + .../tests/concurrent_commits.rs | 1 + .../layerfs-daemon/tests/forced_producers.rs | 1 + .../crates/layerfs-daemon/tests/lane_merge.rs | 2 + .../layerfs-daemon/tests/merge_report.rs | 1 + .../tests/mounted_concurrency.rs | 1 + .../layerfs-daemon/tests/mounted_cycles.rs | 1 + .../tests/mounted_orphan_commit.rs | 1 + .../tests/mounted_parallel_commits.rs | 1 + .../crates/layerfs-daemon/tests/slot_state.rs | 1 + .../layerfs-daemon/tests/support/mounted.rs | 1 + .../layerfs-daemon/tests/unmount_reclaim.rs | 1 + .../crates/layerfs-nfs/examples/daemon_nfs.rs | 1 + engine/crates/layerfs-nfs/tests/daemon.rs | 1 + engine/crates/layerfs-nfs/tests/mounter.rs | 2 + .../examples/gc_bench/gc_fixture.rs | 1 + .../examples/issue327_counters_v2.rs | 1 + .../examples/issue327_counters_v3.rs | 1 + .../examples/issue327_counters_v4.rs | 1 + .../examples/issue327_counters_v5.rs | 1 + .../examples/pg_gc_profile.rs | 1 + .../queries/history/commit_advance_branch.sql | 2 +- .../layerfs-persistence/src/history/commit.rs | 43 +++- .../tests/branch_removal.rs | 2 + .../tests/commit_required_head.rs | 174 +++++++++++++ .../tests/diagnostic_facts.rs | 1 + .../tests/diagnostic_history.rs | 2 + .../tests/diagnostic_namespace.rs | 1 + .../tests/diagnostic_overwrite.rs | 1 + .../layerfs-persistence/tests/epoch_fence.rs | 1 + .../layerfs-persistence/tests/gc_backfill.rs | 1 + .../crates/layerfs-persistence/tests/heads.rs | 1 + .../tests/history_remediation.rs | 1 + .../layerfs-persistence/tests/kept_node.rs | 1 + .../tests/kept_node_closure.rs | 1 + .../layerfs-persistence/tests/kept_objects.rs | 1 + .../tests/kept_objects_bounded.rs | 1 + .../tests/layerstack_removal.rs | 1 + .../tests/lineage_backfill.rs | 1 + .../layerfs-persistence/tests/path_removal.rs | 1 + .../tests/postgresql_commit_round_trips.rs | 1 + .../tests/postgresql_compact.rs | 1 + .../tests/postgresql_compact_fixtures.rs | 2 + .../tests/postgresql_identical_ids.rs | 1 + .../tests/postgresql_position_columns.rs | 1 + .../tests/sqlite_compact.rs | 1 + .../tests/sqlite_compact_crash.rs | 1 + .../tests/sqlite_compact_fixtures.rs | 1 + .../tests/sqlite_compact_matrix.rs | 1 + .../tests/store_diagnostic.rs | 1 + .../tests/support/marks.rs | 1 + .../layerfs-persistence/tests/support/pg.rs | 1 + .../layerfs-store-service/src/store/commit.rs | 61 ++++- .../src/store/commit_types.rs | 6 + .../layerfs-store-service/src/write/files.rs | 1 + .../tests/commit_expected.rs | 231 ++++++++++++++++++ .../tests/commit_pipeline.rs | 1 + .../tests/commit_reclaim.rs | 1 + .../tests/commit_settle.rs | 2 +- .../tests/postgresql_phase_attribution.rs | 1 + .../tests/postgresql_round_trips.rs | 1 + .../tests/relink_commit.rs | 1 + .../tests/scale_lineage_cap.rs | 1 + .../tests/support/sdk.rs | 1 + 77 files changed, 653 insertions(+), 37 deletions(-) create mode 100644 engine/crates/layerfs-persistence/tests/commit_required_head.rs create mode 100644 engine/crates/layerfs-store-service/tests/commit_expected.rs diff --git a/control/crates/layerfs-control/tests/kernel_application.rs b/control/crates/layerfs-control/tests/kernel_application.rs index 84077017d4..f38f596081 100644 --- a/control/crates/layerfs-control/tests/kernel_application.rs +++ b/control/crates/layerfs-control/tests/kernel_application.rs @@ -151,7 +151,7 @@ fn actual_daemon_install_hello_bind_status_no_constructor_and_session_end() { // The real binary's Commit of an unchanged Workspace: the same root, no // new Commit record. assert!( - matches!(control.call(Request::Commit(layerfs_bridge::control::CommitControl { token: bound.token, force: false, message: None, })).unwrap(), Reply::Committed(layerfs_history::CommitOutcome::UpToDate { head: None, root }) if root == bound.binding.effective_root) + matches!(control.call(Request::Commit(layerfs_bridge::control::CommitControl { token: bound.token, force: false, message: None, expected: None })).unwrap(), Reply::Committed(layerfs_history::CommitOutcome::UpToDate { head: None, root }) if root == bound.binding.effective_root) ); let after = layerfs_sandbox::internal::workspace(&mut control) .status(bound.token) diff --git a/control/crates/layerfs-control/tests/mount_control.rs b/control/crates/layerfs-control/tests/mount_control.rs index 3382907816..c8ec5e5672 100644 --- a/control/crates/layerfs-control/tests/mount_control.rs +++ b/control/crates/layerfs-control/tests/mount_control.rs @@ -152,6 +152,7 @@ fn original_lost_control_reply_is_not_replayed_or_settled_by_an_observer() { token, force: false, message: None, + expected: None, }) ); let OperationCause::Exchange(original) = &failure.cause else { @@ -222,6 +223,7 @@ fn another_control_channel_observes_running_commit_and_refuses_unmount_before_ef token, force: false, message: None, + expected: None, })) }); entered.recv_timeout(Duration::from_secs(3)).unwrap(); @@ -294,7 +296,7 @@ fn an_original_unknown_blocks_another_commit_and_normal_unmount() { let (token, binding) = mount(&mut client, identity(89), branch); fixture::write(&f.service, token, b'U'); assert!( - matches!(client.call(Request::Commit(layerfs_bridge::control::CommitControl { token, force: false, message: None, })).unwrap(),Reply::Refused(value) if value.code==ControlCode::Unknown) + matches!(client.call(Request::Commit(layerfs_bridge::control::CommitControl { token, force: false, message: None, expected: None })).unwrap(),Reply::Refused(value) if value.code==ControlCode::Unknown) ); let observed = status(&mut client, token); assert_eq!(observed.activity, Activity::Uncertain); @@ -302,14 +304,14 @@ fn an_original_unknown_blocks_another_commit_and_normal_unmount() { assert!(observed.published.is_none()); assert!(observed.local.unwrap().captured.is_some()); assert!( - matches!(f.service.execute_control(&Request::Commit(layerfs_bridge::control::CommitControl { token, force: false, message: None, })), + matches!(f.service.execute_control(&Request::Commit(layerfs_bridge::control::CommitControl { token, force: false, message: None, expected: None })), Err(layerfs_daemon::control::Failure::Custody(value)) if value.code == ControlCode::Unknown && value.published.is_none()) ); assert!( matches!(client.call(Request::Unmount(layerfs_bridge::control::UnmountControl { token, discard: true })).unwrap(),Reply::Refused(value) if value.code==ControlCode::Unknown) ); assert!( - matches!(client.call(Request::Commit(layerfs_bridge::control::CommitControl { token, force: false, message: None, })).unwrap(),Reply::Refused(value) if value.code==ControlCode::Unknown) + matches!(client.call(Request::Commit(layerfs_bridge::control::CommitControl { token, force: false, message: None, expected: None })).unwrap(),Reply::Refused(value) if value.code==ControlCode::Unknown) ); let retained = worker.join(); assert!(retained.outcome.is_err()); @@ -364,6 +366,7 @@ fn status_retains_known_publication_when_the_engine_is_unavailable() { token, force: false, message: None, + expected: None, })); (client, reply) }); @@ -433,6 +436,7 @@ fn product_control_commit_captures_the_frontier_releases_its_owners_and_is_then_ }, force: false, message: None, + expected: None, })), Err(layerfs_daemon::control::Failure::Rejected( ControlCode::Invalid, @@ -448,6 +452,7 @@ fn product_control_commit_captures_the_frontier_releases_its_owners_and_is_then_ token, force: false, message: None, + expected: None, })) .unwrap(); let record = match &done.reply { @@ -483,6 +488,7 @@ fn product_control_commit_captures_the_frontier_releases_its_owners_and_is_then_ token, force: false, message: None, + expected: None, })) .unwrap(); assert!( @@ -648,6 +654,7 @@ fn a_definite_commit_failure_whose_capture_is_not_resolved_answers_unknown() { token, force: false, message: None, + expected: None, })); (client, reply) }); @@ -750,6 +757,7 @@ fn an_unresolved_moved_head_failure_is_answered_and_not_dropped() { token, force: false, message: None, + expected: None, })); (client, reply) }); diff --git a/control/crates/layerfs-sandbox/src/daemon/workspace/commit.rs b/control/crates/layerfs-sandbox/src/daemon/workspace/commit.rs index 00c4c2c792..dd4a0b994e 100644 --- a/control/crates/layerfs-sandbox/src/daemon/workspace/commit.rs +++ b/control/crates/layerfs-sandbox/src/daemon/workspace/commit.rs @@ -30,6 +30,7 @@ impl WorkspaceApi<'_> { token, force: false, message: None, + expected: None, }); match self.exchange(request.clone())? { Reply::Committed(outcome) => Ok(outcome), diff --git a/control/crates/layerfs-sandbox/src/workspace/serve.rs b/control/crates/layerfs-sandbox/src/workspace/serve.rs index a0aca45cb3..53bb8ceb8e 100644 --- a/control/crates/layerfs-sandbox/src/workspace/serve.rs +++ b/control/crates/layerfs-sandbox/src/workspace/serve.rs @@ -324,6 +324,35 @@ pub fn listed_head(listed: &SdkValue, id: BranchId) -> Option { /// resolver, a full id or a prefix of 8 or more of its characters. pub type Resolve<'a> = dyn FnMut(&str) -> Outcome + 'a; +/// The daemon's `HeadMoved` for a Commit sent with `--expected`: the head +/// moved after the check above, and the publication refused it with nothing +/// committed. Answered as the check answers a head that is not the expected +/// one: `Conflict`, naming the head as `commit`. +fn moved_from_expected( + expected: Option, + failure: &crate::OperationFailure, +) -> Option { + let OperationCause::Remote(refused) = &failure.cause else { + return None; + }; + let moved = match (expected, refused.code, &refused.moved) { + (Some(_), layerfs_bridge::control::ControlCode::HeadMoved, Some(moved)) => moved, + _ => return None, + }; + let head = layerfs_bridge::sdk_values::node_text(moved.actual_head.map_or( + layerfs_history::NodeId::Layer(moved.actual_base), + layerfs_history::NodeId::Commit, + )); + let refusal = layerfs_home::outcome::refused( + "Conflict", + format!( + "the Branch's head moved to {head} after --expected was checked; nothing was committed" + ), + ); + let refusal = with_next(refusal, "commit", SdkValue::text(head)); + Some(with_next(refusal, "conflicts", SdkValue::List(Vec::new()))) +} + /// The full id of the Commit `--expected` names, resolved in the Store: a /// prefix more than one Commit starts with is refused `InvalidInput` with /// `matches` beside it; one no Commit has, `NoSuchCommit`. @@ -350,9 +379,10 @@ fn expected_id(text: &str, resolve: &mut Resolve<'_>) -> Result, @@ -396,13 +426,29 @@ pub fn commit_with( return Err(with_next(refusal, "conflicts", SdkValue::List(Vec::new()))); } } + let expected = expected + .map(|text| { + layerfs_bridge::sdk_values::unhex(text) + .and_then(|bytes| layerfs_history::NodeId::from_slice(&bytes).ok()) + .ok_or_else(|| { + layerfs_home::outcome::refused( + "Failed", + "the Store named no Commit id for --expected; nothing was committed", + ) + }) + }) + .transpose()?; let reply = workspace(&mut control) .commit_with(CommitControl { token, force, message: host.message.text().map(str::to_owned), + expected, }) - .map_err(values::failure)?; + .map_err(|failure| match moved_from_expected(expected, &failure) { + Some(refusal) => refusal, + None => values::failure(failure), + })?; let value = values::commit(&reply)?; // the Layer the Branch was forked at, from the mount this process // holds (no read): an unchanged fresh fork's head (call surface 2.0) diff --git a/control/crates/layerfs-sandbox/tests/daemon_unreadable_reply.rs b/control/crates/layerfs-sandbox/tests/daemon_unreadable_reply.rs index 9db0b3aa22..760bb75266 100644 --- a/control/crates/layerfs-sandbox/tests/daemon_unreadable_reply.rs +++ b/control/crates/layerfs-sandbox/tests/daemon_unreadable_reply.rs @@ -44,6 +44,7 @@ fn an_unreadable_commit_answer_leaves_its_outcome_unknown() { token: token(), force: false, message: None, + expected: None, }); let refused = refusal(&unreadable(commit)).unwrap(); assert_eq!(refused.code, "Unknown"); diff --git a/core/crates/layerfs-history/src/contract/records.rs b/core/crates/layerfs-history/src/contract/records.rs index c62188c64c..ffb23800de 100644 --- a/core/crates/layerfs-history/src/contract/records.rs +++ b/core/crates/layerfs-history/src/contract/records.rs @@ -338,6 +338,11 @@ pub struct CommitRequest { pub meta: CommitMeta, /// Overwrite a head that moved instead of refusing. pub force: bool, + /// The node the Branch must answer as its head (its head Commit, else + /// its base Layer) when the transaction publishes, whatever `force` + /// says; another head is refused `HeadMoved`. `None` checks only + /// `expected_head` and `force`. + pub required_head: Option, } /// One side of a Branch merge. diff --git a/docs/architecture/api/sdk/workspace.md b/docs/architecture/api/sdk/workspace.md index e7afe33b3f..9a8de49e6c 100644 --- a/docs/architecture/api/sdk/workspace.md +++ b/docs/architecture/api/sdk/workspace.md @@ -323,8 +323,11 @@ long form adds `outcome`, `branch`, `parent` (the Commit before it, or for a Branch's first Commit the publication it was forked at; null when unchanged), `root`, `message`, `created_at` and `merged_from`. `--expected C` refuses `Conflict` unless the Branch's head is `C`, an id or a prefix of -8 or more characters resolved as `commit get` resolves it; the check is one -read before the Commit. +8 or more characters resolved as `commit get` resolves it. It is checked +before the Commit and again inside the publication's own transaction: a head +that moves after the first check is refused the same way, with nothing +committed, and is never merged with. `--force --expected C` replaces only +`C`. | Refusal | When | | --- | --- | diff --git a/docs/architecture/core/history/README.md b/docs/architecture/core/history/README.md index c2c84bb113..e1dc5389b0 100644 --- a/docs/architecture/core/history/README.md +++ b/docs/architecture/core/history/README.md @@ -96,7 +96,9 @@ or any process, memory, socket or stdout/stderr state. | --- | --- | | Stack profile or scope differs | `Integrity("Commit context")` | | Base moved, or head moved without `force` | `HeadMoved(MovedState)` with expected and actual head and base | -| Head moved, `force`, base unchanged | new Commit keeps `expected_head` as parent; `displaced` names the old head | +| `required_head` set and the Branch answers another head (its head Commit, else its base Layer), forced or not | `HeadMoved(MovedState)` | +| Head moved, `force`, base unchanged | new Commit keeps `expected_head` as parent; `displaced` names the head the transaction read. Commits between `expected_head` and it stay on its first-parent chain, so `displaced` and parent links reach them all (and keep them, for collection) | +| Branch advance matches no row | `HeadMoved`: the advance replaces only the head this transaction read (`commit_advance_branch` has a `head_commit_id` predicate), so a writer that moved the Branch meanwhile (a PostgreSQL lane connection lost inside the lane) publishes nothing over it | | `candidate_root` equals the effective root | `UpToDate { head, root }` | | Otherwise | `Committed { record, displaced: None }` | diff --git a/docs/architecture/engine/commit/README.md b/docs/architecture/engine/commit/README.md index d0d1e5c6b2..f6c826de33 100644 --- a/docs/architecture/engine/commit/README.md +++ b/docs/architecture/engine/commit/README.md @@ -65,7 +65,8 @@ phase is a telemetry child (`uptodate.state`, `capture`, `producer`, `begin`, | Head moved, `force` false | `merge_candidate`: `merge_roots(base, ours, theirs)` in the Commit's own Save, before the lane; published against the head it merged with (`MergeReport`) | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs) | | Head moved again before the lane | `merge_in_lane`: only what landed in between, with its own Save, at most `LANE_MERGE_PATHS` serials | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs) | | Merge conflict | Nothing published; the merge with marker blocks becomes the local base, `PendingMerge` is kept and the history binding moves to the head. A conflict found before the lane never takes it; one found by the in-lane step releases it before validation and install. Only a publication holds the lane | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs), [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs) | -| `force` with a moved head | No merge; published over the head, the displaced head recorded | [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs), [`history/commit.rs`](../../../../engine/crates/layerfs-persistence/src/history/commit.rs) | +| `force` with a moved head | No merge, and no head read decides it before the lane: the publication's own transaction, inside the lane, reads the head and publishes over it, recording it as `displaced` (the Commits before it stay on its first-parent chain) | +| `expected` (`--expected`) | `CommitOptions::expected`, the node the Branch must answer as its head, is checked when the head is read (another head: `HeadMoved` before any merge) and travels in the publish intent as `CommitRequest::required_head`, checked again inside `commit_branch`'s transaction. A head that moves again before the lane is not merged with; the publication refuses it. With `force`, only that head is displaced | [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs), [`history/commit.rs`](../../../../engine/crates/layerfs-persistence/src/history/commit.rs) | | Relink (unlink and re-create with equal bytes) | A fresh chunked file whose overlay digest names an already saved root reuses it (`files_reused`); others are built and `record_file_digests` stores their digest. Files below the Store's `small_file_threshold_bytes` are rebuilt to the same object id | [`digests.rs`](../../../../engine/crates/layerfs-store-service/src/store/digests.rs), [`digest.rs`](../../../../engine/crates/layerfs-overlay/src/payload/digest.rs) | | Install | `prepare_base_install` rebinds the base to the new root without a tree walk; after publish, `install_prepared_base` waits for `base_readers == 0`, then `Overlay::install` sets `base_root`, `installed := G`, `captured := None` and queues `RETIRE` of G, in one SQL transaction | [`install.rs`](../../../../engine/crates/layerfs-workspace/src/workspace/install.rs), [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs) | | Rows written after the capture | Untouched by install; still the top of the effective view. An mtime-only change keeps the base row and carries its live row into G+1 (`keep_live_row`); until a write, that row is not dirty and `active_inodes` (Dirty check, `workspace status`) leaves it out | [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs), [`inodes.rs`](../../../../engine/crates/layerfs-workspace/src/construction/namespace/inodes.rs) | diff --git a/docs/architecture/engine/store/README.md b/docs/architecture/engine/store/README.md index d67ec1e953..8c16236b05 100644 --- a/docs/architecture/engine/store/README.md +++ b/docs/architecture/engine/store/README.md @@ -81,7 +81,7 @@ except the statements PostgreSQL replaces | --- | --- | --- | --- | | `initialize_layerstack` | Insert the stack and its genesis Layer | name or identity taken: `Integrity` | [`layerstack.rs`](../../../../engine/crates/layerfs-persistence/src/history/layerstack.rs) | | `fork` | Insert one Branch row at a Layer, or at a Commit on the source Branch's first-parent chain; nothing is copied | Commit not in history: `NotInHistory` | [`branch.rs`](../../../../engine/crates/layerfs-persistence/src/history/branch.rs) | -| `commit_branch` | Check the expected head and base, insert or verify the Commit, record its lineage, advance the Branch | moved head: `HeadMoved` unless `force` with the same base; same root: `UpToDate` | [`commit.rs`](../../../../engine/crates/layerfs-persistence/src/history/commit.rs) | +| `commit_branch` | Check the expected head and base (and `required_head`), insert or verify the Commit, record its lineage, advance the Branch from the head it read | moved head: `HeadMoved` unless `force` with the same base; another `required_head`, or an advance that matches no row: `HeadMoved`; same root: `UpToDate` | [`commit.rs`](../../../../engine/crates/layerfs-persistence/src/history/commit.rs) | | `add_layer` | Publish a Branch head Commit as a Layer on the stack head and record the Layers it overwrote | `HeadMoved`, `StackMoved`, `BaseMismatch`; outcomes `UpToDate`, `NoChanges` | [`layerstack.rs`](../../../../engine/crates/layerfs-persistence/src/history/layerstack.rs) | | `merge_branch` | Check both sides still sit at the merged nodes, then insert a new Branch: a fast-forward to a Layer or Commit, or a merge Commit with `second_parent` | moved side: `StackMoved` / `HeadMoved` | [`merge.rs`](../../../../engine/crates/layerfs-persistence/src/history/merge.rs) | | `reserve_inodes` | Consume a half-open inode range for a scope; serials are never recycled | past `i64::MAX`: `Capacity` | [`allocation.rs`](../../../../engine/crates/layerfs-persistence/src/history/allocation.rs) | diff --git a/engine/crates/layerfs-bridge/src/control_merge.rs b/engine/crates/layerfs-bridge/src/control_merge.rs index 503f9204c6..22c12607df 100644 --- a/engine/crates/layerfs-bridge/src/control_merge.rs +++ b/engine/crates/layerfs-bridge/src/control_merge.rs @@ -5,11 +5,13 @@ //! out. Paths and lines are never cut in the middle. use crate::{ control::{ControlError, WorkspaceToken}, - control_history::{boolean, head, outcome, put_head, put_outcome, put_token, token}, + control_history::{ + boolean, head, node, outcome, put_head, put_node, put_outcome, put_token, token, + }, wire::{Reader, Writer, LIMIT}, }; use layerfs_content::merge::{Conflict, ConflictKind, Hunk, LwwDecision}; -use layerfs_history::{CommitId, CommitOutcome, MAXIMUM_MESSAGE_BYTES}; +use layerfs_history::{CommitId, CommitOutcome, NodeId, MAXIMUM_MESSAGE_BYTES}; /// Longest path or line carried. pub const TEXT_FIELD_LIMIT: usize = 4096; @@ -25,6 +27,10 @@ pub struct CommitControl { pub force: bool, /// Description of the captured filesystem change. pub message: Option, + /// The head the Commit must be made over (`--expected`), as the Branch + /// answers it: its head Commit, else its base Layer. The publication + /// checks it in its own transaction; another head is `HeadMoved`. + pub expected: Option, } /// A Commit published after merging with a moved head. @@ -72,7 +78,7 @@ pub(crate) fn put_commit_control( } out.blob(text.as_bytes())?; } - Ok(()) + put_node(out, value.expected) } pub(crate) fn commit_control(input: &mut Reader<'_>) -> Result { @@ -86,10 +92,12 @@ pub(crate) fn commit_control(input: &mut Reader<'_>) -> Result self.unmount(*control), diff --git a/engine/crates/layerfs-daemon/tests/concurrent_commits.rs b/engine/crates/layerfs-daemon/tests/concurrent_commits.rs index 088942e940..7aeeb8cb6b 100644 --- a/engine/crates/layerfs-daemon/tests/concurrent_commits.rs +++ b/engine/crates/layerfs-daemon/tests/concurrent_commits.rs @@ -127,6 +127,7 @@ fn commit_together( token, force: false, message: None, + expected: None, })) .map(|done| done.reply) }) diff --git a/engine/crates/layerfs-daemon/tests/forced_producers.rs b/engine/crates/layerfs-daemon/tests/forced_producers.rs index e6a419de85..875c18e068 100644 --- a/engine/crates/layerfs-daemon/tests/forced_producers.rs +++ b/engine/crates/layerfs-daemon/tests/forced_producers.rs @@ -598,6 +598,7 @@ fn commit( token, force: false, message: None, + expected: None, }); let result = match gate { Some(gate) => service.execute(&request, move |_, _, snapshot| { diff --git a/engine/crates/layerfs-daemon/tests/lane_merge.rs b/engine/crates/layerfs-daemon/tests/lane_merge.rs index f789d656d4..6657e1e6de 100644 --- a/engine/crates/layerfs-daemon/tests/lane_merge.rs +++ b/engine/crates/layerfs-daemon/tests/lane_merge.rs @@ -357,6 +357,7 @@ fn commit_held( token, force: false, message: None, + expected: None, })) .map(|done| done.reply) .map_err(|failure| format!("{failure:?}")) @@ -393,6 +394,7 @@ fn commit_plain(fixture: &Fixture, token: layerfs_bridge::control::WorkspaceToke token, force: false, message: None, + expected: None, })) .map(|done| done.reply) .map_err(|failure| format!("{failure:?}")); diff --git a/engine/crates/layerfs-daemon/tests/merge_report.rs b/engine/crates/layerfs-daemon/tests/merge_report.rs index b050542d7e..e6e9715522 100644 --- a/engine/crates/layerfs-daemon/tests/merge_report.rs +++ b/engine/crates/layerfs-daemon/tests/merge_report.rs @@ -93,6 +93,7 @@ fn conflicted_commit(label: &str, id: u8, count: usize) -> (Vec, bool) { token, force: false, message: None, + expected: None, })) .unwrap() .reply; diff --git a/engine/crates/layerfs-daemon/tests/mounted_concurrency.rs b/engine/crates/layerfs-daemon/tests/mounted_concurrency.rs index cf52606be2..c709135c0d 100644 --- a/engine/crates/layerfs-daemon/tests/mounted_concurrency.rs +++ b/engine/crates/layerfs-daemon/tests/mounted_concurrency.rs @@ -498,6 +498,7 @@ fn commit(rig: &Rig, token: WorkspaceToken, what: &str) -> CommitRecord { token, force: false, message: None, + expected: None, }, )) { Ok(done) => { diff --git a/engine/crates/layerfs-daemon/tests/mounted_cycles.rs b/engine/crates/layerfs-daemon/tests/mounted_cycles.rs index ea0362c048..dfd459db1d 100644 --- a/engine/crates/layerfs-daemon/tests/mounted_cycles.rs +++ b/engine/crates/layerfs-daemon/tests/mounted_cycles.rs @@ -1063,6 +1063,7 @@ fn simultaneous_mounts_over_related_roots_are_isolated_and_a_stale_token_never_r token, force: false, message: None, + expected: None, }), Request::Attach(token), Request::Unmount(layerfs_bridge::control::UnmountControl { diff --git a/engine/crates/layerfs-daemon/tests/mounted_orphan_commit.rs b/engine/crates/layerfs-daemon/tests/mounted_orphan_commit.rs index 0e89d4d340..d22b2efdcf 100644 --- a/engine/crates/layerfs-daemon/tests/mounted_orphan_commit.rs +++ b/engine/crates/layerfs-daemon/tests/mounted_orphan_commit.rs @@ -363,6 +363,7 @@ fn commit(service: Arc, token: WorkspaceToken) -> JoinHandle token, force: false, message: None, + expected: None, }); match service.execute_control(&request) { Ok(done) => Finished { diff --git a/engine/crates/layerfs-daemon/tests/mounted_parallel_commits.rs b/engine/crates/layerfs-daemon/tests/mounted_parallel_commits.rs index 0cb39aa2ce..03ead15564 100644 --- a/engine/crates/layerfs-daemon/tests/mounted_parallel_commits.rs +++ b/engine/crates/layerfs-daemon/tests/mounted_parallel_commits.rs @@ -110,6 +110,7 @@ fn parallel_workspace_commits_keep_distinct_captures_and_one_admission_each() { token, force: false, message: None, + expected: None, }, )); let _ = tx.send((tag, result)); diff --git a/engine/crates/layerfs-daemon/tests/slot_state.rs b/engine/crates/layerfs-daemon/tests/slot_state.rs index d8c9f17bac..d63f8ba2a1 100644 --- a/engine/crates/layerfs-daemon/tests/slot_state.rs +++ b/engine/crates/layerfs-daemon/tests/slot_state.rs @@ -426,6 +426,7 @@ fn recovery_request_admits_only_the_recovery_set() { token, force: false, message: None, + expected: None, } ))); } diff --git a/engine/crates/layerfs-daemon/tests/support/mounted.rs b/engine/crates/layerfs-daemon/tests/support/mounted.rs index da97018438..8f388c827b 100644 --- a/engine/crates/layerfs-daemon/tests/support/mounted.rs +++ b/engine/crates/layerfs-daemon/tests/support/mounted.rs @@ -152,6 +152,7 @@ impl Harness { token, force: false, message: None, + expected: None, })) } pub fn try_unmount(&self, token: WorkspaceToken) -> Result { diff --git a/engine/crates/layerfs-daemon/tests/unmount_reclaim.rs b/engine/crates/layerfs-daemon/tests/unmount_reclaim.rs index f63aa9e333..0326400b7b 100644 --- a/engine/crates/layerfs-daemon/tests/unmount_reclaim.rs +++ b/engine/crates/layerfs-daemon/tests/unmount_reclaim.rs @@ -121,6 +121,7 @@ fn committed(fixture: &Fixture, id: u8) -> WorkspaceToken { token, force: false, message: None, + expected: None, })) .unwrap_or_else(|failure| panic!("Commit: {failure:?}")); assert!( diff --git a/engine/crates/layerfs-nfs/examples/daemon_nfs.rs b/engine/crates/layerfs-nfs/examples/daemon_nfs.rs index 2ce0ea9dd1..3ee5451329 100644 --- a/engine/crates/layerfs-nfs/examples/daemon_nfs.rs +++ b/engine/crates/layerfs-nfs/examples/daemon_nfs.rs @@ -110,6 +110,7 @@ fn main() { token, force: false, message: Some("a3 over nfs".into()), + expected: None, })); let ms = at.elapsed().as_millis(); match done { diff --git a/engine/crates/layerfs-nfs/tests/daemon.rs b/engine/crates/layerfs-nfs/tests/daemon.rs index 2d831256bb..2a80da1d7b 100644 --- a/engine/crates/layerfs-nfs/tests/daemon.rs +++ b/engine/crates/layerfs-nfs/tests/daemon.rs @@ -88,6 +88,7 @@ fn commit(service: &Service, token: WorkspaceToken) -> Reply { token, force: false, message: Some("over nfs".into()), + expected: None, })) .unwrap() .reply diff --git a/engine/crates/layerfs-nfs/tests/mounter.rs b/engine/crates/layerfs-nfs/tests/mounter.rs index 2daffa7624..775d8e87a6 100644 --- a/engine/crates/layerfs-nfs/tests/mounter.rs +++ b/engine/crates/layerfs-nfs/tests/mounter.rs @@ -104,6 +104,7 @@ fn default_flush_commits_with_the_export_volume_and_refuses_without_it() { token, force: false, message: Some("first".into()), + expected: None, })) .unwrap() .reply @@ -122,6 +123,7 @@ fn default_flush_commits_with_the_export_volume_and_refuses_without_it() { token, force: false, message: Some("second".into()), + expected: None, })) { Err(Failure::Kernel(failure)) => { assert_eq!( diff --git a/engine/crates/layerfs-persistence/examples/gc_bench/gc_fixture.rs b/engine/crates/layerfs-persistence/examples/gc_bench/gc_fixture.rs index 78a4cc99d9..8e107f1cf0 100644 --- a/engine/crates/layerfs-persistence/examples/gc_bench/gc_fixture.rs +++ b/engine/crates/layerfs-persistence/examples/gc_bench/gc_fixture.rs @@ -599,6 +599,7 @@ fn commit_and_publish( second_parent: None, meta, force: false, + required_head: None, }) .expect("commit") { diff --git a/engine/crates/layerfs-persistence/examples/issue327_counters_v2.rs b/engine/crates/layerfs-persistence/examples/issue327_counters_v2.rs index 827ca6305e..50de7d753e 100644 --- a/engine/crates/layerfs-persistence/examples/issue327_counters_v2.rs +++ b/engine/crates/layerfs-persistence/examples/issue327_counters_v2.rs @@ -153,6 +153,7 @@ fn main() { second_parent: None, meta, force: false, + required_head: None, }) .unwrap(); if let CommitOutcome::Committed { record, .. } = result { diff --git a/engine/crates/layerfs-persistence/examples/issue327_counters_v3.rs b/engine/crates/layerfs-persistence/examples/issue327_counters_v3.rs index 237c97bc10..eeb911ba7c 100644 --- a/engine/crates/layerfs-persistence/examples/issue327_counters_v3.rs +++ b/engine/crates/layerfs-persistence/examples/issue327_counters_v3.rs @@ -159,6 +159,7 @@ fn main() { second_parent: None, meta, force: false, + required_head: None, }) .unwrap(); if let CommitOutcome::Committed { record, .. } = result { diff --git a/engine/crates/layerfs-persistence/examples/issue327_counters_v4.rs b/engine/crates/layerfs-persistence/examples/issue327_counters_v4.rs index 2245058b5a..29b73e4523 100644 --- a/engine/crates/layerfs-persistence/examples/issue327_counters_v4.rs +++ b/engine/crates/layerfs-persistence/examples/issue327_counters_v4.rs @@ -159,6 +159,7 @@ fn main() { second_parent: None, meta, force: false, + required_head: None, }) .unwrap(); if let CommitOutcome::Committed { record, .. } = result { diff --git a/engine/crates/layerfs-persistence/examples/issue327_counters_v5.rs b/engine/crates/layerfs-persistence/examples/issue327_counters_v5.rs index 8434a0296f..e663d91a23 100644 --- a/engine/crates/layerfs-persistence/examples/issue327_counters_v5.rs +++ b/engine/crates/layerfs-persistence/examples/issue327_counters_v5.rs @@ -159,6 +159,7 @@ fn main() { second_parent: None, meta, force: false, + required_head: None, }) .unwrap(); if let CommitOutcome::Committed { record, .. } = result { diff --git a/engine/crates/layerfs-persistence/examples/pg_gc_profile.rs b/engine/crates/layerfs-persistence/examples/pg_gc_profile.rs index 394913576e..91c01aca4b 100644 --- a/engine/crates/layerfs-persistence/examples/pg_gc_profile.rs +++ b/engine/crates/layerfs-persistence/examples/pg_gc_profile.rs @@ -297,6 +297,7 @@ fn commit_and_publish( second_parent: None, meta, force: false, + required_head: None, }) .expect("commit") { diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/commit_advance_branch.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/commit_advance_branch.sql index 1157ecd59e..a35b7bf7e6 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/commit_advance_branch.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/commit_advance_branch.sql @@ -1 +1 @@ -UPDATE branch SET head_commit_id = $1 WHERE branch_id = $2 AND base_layer_id = $3 RETURNING 1; +UPDATE branch SET head_commit_id = $1 WHERE branch_id = $2 AND base_layer_id = $3 AND (head_commit_id = $4 OR (head_commit_id IS NULL AND $4 IS NULL)) RETURNING 1; diff --git a/engine/crates/layerfs-persistence/src/history/commit.rs b/engine/crates/layerfs-persistence/src/history/commit.rs index 5c0efa12b9..6cad612049 100644 --- a/engine/crates/layerfs-persistence/src/history/commit.rs +++ b/engine/crates/layerfs-persistence/src/history/commit.rs @@ -107,13 +107,15 @@ pub(crate) fn commit_branch( } let moved = branch.base_layer != request.expected_base || branch.head_commit != request.expected_head; - if moved && (!request.force || branch.base_layer != request.expected_base) { - return Err(HistoryError::HeadMoved(Box::new(MovedState { - expected_head: request.expected_head, - actual_head: branch.head_commit, - expected_base: request.expected_base, - actual_base: branch.base_layer, - }))); + let answered = branch + .head_commit + .map_or(NodeId::Layer(branch.base_layer), NodeId::Commit); + let refused = (moved && (!request.force || branch.base_layer != request.expected_base)) + || request + .required_head + .is_some_and(|required| required != answered); + if refused { + return Err(head_moved(request, &branch)); } // Past the check above the expected base is the Branch's own. let base_root = rows @@ -159,6 +161,9 @@ pub(crate) fn commit_branch( ..request.meta.clone() }, )?; + // The advance replaces only the head this transaction read: if another + // writer moved the Branch meanwhile (a PostgreSQL lane connection lost + // inside the lane), no row matches and nothing is published. let advanced = tx .execute( ADVANCE_BRANCH, @@ -166,11 +171,18 @@ pub(crate) fn commit_branch( record.id.as_slice(), branch.id.as_slice(), request.expected_base.as_slice(), + branch.head_commit.map(|id| id.to_bytes().to_vec()), ], ) .map_err(sql)?; - if advanced != 1 { - return Err(HistoryError::Integrity("Branch advance")); + match advanced { + 1 => {} + 0 => { + let now = super::branch::snapshot_rows(tx, request.branch)? + .ok_or(HistoryError::Missing(Missing::Branch))?; + return Err(head_moved(request, &now.branch)); + } + _ => return Err(HistoryError::Integrity("Branch advance")), } fence.confirm(tx)?; let displaced = branch.head_commit.filter(|_| moved); @@ -180,6 +192,19 @@ pub(crate) fn commit_branch( }) } +/// The refusal of a publication over a head other than the one it expects. +fn head_moved( + request: &CommitRequest, + branch: &layerfs_history::records::BranchRecord, +) -> HistoryError { + HistoryError::HeadMoved(Box::new(MovedState { + expected_head: request.expected_head, + actual_head: branch.head_commit, + expected_base: request.expected_base, + actual_base: branch.base_layer, + })) +} + /// Derives, checks and inserts one Commit made on `branch` now, or verifies /// the identical record that already exists. #[allow(clippy::too_many_arguments)] diff --git a/engine/crates/layerfs-persistence/tests/branch_removal.rs b/engine/crates/layerfs-persistence/tests/branch_removal.rs index d82ff50843..3741d37fdf 100644 --- a/engine/crates/layerfs-persistence/tests/branch_removal.rs +++ b/engine/crates/layerfs-persistence/tests/branch_removal.rs @@ -85,6 +85,7 @@ fn a_removed_branch_is_hidden_and_the_epoch_bumps_once() { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); let CommitOutcome::Committed { record, .. } = outcome else { @@ -274,6 +275,7 @@ fn a_live_commit_source_still_forks() { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); let CommitOutcome::Committed { record, .. } = outcome else { diff --git a/engine/crates/layerfs-persistence/tests/commit_required_head.rs b/engine/crates/layerfs-persistence/tests/commit_required_head.rs new file mode 100644 index 0000000000..084946ed7f --- /dev/null +++ b/engine/crates/layerfs-persistence/tests/commit_required_head.rs @@ -0,0 +1,174 @@ +//! A publication made over one head only (`CommitRequest::required_head`, +//! the Workspace Commit's `--expected`): checked inside `commit_branch`'s own +//! transaction, forced or not, and a forced publication decides on the head +//! that transaction reads. The Branch advance replaces only the head the +//! transaction read (`commit_advance_branch`'s head predicate, shared by +//! both backends). Each case runs on SQLite, and on PostgreSQL when +//! `LAYERFS_TEST_POSTGRES_URL` names a server (else that half is NOT_RUN). +mod support; + +use layerfs_history::error::HistoryError; +use layerfs_history::records::{ + CommitMeta, CommitOutcome, CommitRecord, CommitRequest, CommitVia, ForkRequest, ForkSource, + StackInitialization, +}; +use layerfs_history::{BranchId, HistoryCatalog, HistoryCatalogConfig, LayerId, NodeId}; +use support::{branch_id, name, root, stack, Temp}; + +/// Runs `case` on a fresh SQLite Store, then on a fresh PostgreSQL schema +/// when a server is named. +fn on_both(tag: &str, case: impl Fn(&dyn HistoryCatalog)) { + let temp = Temp::new(tag); + let sqlite = support::sqlite::create( + &temp.join("store.sqlite"), + &HistoryCatalogConfig { + cursor_key: [61; 32], + binding_key: b"required-head".to_vec(), + incarnation: 1, + }, + ) + .expect("catalog"); + case(&sqlite); + if let Some(url) = support::pg::url() { + let schema = support::pg::Schema::new(url, &tag.replace('-', "_")); + let handles = schema.create(b"required-head", [61; 32]); + case(&handles.history); + } +} + +/// Project `proj` with one Branch `work` at its genesis Layer. +fn project(history: &dyn HistoryCatalog) -> (BranchId, LayerId) { + let record = history + .initialize_layerstack(&StackInitialization { + logical: 1, + stack: stack(1), + name: name("proj"), + scope: root(200), + profile: root(201), + genesis_root: root(1), + }) + .unwrap(); + let branch = branch_id(1); + history + .fork(&ForkRequest { + stack: stack(1), + branch, + name: name("work"), + source: ForkSource::Layer(record.head_layer), + }) + .unwrap(); + (branch, record.head_layer) +} + +/// A Commit of `tag` made over the Branch as it is now. +fn over_now(history: &dyn HistoryCatalog, branch: BranchId, tag: u8) -> CommitRequest { + let record = history.branch(branch).unwrap().unwrap(); + let expected_root = match record.head_commit { + Some(head) => history.commit(head).unwrap().unwrap().root, + None => history.layer(record.base_layer).unwrap().unwrap().root, + }; + CommitRequest { + branch, + expected_head: record.head_commit, + expected_base: record.base_layer, + expected_root, + candidate_root: root(tag), + profile: root(201), + scope: root(200), + second_parent: None, + meta: CommitMeta::new(CommitVia::Files), + force: false, + required_head: None, + } +} + +fn committed(outcome: CommitOutcome) -> (CommitRecord, Option) { + match outcome { + CommitOutcome::Committed { record, displaced } => (*record, displaced), + other => panic!("not committed: {other:?}"), + } +} + +#[test] +fn another_head_is_refused_forced_or_not() { + on_both("required-head-refused", another_head_is_refused); +} +fn another_head_is_refused(history: &dyn HistoryCatalog) { + let (branch, genesis) = project(history); + let stale = over_now(history, branch, 10); + let (first, _) = committed( + history + .commit_branch(&over_now(history, branch, 11)) + .unwrap(), + ); + for force in [false, true] { + let request = CommitRequest { + force, + required_head: Some(NodeId::Layer(genesis)), + ..stale.clone() + }; + let refused = history.commit_branch(&request).expect_err("head moved"); + assert!( + matches!(&refused, HistoryError::HeadMoved(state) + if state.actual_head == Some(first.id)), + "force {force}: {refused:?}" + ); + } + let now = history.branch(branch).unwrap().unwrap(); + assert_eq!(now.head_commit, Some(first.id), "nothing published"); +} + +#[test] +fn forced_over_the_required_head_displaces_only_it() { + on_both("required-head-forced", forced_over_the_required_head); +} +fn forced_over_the_required_head(history: &dyn HistoryCatalog) { + let (branch, _) = project(history); + let stale = over_now(history, branch, 20); + let (first, _) = committed( + history + .commit_branch(&over_now(history, branch, 21)) + .unwrap(), + ); + let (forced, displaced) = committed( + history + .commit_branch(&CommitRequest { + force: true, + required_head: Some(NodeId::Commit(first.id)), + ..stale + }) + .unwrap(), + ); + assert_eq!(displaced, Some(first.id)); + assert_eq!(forced.parent, None, "keeps its captured parent"); + let now = history.branch(branch).unwrap().unwrap(); + assert_eq!(now.head_commit, Some(forced.id)); +} + +/// A forced request built before the head moved twice displaces the head +/// its own transaction reads, the newest; the one between stays on that +/// head's first-parent chain. +#[test] +fn force_decides_on_the_head_its_transaction_reads() { + on_both("required-head-force-reads", force_reads_in_its_transaction); +} +fn force_reads_in_its_transaction(history: &dyn HistoryCatalog) { + let (branch, _) = project(history); + let stale = CommitRequest { + force: true, + ..over_now(history, branch, 30) + }; + let (first, _) = committed( + history + .commit_branch(&over_now(history, branch, 31)) + .unwrap(), + ); + let (second, _) = committed( + history + .commit_branch(&over_now(history, branch, 32)) + .unwrap(), + ); + let (_, displaced) = committed(history.commit_branch(&stale).unwrap()); + assert_eq!(displaced, Some(second.id)); + assert_eq!(second.parent, Some(first.id)); +} diff --git a/engine/crates/layerfs-persistence/tests/diagnostic_facts.rs b/engine/crates/layerfs-persistence/tests/diagnostic_facts.rs index 40c9e646d8..604b82ff8a 100644 --- a/engine/crates/layerfs-persistence/tests/diagnostic_facts.rs +++ b/engine/crates/layerfs-persistence/tests/diagnostic_facts.rs @@ -45,6 +45,7 @@ fn fixture() -> Fixture { second_parent: None, force: false, meta, + required_head: None, }) .unwrap(); f diff --git a/engine/crates/layerfs-persistence/tests/diagnostic_history.rs b/engine/crates/layerfs-persistence/tests/diagnostic_history.rs index dbd394fa91..1387ec6d64 100644 --- a/engine/crates/layerfs-persistence/tests/diagnostic_history.rs +++ b/engine/crates/layerfs-persistence/tests/diagnostic_history.rs @@ -45,6 +45,7 @@ fn commit(f: &Fixture, b: BranchId, n: u8, second: Option) -> CommitReco second_parent: second, force: false, meta: CommitMeta::new(CommitVia::Files), + required_head: None, }) .unwrap() else { @@ -169,6 +170,7 @@ fn valid_forced_history_and_removed_project_retained_objects_pass() { second_parent: None, force: true, meta: CommitMeta::new(CommitVia::Files), + required_head: None, }) .unwrap(); assert!(matches!(result, CommitOutcome::Committed { .. })); diff --git a/engine/crates/layerfs-persistence/tests/diagnostic_namespace.rs b/engine/crates/layerfs-persistence/tests/diagnostic_namespace.rs index 4af4f553d7..dec21af40a 100644 --- a/engine/crates/layerfs-persistence/tests/diagnostic_namespace.rs +++ b/engine/crates/layerfs-persistence/tests/diagnostic_namespace.rs @@ -155,6 +155,7 @@ fn c09_old_corrupt_namespace_is_checked_after_current_head_becomes_valid() { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() else { diff --git a/engine/crates/layerfs-persistence/tests/diagnostic_overwrite.rs b/engine/crates/layerfs-persistence/tests/diagnostic_overwrite.rs index 6e7a35f476..6bb438f922 100644 --- a/engine/crates/layerfs-persistence/tests/diagnostic_overwrite.rs +++ b/engine/crates/layerfs-persistence/tests/diagnostic_overwrite.rs @@ -41,6 +41,7 @@ impl Graph<'_> { second_parent: second, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); match result { diff --git a/engine/crates/layerfs-persistence/tests/epoch_fence.rs b/engine/crates/layerfs-persistence/tests/epoch_fence.rs index 6e8462c475..d47be6242f 100644 --- a/engine/crates/layerfs-persistence/tests/epoch_fence.rs +++ b/engine/crates/layerfs-persistence/tests/epoch_fence.rs @@ -84,6 +84,7 @@ fn commit_request(history: &dyn HistoryCatalog, branch: BranchId, tag: u8) -> Co second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, } } diff --git a/engine/crates/layerfs-persistence/tests/gc_backfill.rs b/engine/crates/layerfs-persistence/tests/gc_backfill.rs index ac659a54b0..87e1ee0ca9 100644 --- a/engine/crates/layerfs-persistence/tests/gc_backfill.rs +++ b/engine/crates/layerfs-persistence/tests/gc_backfill.rs @@ -136,6 +136,7 @@ fn commit(handles: &SqliteHandles, branch: BranchId, tag: u8) -> CommitRecord { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/heads.rs b/engine/crates/layerfs-persistence/tests/heads.rs index c5420eb05c..693e461f16 100644 --- a/engine/crates/layerfs-persistence/tests/heads.rs +++ b/engine/crates/layerfs-persistence/tests/heads.rs @@ -44,6 +44,7 @@ fn commit(history: &dyn HistoryCatalog, branch: BranchId, tag: u8) { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); assert!( diff --git a/engine/crates/layerfs-persistence/tests/history_remediation.rs b/engine/crates/layerfs-persistence/tests/history_remediation.rs index bf1614cac3..5b6cc7fff8 100644 --- a/engine/crates/layerfs-persistence/tests/history_remediation.rs +++ b/engine/crates/layerfs-persistence/tests/history_remediation.rs @@ -37,6 +37,7 @@ fn append(c: &dyn HistoryCatalog, b: BranchId, n: u8) -> CommitRecord { second_parent: None, meta: CommitMeta::new(CommitVia::Workspace), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/kept_node.rs b/engine/crates/layerfs-persistence/tests/kept_node.rs index 5d65fc5ca2..8416167553 100644 --- a/engine/crates/layerfs-persistence/tests/kept_node.rs +++ b/engine/crates/layerfs-persistence/tests/kept_node.rs @@ -126,6 +126,7 @@ fn commit(handles: &SqliteHandles, branch: BranchId, tag: u8) -> CommitRecord { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/kept_node_closure.rs b/engine/crates/layerfs-persistence/tests/kept_node_closure.rs index ab3e646520..2e1a530809 100644 --- a/engine/crates/layerfs-persistence/tests/kept_node_closure.rs +++ b/engine/crates/layerfs-persistence/tests/kept_node_closure.rs @@ -128,6 +128,7 @@ fn commits(handles: &SqliteHandles, branch: BranchId, seed: u64, count: u64) -> second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/kept_objects.rs b/engine/crates/layerfs-persistence/tests/kept_objects.rs index c25913fae4..99360f6552 100644 --- a/engine/crates/layerfs-persistence/tests/kept_objects.rs +++ b/engine/crates/layerfs-persistence/tests/kept_objects.rs @@ -93,6 +93,7 @@ fn commit(handles: &SqliteHandles, branch: BranchId, candidate_root: ObjectId) - second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/kept_objects_bounded.rs b/engine/crates/layerfs-persistence/tests/kept_objects_bounded.rs index 09e04e6b52..4f3f2b1d51 100644 --- a/engine/crates/layerfs-persistence/tests/kept_objects_bounded.rs +++ b/engine/crates/layerfs-persistence/tests/kept_objects_bounded.rs @@ -142,6 +142,7 @@ fn retain(handles: &SqliteHandles, roots: &[ObjectId]) { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/layerstack_removal.rs b/engine/crates/layerfs-persistence/tests/layerstack_removal.rs index 60e2b84f71..6c11385d19 100644 --- a/engine/crates/layerfs-persistence/tests/layerstack_removal.rs +++ b/engine/crates/layerfs-persistence/tests/layerstack_removal.rs @@ -69,6 +69,7 @@ fn commit(history: &dyn HistoryCatalog, branch: BranchId, tag: u8) -> CommitReco second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); let CommitOutcome::Committed { record, .. } = outcome else { diff --git a/engine/crates/layerfs-persistence/tests/lineage_backfill.rs b/engine/crates/layerfs-persistence/tests/lineage_backfill.rs index 8397172abb..15ed2e6300 100644 --- a/engine/crates/layerfs-persistence/tests/lineage_backfill.rs +++ b/engine/crates/layerfs-persistence/tests/lineage_backfill.rs @@ -147,6 +147,7 @@ impl Builder<'_> { second_parent: second, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); let CommitOutcome::Committed { record, .. } = outcome else { diff --git a/engine/crates/layerfs-persistence/tests/path_removal.rs b/engine/crates/layerfs-persistence/tests/path_removal.rs index 06e4510c72..847df30ed1 100644 --- a/engine/crates/layerfs-persistence/tests/path_removal.rs +++ b/engine/crates/layerfs-persistence/tests/path_removal.rs @@ -54,6 +54,7 @@ fn commit(history: &dyn HistoryCatalog, branch: BranchId, tag: u8) -> CommitReco second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); let CommitOutcome::Committed { record, .. } = outcome else { diff --git a/engine/crates/layerfs-persistence/tests/postgresql_commit_round_trips.rs b/engine/crates/layerfs-persistence/tests/postgresql_commit_round_trips.rs index 9515ce1e28..fd4c0f7592 100644 --- a/engine/crates/layerfs-persistence/tests/postgresql_commit_round_trips.rs +++ b/engine/crates/layerfs-persistence/tests/postgresql_commit_round_trips.rs @@ -213,6 +213,7 @@ fn run(engine: &Engine<'_>, branch: BranchId) -> Vec<(&'static str, Delta)> { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); drop(lane); diff --git a/engine/crates/layerfs-persistence/tests/postgresql_compact.rs b/engine/crates/layerfs-persistence/tests/postgresql_compact.rs index 65d74746b3..289f474ad6 100644 --- a/engine/crates/layerfs-persistence/tests/postgresql_compact.rs +++ b/engine/crates/layerfs-persistence/tests/postgresql_compact.rs @@ -313,6 +313,7 @@ fn commit( second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/postgresql_compact_fixtures.rs b/engine/crates/layerfs-persistence/tests/postgresql_compact_fixtures.rs index dbf7faca07..29dd0a265a 100644 --- a/engine/crates/layerfs-persistence/tests/postgresql_compact_fixtures.rs +++ b/engine/crates/layerfs-persistence/tests/postgresql_compact_fixtures.rs @@ -609,6 +609,7 @@ fn commit_request( second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, } } @@ -639,6 +640,7 @@ fn commit( second_parent: None, meta, force: false, + required_head: None, }) .expect("commit") { diff --git a/engine/crates/layerfs-persistence/tests/postgresql_identical_ids.rs b/engine/crates/layerfs-persistence/tests/postgresql_identical_ids.rs index 000ce2ea39..e9addb9b11 100644 --- a/engine/crates/layerfs-persistence/tests/postgresql_identical_ids.rs +++ b/engine/crates/layerfs-persistence/tests/postgresql_identical_ids.rs @@ -85,6 +85,7 @@ fn commit(history: &dyn HistoryCatalog, branch: BranchId, candidate: ObjectId) - second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); let CommitOutcome::Committed { record, .. } = outcome else { diff --git a/engine/crates/layerfs-persistence/tests/postgresql_position_columns.rs b/engine/crates/layerfs-persistence/tests/postgresql_position_columns.rs index acc3116d94..e2dfee01fd 100644 --- a/engine/crates/layerfs-persistence/tests/postgresql_position_columns.rs +++ b/engine/crates/layerfs-persistence/tests/postgresql_position_columns.rs @@ -187,6 +187,7 @@ fn commit(handles: &PostgresHandles, branch: BranchId, tag: u8) -> CommitRecord second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/sqlite_compact.rs b/engine/crates/layerfs-persistence/tests/sqlite_compact.rs index 6a2a4c735b..3a622c7a3b 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_compact.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_compact.rs @@ -287,6 +287,7 @@ fn commit(handles: &SqliteHandles, branch: BranchId, candidate_root: ObjectId) - second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/sqlite_compact_crash.rs b/engine/crates/layerfs-persistence/tests/sqlite_compact_crash.rs index ea4f8ae1b7..46be61ce4a 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_compact_crash.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_compact_crash.rs @@ -240,6 +240,7 @@ fn commit(handles: &SqliteHandles, branch: BranchId, candidate_root: ObjectId) - second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/sqlite_compact_fixtures.rs b/engine/crates/layerfs-persistence/tests/sqlite_compact_fixtures.rs index 194d52d48f..fc05416d1d 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_compact_fixtures.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_compact_fixtures.rs @@ -355,6 +355,7 @@ fn commit( second_parent: None, meta, force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/sqlite_compact_matrix.rs b/engine/crates/layerfs-persistence/tests/sqlite_compact_matrix.rs index d85c08b4b2..866c8cb5bc 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_compact_matrix.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_compact_matrix.rs @@ -705,6 +705,7 @@ fn commit_once(path: &Path) -> Result<(Vec, [u8; 32]), String> { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }); match outcome { Ok(CommitOutcome::Committed { record, .. }) => { diff --git a/engine/crates/layerfs-persistence/tests/store_diagnostic.rs b/engine/crates/layerfs-persistence/tests/store_diagnostic.rs index 379489242a..f7b86f127a 100644 --- a/engine/crates/layerfs-persistence/tests/store_diagnostic.rs +++ b/engine/crates/layerfs-persistence/tests/store_diagnostic.rs @@ -250,6 +250,7 @@ fn independent_history_lineage_checks_accept_real_forks_and_detect_damage() { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); let CommitOutcome::Committed { record, .. } = outcome else { diff --git a/engine/crates/layerfs-persistence/tests/support/marks.rs b/engine/crates/layerfs-persistence/tests/support/marks.rs index 96473d0265..1dbc64b594 100644 --- a/engine/crates/layerfs-persistence/tests/support/marks.rs +++ b/engine/crates/layerfs-persistence/tests/support/marks.rs @@ -143,6 +143,7 @@ pub fn retain(handles: &SqliteHandles, roots: &[ObjectId]) { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap() { diff --git a/engine/crates/layerfs-persistence/tests/support/pg.rs b/engine/crates/layerfs-persistence/tests/support/pg.rs index 5952125420..fd48ea16bb 100644 --- a/engine/crates/layerfs-persistence/tests/support/pg.rs +++ b/engine/crates/layerfs-persistence/tests/support/pg.rs @@ -161,6 +161,7 @@ pub fn commit_request( second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, } } diff --git a/engine/crates/layerfs-store-service/src/store/commit.rs b/engine/crates/layerfs-store-service/src/store/commit.rs index a3cfdffdde..979c2e7ebc 100644 --- a/engine/crates/layerfs-store-service/src/store/commit.rs +++ b/engine/crates/layerfs-store-service/src/store/commit.rs @@ -5,13 +5,39 @@ use super::{ }; use crate::telemetry::phase; use layerfs_content::filesystem::FilesystemRootId; -use layerfs_history::{BranchSnapshot, CommitMeta, CommitOutcome, CommitRequest, CommitVia}; +use layerfs_history::{ + error::MovedState, BranchSnapshot, CommitMeta, CommitOutcome, CommitRequest, CommitVia, + HistoryError, NodeId, +}; use layerfs_overlay::Capture; use layerfs_storage::Save; use layerfs_telemetry::timer::{Active, TimingScope}; use layerfs_workspace::WorkspaceError; use std::sync::{atomic::Ordering, Arc}; +/// The node a Branch answers as its head: its head Commit, else its base +/// Layer (`branch get`, `--expected`). +fn answered(snapshot: &BranchSnapshot) -> NodeId { + snapshot + .branch + .head_commit + .map_or(NodeId::Layer(snapshot.branch.base_layer), NodeId::Commit) +} + +/// `HeadMoved` for a Branch whose head is not the `expected` one. +fn expected_moved(expected: NodeId, current: &BranchSnapshot) -> CommitError { + let (expected_head, expected_base) = match expected { + NodeId::Commit(id) => (Some(id), current.branch.base_layer), + NodeId::Layer(layer) => (None, layer), + }; + CommitError::History(HistoryError::HeadMoved(Box::new(MovedState { + expected_head, + actual_head: current.branch.head_commit, + expected_base, + actual_base: current.branch.base_layer, + }))) +} + /// Admission belongs to exactly one invocation. It stays held unless that /// invocation establishes a safe disposition, including its captured releases. /// Unwinding or an unknown result conservatively retains admission. @@ -210,6 +236,13 @@ impl BoundWorkspace { })?; let moved = current.branch.head_commit != snapshot.branch.head_commit || current.branch.base_layer != snapshot.branch.base_layer; + // `expected`: the Commit is made over that head only; the + // publication checks it again in its own transaction. + if let Some(expected) = options.expected { + if answered(¤t) != expected { + return Err(expected_moved(expected, ¤t)); + } + } let root = if moved && !force { let (root, report) = phase(timing, "merge", || { self.merge_candidate(&save, &snapshot, ¤t, candidate) @@ -278,8 +311,10 @@ impl BoundWorkspace { .map_err(CommitError::History) })?) }; - let (current, root, moved, logical) = if force || conflicted { - (current, root, moved, logical) + // A forced Commit is decided by the publication itself, + // which reads the head inside the lane. + let (current, root, logical) = if force || conflicted { + (current, root, logical) } else { let now = phase(timing, "head.lane", || { self.store @@ -288,10 +323,13 @@ impl BoundWorkspace { .map_err(CommitError::History)? .ok_or(CommitError::Context("bound Branch is absent")) })?; - if now.branch.head_commit == current.branch.head_commit - && now.branch.base_layer == current.branch.base_layer + // With `expected`, a head that moved again is not merged + // with: the publication refuses it `HeadMoved`. + if (now.branch.head_commit == current.branch.head_commit + && now.branch.base_layer == current.branch.base_layer) + || options.expected.is_some() { - (current, root, moved, logical) + (current, root, logical) } else { // The in-lane step has its own Save; its count and // hints cover only what it changed in the result. @@ -328,13 +366,13 @@ impl BoundWorkspace { }, None => step, }); - (now, stepped, true, logical) + (now, stepped, logical) } }; - Ok((root, candidate, current, moved, logical, lane, early)) + Ok((root, candidate, current, logical, lane, early)) })(); retained.storage = Some(super::producer::since(storage.diagnostics(), before)); - let (candidate, ours, current, moved, logical, lane, early) = built?; + let (candidate, ours, current, logical, lane, early) = built?; if candidate != ours { replaced = Some((ours.0, candidate.0)); } @@ -391,7 +429,10 @@ impl BoundWorkspace { .map_or_else(Vec::new, |report| report.lww.clone()), ..CommitMeta::new(via) }, - force: force && moved, + // The transaction reads the head in the lane: forced + // over whatever head it finds there, unless `expected`. + force, + required_head: options.expected, }); } retained.phase = CommitPhase::Validate; diff --git a/engine/crates/layerfs-store-service/src/store/commit_types.rs b/engine/crates/layerfs-store-service/src/store/commit_types.rs index 9a6e67bef9..4011a3d41c 100644 --- a/engine/crates/layerfs-store-service/src/store/commit_types.rs +++ b/engine/crates/layerfs-store-service/src/store/commit_types.rs @@ -92,6 +92,12 @@ pub struct CommitOptions { pub force: bool, /// Description of the captured filesystem change. pub message: Option, + /// The head the Commit must be made over (`--expected`): the node the + /// Branch answers as its head, its head Commit or else its base Layer. + /// Checked when the head is read and again inside the publication's + /// own transaction; another head is refused `HeadMoved` and nothing is + /// published. A forced Commit then displaces only this head. + pub expected: Option, } /// A Commit merged with a Branch head that moved since the Workspace bound. #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/engine/crates/layerfs-store-service/src/write/files.rs b/engine/crates/layerfs-store-service/src/write/files.rs index c877109a27..3c02e8c89a 100644 --- a/engine/crates/layerfs-store-service/src/write/files.rs +++ b/engine/crates/layerfs-store-service/src/write/files.rs @@ -125,6 +125,7 @@ pub fn commit( &crate::store::CommitOptions { force: false, message: Some(message.unwrap_or("Apply filesystem changes").to_owned()), + expected: None, }, CommitVia::Files, ); diff --git a/engine/crates/layerfs-store-service/tests/commit_expected.rs b/engine/crates/layerfs-store-service/tests/commit_expected.rs new file mode 100644 index 0000000000..398ddce9b3 --- /dev/null +++ b/engine/crates/layerfs-store-service/tests/commit_expected.rs @@ -0,0 +1,231 @@ +//! A Workspace Commit made over one head only (`CommitOptions::expected`, +//! `--expected`) and a forced Commit. The expected head is checked when the +//! head is read and again inside the publication's own transaction, so a +//! head that moves after the check, even inside the lane, is refused +//! `HeadMoved` with nothing published. A forced Commit is decided by the +//! head its publication reads in the lane, not by a read before it. +#[path = "support/installed_store.rs"] +#[allow(dead_code)] +mod installed; +#[path = "support/live.rs"] +#[allow(dead_code)] +mod live; +#[path = "support/sdk.rs"] +#[allow(dead_code)] +mod support; + +use layerfs_history::{CommitId, CommitOutcome, HistoryError, NodeId}; +use layerfs_store_service::store::{BoundWorkspace, CommitError, CommitOptions, CommitPhase}; +use layerfs_store_service::telemetry::{mark_phases, Recording}; +use std::{cell::Cell, sync::Once}; +use support::Change; + +fn tmp() { + static SET: Once = Once::new(); + SET.call_once(|| std::env::set_var("TMPDIR", env!("CARGO_TARGET_TMPDIR"))); +} + +fn base(source: &std::path::Path) -> usize { + std::fs::write(source.join("a.txt"), b"alpha\n").unwrap(); + std::fs::write(source.join("b.txt"), b"bravo\n").unwrap(); + 2 +} + +fn head(fixture: &support::Fixture) -> Option { + fixture + .service + .store + .history() + .branch_snapshot(live::branch("lane")) + .unwrap() + .unwrap() + .branch + .head_commit +} + +/// Another Workspace commits `bytes` to `/b.txt` on the lane. +fn land(fixture: &support::Fixture, id: u8, bytes: &[u8]) -> CommitId { + fixture.workspace_commit("lane", &[Change::Write("/b.txt", bytes)], id, || {}); + head(fixture).expect("landed") +} + +fn options(force: bool, expected: Option) -> CommitOptions { + CommitOptions { + force, + message: Some("expected".into()), + expected: expected.map(NodeId::Commit), + } +} + +/// Commits `workspace` while, as the lane is about to be taken, another +/// Workspace lands a Commit on the lane: the head moves inside the window +/// a read before the lane cannot see. +fn commit_racing_lane( + fixture: &support::Fixture, + workspace: &BoundWorkspace, + options: &CommitOptions, + lander: u8, +) -> ( + Result< + layerfs_store_service::store::CommitSuccess, + Box, + >, + CommitId, +) { + let landed = std::rc::Rc::new(Cell::new(None)); + let busy = std::rc::Rc::new(Cell::new(false)); + let set = landed.clone(); + let host = fixture as *const support::Fixture as usize; + let recording = Recording::start(); + mark_phases(Some(Box::new(move |name, end| { + // Once, at the first lane of this Commit; the landing Commit's own + // phases pass through here too and are ignored. + if name == "lane" && !end && set.get().is_none() && !busy.get() { + // SAFETY: the fixture outlives this Commit, which runs on this + // thread; the hook is removed before the fixture is used again. + let fixture = unsafe { &*(host as *const support::Fixture) }; + busy.set(true); + // Bytes of its own, so the landing is never UpToDate. + let bytes = format!("landed by {lander}\n"); + set.set(Some(land(fixture, lander, bytes.as_bytes()))); + busy.set(false); + } + }))); + let result = workspace.commit_captured(options); + mark_phases(None); + drop(recording); + ( + result, + landed.get().expect("a Commit landed before the lane"), + ) +} + +#[test] +fn a_moved_expected_head_is_refused_before_the_merge() { + tmp(); + let fixture = support::Fixture::new("expected-moved", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 61, "lane"); + let bound = head(&fixture); + live::change(&workspace, &[Change::Write("/a.txt", b"ours!\n")]); + let theirs = land(&fixture, 62, b"theirs\n"); + let refused = workspace + .commit_captured(&CommitOptions { + expected: Some(match bound { + Some(id) => NodeId::Commit(id), + None => NodeId::Layer( + fixture + .service + .store + .history() + .branch_snapshot(live::branch("lane")) + .unwrap() + .unwrap() + .branch + .base_layer, + ), + }), + ..options(false, None) + }) + .expect_err("head moved"); + assert!( + matches!( + &refused.error, + CommitError::History(HistoryError::HeadMoved(_)) + ), + "{refused:?}" + ); + assert!(refused.locally_settled, "{refused:?}"); + assert_eq!(head(&fixture), Some(theirs), "nothing published"); + // The change is kept; over the head it now expects, it merges. + let merged = workspace + .commit_captured(&options(false, Some(theirs))) + .unwrap_or_else(|failure| panic!("{failure:?}")); + assert!(merged.merge.is_some(), "merged"); + assert_eq!( + live::committed(&fixture, "lane", "/a.txt").as_deref(), + Some("ours!\n") + ); + workspace.close().unwrap(); + fixture.cleanup(); +} + +/// The head moves after the expected head was checked and merged with: +/// the in-lane step does not merge with it and the publication refuses it. +#[test] +fn an_expected_head_that_moves_in_the_lane_is_refused() { + tmp(); + let fixture = support::Fixture::new("expected-lane", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 63, "lane"); + live::change(&workspace, &[Change::Write("/a.txt", b"ours!\n")]); + land(&fixture, 64, b"theirs\n"); + for force in [false, true] { + // Expected: the head as it is now, which the head read sees. + let expected = head(&fixture); + let (result, landed) = commit_racing_lane( + &fixture, + &workspace, + &options(force, expected), + 70 + u8::from(force), + ); + let refused = result.expect_err("head moved in the lane"); + assert!( + matches!( + &refused.error, + CommitError::History(HistoryError::HeadMoved(_)) + ), + "force {force}: {refused:?}" + ); + assert_eq!(refused.phase, CommitPhase::Publish, "{refused:?}"); + assert!(refused.locally_settled, "{refused:?}"); + assert_eq!(head(&fixture), Some(landed), "nothing published"); + } + assert_eq!(live::live(&workspace, "/a.txt").unwrap(), b"ours!\n"); + workspace.close().unwrap(); + fixture.cleanup(); +} + +/// A forced Commit over a head that was unmoved before the lane and moved +/// inside it publishes over the head the publication reads, displacing it. +#[test] +fn force_publishes_over_the_head_read_in_the_lane() { + tmp(); + let fixture = support::Fixture::new("force-lane", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 65, "lane"); + live::change(&workspace, &[Change::Write("/a.txt", b"forced\n")]); + let (result, landed) = commit_racing_lane(&fixture, &workspace, &options(true, None), 72); + let committed = result.unwrap_or_else(|failure| panic!("{failure:?}")); + let Some(CommitOutcome::Committed { displaced, record }) = committed.history else { + panic!("{:?}", committed.history); + }; + assert_eq!(displaced, Some(landed)); + assert_eq!(head(&fixture), Some(record.id)); + assert_eq!( + live::committed(&fixture, "lane", "/a.txt").as_deref(), + Some("forced\n") + ); + workspace.close().unwrap(); + fixture.cleanup(); +} + +/// `--force --expected` displaces exactly the expected head. +#[test] +fn force_with_expected_displaces_that_head() { + tmp(); + let fixture = support::Fixture::new("force-expected", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 66, "lane"); + live::change(&workspace, &[Change::Write("/a.txt", b"forced\n")]); + let theirs = land(&fixture, 67, b"theirs\n"); + let committed = workspace + .commit_captured(&options(true, Some(theirs))) + .unwrap_or_else(|failure| panic!("{failure:?}")); + let Some(CommitOutcome::Committed { displaced, .. }) = committed.history else { + panic!("{:?}", committed.history); + }; + assert_eq!(displaced, Some(theirs)); + workspace.close().unwrap(); + fixture.cleanup(); +} diff --git a/engine/crates/layerfs-store-service/tests/commit_pipeline.rs b/engine/crates/layerfs-store-service/tests/commit_pipeline.rs index 9542cdfbc7..83b3477fa7 100644 --- a/engine/crates/layerfs-store-service/tests/commit_pipeline.rs +++ b/engine/crates/layerfs-store-service/tests/commit_pipeline.rs @@ -131,6 +131,7 @@ fn options() -> CommitOptions { CommitOptions { force: false, message: Some("pipeline".into()), + expected: None, } } diff --git a/engine/crates/layerfs-store-service/tests/commit_reclaim.rs b/engine/crates/layerfs-store-service/tests/commit_reclaim.rs index f916cac764..f69631be46 100644 --- a/engine/crates/layerfs-store-service/tests/commit_reclaim.rs +++ b/engine/crates/layerfs-store-service/tests/commit_reclaim.rs @@ -94,6 +94,7 @@ fn committed(fixture: &support::Fixture, id: u8) -> (BoundWorkspace, Vec) { .commit_captured(&CommitOptions { force: false, message: Some("new file".into()), + expected: None, }) .unwrap_or_else(|failure| panic!("Workspace Commit: {failure:?}")); assert!(matches!( diff --git a/engine/crates/layerfs-store-service/tests/commit_settle.rs b/engine/crates/layerfs-store-service/tests/commit_settle.rs index 0a1cb9946b..cc36775530 100644 --- a/engine/crates/layerfs-store-service/tests/commit_settle.rs +++ b/engine/crates/layerfs-store-service/tests/commit_settle.rs @@ -37,7 +37,7 @@ fn options() -> CommitOptions { CommitOptions { force: false, message: Some("settle".into()), - ..CommitOptions::default() + expected: None, } } diff --git a/engine/crates/layerfs-store-service/tests/postgresql_phase_attribution.rs b/engine/crates/layerfs-store-service/tests/postgresql_phase_attribution.rs index 79d85787ba..c5b1a3c384 100644 --- a/engine/crates/layerfs-store-service/tests/postgresql_phase_attribution.rs +++ b/engine/crates/layerfs-store-service/tests/postgresql_phase_attribution.rs @@ -532,6 +532,7 @@ impl Run { workspace.commit_captured(&CommitOptions { force: false, message: Some(label.to_owned()), + expected: None, }) }, vec![], diff --git a/engine/crates/layerfs-store-service/tests/postgresql_round_trips.rs b/engine/crates/layerfs-store-service/tests/postgresql_round_trips.rs index 13ac05db87..8ccac7dc84 100644 --- a/engine/crates/layerfs-store-service/tests/postgresql_round_trips.rs +++ b/engine/crates/layerfs-store-service/tests/postgresql_round_trips.rs @@ -531,6 +531,7 @@ impl Run { workspace.commit_captured(&CommitOptions { force: false, message: Some(name.to_owned()), + expected: None, }) }); let reports = recording.finish(); diff --git a/engine/crates/layerfs-store-service/tests/relink_commit.rs b/engine/crates/layerfs-store-service/tests/relink_commit.rs index 9535e0d8b1..69fc773241 100644 --- a/engine/crates/layerfs-store-service/tests/relink_commit.rs +++ b/engine/crates/layerfs-store-service/tests/relink_commit.rs @@ -191,6 +191,7 @@ fn relink( &layerfs_store_service::store::CommitOptions { force: false, message: Some("relink".to_owned()), + expected: None, }, CommitVia::Files, ) diff --git a/engine/crates/layerfs-store-service/tests/scale_lineage_cap.rs b/engine/crates/layerfs-store-service/tests/scale_lineage_cap.rs index 0f9a45b8e3..a1a9792bfc 100644 --- a/engine/crates/layerfs-store-service/tests/scale_lineage_cap.rs +++ b/engine/crates/layerfs-store-service/tests/scale_lineage_cap.rs @@ -121,6 +121,7 @@ fn commit(fixture: &Fixture, name: &str, root: ObjectId) -> CommitId { second_parent: None, meta: CommitMeta::new(CommitVia::Files), force: false, + required_head: None, }) .unwrap(); let CommitOutcome::Committed { record, .. } = outcome else { diff --git a/engine/crates/layerfs-store-service/tests/support/sdk.rs b/engine/crates/layerfs-store-service/tests/support/sdk.rs index 1473727ec3..531ef15072 100644 --- a/engine/crates/layerfs-store-service/tests/support/sdk.rs +++ b/engine/crates/layerfs-store-service/tests/support/sdk.rs @@ -322,6 +322,7 @@ impl Fixture { .commit_captured(&CommitOptions { force: false, message: Some("Workspace changes".into()), + expected: None, }) .unwrap_or_else(|failure| panic!("Workspace Commit: {failure:?}")); workspace.close().unwrap(); From 54e4913c5f6fb3aac1c281d1108440e5ce6f7dd3 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 14:56:53 +0800 Subject: [PATCH 3/6] Commit: refuse a merged install that overlaps the live generation Finding #1 (merged install over the live generation): a Commit that merged with a head that moved installs the merged root as the new base under rows written after its capture. Those rows hold absolute facts (size, inherited cutoff, link and entry counts) computed against the old base, so a row the merge changed under was silently wrong: a touch after the capture truncated or zero-filled a file the merge lengthened, a removal under a directory the merge added to counted the directory empty, and a write in the Commit's window could land between the check and the install. A carried mtime-only row (keep_live_row) kept the old base's facts after the merge changed the file. And UpToDate (the merge equal to the head) installed over a view that still differed. Now, after the merge, the Commit collects the serials whose stored inode value differs between its constructed root and the merged root (inode_differences, first-stage and in-lane merges unioned). When the merged candidate differs from its own root it takes a MutationHold on the Workspace (store-service overlay/hold.rs: later mutations wait behind it as behind a waiting Capture), then reads the active generation's inode rows and name bindings a window at a time. An inode row of a changed serial, or a binding under a changed directory, is an overlap: the Commit drops the hold and the lane and refuses with the new definite CommitError::LiveConflict (paths named best effort, at most 16; daemon code Busy). Nothing is published and the capture folds back. With no overlap the hold lasts through publication and install, so no checked row changes before the new base is in place; the install (Overlay::install_merged) deletes carried mtime-only rows whose serial the merge changed, so they fall through to the merged base. The UpToDate case runs the same check, because its candidate is the merged head. Docs in the same commit: engine/commit (results, phases, limits), flows/commit, engine/overlay/lifetimes, core/compare-and-merge, engine/workspace. Tests (new engine/crates/layerfs-store-service/tests/commit_live_merge.rs): a touched file is not truncated by a longer merge; rm d/x after the capture with the merge adding d/y is refused; a write in the Commit window to a merged file is refused; rows under a directory the merge replaced are refused; a merge with no overlap publishes and installs; a held Workspace delays mutations until the hold ends (owner level: a Commit-level window test would need the harness to mutate while holding a counted base source, which no product caller does). With the check disabled the first four fail (the touch left the file truncated to 11 bytes). No test deleted. Production LOC: 206,681 -> 206,898 (delta +217) core 40,989 -> 40,989 (0) engine 96,001 -> 96,218 (+217) layerfs-daemon +8, layerfs-overlay +36, layerfs-store-service +163, layerfs-workspace +10 control 59,366 -> 59,366 (0) api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent c7eb6ac1f6 and the committed tree Co-Authored-By: Claude Opus 5.5 --- .../core/compare-and-merge/README.md | 5 +- docs/architecture/engine/commit/README.md | 13 +- docs/architecture/engine/overlay/lifetimes.md | 5 +- docs/architecture/engine/workspace/README.md | 2 +- docs/architecture/flows/commit.md | 8 +- .../layerfs-daemon/src/control/failure.rs | 10 + .../src/lifetime/generation.rs | 47 +++ .../crates/layerfs-store-service/src/lib.rs | 2 +- .../layerfs-store-service/src/overlay/hold.rs | 44 ++- .../src/overlay/state.rs | 10 +- .../layerfs-store-service/src/store/commit.rs | 33 +- .../src/store/commit_types.rs | 8 + .../layerfs-store-service/src/store/live.rs | 137 ++++++++ .../layerfs-store-service/src/store/mod.rs | 2 + .../tests/commit_live_merge.rs | 304 ++++++++++++++++++ .../src/workspace/install.rs | 19 +- 16 files changed, 630 insertions(+), 19 deletions(-) create mode 100644 engine/crates/layerfs-store-service/src/store/live.rs create mode 100644 engine/crates/layerfs-store-service/tests/commit_live_merge.rs diff --git a/docs/architecture/core/compare-and-merge/README.md b/docs/architecture/core/compare-and-merge/README.md index 17b54ebff2..3d24c06d30 100644 --- a/docs/architecture/core/compare-and-merge/README.md +++ b/docs/architecture/core/compare-and-merge/README.md @@ -55,7 +55,10 @@ A conflict is decided, not left open: text files get marker blocks, binary or type conflicts keep one side, and each path is listed with a `ConflictKind`. `branch.merge` refuses a conflicted result; merge-on-commit installs it as the Workspace's base and refuses the next Commit while a listed file still holds a -complete marker block ([Merge](merge.md)). +complete marker block ([Merge](merge.md)). The Workspace's view changes where +the merge changed it; a merge whose changes rows written after the capture +cover is not installed at all, clean or conflicted (`LiveConflict`, +[Commit](../../engine/commit/README.md#what-it-does)). ### Tree comparison diff --git a/docs/architecture/engine/commit/README.md b/docs/architecture/engine/commit/README.md index f6c826de33..69095957c1 100644 --- a/docs/architecture/engine/commit/README.md +++ b/docs/architecture/engine/commit/README.md @@ -38,7 +38,8 @@ Capturing a Workspace's published frontier, constructing it, publishing a Commit `BoundWorkspace::commit_admitted` runs every phase on the Commit thread; each phase is a telemetry child (`uptodate.state`, `capture`, `producer`, `begin`, `construct`, `head`, `merge`, `finish`, `validate`, `lane`, `head.lane`, -`publish`, `install`). +`live`, `publish`, `install`; a merge adds `merge.changed`, and an in-lane +step `merge.lane.changed`). | Phase (`CommitPhase`) | Lock held | Source | | --- | --- | --- | @@ -69,8 +70,9 @@ phase is a telemetry child (`uptodate.state`, `capture`, `producer`, `begin`, | `expected` (`--expected`) | `CommitOptions::expected`, the node the Branch must answer as its head, is checked when the head is read (another head: `HeadMoved` before any merge) and travels in the publish intent as `CommitRequest::required_head`, checked again inside `commit_branch`'s transaction. A head that moves again before the lane is not merged with; the publication refuses it. With `force`, only that head is displaced | [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs), [`history/commit.rs`](../../../../engine/crates/layerfs-persistence/src/history/commit.rs) | | Relink (unlink and re-create with equal bytes) | A fresh chunked file whose overlay digest names an already saved root reuses it (`files_reused`); others are built and `record_file_digests` stores their digest. Files below the Store's `small_file_threshold_bytes` are rebuilt to the same object id | [`digests.rs`](../../../../engine/crates/layerfs-store-service/src/store/digests.rs), [`digest.rs`](../../../../engine/crates/layerfs-overlay/src/payload/digest.rs) | | Install | `prepare_base_install` rebinds the base to the new root without a tree walk; after publish, `install_prepared_base` waits for `base_readers == 0`, then `Overlay::install` sets `base_root`, `installed := G`, `captured := None` and queues `RETIRE` of G, in one SQL transaction | [`install.rs`](../../../../engine/crates/layerfs-workspace/src/workspace/install.rs), [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs) | -| Rows written after the capture | Untouched by install; still the top of the effective view. An mtime-only change keeps the base row and carries its live row into G+1 (`keep_live_row`); until a write, that row is not dirty and `active_inodes` (Dirty check, `workspace status`) leaves it out | [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs), [`inodes.rs`](../../../../engine/crates/layerfs-workspace/src/construction/namespace/inodes.rs) | -| Kernel caches after install | Own root installed: nothing sent, the visible tree is unchanged. A merge root: the daemon invalidates the entries `stale_after_install` names before it answers | [`invalidate.rs`](../../../../engine/crates/layerfs-daemon/src/control/invalidate.rs) | +| Rows written after the capture | Untouched by the install of the Workspace's own root; still the top of the effective view. An mtime-only change keeps the base row and carries its live row into G+1 (`keep_live_row`); until a write, that row is not dirty and `active_inodes` (Dirty check, `workspace status`) leaves it out | +| Rows written after the capture, merged install | A G+1 row holds absolute facts (size, inherited cutoff, link and entry counts, inherited bits) computed against the old base, so a merge must not change what it covers. Before publishing a merge (or installing a conflicted one) the Commit takes a `MutationHold` (the Workspace's mutations wait; reads and other jobs run), lists the serials whose value differs between its candidate and the merged root (`changed_serials`, the in-lane step's added), and reads the active rows: an inode row of a changed serial, or a name binding under a changed directory, refuses the Commit `LiveConflict { paths }` (code `Busy`). Nothing is published, the capture folds back and the next Commit takes those rows too. Without overlap the hold lasts through publication and install. A carried mtime-only row is no overlap; `install_merged` deletes it when its serial changed (its live mtime is never committed), so the view and a later `UpToDate` agree with the head. Rows of unchanged serials stay valid: the merged root holds the same value for them | [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs), [`inodes.rs`](../../../../engine/crates/layerfs-workspace/src/construction/namespace/inodes.rs) | +| Kernel caches after install | Own root installed: nothing sent, the visible tree is unchanged. A merge root: the visible tree changes where the merge changed it (no row written after the capture covers that); the daemon invalidates the entries `stale_after_install` names before it answers | [`invalidate.rs`](../../../../engine/crates/layerfs-daemon/src/control/invalidate.rs) | | Cache admission | Objects the construction staged enter the shared object cache only in the `published` callback; every other path drops them | [`captured.rs`](../../../../engine/crates/layerfs-store-service/src/store/captured.rs) | | SDK `file.*` writes | Same route through a private Workspace, `CommitVia::Files` | [`files.rs`](../../../../engine/crates/layerfs-store-service/src/write/files.rs) | | Where a control Commit runs | On the daemon's control thread; the Commit spawns its one construction thread | [`operations.rs`](../../../../engine/crates/layerfs-daemon/src/control/operations.rs) | @@ -141,7 +143,7 @@ own failure (`Save::take_failure`) as its first cause when there is one. | No Workspace lock across construction or Store I/O | Every overlay call is one short owner job: [`owner.rs`](../../../../engine/crates/layerfs-store-service/src/overlay/owner.rs) | | Short holds: work that grows with the Commit (Save finish, logical count, binding hints, first merge, validation) runs before the lane | [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs) | | Content, Storage and Persistence are shared with Init; no Commit-only encoder | Objects go to `Save::sink`: [`captured.rs`](../../../../engine/crates/layerfs-store-service/src/store/captured.rs) | -| Install keeps later mutations and changes only base root, floor and captured state | [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs) | +| Install keeps later mutations and changes only base root, floor and captured state; a merged install also deletes carried mtime-only rows of serials the merge changed, and is refused while any other later row overlaps what it changed | [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs) | | Root inode identity never changes at install | `validate_candidate` refuses "candidate changes root inode identity": [`commit.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit.rs) | | A lost reply does not remove a published Commit | Publication is one history transaction; `published` is kept and blocks the next Commit: [`commit_types.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_types.rs) | | No retry, replay or guessed outcome | `settle_failure` resolves only a definite nonpublication and never reads history to guess: [`settle.rs`](../../../../engine/crates/layerfs-store-service/src/store/settle.rs) | @@ -155,7 +157,8 @@ own failure (`Save::take_failure`) as its first cause when there is one. | Captured page | `PAGE_ROWS` = 1,024 rows | [`types.rs`](../../../../engine/crates/layerfs-overlay/src/contract/types.rs) | | Head moved again after the merge | Up to `LANE_MERGE_PATHS` = 1,024 serials merged in the lane, else `CommitError::LaneMerge { paths, limit }`; nothing published | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs) | | Paths listed for a conflict | `WRITTEN_PATHS` = 4,096 (`written_truncated` when cut) | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs) | -| Marker blocks still present | `CommitError::Markers`; nothing published | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs) | +| Marker blocks still present | `CommitError::Markers`; nothing published | +| Rows written after the capture overlap a merge | `CommitError::LiveConflict { paths }`, at most `LIVE_CONFLICT_PATHS` = 16 named; nothing published; code `Busy` | [`live.rs`](../../../../engine/crates/layerfs-store-service/src/store/live.rs) | [`commit_merge.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_merge.rs) | | Moved head without merge | `HeadMoved` from `commit_branch` unless `force` | [`history/commit.rs`](../../../../engine/crates/layerfs-persistence/src/history/commit.rs) | | Base sources still open at install | Install waits; `OverlayError::BaseSourcesPending` if called unready | [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs) | | Install failed after publish | `OwnerError::Install` with the `PreparedBase`, never replayed; `CommitFailure.published` is `Some`; activity `LocalFailure` | [`owner.rs`](../../../../engine/crates/layerfs-store-service/src/overlay/owner.rs), [`operations.rs`](../../../../engine/crates/layerfs-daemon/src/control/operations.rs) | diff --git a/docs/architecture/engine/overlay/lifetimes.md b/docs/architecture/engine/overlay/lifetimes.md index 56af5bcd13..4f85d706cf 100644 --- a/docs/architecture/engine/overlay/lifetimes.md +++ b/docs/architecture/engine/overlay/lifetimes.md @@ -37,10 +37,13 @@ When [Overlay](README.md) state can be released and how it is reclaimed: generat | --- | --- | --- | | Capture | `capture()`: active g becomes captured, active g+1; dirty counts 0; copies no rows | [`generation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/generation.rs) | | Known success | `install(capture, root)`: `installed = g`, `base_root = root`, queue `RETIRE g` | same | +| Known success, merged root | `install_merged(capture, root, changed)`: as `install`, and in the same transaction deletes the active row `keep_live_row` carried for each serial in `changed` (it would let bytes fall through to the merge's different ones). The caller refuses the install while any other active row overlaps `changed`, and holds mutations from that check to the install ([Commit](../commit/README.md#what-it-does)) | same | | Definite failure | `resolve_failed_capture`: `consolidating = g`, queue `FOLD g` | [`composition.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/composition.rs) | The frontier rule lives in the Workspace lock, not the engine: while a -Capture waits, later mutations wait before any effect; while a known install +Capture waits, later mutations wait before any effect; while a merged Commit +holds the Workspace (`MutationHold`, from its check of the active rows to its +install), mutations wait too; while a known install waits, later base-source acquisitions wait ([`state.rs`](../../../../engine/crates/layerfs-store-service/src/overlay/state.rs), [`owner.rs`](../../../../engine/crates/layerfs-store-service/src/overlay/owner.rs)). diff --git a/docs/architecture/engine/workspace/README.md b/docs/architecture/engine/workspace/README.md index 5797e60659..fba5819cb3 100644 --- a/docs/architecture/engine/workspace/README.md +++ b/docs/architecture/engine/workspace/README.md @@ -120,7 +120,7 @@ Store I/O ([`ports/overlay.rs`](../../../../engine/crates/layerfs-workspace/src/ | Route | `Route { namespace > 0, engine != 0, incarnation != 0 }`; every source, file, capture and kernel mount is checked against its engine, else `Stale` | [`route.rs`](../../../../engine/crates/layerfs-workspace/src/workspace/route.rs) | | Source view | `view_for_source(BaseSource)` checks engine and current root (`BaseChanged`); `stat` reads overlay, base, then overlay again, so a row published meanwhile wins | [`view.rs`](../../../../engine/crates/layerfs-workspace/src/workspace/view.rs) | | Serials | Reserved from the scope's `InodeSerials` allocator `SERIAL_REFILL` (1,024) at a time, outside every lock; consumed, never recycled; one call makes at most one allocator request; an optional low-water refills early | [`serials.rs`](../../../../engine/crates/layerfs-workspace/src/workspace/serials.rs) | -| Install | `prepare_base_install(capture, root)` opens the new root with no lock; `install_prepared_base` holds the base write lock for one SQL step (`overlay.install`), with nothing fallible after it; later changes stay | [`install.rs`](../../../../engine/crates/layerfs-workspace/src/workspace/install.rs) | +| Install | `prepare_base_install(capture, root)` opens the new root with no lock; `install_prepared_base` holds the base write lock for one SQL step (`overlay.install_merged`, which for a merged root also drops carried mtime-only rows of changed serials), with nothing fallible after it; later changes stay | [`install.rs`](../../../../engine/crates/layerfs-workspace/src/workspace/install.rs) | ### Ports diff --git a/docs/architecture/flows/commit.md b/docs/architecture/flows/commit.md index 747191057e..769a8ab770 100644 --- a/docs/architecture/flows/commit.md +++ b/docs/architecture/flows/commit.md @@ -28,10 +28,14 @@ head re-read writer lock] moved again? merge validate, prepare + merge? hold mutations; + later rows overlap it? + -> LiveConflict commit_branch ------> 1 write tx drop lane ==========> [FREE] install job (base := - new root; G+1 stays) + new root; G+1 stays), + release the hold <--- Committed | MergeCommitted | Conflict <== {kind, head, commit, merged, lww} | Conflict refusal ==| ``` @@ -54,7 +58,7 @@ reply arrives, and nothing guesses or resends. | 6 | One producer constructs the candidate root from the capture; unchanged input is reused, changed files are chunked into the Commit's Save. | [Commit: construction](../engine/commit/construction.md), [Files: edits](../core/files/edits.md), [Filesystem trees: updates](../core/filesystem-trees/updates.md), [Physical storage: saves](../core/physical-storage/README.md#saves) | | 7 | If the head moved and `force` is false, the candidate is merged with the head in the same Save; then `Save::finish`, before the lane. | [Commit: what it does](../engine/commit/README.md#what-it-does), [Compare and merge: merge](../core/compare-and-merge/merge.md) | | 8 | Under the lane: head re-read, an in-lane merge of only what landed, then one write transaction that checks the expected head and advances the Branch. | [Store: the publish lane in a Commit](../engine/store/README.md#the-publish-lane-in-a-commit), [History: operations](../core/history/README.md#operations) | -| 9 | After the lane, install sets the base to the published root; rows written after the capture stay on top of the view. | [Commit: what it does](../engine/commit/README.md#what-it-does), [Workspace: state, serials and install](../engine/workspace/README.md#state-serials-and-install) | +| 9 | After the lane, install sets the base to the published root; rows written after the capture stay on top of the view. A merged root is installed only when no such row covers what the merge changed (else `LiveConflict`, nothing published, the capture folds back); mutations wait from that check to the install. | [Commit: what it does](../engine/commit/README.md#what-it-does), [Workspace: state, serials and install](../engine/workspace/README.md#state-serials-and-install) | | 10 | For a merged root, the daemon invalidates the kernel entries that changed before it replies. | [Kernel routes: coherence](../engine/kernel-routes/README.md#coherence) | | 11 | The reply is `Committed` or `UpToDate`; a conflict is the `Conflict` refusal and nothing is published. A published Commit whose install failed, or an uncertain outcome, is kept as custody and refuses the next Commit. | [Commit: custody and settle](../engine/commit/README.md#custody-and-settle), [Errors and events](../api/calls/errors-and-events.md) | diff --git a/engine/crates/layerfs-daemon/src/control/failure.rs b/engine/crates/layerfs-daemon/src/control/failure.rs index 2cc6aac760..cb20d192d5 100644 --- a/engine/crates/layerfs-daemon/src/control/failure.rs +++ b/engine/crates/layerfs-daemon/src/control/failure.rs @@ -216,6 +216,9 @@ fn commit(error: &CommitError) -> (ControlCode, Option, String) { storage(error) } CommitError::Owner(error) => owner(error), + // The live view changed what the merge changed: nothing was + // published and the next Commit takes it. + CommitError::LiveConflict { .. } => ControlCode::Busy, _ => ControlCode::Failed, } }; @@ -230,6 +233,13 @@ fn commit(error: &CommitError) -> (ControlCode, Option, String) { CommitError::Context(reason) => (*reason).into(), CommitError::History(error) => error.to_string(), CommitError::Markers(paths) => format!("{} files still hold conflict markers", paths.len()), + CommitError::LiveConflict { paths } => format!( + "files changed during the Commit overlap what the merge changed{}; nothing was published, commit again", + match paths.first() { + Some(path) => format!(" ({path}, {} in all named)", paths.len()), + None => String::new(), + } + ), CommitError::LaneMerge { paths, limit } => { format!("the head moved again by more than {limit} paths ({paths}) after the merge") } diff --git a/engine/crates/layerfs-overlay/src/lifetime/generation.rs b/engine/crates/layerfs-overlay/src/lifetime/generation.rs index 7c0238dee3..ef54e52742 100644 --- a/engine/crates/layerfs-overlay/src/lifetime/generation.rs +++ b/engine/crates/layerfs-overlay/src/lifetime/generation.rs @@ -10,11 +10,58 @@ impl Overlay { /// Later active rows and pending replies remain untouched. Physical retire /// work is queued; last-owner eligibility/automatic deletion is S6 work. pub fn install(&self, capture: Capture, root: [u8; 32]) -> OverlayResult<()> { + self.install_merged(capture, root, &[]) + } + /// [`Self::install`] of a root other than the one constructed from the + /// capture (a merge). `changed` lists, sorted, the serials whose value + /// differs between the two roots. A row [`Self::keep_live_row`] carried + /// for one of them would let its bytes fall through to the new base's + /// different ones, so it is deleted with the install: its only change, a + /// live mtime, is never committed. Every other active row of a changed + /// serial, or under a changed directory, was computed against the old + /// base: the caller refuses the install while one exists and holds + /// later mutations until it is done (`layerfs-store-service` + /// `store/live.rs`). Rows of unchanged serials stay valid over the new + /// base, which holds the same value for them. + pub fn install_merged( + &self, + capture: Capture, + root: [u8; 32], + changed: &[u64], + ) -> OverlayResult<()> { self.atomic_cleanup(|| { if !self.install_ready(capture)? { return Err(OverlayError::BaseSourcesPending); } + let active = self.state()?.active; + let stale: Vec = self + .open + .borrow() + .kept_live + .rows + .keys() + .copied() + .filter(|serial| { + u64::try_from(*serial) + .is_ok_and(|serial| changed.binary_search(&serial).is_ok()) + }) + .collect(); + for serial in &stale { + self.execute( + StatementKind::Inode, + "DELETE FROM fs_inode WHERE inode=?1 AND generation=?2", + &[serial, &active.0], + 24, + )?; + self.open.borrow_mut().kept_live.remove(*serial); + } self.change_state(|state| { + if !stale.is_empty() { + state.revision = state + .revision + .checked_add(1) + .ok_or(OverlayError::Invalid("revision exhausted"))?; + } state.base_root = root; state.installed = capture.generation.0; state.captured = None; diff --git a/engine/crates/layerfs-store-service/src/lib.rs b/engine/crates/layerfs-store-service/src/lib.rs index e764cefbb4..03bdbec37e 100644 --- a/engine/crates/layerfs-store-service/src/lib.rs +++ b/engine/crates/layerfs-store-service/src/lib.rs @@ -28,7 +28,7 @@ mod store_service; pub mod telemetry; pub mod write; -pub use overlay::hold::MaintenanceHold; +pub use overlay::hold::{MaintenanceHold, MutationHold}; pub use overlay::owner; pub use owner::{OriginalInput, Owner, OwnerClient, OwnerConfig, OwnerError, WorkspacePanic}; pub use service::observations::JobWork; diff --git a/engine/crates/layerfs-store-service/src/overlay/hold.rs b/engine/crates/layerfs-store-service/src/overlay/hold.rs index 705f8eee04..1f0c0f42f6 100644 --- a/engine/crates/layerfs-store-service/src/overlay/hold.rs +++ b/engine/crates/layerfs-store-service/src/overlay/hold.rs @@ -1,4 +1,5 @@ -//! A terminal unmount's hold on a Workspace's queued maintenance (#679). +//! A terminal unmount's hold on a Workspace's queued maintenance (#679), and +//! a merged Commit's hold on its mutations. //! //! The reclamation a Commit leaves queued drops rows of the Workspace's own //! overlay file, which terminal close deletes as a whole. While a hold is @@ -39,6 +40,47 @@ impl OwnerClient { }) } } +/// Held while it lives: the Workspace's mutations wait (the frontier wait +/// of `owner.rs`, lock released) until it is dropped. A merged Commit takes +/// it before it checks the active rows and keeps it through its publication +/// and install, so no row it checked changes before the new base is in +/// place (`store/live.rs`). It holds no lock and runs no job; other jobs, +/// the install among them, run as usual. Like [`MaintenanceHold`] it keeps +/// no connection alive. +#[must_use = "mutations resume when it is dropped"] +pub struct MutationHold { + shared: Weak, +} +impl OwnerClient { + /// Holds the mutations of the Workspace at `route` until the returned + /// hold is dropped. A mutation already running finishes first: the hold + /// is taken under the Workspace lock. Holds count, so they nest. + pub fn hold_mutations(&self, route: Route) -> Result { + if let Some(pool) = self.roster() { + return pool.client(route.namespace())?.hold_mutations(route); + } + let shared = self.connection()?; + if shared.route.get() != Some(&route) { + return Err(OwnerError::Overlay(OverlayError::Stale)); + } + let mut state = + shared.foreground(|| shared.state.lock().unwrap_or_else(|e| e.into_inner())); + state.mutation_holds += 1; + Ok(MutationHold { + shared: Arc::downgrade(shared), + }) + } +} +impl Drop for MutationHold { + fn drop(&mut self) { + if let Some(shared) = self.shared.upgrade() { + let mut state = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + state.mutation_holds -= 1; + drop(state); + shared.changed.notify_all(); + } + } +} impl Drop for MaintenanceHold { fn drop(&mut self) { if let Some(shared) = self.shared.upgrade() { diff --git a/engine/crates/layerfs-store-service/src/overlay/state.rs b/engine/crates/layerfs-store-service/src/overlay/state.rs index 634cd35635..e54762ec94 100644 --- a/engine/crates/layerfs-store-service/src/overlay/state.rs +++ b/engine/crates/layerfs-store-service/src/overlay/state.rs @@ -19,6 +19,9 @@ pub struct State { /// waiting for earlier base sources: their frontiers stay finite. pub captures_waiting: u32, pub installs_waiting: u32, + /// Merged Commits between their check of the active rows and their + /// install (`hold.rs` `MutationHold`): mutations wait behind them. + pub mutation_holds: u32, } pub struct Shared { pub namespace: i64, @@ -49,6 +52,7 @@ impl Shared { backing: None, captures_waiting: 0, installs_waiting: 0, + mutation_holds: 0, }), changed: Condvar::new(), held: AtomicU32::new(0), @@ -57,11 +61,11 @@ impl Shared { } } impl State { - /// A later mutation waits behind a waiting Capture, and a later source - /// acquisition behind a waiting known install. + /// A later mutation waits behind a waiting Capture or a held merged + /// install, and a later source acquisition behind a waiting known install. pub fn behind_frontier(&self, class: ServiceClass) -> bool { match class { - ServiceClass::Mutation => self.captures_waiting != 0, + ServiceClass::Mutation => self.captures_waiting != 0 || self.mutation_holds != 0, ServiceClass::Source => self.installs_waiting != 0, _ => false, } diff --git a/engine/crates/layerfs-store-service/src/store/commit.rs b/engine/crates/layerfs-store-service/src/store/commit.rs index 979c2e7ebc..d3dc446b14 100644 --- a/engine/crates/layerfs-store-service/src/store/commit.rs +++ b/engine/crates/layerfs-store-service/src/store/commit.rs @@ -243,11 +243,17 @@ impl BoundWorkspace { return Err(expected_moved(expected, ¤t)); } } + // What a merge changed against our candidate, for the check of + // rows written since the capture (`live.rs`). + let mut changed = Vec::new(); let root = if moved && !force { let (root, report) = phase(timing, "merge", || { self.merge_candidate(&save, &snapshot, ¤t, candidate) })?; merge = Some(report); + changed = phase(timing, "merge.changed", || { + super::live::changed_serials(&save, candidate, root) + })?; root } else { candidate @@ -358,6 +364,10 @@ impl BoundWorkspace { stepped, ) })?; + let step_changed = phase(timing, "merge.lane.changed", || { + super::live::changed_serials(&reader, root, stepped) + })?; + changed = super::live::union(&changed, &step_changed); merge = Some(match merge.take() { Some(first) => MergeReport { from: first.from, @@ -369,10 +379,10 @@ impl BoundWorkspace { (now, stepped, logical) } }; - Ok((root, candidate, current, logical, lane, early)) + Ok((root, candidate, current, logical, lane, early, changed)) })(); retained.storage = Some(super::producer::since(storage.diagnostics(), before)); - let (candidate, ours, current, logical, lane, early) = built?; + let (candidate, ours, current, logical, lane, early, changed) = built?; if candidate != ours { replaced = Some((ours.0, candidate.0)); } @@ -445,6 +455,24 @@ impl BoundWorkspace { self.validate_candidate(target, candidate, capture, &original_base) })? }); + // A merge installs a root other than our own. Rows written since + // the capture were computed against the old base: mutations are + // held from here through the install, and an active row that + // overlaps what the merge changed refuses it before anything is + // published or installed (`live.rs`). + let held = if candidate != ours { + let (hold, overlap) = phase(timing, "live", || self.hold_live(&changed))?; + if !overlap.is_empty() { + drop(hold); + drop(lane); + return Err(self.live_conflict(snapshot.scope, ours, candidate, &overlap)); + } + let changed: Arc<[u64]> = changed.into(); + retained.prepared = retained.prepared.take().map(|ready| ready.merged(changed)); + Some(hold) + } else { + None + }; let pending = if conflicted { // Nothing is published: the history binding follows the head // merged with, and the merge stays the local base. @@ -490,6 +518,7 @@ impl BoundWorkspace { }) .map_err(CommitError::Owner) })?; + drop(held); *self .snapshot .lock() diff --git a/engine/crates/layerfs-store-service/src/store/commit_types.rs b/engine/crates/layerfs-store-service/src/store/commit_types.rs index 4011a3d41c..b1728b413f 100644 --- a/engine/crates/layerfs-store-service/src/store/commit_types.rs +++ b/engine/crates/layerfs-store-service/src/store/commit_types.rs @@ -53,6 +53,14 @@ pub enum CommitError { paths: u64, limit: u64, }, + /// A merge would install a root other than the Workspace's own while + /// rows written after the capture change what the merge changed: those + /// rows were computed against the old base (`live.rs`). Nothing is + /// published; the capture folds back, and a later Commit takes those + /// rows too. `paths` names some of them, at most `LIVE_CONFLICT_PATHS`. + LiveConflict { + paths: Vec, + }, } /// What the product constructor's one namespace attempt acquired, counted and /// released. A named reader or owner here was acquired and is not known diff --git a/engine/crates/layerfs-store-service/src/store/live.rs b/engine/crates/layerfs-store-service/src/store/live.rs new file mode 100644 index 0000000000..f05105af5d --- /dev/null +++ b/engine/crates/layerfs-store-service/src/store/live.rs @@ -0,0 +1,137 @@ +//! A merged install over rows written after the capture. +//! +//! Rows of the active generation hold absolute facts (size, inherited +//! cutoff, link and entry counts, inherited bits) computed against the base +//! under them. Install moves only the base, so a merge that changes a serial +//! or a directory's listing under such a row would leave it wrong: bytes cut +//! off or zero-filled, a non-empty directory counted empty. Before a merge is +//! published (or, conflicted, installed) the Commit holds the Workspace's +//! mutations and refuses with `LiveConflict` when an active row overlaps +//! what the merge changed; nothing is published and the capture folds back. +//! Without overlap the hold lasts through the publication and install, so no +//! checked row changes before the new base is in place. +use super::{BoundWorkspace, CommitError}; +use crate::MutationHold; +use layerfs_content::{ + compare::{inode_differences, tree::locate, DifferenceWork, TreeTable}, + filesystem::FilesystemRootId, + AuthenticatedObjects, ObjectId, +}; +use std::collections::BTreeSet; + +/// Paths a `LiveConflict` names, at most. +pub const LIVE_CONFLICT_PATHS: usize = 16; +/// Directories one path search lists, at most. +const LOCATE_DIRECTORIES: usize = 4096; + +/// Serials whose stored inode value (content, metadata, link count, a +/// directory's listing) differs between two roots, or that only one holds, +/// in serial order. Work follows the difference, not the tree. +pub(super) fn changed_serials( + reader: &dyn AuthenticatedObjects, + from: FilesystemRootId, + to: FilesystemRootId, +) -> Result, CommitError> { + let mut changed = Vec::new(); + if from == to { + return Ok(changed); + } + let (before, after) = ( + TreeTable::open(reader, from).map_err(CommitError::from)?, + TreeTable::open(reader, to).map_err(CommitError::from)?, + ); + inode_differences( + reader, + Some(&before), + &after, + &mut DifferenceWork::default(), + |serial, _, _| { + changed.push(serial); + Ok(()) + }, + ) + .map_err(CommitError::from)?; + Ok(changed) +} + +/// The sorted union of two sorted serial lists. +pub(super) fn union(first: &[u64], second: &[u64]) -> Vec { + let mut all: Vec = first.iter().chain(second).copied().collect(); + all.sort_unstable(); + all.dedup(); + all +} + +impl BoundWorkspace { + /// Holds this Workspace's mutations, then reads the active generation's + /// changed rows a window at a time: an inode row of a changed serial, or + /// a name binding under a changed directory, overlaps the merge. A row + /// carried for an mtime-only capture and not written since holds no data + /// of its own: it is no overlap, and the install deletes it when its + /// serial changed. Returns the hold and up to `LIVE_CONFLICT_PATHS` + /// overlapping serials; empty means the install may proceed. + pub(super) fn hold_live( + &self, + changed: &[u64], + ) -> Result<(MutationHold, Vec), CommitError> { + let route = self.route(); + let hold = self + .owner + .hold_mutations(route) + .map_err(CommitError::Owner)?; + let hit = |serial: u64| changed.binary_search(&serial).is_ok(); + let mut found = BTreeSet::new(); + let mut after = 0; + while found.len() < LIVE_CONFLICT_PATHS { + let window = self + .owner + .active_inodes(route, after) + .map_err(CommitError::Owner)?; + let Some(last) = window.last() else { break }; + after = last.serial; + found.extend(window.iter().map(|row| row.serial).filter(|s| hit(*s))); + } + let mut cursor = None; + while found.len() < LIVE_CONFLICT_PATHS { + let window = self + .owner + .active_directory_entries(route, cursor.clone()) + .map_err(CommitError::Owner)?; + let Some(last) = window.last() else { break }; + cursor = Some((last.parent, last.name.clone())); + found.extend(window.iter().map(|row| row.parent).filter(|p| hit(*p))); + } + Ok((hold, found.into_iter().take(LIVE_CONFLICT_PATHS).collect())) + } + + /// The refusal of a merged install that overlaps `serials`, naming their + /// paths in `ours` (the Workspace's own constructed root), else in the + /// merged root. Naming is a bounded search and best effort: a path it + /// does not find, or a read that fails, is left out, never the refusal. + pub(super) fn live_conflict( + &self, + scope: ObjectId, + ours: FilesystemRootId, + merged: FilesystemRootId, + serials: &[u64], + ) -> CommitError { + let ports = self.store.ports(scope); + let reader = &*ports; + let mut wanted: BTreeSet = serials.iter().copied().collect(); + let mut paths = Vec::new(); + for root in [ours, merged] { + if wanted.is_empty() { + break; + } + let found = TreeTable::open(reader, root) + .and_then(|tree| locate(reader, &tree, &wanted, LOCATE_DIRECTORIES)) + .unwrap_or_default(); + for (serial, path) in found { + wanted.remove(&serial); + paths.push(path); + } + } + paths.sort(); + CommitError::LiveConflict { paths } + } +} diff --git a/engine/crates/layerfs-store-service/src/store/mod.rs b/engine/crates/layerfs-store-service/src/store/mod.rs index dba2719b9b..0371536168 100644 --- a/engine/crates/layerfs-store-service/src/store/mod.rs +++ b/engine/crates/layerfs-store-service/src/store/mod.rs @@ -6,6 +6,7 @@ pub mod commit_merge; pub mod commit_types; pub mod digests; pub mod hints; +mod live; pub mod open; pub mod operation; mod pipeline; @@ -21,6 +22,7 @@ pub use bind::checked_base; pub use commit_merge::{Stale, StaleError, LANE_MERGE_PATHS}; pub use hints::record_new_bindings; pub use hints::CatalogHints; +pub use live::LIVE_CONFLICT_PATHS; pub use commit_types::{ CapturedConstruction, CommitError, CommitFailure, CommitOptions, CommitPhase, CommitSuccess, diff --git a/engine/crates/layerfs-store-service/tests/commit_live_merge.rs b/engine/crates/layerfs-store-service/tests/commit_live_merge.rs new file mode 100644 index 0000000000..b1a0f91e2a --- /dev/null +++ b/engine/crates/layerfs-store-service/tests/commit_live_merge.rs @@ -0,0 +1,304 @@ +//! A Commit that merges installs a root other than the Workspace's own. +//! Rows written after the capture were computed against the old base, so an +//! install under rows that overlap what the merge changed is refused +//! (`LiveConflict`) before anything is published: the capture folds back, +//! nothing is lost, and the next Commit takes everything. A row carried only +//! for an mtime-only change holds no data: the merged install drops it when +//! its serial changed. Mutations that arrive between the check and the +//! install wait for the install. +#[path = "support/installed_store.rs"] +#[allow(dead_code)] +mod installed; +#[path = "support/live.rs"] +#[allow(dead_code)] +mod live; +#[path = "support/sdk.rs"] +#[allow(dead_code)] +mod support; + +use layerfs_history::CommitOutcome; +use layerfs_store_service::store::{ + BoundWorkspace, CommitError, CommitFailure, CommitOptions, CommitSuccess, +}; +use layerfs_store_service::telemetry::{mark_phases, Recording}; +use std::{cell::Cell, rc::Rc, sync::Once}; +use support::Change; + +fn tmp() { + static SET: Once = Once::new(); + SET.call_once(|| std::env::set_var("TMPDIR", env!("CARGO_TARGET_TMPDIR"))); +} + +fn base(source: &std::path::Path) -> usize { + std::fs::write(source.join("a.txt"), b"alpha\n").unwrap(); + std::fs::write(source.join("b.txt"), b"bravo\n").unwrap(); + std::fs::write(source.join("f.txt"), b"0123456789\n").unwrap(); + std::fs::create_dir(source.join("d")).unwrap(); + std::fs::write(source.join("d/x"), b"x\n").unwrap(); + 5 +} + +fn options() -> CommitOptions { + CommitOptions { + force: false, + message: Some("live merge".into()), + expected: None, + } +} + +/// Commits `workspace`; `during` runs once on the Commit thread at the start +/// of the phase `at` (after the capture), as a write in the Commit window. +fn commit_with_window( + workspace: &BoundWorkspace, + at: &'static str, + during: impl FnOnce() + 'static, +) -> Result> { + let pending = Rc::new(Cell::new(Some(Box::new(during) as Box))); + let take = pending.clone(); + let recording = Recording::start(); + mark_phases(Some(Box::new(move |name, end| { + if name == at && !end { + if let Some(during) = take.take() { + during(); + } + } + }))); + let result = workspace.commit_captured(&options()); + mark_phases(None); + drop(recording); + assert!(pending.take().is_none(), "the window at {at} was reached"); + result +} + +/// A `'static` handle on a Workspace for a window closure. SAFETY: every +/// closure runs inside the Commit of that same Workspace, which outlives it. +fn handle(workspace: &BoundWorkspace) -> &'static BoundWorkspace { + unsafe { &*(workspace as *const BoundWorkspace) } +} + +fn live_conflict(failure: &CommitFailure) -> &[String] { + match &failure.error { + CommitError::LiveConflict { paths } => paths, + other => panic!("not a live conflict: {other:?} ({failure:?})"), + } +} + +fn text(workspace: &BoundWorkspace, path: &str) -> String { + String::from_utf8(live::live(workspace, path).unwrap()).unwrap() +} + +/// `touch F`; the other side commits a longer F; this side's Commit merges +/// and installs it. F must read whole, not cut at its old length, and the +/// next Commit has nothing to publish. +#[test] +fn touched_file_is_not_truncated_by_a_merge() { + tmp(); + let fixture = support::Fixture::new("live-touch", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 81, "lane"); + live::change(&workspace, &[Change::Mtime("/f.txt", 999)]); + let longer = b"0123456789 and twenty more bytes\n"; + fixture.workspace_commit("lane", &[Change::Write("/f.txt", longer)], 82, || {}); + let committed = workspace + .commit_captured(&options()) + .unwrap_or_else(|failure| panic!("{failure:?}")); + assert!(committed.merge.is_some(), "merged"); + assert_eq!(live::live(&workspace, "/f.txt").unwrap(), longer); + let again = workspace.commit_captured(&options()).unwrap(); + assert!( + matches!(again.history, Some(CommitOutcome::UpToDate { .. })), + "{:?}", + again.history + ); + assert_eq!( + live::committed(&fixture, "lane", "/f.txt").as_deref(), + Some(std::str::from_utf8(longer).unwrap()) + ); + workspace.close().unwrap(); + fixture.cleanup(); +} + +/// `rm d/x` after the capture while the merge adds `d/y`: refused, nothing +/// lost; `d` is not empty and the next Commit keeps `y` and removes `x`. +#[test] +fn removal_after_capture_under_a_merged_directory_is_refused() { + tmp(); + let fixture = support::Fixture::new("live-rm", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 83, "lane"); + live::change(&workspace, &[Change::Write("/a.txt", b"ALPHA\n")]); + fixture.workspace_commit("lane", &[Change::Create("/d/y", b"y\n")], 84, || {}); + let window = handle(&workspace); + let refused = commit_with_window(&workspace, "merge", move || { + live::change(window, &[Change::Unlink("/d/x")]); + }) + .expect_err("live conflict"); + assert!( + live_conflict(&refused).contains(&"/d".to_owned()), + "{refused:?}" + ); + assert!(refused.locally_settled, "{refused:?}"); + assert!(refused.published.is_none(), "{refused:?}"); + assert_eq!(text(&workspace, "/a.txt"), "ALPHA\n"); + assert!(live::live(&workspace, "/d/x").is_err(), "x stays removed"); + let committed = workspace + .commit_captured(&options()) + .unwrap_or_else(|failure| panic!("{failure:?}")); + assert!(committed.merge.is_some(), "merged"); + assert_eq!(text(&workspace, "/d/y"), "y\n"); + assert!(live::live(&workspace, "/d/x").is_err()); + assert!( + live::try_change(&workspace, Change::Rmdir("/d")).is_err(), + "d holds y" + ); + assert_eq!(live::committed(&fixture, "lane", "/d/x"), None); + assert_eq!( + live::committed(&fixture, "lane", "/d/y").as_deref(), + Some("y\n") + ); + assert_eq!( + live::committed(&fixture, "lane", "/a.txt").as_deref(), + Some("ALPHA\n") + ); + workspace.close().unwrap(); + fixture.cleanup(); +} + +/// A write during the Commit window to a file the other side changed is +/// refused and kept. +#[test] +fn write_in_the_window_to_a_merged_file_is_refused() { + tmp(); + let fixture = support::Fixture::new("live-write", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 85, "lane"); + live::change(&workspace, &[Change::Write("/a.txt", b"ALPHA\n")]); + fixture.workspace_commit("lane", &[Change::Write("/b.txt", b"BRAVO\n")], 86, || {}); + let window = handle(&workspace); + let refused = commit_with_window(&workspace, "lane", move || { + live::change(window, &[Change::Write("/b.txt", b"bravo, mine\n")]); + }) + .expect_err("live conflict"); + assert_eq!(live_conflict(&refused), ["/b.txt".to_owned()]); + assert!(refused.locally_settled, "{refused:?}"); + assert_eq!(text(&workspace, "/b.txt"), "bravo, mine\n"); + assert_eq!(text(&workspace, "/a.txt"), "ALPHA\n"); + workspace.close().unwrap(); + fixture.cleanup(); +} + +/// Both sides create directory `n`: the merge keeps the other side's `n`, +/// so this side's directory serial is gone from the merged root. A file +/// created under this side's `n` after the capture is refused, and the next +/// Commit merges all three files into one `n`. +#[test] +fn rows_under_a_directory_the_merge_replaced_are_refused() { + tmp(); + let fixture = support::Fixture::new("live-dir", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 87, "lane"); + live::change( + &workspace, + &[Change::Mkdir("/n"), Change::Create("/n/a", b"a\n")], + ); + fixture.workspace_commit( + "lane", + &[Change::Mkdir("/n"), Change::Create("/n/b", b"b\n")], + 88, + || {}, + ); + let window = handle(&workspace); + let refused = commit_with_window(&workspace, "merge", move || { + live::change(window, &[Change::Create("/n/c", b"c\n")]); + }) + .expect_err("live conflict"); + assert!( + live_conflict(&refused).contains(&"/n".to_owned()), + "{refused:?}" + ); + assert!(refused.locally_settled, "{refused:?}"); + workspace + .commit_captured(&options()) + .unwrap_or_else(|failure| panic!("{failure:?}")); + for (path, bytes) in [("/n/a", "a\n"), ("/n/b", "b\n"), ("/n/c", "c\n")] { + assert_eq!(text(&workspace, path), bytes, "{path}"); + assert_eq!( + live::committed(&fixture, "lane", path).as_deref(), + Some(bytes), + "{path}" + ); + } + workspace.close().unwrap(); + fixture.cleanup(); +} + +/// A merge whose changes no row written after the capture touches still +/// publishes and installs; the new file stays on top of the merged view. +#[test] +fn a_merge_with_no_overlap_publishes_and_installs() { + tmp(); + let fixture = support::Fixture::new("live-clean", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 89, "lane"); + live::change(&workspace, &[Change::Write("/a.txt", b"ALPHA\n")]); + fixture.workspace_commit("lane", &[Change::Write("/b.txt", b"BRAVO\n")], 90, || {}); + let window = handle(&workspace); + let committed = commit_with_window(&workspace, "merge", move || { + live::change(window, &[Change::Create("/c.txt", b"charlie\n")]); + }) + .unwrap_or_else(|failure| panic!("{failure:?}")); + assert!( + matches!(committed.history, Some(CommitOutcome::Committed { .. })), + "{:?}", + committed.history + ); + assert!(committed.replaced.is_some(), "a merged root installed"); + assert_eq!(text(&workspace, "/a.txt"), "ALPHA\n"); + assert_eq!(text(&workspace, "/b.txt"), "BRAVO\n"); + assert_eq!(text(&workspace, "/c.txt"), "charlie\n"); + assert_eq!(live::committed(&fixture, "lane", "/c.txt"), None); + workspace + .commit_captured(&options()) + .unwrap_or_else(|failure| panic!("{failure:?}")); + assert_eq!( + live::committed(&fixture, "lane", "/c.txt").as_deref(), + Some("charlie\n") + ); + workspace.close().unwrap(); + fixture.cleanup(); +} + +/// The hold a merged Commit keeps from its check of the active rows through +/// its install: a mutation that arrives while it is held waits, lock +/// released, and runs once it is dropped. Reads and other jobs run. +/// +/// The Commit itself is not driven here: this harness mutates through a +/// counted base source, and a known install waits for base sources to +/// drain, so a write held during a Commit's publication would never let +/// that install run. No product caller mutates while holding one (kernel +/// requests take none; SDK file writes release theirs before their Commit). +#[test] +fn a_held_workspace_delays_mutations_until_the_hold_ends() { + tmp(); + let fixture = support::Fixture::new("live-hold", base); + fixture.fork("lane"); + let workspace = live::bind(&fixture, 91, "lane"); + let route = workspace.operation().unwrap().workspace().route(); + let hold = fixture.owner.client().hold_mutations(route).unwrap(); + let landed = std::sync::atomic::AtomicBool::new(false); + std::thread::scope(|scope| { + let (workspace, landed) = (&workspace, &landed); + let writer = scope.spawn(move || { + live::change(workspace, &[Change::Write("/b.txt", b"BRAVO\n")]); + landed.store(true, std::sync::atomic::Ordering::SeqCst); + }); + std::thread::sleep(std::time::Duration::from_millis(200)); + assert!(!landed.load(std::sync::atomic::Ordering::SeqCst), "held"); + assert_eq!(text(workspace, "/b.txt"), "bravo\n", "reads run"); + drop(hold); + writer.join().unwrap(); + }); + assert_eq!(text(&workspace, "/b.txt"), "BRAVO\n"); + workspace.close().unwrap(); + fixture.cleanup(); +} diff --git a/engine/crates/layerfs-workspace/src/workspace/install.rs b/engine/crates/layerfs-workspace/src/workspace/install.rs index 9d02c35c3c..cadfa294c0 100644 --- a/engine/crates/layerfs-workspace/src/workspace/install.rs +++ b/engine/crates/layerfs-workspace/src/workspace/install.rs @@ -10,6 +10,9 @@ pub struct PreparedBase { capture: Capture, expected: FilesystemRootId, next: BaseView, + /// Sorted serials a merge changed against the root constructed from the + /// capture; empty when that root itself is installed. + merged: std::sync::Arc<[u64]>, } impl PreparedBase { pub const fn capture(&self) -> Capture { @@ -18,6 +21,14 @@ impl PreparedBase { pub fn root(&self) -> FilesystemRootId { self.next.identity() } + /// The install of a merge: `changed` lists, sorted, the serials whose + /// value differs between the root constructed from the capture and this + /// one ([`Overlay::install_merged`]). + #[must_use] + pub fn merged(mut self, changed: std::sync::Arc<[u64]>) -> Self { + self.merged = changed; + self + } } impl Workspace { /// Demand/validate one new canonical root before acquiring install state. @@ -43,6 +54,7 @@ impl Workspace { capture, expected, next, + merged: std::sync::Arc::from([]), }) } /// One local install after exact known upstream publication/UpToDate. @@ -71,8 +83,11 @@ impl Workspace { prepared, )); } - if let Err(error) = overlay.install(prepared.capture, prepared.next.identity().0.to_bytes()) - { + if let Err(error) = overlay.install_merged( + prepared.capture, + prepared.next.identity().0.to_bytes(), + &prepared.merged, + ) { return Err((error.into(), prepared)); } // No fallible work follows known SQL success; old immutable plans own From 384dbb33fcc52b5df5f186912ea675f2b8d5daba Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 15:19:37 +0800 Subject: [PATCH 4/6] Commit: one exact resolution of retained custody at the next Commit Finding #5 (V-CC-3): a Commit whose publication answered with an unknown outcome, or whose install failed after a known publication, kept custody; every later Commit was refused Unknown, and the only exit was a force unmount (needing relinquish_unknown and an attached kernel connection) that discarded every change made since the capture. Nothing compared the head with the saved candidate. Such a failure now also leaves a record on the BoundWorkspace (new store-service store/resolve.rs): the capture, the intent, the binding, the known publication, a merge's own root and changed serials (new CommitFailure::merged_over), and the captured reader and operation owner. Only an unanswered publication (phase Publish, nothing known published) or an install that failed definitely after a known publication qualifies; local uncertainty, an unreleased construction custody and a release error keep no record and stay as before. The Workspace's next Commit request first runs BoundWorkspace::resolve_retained once (daemon control/resolve.rs, before admission; activity Committing, phase resolve). It reads the head once, through the control reader's own connection (a writer session the unknown outcome quarantined does not stop it): a known publication, or a head that is a Commit with our candidate root over the head and base Layer we published against, is installed with the same validation, live check and mutation hold as a merged install; the head still the one we published against folds the capture back (or, holding our root, installs it as UpToDate); anything else stays retained and refuses the Commit Unknown with the reason. It is not a retry: nothing is resent and the record is used once, whatever it finds. Resolved, the captured owners are released, the entry goes Idle and the Commit is admitted; an install of a merged root is invalidated in the kernel as a Commit's own. Docs in the same commit: engine/commit (custody table, new "One resolution of retained custody" section, demonstration rows for this branch's tests), engine/daemon/control-calls, flows/commit, api/sdk/workspace. Tests (layerfs-daemon tests/store_commit.rs, new history_boundary::Boundary::LostRequest): a lost acknowledgement is resolved by installing the Commit, and the next Commit's parent is it; a lost request folds back and the next Commit publishes the kept change; an unknown outcome under a head another Commit moved stays retained and still refuses a Commit; a product (captured) Commit's resolution releases its reader and operation owner and the next product Commit publishes. No test deleted. Not covered: the daemon's resolve_custody wiring runs only through the Service (mounted, Linux) tests, which were not run here. Production LOC: 206,898 -> 207,195 (delta +297) core 40,989 -> 40,989 (0) engine 96,218 -> 96,515 (+297) layerfs-daemon +66, layerfs-store-service +231 control 59,366 -> 59,366 (0) api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent 54e4913c5f and the staged tree Co-Authored-By: Claude Opus 5.5 --- docs/architecture/api/sdk/workspace.md | 2 +- docs/architecture/engine/commit/README.md | 45 ++- .../engine/daemon/control-calls.md | 1 + docs/architecture/flows/commit.md | 2 +- .../crates/layerfs-daemon/src/control/mod.rs | 1 + .../layerfs-daemon/src/control/operations.rs | 3 + .../layerfs-daemon/src/control/resolve.rs | 76 +++++ .../layerfs-daemon/tests/store_commit.rs | 195 +++++++++++++ .../tests/support/history_boundary.rs | 4 + .../layerfs-store-service/src/store/bind.rs | 1 + .../src/store/captured.rs | 5 +- .../layerfs-store-service/src/store/commit.rs | 6 +- .../src/store/commit_types.rs | 7 +- .../layerfs-store-service/src/store/mod.rs | 2 + .../src/store/operation.rs | 2 + .../src/store/resolve.rs | 265 ++++++++++++++++++ 16 files changed, 609 insertions(+), 8 deletions(-) create mode 100644 engine/crates/layerfs-daemon/src/control/resolve.rs create mode 100644 engine/crates/layerfs-store-service/src/store/resolve.rs diff --git a/docs/architecture/api/sdk/workspace.md b/docs/architecture/api/sdk/workspace.md index 9a8de49e6c..ae726ce93f 100644 --- a/docs/architecture/api/sdk/workspace.md +++ b/docs/architecture/api/sdk/workspace.md @@ -334,7 +334,7 @@ committed, and is never merged with. `--force --expected C` replaces only | `Conflict` | a path conflicts, or the head is not `--expected`; nothing is committed. It carries `commit` (the head), `conflicts` (the first 20 paths) and `conflicts_count` | | `InvalidInput` | an `--expected` prefix several Commits start with (`matches`) | | `Busy` | another control operation runs on the Workspace ([`control/registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs)) | -| `Unknown` | an earlier Commit's install was uncertain or failed (`detail.phase: "admission"`): the daemon keeps that custody and refuses new Commits; or the reply was lost | +| `Unknown` | an earlier Commit's outcome was unknown or its install failed, and the one resolution this Commit ran first did not settle it (`detail.phase: "admission"`, the reason in `detail`): the daemon keeps that custody and refuses new Commits; or the reply was lost | After an uncertain Commit read `commit list` (a new head?) and `workspace status`. A lost reply does not remove a published Commit. diff --git a/docs/architecture/engine/commit/README.md b/docs/architecture/engine/commit/README.md index 69095957c1..ec9edacb24 100644 --- a/docs/architecture/engine/commit/README.md +++ b/docs/architecture/engine/commit/README.md @@ -113,13 +113,13 @@ is a different install, placing a sealed Store file into a project volume; see the work counted and the release error that stopped the sequence ([`commit_types.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_types.rs)). `CommitFailure` carries `phase`, `intent`, `capture`, `prepared`, `saved`, -`published` and `locally_settled`. +`published`, `locally_settled` and, for a merge, `merged_over` (its own root and the serials the merge changed). | Failure kind | Daemon activity | Next Commit | Source | | --- | --- | --- | --- | | Definite, settled, owners released | `Idle` | Admitted | [`operations.rs`](../../../../engine/crates/layerfs-daemon/src/control/operations.rs) | -| Published, then install or a release failed | `LocalFailure` | Refused: code `Unknown`, phase `admission`; the daemon keeps `published`, the SDK refusal does not carry it | [`registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs) | -| Uncertain (`CommitFailure::uncertain()`) | `Uncertain` | Refused as above | [`commit_types.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_types.rs), [`registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs) | +| Published, then install or a release failed | `LocalFailure` | Its one resolution first (below); unresolved, refused: code `Unknown`, phase `admission`; the daemon keeps `published`, the SDK refusal does not carry it | [`resolve.rs`](../../../../engine/crates/layerfs-daemon/src/control/resolve.rs), [`registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs) | +| Uncertain (`CommitFailure::uncertain()`) | `Uncertain` | As above | [`commit_types.rs`](../../../../engine/crates/layerfs-store-service/src/store/commit_types.rs), [`registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs) | `CommitFailure::uncertain()` depends on the phase. `commit_branch` is the only write that publishes, so before the `Publish` phase nothing in history @@ -133,6 +133,41 @@ or port). From the `Publish` phase until the answer is known, `CommitError::uncertain()` decides. A merge-stage failure reports the Save's own failure (`Save::take_failure`) as its first cause when there is one. +### One resolution of retained custody + +A Commit whose publication answered with an unknown outcome (phase +`Publish`, nothing known published), or whose install failed definitely after +a known publication (phase `Install`), keeps a record beside its custody: the +capture, the intent, the binding, the known publication, the merge's own root +and changed serials, and the captured reader and operation owner +([`resolve.rs`](../../../../engine/crates/layerfs-store-service/src/store/resolve.rs)). +Local uncertainty (an uncertain overlay or owner job, a poisoned binding) and +a namespace receipt with unreleased custody or a release error keep no +record: their custody stays until force unmount, as before. + +The Workspace's next Commit request runs `BoundWorkspace::resolve_retained` +once, before its own admission (daemon +[`resolve.rs`](../../../../engine/crates/layerfs-daemon/src/control/resolve.rs), +activity `Committing`, phase `resolve`). It is not a retry: nothing is +resent, the head is read once and the record is used once, whatever it finds. + +| Head read through the control reader | Step | Then | +| --- | --- | --- | +| Publication already known | Install its root (same validation, live check and mutation hold as a merged install) | Custody released, `Idle`; the Commit is admitted | +| A Commit with our candidate root, parent and base Layer equal to the head and base we published against | Install it, as above | As above | +| Still the head we published against, with another root | Nothing was published: `resolve_failed` folds the capture back | As above | +| Still that head, with our root | `UpToDate`: install it | As above | +| Anything else, a failed read, or a failed install or fold-back | None | Custody stays (`LocalFailure` once a publication is known, else as it was); the Commit is refused `Unknown` with the reason | + +The head is read on the control reader's own connection, so a writer session +that the unknown outcome quarantined does not stop it. The read follows the +next Commit request, not the failure. On PostgreSQL a COMMIT whose +connection was lost may still finish on the server shortly after; reading +the old head then folds the capture back, and the next Commit finds the +head moved and merges the kept change with it. A known +install after a merge with overlapping live rows is refused like a +Commit's own (`LiveConflict` in the reason), and the custody stays. + ## Invariants | Rule | Enforced by | @@ -177,6 +212,10 @@ construction state lives in indexed operation records. | [`lane_merge.rs`](../../../../engine/crates/layerfs-daemon/tests/lane_merge.rs) | `cargo +1.85.1 test --locked -p layerfs-daemon --test lane_merge` | any | A Commit landing while another waits for the lane is merged in the lane; over the bound is `LaneMerge` | | [`captured_namespace.rs`](../../../../engine/crates/layerfs-workspace/tests/captured_namespace.rs) | `cargo +1.85.1 test --locked -p layerfs-workspace --test captured_namespace` | any | One captured reader becomes one complete root; mutations after the capture land only in the next | | [`mounted_install.rs`](../../../../engine/crates/layerfs-daemon/tests/mounted_install.rs) | `cargo +1.85.1 test --locked -p layerfs-daemon --test mounted_install` | Linux, `/dev/fuse` | Installing the Workspace's own root sends no notification; the mount reads the same through open descriptors, caches and `O_DIRECT` | +| [`commit_settle.rs`](../../../../engine/crates/layerfs-store-service/tests/commit_settle.rs) | `cargo +1.85.1 test --locked -p layerfs-store-service --test commit_settle` | any | A failure before publication folds back; local uncertainty keeps custody; a conflicted merge takes no lane | +| [`commit_expected.rs`](../../../../engine/crates/layerfs-store-service/tests/commit_expected.rs) | `cargo +1.85.1 test --locked -p layerfs-store-service --test commit_expected` | any | `--expected` is checked inside the publication; `--force` publishes over the head read in the lane | +| [`commit_live_merge.rs`](../../../../engine/crates/layerfs-store-service/tests/commit_live_merge.rs) | `cargo +1.85.1 test --locked -p layerfs-store-service --test commit_live_merge` | any | A merged install that overlaps rows written after the capture is refused `LiveConflict`; one with no overlap publishes | +| [`store_commit.rs`](../../../../engine/crates/layerfs-daemon/tests/store_commit.rs) | `cargo +1.85.1 test --locked -p layerfs-daemon --test store_commit` | any | Custody and settle by phase; one resolution of an unknown outcome installs a landed Commit, folds a lost one back and leaves a moved head retained | Run each under a wall timeout of at most 120 s. diff --git a/docs/architecture/engine/daemon/control-calls.md b/docs/architecture/engine/daemon/control-calls.md index 68c9f8a1ed..eedec05aa7 100644 --- a/docs/architecture/engine/daemon/control-calls.md +++ b/docs/architecture/engine/daemon/control-calls.md @@ -43,6 +43,7 @@ Service.entries: Mutex> | --- | --- | | A token is `(WorkspaceId, namespace)`; a stale namespace is refused, never redirected | [`registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs) | | Admission requires `Idle` and marks the activity inside the lock; `Uncertain` or `LocalFailure` answers `Unknown` with the retained publication | [`registry.rs`](../../../../engine/crates/layerfs-daemon/src/control/registry.rs) | +| A Commit request on an `Uncertain` or `LocalFailure` Workspace that kept a resolution record first runs its one resolution ([Commit](../commit/README.md#one-resolution-of-retained-custody)): resolved, the entry is `Idle` and admission follows; unresolved, it answers `Unknown` with the reason | [`resolve.rs`](../../../../engine/crates/layerfs-daemon/src/control/resolve.rs) | | Mount checks, inside the lock, that no entry exists, capacity remains and no maintenance failure is retained, then inserts `Entry::Binding` | [`operations.rs`](../../../../engine/crates/layerfs-daemon/src/control/operations.rs) | | The registry is the sole authority for which kernel connection an entry owns | [`kernel.rs`](../../../../engine/crates/layerfs-daemon/src/control/kernel.rs) | | A Commit whose captured reader or operation owner could not be released leaves `LocalFailure`; nothing later is admitted past it | [`operations.rs`](../../../../engine/crates/layerfs-daemon/src/control/operations.rs) | diff --git a/docs/architecture/flows/commit.md b/docs/architecture/flows/commit.md index 769a8ab770..2ed241e44a 100644 --- a/docs/architecture/flows/commit.md +++ b/docs/architecture/flows/commit.md @@ -60,7 +60,7 @@ reply arrives, and nothing guesses or resends. | 8 | Under the lane: head re-read, an in-lane merge of only what landed, then one write transaction that checks the expected head and advances the Branch. | [Store: the publish lane in a Commit](../engine/store/README.md#the-publish-lane-in-a-commit), [History: operations](../core/history/README.md#operations) | | 9 | After the lane, install sets the base to the published root; rows written after the capture stay on top of the view. A merged root is installed only when no such row covers what the merge changed (else `LiveConflict`, nothing published, the capture folds back); mutations wait from that check to the install. | [Commit: what it does](../engine/commit/README.md#what-it-does), [Workspace: state, serials and install](../engine/workspace/README.md#state-serials-and-install) | | 10 | For a merged root, the daemon invalidates the kernel entries that changed before it replies. | [Kernel routes: coherence](../engine/kernel-routes/README.md#coherence) | -| 11 | The reply is `Committed` or `UpToDate`; a conflict is the `Conflict` refusal and nothing is published. A published Commit whose install failed, or an uncertain outcome, is kept as custody and refuses the next Commit. | [Commit: custody and settle](../engine/commit/README.md#custody-and-settle), [Errors and events](../api/calls/errors-and-events.md) | +| 11 | The reply is `Committed` or `UpToDate`; a conflict is the `Conflict` refusal and nothing is published. A published Commit whose install failed, or an uncertain outcome, is kept as custody; the next Commit request first runs one resolution (read the head once: our Commit is installed, the unmoved head folds the capture back) and is refused `Unknown` only when that does not settle it. | [Commit: custody and settle](../engine/commit/README.md#custody-and-settle), [Errors and events](../api/calls/errors-and-events.md) | ## Related diff --git a/engine/crates/layerfs-daemon/src/control/mod.rs b/engine/crates/layerfs-daemon/src/control/mod.rs index f3fec9b3f0..6203b313e2 100644 --- a/engine/crates/layerfs-daemon/src/control/mod.rs +++ b/engine/crates/layerfs-daemon/src/control/mod.rs @@ -18,6 +18,7 @@ mod kernel; mod observation; mod operations; mod registry; +mod resolve; mod serve; #[cfg(target_os = "linux")] mod serving; diff --git a/engine/crates/layerfs-daemon/src/control/operations.rs b/engine/crates/layerfs-daemon/src/control/operations.rs index dfbe6ccf0f..4a8d38c86b 100644 --- a/engine/crates/layerfs-daemon/src/control/operations.rs +++ b/engine/crates/layerfs-daemon/src/control/operations.rs @@ -280,6 +280,9 @@ impl Service { token: WorkspaceToken, run: impl FnOnce(&BoundWorkspace) -> Result>, ) -> Result { + // Retained custody of an earlier Commit gets its one resolution + // first; unresolved, it refuses this Commit as admission would. + self.resolve_custody(token)?; let workspace = self.admit(token, Activity::Committing)?; // NFS route: what the client buffered is written back first, as a // FUSE write has already reached the Workspace when it returned. diff --git a/engine/crates/layerfs-daemon/src/control/resolve.rs b/engine/crates/layerfs-daemon/src/control/resolve.rs new file mode 100644 index 0000000000..36a657be9f --- /dev/null +++ b/engine/crates/layerfs-daemon/src/control/resolve.rs @@ -0,0 +1,76 @@ +//! The one resolution of a Workspace's retained Commit custody, run when its +//! next Commit is requested (store-service `store/resolve.rs`). It is not a +//! retry: nothing is resent, and the record is used once. +use super::{registry::bound_mut, Failure, Service}; +use crate::store::Resolution; +use layerfs_bridge::control::{Activity, ControlCode, ControlRefusal, WorkspaceToken}; + +impl Service { + /// When `token`'s Workspace is `Uncertain` or `LocalFailure` with a + /// retained Commit record, takes the entry for the attempt (activity + /// `Committing`, phase `resolve`), runs it once and settles the entry: + /// resolved, it is `Idle` and the Commit's own admission follows; + /// unresolved, it keeps custody (`LocalFailure` once a publication is + /// known) and the Commit is refused `Unknown` with the reason. Any other + /// entry is left to that admission. + pub(super) fn resolve_custody(&self, token: WorkspaceToken) -> Result<(), Failure> { + let (workspace, before) = { + let mut entries = self.entries.lock().map_err(|_| Failure::Poisoned)?; + let value = bound_mut(&mut entries, token)?; + let before = value.activity; + if !matches!(before, Activity::Uncertain | Activity::LocalFailure) + || !value.workspace.has_retained() + { + return Ok(()); + } + value.enter(Activity::Committing); + value.phase = "resolve"; + value.epoch = value.epoch.saturating_add(1); + (value.workspace.clone(), before) + }; + let result = workspace.resolve_retained(); + // An install of a merged root replaced what the Workspace showed. + let invalidated = match &result { + Ok(Some(Resolution { + replaced: Some((shown, installed)), + .. + })) => self.invalidate(token, &workspace, *shown, *installed), + _ => Ok(()), + }; + let mut entries = self.entries.lock().map_err(|_| Failure::Poisoned)?; + let value = bound_mut(&mut entries, token)?; + value.epoch = value.epoch.saturating_add(1); + match result { + Ok(Some(_)) => { + value.snapshot = workspace.snapshot().map_err(Failure::Workspace)?; + value.published = None; + value.enter(Activity::Idle); + invalidated + } + Ok(None) => { + value.enter(before); + Ok(()) + } + Err(unresolved) => { + if unresolved.published.is_some() { + value.published = unresolved.published; + } + value.enter(if value.published.is_some() { + Activity::LocalFailure + } else { + before + }); + Err(Failure::Custody(Box::new(ControlRefusal { + code: ControlCode::Unknown, + phase: "admission".into(), + moved: None, + published: value.published.clone(), + detail: super::kernel::bounded(&format!( + "original Commit custody retained; its one resolution did not settle it: {}", + unresolved.reason + )), + }))) + } + } + } +} diff --git a/engine/crates/layerfs-daemon/tests/store_commit.rs b/engine/crates/layerfs-daemon/tests/store_commit.rs index 3685972d69..c82c9d1143 100644 --- a/engine/crates/layerfs-daemon/tests/store_commit.rs +++ b/engine/crates/layerfs-daemon/tests/store_commit.rs @@ -782,3 +782,198 @@ fn nested_storage_unknown_before_publication_folds_back() { drop(store); f.cleanup(); } + +/// An unknown publication outcome in one Workspace of an observed Store: +/// the Commit of `value` fails in the Publish phase and keeps custody. +fn unknown_publication( + label: &str, + boundary: history_boundary::Boundary, + value: &[u8], +) -> ( + support::Fixture, + Arc, + Owner, + Arc, + Box, +) { + let f = support::Fixture::new(8, label); + let (store, _handles) = observed_store(&f, boundary); + let owner = Owner::start( + &f.directory.join("overlay.sqlite"), + ProfileConfig::default(), + OwnerConfig::default(), + ) + .unwrap(); + let workspace = bind(&store, &owner, &f, 1); + write(&workspace, value); + let failed = workspace + .commit(|save, _, snapshot| construct(save, snapshot, value, store.policy().construction())) + .unwrap_err(); + assert_eq!(failed.phase, CommitPhase::Publish); + assert!(matches!( + failed.error, + CommitError::History(HistoryError::UnknownOutcome) + )); + assert!(!failed.locally_settled && failed.published.is_none()); + assert!(workspace.has_retained(), "custody kept for its resolution"); + (f, store, owner, workspace, failed) +} + +/// Finding #5: the head shows the Commit whose acknowledgement was lost, so +/// its one resolution installs it and releases the custody; the next Commit +/// is admitted and publishes. +#[test] +fn a_lost_acknowledgement_is_resolved_by_installing_the_commit() { + let (f, store, owner, workspace, failed) = unknown_publication( + "resolve-landed", + history_boundary::Boundary::LostAcknowledgement, + &bytes(b'R'), + ); + let candidate = failed.intent.as_ref().unwrap().candidate_root; + let resolved = workspace.resolve_retained().unwrap().expect("retained"); + let Some(CommitOutcome::Committed { record, displaced }) = resolved.outcome else { + panic!("{resolved:?}"); + }; + assert_eq!((record.root, displaced), (candidate, None)); + let bound = workspace.snapshot().unwrap(); + assert_eq!(bound.branch.head_commit, Some(record.id)); + assert_eq!(bound.effective_root, candidate); + assert!(!workspace.has_retained()); + assert_eq!(read(&workspace), bytes(b'R')); + // The record is used once: nothing is left to resolve. + assert!(workspace.resolve_retained().unwrap().is_none()); + write(&workspace, &bytes(b'S')); + let later = workspace + .commit(|save, _, snapshot| { + construct(save, snapshot, &bytes(b'S'), store.policy().construction()) + }) + .unwrap(); + let Some(CommitOutcome::Committed { record: next, .. }) = &later.history else { + panic!("{:?}", later.history); + }; + assert_eq!( + next.parent, + Some(record.id), + "published over the resolved Commit" + ); + drop((later, failed)); + close(&owner, &workspace); + owner.stop().unwrap(); + drop(store); + f.cleanup(); +} + +/// The head is still the one the Commit was published against: nothing was +/// published, so the capture folds back, the change stays and the next +/// Commit publishes it. +#[test] +fn a_lost_request_is_resolved_by_folding_the_capture_back() { + let (f, store, owner, workspace, failed) = unknown_publication( + "resolve-lost", + history_boundary::Boundary::LostRequest, + &bytes(b'T'), + ); + let original = failed.binding.clone().unwrap(); + let resolved = workspace.resolve_retained().unwrap().expect("retained"); + assert!(resolved.outcome.is_none() && resolved.replaced.is_none()); + assert_eq!(workspace.snapshot().unwrap(), original); + assert_eq!(read(&workspace), bytes(b'T')); + let later = workspace + .commit(|save, _, snapshot| { + construct(save, snapshot, &bytes(b'T'), store.policy().construction()) + }) + .unwrap(); + assert!(matches!( + later.history, + Some(CommitOutcome::Committed { .. }) + )); + drop((later, failed)); + close(&owner, &workspace); + owner.stop().unwrap(); + drop(store); + f.cleanup(); +} + +/// Another Commit moved the head after the lost request: the head is +/// neither this Commit nor the head it expected, so the attempt does not +/// resolve, the custody stays and the Workspace still refuses a Commit. +#[test] +fn an_unknown_outcome_under_a_moved_head_stays_retained() { + let (f, store, owner, workspace, failed) = unknown_publication( + "resolve-moved", + history_boundary::Boundary::LostRequest, + &bytes(b'U'), + ); + let other = bind(&store, &owner, &f, 2); + write(&other, &bytes(b'V')); + let landed = other + .commit(|save, _, snapshot| { + construct(save, snapshot, &bytes(b'V'), store.policy().construction()) + }) + .unwrap(); + assert!(matches!( + landed.history, + Some(CommitOutcome::Committed { .. }) + )); + let unresolved = workspace.resolve_retained().unwrap_err(); + assert!(unresolved.published.is_none(), "{unresolved:?}"); + assert!( + unresolved.reason.contains("neither this Commit"), + "{unresolved:?}" + ); + assert!(matches!( + workspace + .commit(|_, _, _| unreachable!()) + .unwrap_err() + .error, + CommitError::InFlight + )); + // One attempt: the record is spent. + assert!(!workspace.has_retained()); + assert_eq!(read(&workspace), bytes(b'U')); + drop((landed, failed)); + close(&owner, &other); + owner.stop().unwrap(); + drop((workspace, store)); + f.cleanup(); +} + +/// The product Commit keeps its captured reader and operation owner with an +/// unknown outcome; the resolution releases them with the custody, and the +/// next product Commit is admitted. +#[test] +fn resolving_a_product_commit_releases_its_captured_owners() { + let f = support::Fixture::new(8, "resolve-captured"); + let (store, _handles) = observed_store(&f, history_boundary::Boundary::LostAcknowledgement); + let owner = Owner::start( + &f.directory.join("overlay.sqlite"), + ProfileConfig::default(), + OwnerConfig::default(), + ) + .unwrap(); + let workspace = bind(&store, &owner, &f, 1); + write(&workspace, &bytes(b'W')); + let failed = workspace.commit_captured(&Default::default()).unwrap_err(); + assert_eq!(failed.phase, CommitPhase::Publish); + assert!(failed + .namespace + .as_ref() + .is_some_and(|held| held.retained())); + let resolved = workspace.resolve_retained().unwrap().expect("retained"); + assert!(matches!( + resolved.outcome, + Some(CommitOutcome::Committed { .. }) + )); + assert_eq!(read(&workspace), bytes(b'W')); + write(&workspace, &bytes(b'X')); + let later = workspace.commit_captured(&Default::default()).unwrap(); + assert!(matches!( + later.history, + Some(CommitOutcome::Committed { .. }) + )); + drop((later, failed)); + close(&owner, &workspace); + owner.stop().unwrap(); + drop(store); + f.cleanup(); +} diff --git a/engine/crates/layerfs-daemon/tests/support/history_boundary.rs b/engine/crates/layerfs-daemon/tests/support/history_boundary.rs index 8d34008a22..9fda34efce 100644 --- a/engine/crates/layerfs-daemon/tests/support/history_boundary.rs +++ b/engine/crates/layerfs-daemon/tests/support/history_boundary.rs @@ -12,6 +12,9 @@ use std::{ pub enum Boundary { HeldWriter, LostAcknowledgement, + /// The request is lost before it reaches the Store: unknown to the + /// caller, nothing published. + LostRequest, } pub struct ObservedHistory { pub handles: Arc, @@ -68,6 +71,7 @@ impl HistoryCatalog for ObservedHistory { // I/O/quarantine qualification. Original caller remains unknown. Err(HistoryError::UnknownOutcome) } + Boundary::LostRequest => Err(HistoryError::UnknownOutcome), } } } diff --git a/engine/crates/layerfs-store-service/src/store/bind.rs b/engine/crates/layerfs-store-service/src/store/bind.rs index aead23e52c..d0c6daf2ba 100644 --- a/engine/crates/layerfs-store-service/src/store/bind.rs +++ b/engine/crates/layerfs-store-service/src/store/bind.rs @@ -163,6 +163,7 @@ impl Store { committing: std::sync::atomic::AtomicBool::new(false), producer: Default::default(), pending: std::sync::Mutex::new(None), + retained: std::sync::Mutex::new(None), }; // ยง4.3: a mount of a node at or below a marker frontier applies // the whiteout, so its view hides the path and its next Commit diff --git a/engine/crates/layerfs-store-service/src/store/captured.rs b/engine/crates/layerfs-store-service/src/store/captured.rs index 4e7ad30989..eb075e48d7 100644 --- a/engine/crates/layerfs-store-service/src/store/captured.rs +++ b/engine/crates/layerfs-store-service/src/store/captured.rs @@ -102,6 +102,9 @@ impl BoundWorkspace { } admission.released = failure.locally_settled && held.as_ref().is_none_or(|held| !held.retained()); + if !admission.released { + self.retain(&failure, held.as_ref()); + } failure.namespace = held; Err(failure) } @@ -239,7 +242,7 @@ impl BoundWorkspace { /// sequence; what it did not release stays named in the receipt. A done /// release's receipt is dropped at once. Neither release drains the /// reclamation it readies: that follows the answer (`reclaim`). - fn release_captured(&self, held: &mut CapturedConstruction) { + pub(super) fn release_captured(&self, held: &mut CapturedConstruction) { held.custody = None; if let Some(reader) = held.reader { if !self.released( diff --git a/engine/crates/layerfs-store-service/src/store/commit.rs b/engine/crates/layerfs-store-service/src/store/commit.rs index d3dc446b14..47470b9653 100644 --- a/engine/crates/layerfs-store-service/src/store/commit.rs +++ b/engine/crates/layerfs-store-service/src/store/commit.rs @@ -82,6 +82,9 @@ impl BoundWorkspace { Ok(_) => true, Err(failure) => failure.locally_settled, }; + if let Err(failure) = &result { + self.retain(failure, None); + } result } pub(super) fn admit_commit(&self) -> Result, Box> { @@ -468,6 +471,7 @@ impl BoundWorkspace { return Err(self.live_conflict(snapshot.scope, ours, candidate, &overlap)); } let changed: Arc<[u64]> = changed.into(); + retained.merged_over = Some((ours, changed.clone())); retained.prepared = retained.prepared.take().map(|ready| ready.merged(changed)); Some(hold) } else { @@ -551,7 +555,7 @@ impl BoundWorkspace { /// its local install; reads only immutable published objects, through /// the Workspace's own reader, opened at bind (#95: a Commit opens no /// control reader for them). - fn validate_candidate( + pub(super) fn validate_candidate( &self, target: &BranchSnapshot, candidate: FilesystemRootId, diff --git a/engine/crates/layerfs-store-service/src/store/commit_types.rs b/engine/crates/layerfs-store-service/src/store/commit_types.rs index b1728b413f..3fc54bb4eb 100644 --- a/engine/crates/layerfs-store-service/src/store/commit_types.rs +++ b/engine/crates/layerfs-store-service/src/store/commit_types.rs @@ -2,7 +2,7 @@ use super::PortError; use crate::OwnerError; use layerfs_content::{ - filesystem::FilesystemUpdateCounters, + filesystem::{FilesystemRootId, FilesystemUpdateCounters}, merge::{Conflict, LwwDecision}, ContentError, ObjectId, }; @@ -167,6 +167,10 @@ pub struct CommitFailure { pub locally_settled: bool, /// The product constructor's receipt, when its closure ran. pub namespace: Option, + /// For a merge: the Workspace's own constructed root and the serials + /// the merge changed against it (`live.rs`), which an install of the + /// merged root checks again. + pub merged_over: Option<(FilesystemRootId, Arc<[u64]>)>, } impl CommitFailure { pub(super) fn new(error: CommitError, workspace: WorkspaceId, route: Route) -> Self { @@ -185,6 +189,7 @@ impl CommitFailure { local_error: None, locally_settled: false, namespace: None, + merged_over: None, } } } diff --git a/engine/crates/layerfs-store-service/src/store/mod.rs b/engine/crates/layerfs-store-service/src/store/mod.rs index 0371536168..8e00b3f1b7 100644 --- a/engine/crates/layerfs-store-service/src/store/mod.rs +++ b/engine/crates/layerfs-store-service/src/store/mod.rs @@ -15,6 +15,7 @@ pub mod producer; pub mod read_handle; pub mod read_service; pub mod recognizer; +pub mod resolve; pub mod settle; pub mod statistics; pub mod types; @@ -34,6 +35,7 @@ pub use ports::{PortError, StorePorts}; pub use read_handle::StoreReader; pub use read_service::{ReadAdmissionError, ReadServiceWork, ReaderFactory}; pub use recognizer::{Recognizer, RecognizerWork, RECOGNIZER_SLOTS}; +pub use resolve::{Resolution, Unresolved}; pub use types::{ BindError, BindIntent, BindPhase, BindRefusal, BindRequest, BindSuccess, CloseError, NamedBindRequest, diff --git a/engine/crates/layerfs-store-service/src/store/operation.rs b/engine/crates/layerfs-store-service/src/store/operation.rs index 584cdadda8..b38d5d3047 100644 --- a/engine/crates/layerfs-store-service/src/store/operation.rs +++ b/engine/crates/layerfs-store-service/src/store/operation.rs @@ -17,6 +17,8 @@ pub struct BoundWorkspace { pub(super) producer: super::producer::Producer, /// A conflicted merge installed locally and not yet committed. pub(super) pending: Mutex>, + /// A Commit's retained custody awaiting its one resolution (`resolve.rs`). + pub(super) retained: Mutex>, } pub struct StoreOperation { workspace: Workspace, diff --git a/engine/crates/layerfs-store-service/src/store/resolve.rs b/engine/crates/layerfs-store-service/src/store/resolve.rs new file mode 100644 index 0000000000..f9b024358a --- /dev/null +++ b/engine/crates/layerfs-store-service/src/store/resolve.rs @@ -0,0 +1,265 @@ +//! One exact resolution of retained Commit custody, never a retry. +//! +//! A Commit whose publication answered with an unknown outcome, or whose +//! install failed after a known publication, keeps its capture and its +//! captured reader and operation owner, and the Workspace refuses later +//! Commits. Its record stays here. The Workspace's next Commit request runs +//! [`BoundWorkspace::resolve_retained`] once before its own admission: +//! +//! - publication known, or the head now our Commit (our candidate root, over +//! the head we published against): install that root as the new base; +//! - the head still the one we published against, with another root: nothing +//! was published, so the capture folds back; +//! - any other head: unresolved, and the custody stays. +//! +//! Nothing is resent: the head is read once, through the control reader (a +//! connection of its own, unaffected by a writer session the unknown outcome +//! quarantined), and the install or fold-back runs once. The record is taken +//! by the attempt whatever it finds. +use super::{BoundWorkspace, CapturedConstruction, CommitFailure, CommitPhase}; +use layerfs_content::{filesystem::FilesystemRootId, ObjectId}; +use layerfs_history::{BranchSnapshot, CommitOutcome, CommitRecord, CommitRequest}; +use layerfs_overlay::{Capture, CapturedReader, OperationOwner}; +use layerfs_workspace::WorkspaceError; +use std::sync::{atomic::Ordering, Arc}; + +/// What a retained Commit needs for its one resolution. +#[derive(Debug)] +pub(super) struct RetainedCommit { + capture: Capture, + intent: CommitRequest, + /// The binding the Commit started from: Branch identity, scope, profile. + binding: BranchSnapshot, + published: Option, + merged_over: Option<(FilesystemRootId, Arc<[u64]>)>, + reader: Option, + operation: Option, +} + +/// A resolved custody. `outcome` is the publication installed, `None` when +/// nothing was published and the capture folded back. `replaced` is what the +/// Workspace showed and the merged root installed under it, for the kernel's +/// invalidation, as a Commit's own `replaced`. +#[derive(Debug)] +pub struct Resolution { + pub outcome: Option, + pub replaced: Option<(ObjectId, ObjectId)>, +} + +/// The attempt did not resolve: the custody stays, with what it now knows. +#[derive(Debug)] +pub struct Unresolved { + pub published: Option, + pub reason: String, +} + +impl CommitFailure { + /// Whether one read of the head and one local step can settle this + /// failure exactly: an unanswered publication, or an install that failed + /// definitely after a known one. Local uncertainty never qualifies. + fn resolvable(&self) -> bool { + self.capture.is_some() + && self.intent.is_some() + && self.binding.is_some() + && !self.error.locally_uncertain() + && match self.phase { + CommitPhase::Publish => self.published.is_none() && self.error.uncertain(), + CommitPhase::Install => self.published.is_some(), + _ => false, + } + } +} + +impl BoundWorkspace { + /// Keeps what a resolution needs when `failure` retained custody and + /// qualifies; the failure itself still goes to the caller. + pub(super) fn retain(&self, failure: &CommitFailure, held: Option<&CapturedConstruction>) { + if failure.locally_settled + || !failure.resolvable() + || held.is_some_and(|held| held.custody.is_some() || held.release_error.is_some()) + { + return; + } + let (Some(capture), Some(intent), Some(binding)) = ( + failure.capture, + failure.intent.clone(), + failure.binding.clone(), + ) else { + return; + }; + if let Ok(mut slot) = self.retained.lock() { + *slot = Some(RetainedCommit { + capture, + intent, + binding, + published: failure.published.clone(), + merged_over: failure.merged_over.clone(), + reader: held.and_then(|held| held.reader), + operation: held.and_then(|held| held.operation), + }); + } + } + /// True while a retained Commit waits for its resolution. + pub fn has_retained(&self) -> bool { + self.retained.lock().is_ok_and(|slot| slot.is_some()) + } + /// The one resolution attempt (module docs). `Ok(None)`: nothing is + /// retained here. On `Ok(Some)` the custody is released and the next + /// Commit may be admitted. + pub fn resolve_retained(&self) -> Result, Box> { + let kept = self + .retained + .lock() + .map_err(|_| unresolved(None, "retained Commit record poisoned".into()))? + .take(); + let Some(kept) = kept else { return Ok(None) }; + let outcome = match kept.published.clone() { + Some(outcome) => Some(outcome), + None => self.read_outcome(&kept.intent)?, + }; + let replaced = match outcome { + Some(ref published) => self.install_retained(&kept, published)?, + None => { + self.job(|client: &crate::OwnerClient, route| { + client.resolve_failed(route, kept.capture) + }) + .map_err(|error| { + unresolved( + None, + format!("nothing was published; fold back failed: {error:?}"), + ) + })?; + None + } + }; + let mut held = CapturedConstruction { + reader: kept.reader, + operation: kept.operation, + ..Default::default() + }; + self.release_captured(&mut held); + if held.retained() { + return Err(unresolved( + outcome, + format!( + "resolved, but a captured owner was not released: {:?}", + held.release_error + ), + )); + } + self.committing.store(false, Ordering::Release); + Ok(Some(Resolution { outcome, replaced })) + } + /// One read of the head through the control reader. `Some`: the head is + /// our Commit (or, unmoved, already has our root); `None`: the head is + /// unmoved with another root, so nothing was published. + fn read_outcome( + &self, + intent: &CommitRequest, + ) -> Result, Box> { + let (head, record) = self + .store + .published(|history| { + let head = history.branch_snapshot(intent.branch)?; + let record = match head.as_ref().and_then(|head| head.branch.head_commit) { + Some(id) => history.commit(id)?, + None => None, + }; + Ok((head, record)) + }) + .map_err(|error| unresolved(None, format!("head read failed: {error:?}")))?; + let head = head.ok_or_else(|| unresolved(None, "the Branch is absent".into()))?; + let unmoved = head.branch.head_commit == intent.expected_head + && head.branch.base_layer == intent.expected_base; + if unmoved { + return Ok((head.effective_root == intent.candidate_root).then_some( + CommitOutcome::UpToDate { + head: head.branch.head_commit, + root: head.effective_root, + }, + )); + } + match record { + Some(record) if ours(&record, intent) => Ok(Some(CommitOutcome::Committed { + displaced: record.meta.displaced, + record: Box::new(record), + })), + _ => Err(unresolved( + None, + format!( + "the head is {:?}: neither this Commit nor the head it was published against", + head.branch.head_commit + ), + )), + } + } + /// Installs a known publication's root, under the same live check and + /// mutation hold as a Commit's own merged install. + fn install_retained( + &self, + kept: &RetainedCommit, + outcome: &CommitOutcome, + ) -> Result, Box> { + let known = || Some(outcome.clone()); + let candidate = FilesystemRootId(kept.intent.candidate_root); + let mut target = kept.binding.clone(); + target.branch.head_commit = kept.intent.expected_head; + target.branch.base_layer = kept.intent.expected_base; + target.effective_root = kept.intent.expected_root; + let base = self + .workspace + .base() + .map_err(|error| unresolved(known(), format!("base: {error}")))?; + let mut prepared = self + .validate_candidate(&target, candidate, kept.capture, &base) + .map_err(|error| unresolved(known(), format!("validate: {error:?}")))?; + let held = match &kept.merged_over { + Some((ours, changed)) => { + let (hold, overlap) = self + .hold_live(changed) + .map_err(|error| unresolved(known(), format!("live check: {error:?}")))?; + if !overlap.is_empty() { + let conflict = self.live_conflict(target.scope, *ours, candidate, &overlap); + return Err(unresolved( + known(), + format!("published; rows written since overlap the merge: {conflict:?}"), + )); + } + prepared = prepared.merged(changed.clone()); + Some(hold) + } + None => None, + }; + self.job(|client: &crate::OwnerClient, route| { + client.install_prepared(route, self.workspace.clone(), prepared) + }) + .map_err(|error| unresolved(known(), format!("install: {error:?}")))?; + drop(held); + let (head, root) = match outcome { + CommitOutcome::Committed { record, .. } => (Some(record.id), record.root), + CommitOutcome::UpToDate { head, root } => (*head, *root), + }; + let mut next = target; + next.effective_root = candidate.0; + next.branch.head_commit = head; + next.head_root = head.map(|_| root); + let poisoned = || unresolved(known(), format!("{:?}", WorkspaceError::BindingPoisoned)); + *self.snapshot.lock().map_err(|_| poisoned())? = next; + *self.pending.lock().map_err(|_| poisoned())? = None; + Ok(kept + .merged_over + .as_ref() + .map(|(ours, _)| (ours.0, candidate.0))) + } +} + +/// Our Commit: our candidate root, published over the head we expected. +fn ours(record: &CommitRecord, intent: &CommitRequest) -> bool { + record.root == intent.candidate_root + && record.parent == intent.expected_head + && record.base_layer == intent.expected_base +} + +fn unresolved(published: Option, reason: String) -> Box { + Box::new(Unresolved { published, reason }) +} From cecee1eaaba3f6d89f92459832f84fb93f684b65 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 15:56:47 +0800 Subject: [PATCH 5/6] Test: control Commit unknown outcomes follow the phase contract Follow-up to 37c0a8b149 (finding #4), found on an integration branch of PRs #762-#765. layerfs-control tests/mount_control.rs an_original_unknown_blocks_another_commit_and_normal_unmount injected a StorageError::UnknownOutcome from the producer during construction and expected the Workspace to stay Uncertain. Before the Publish phase a Store unknown cannot have published, so under the phase-aware CommitFailure::uncertain() it folds back and answers Failed; the test failed at mount_control.rs:298. The test keeps its intent ("an original unknown blocks another Commit and a normal unmount") with an uncertainty that still holds before Publish: an overlay outcome unknown (OverlayError::Uncertain). It is renamed an_original_local_unknown_blocks_another_commit_and_normal_unmount. The Store unknown it used to inject moves to a new test, a_store_unknown_before_publication_folds_back_and_admits_a_commit: Failed, the Workspace stays Idle on its binding with nothing published, a later Commit publishes over the bound head, and a normal unmount is admitted. No test deleted. Production LOC: 207,195 -> 207,195 (delta 0) core 40,989 -> 40,989 (0) engine 96,515 -> 96,515 (0) control 59,366 -> 59,366 (0) api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent 384dbb33fc and the staged tree (test-only change) Co-Authored-By: Claude Opus 5.5 --- .../layerfs-control/tests/mount_control.rs | 98 +++++++++++++++++-- 1 file changed, 91 insertions(+), 7 deletions(-) diff --git a/control/crates/layerfs-control/tests/mount_control.rs b/control/crates/layerfs-control/tests/mount_control.rs index c8ec5e5672..92a72b7aa0 100644 --- a/control/crates/layerfs-control/tests/mount_control.rs +++ b/control/crates/layerfs-control/tests/mount_control.rs @@ -259,8 +259,12 @@ fn another_control_channel_observes_running_commit_and_refuses_unmount_before_ef f.cleanup(); } +/// An original local uncertainty (the overlay's outcome unknown) keeps the +/// capture: the Workspace is `Uncertain` and refuses another Commit and a +/// normal unmount. Before the Publish phase only local uncertainty does +/// this; a Store unknown there folds back (next test). #[test] -fn an_original_unknown_blocks_another_commit_and_normal_unmount() { +fn an_original_local_unknown_blocks_another_commit_and_normal_unmount() { let f = fixture::Fixture::new("control-unknown"); let branch = f.host.project.branch.branch.id; let service = f.service.clone(); @@ -272,12 +276,13 @@ fn an_original_unknown_blocks_another_commit_and_normal_unmount() { ); let original = service .serve_one(connection, |_, _, _| { - Err(layerfs_daemon::store::CommitError::Storage( - layerfs_storage::StorageError::UnknownOutcome { - original: Box::new(layerfs_storage::StorageError::Integrity( - "original producer uncertainty", - )), - }, + Err(layerfs_daemon::store::CommitError::Workspace( + layerfs_workspace::WorkspaceError::Overlay( + layerfs_overlay::OverlayError::Uncertain { + cause: Box::new(layerfs_overlay::OverlayError::Quarantined), + completion: None, + }, + ), )) }) .unwrap(); @@ -319,6 +324,85 @@ fn an_original_unknown_blocks_another_commit_and_normal_unmount() { drop(retained); f.cleanup(); } + +/// Finding #4: an unknown Store outcome during construction, before the +/// Publish phase, cannot have published. The capture folds back, the reply +/// is `Failed`, the Workspace stays `Idle`, the change is kept, and a later +/// Commit and a normal unmount are admitted. +#[test] +fn a_store_unknown_before_publication_folds_back_and_admits_a_commit() { + let f = fixture::Fixture::new("control-unknown-folds"); + let branch = f.host.project.branch.branch.id; + let service = f.service.clone(); + let policy = f.installed.opened.store.policy().construction(); + let (channel, worker) = support::pair(move |connection| { + drop( + service + .serve_one(connection, |_, _, _| unreachable!()) + .unwrap(), + ); + let original = service + .serve_one(connection, |_, _, _| { + Err(layerfs_daemon::store::CommitError::Storage( + layerfs_storage::StorageError::UnknownOutcome { + original: Box::new(layerfs_storage::StorageError::Integrity( + "original producer uncertainty", + )), + }, + )) + }) + .unwrap(); + drop( + service + .serve_one(connection, |_, _, _| unreachable!()) + .unwrap(), + ); + drop( + service + .serve_one(connection, |save, _, snapshot| { + fixture::construct(save, snapshot, b'U', policy) + }) + .unwrap(), + ); + drop( + service + .serve_one(connection, |_, _, _| unreachable!()) + .unwrap(), + ); + original + }); + let mut client = Control::new(channel); + let (token, binding) = mount(&mut client, identity(90), branch); + fixture::write(&f.service, token, b'U'); + let reply = client + .call(Request::Commit(layerfs_bridge::control::CommitControl { + token, + force: false, + message: None, + expected: None, + })) + .unwrap(); + assert!( + matches!(&reply, Reply::Refused(value) if value.code == ControlCode::Failed), + "{reply:?}" + ); + let observed = status(&mut client, token); + assert_eq!(observed.activity, Activity::Idle); + assert_eq!(observed.binding, binding); + assert!(observed.published.is_none()); + let record = committed(&mut client, token); + assert_eq!(record.parent, binding.branch.head_commit); + close(&mut client, token); + let original = worker.join(); + let failed = match &original.outcome { + Err(layerfs_daemon::control::Failure::Commit(failed)) => failed, + other => panic!("{:?}", other.as_ref().err()), + }; + assert!(failed.locally_settled && !failed.uncertain()); + println!("CONTROL_UNKNOWN_FOLDS producer_unknown_before_publish=Failed capture=folded_back later_commit=Committed normal_unmount=allowed"); + drop(original); + f.cleanup(); +} #[test] fn status_retains_known_publication_when_the_engine_is_unavailable() { let f = fixture::Fixture::new("control-local-failure"); From ec1936cf3af873cfb999ae786e9bdb7607cf6bc2 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 16:05:01 +0800 Subject: [PATCH 6/6] Test: F3 lost acknowledgement is resolved by the next Commit Follow-up to 384dbb33fc (finding #5), found by the nightly mount lane on an integration branch of PRs #762-#765. layerfs-daemon tests/mounted_commit_failures.rs F3 stages Boundary::LostAcknowledgement (a real publication, then UnknownOutcome) and its retained tail expected the next Commit to be refused; under #5 that Commit's one resolution reads the head, finds exactly this Commit and installs it, so the Commit was admitted (panic at mounted_commit_failures.rs:478). F3 is renamed f3_unknown_history_outcome_is_resolved_by_the_next_commit_and_the_mount_still_serves and ends in a new resolved_tail: after the failure the Workspace is Uncertain with both owners kept and the mount still serves the same view and a new write; an independent session reads the head as one Commit of the candidate root over the bound head (published once), and a fresh bind of it is the captured tree; the next Commit is admitted, its parent is that landed Commit, its root carries the write made since and equals the mount's tree (later_exact), the registry is Idle; reads still work and the normal unmount drains and removes the mount. Deleted: the retained_tail helper, its Kept enum, the refused() helper and the SECOND constant, whose only caller was F3's old expectation that the next Commit and a normal unmount are refused under retained custody. That contract no longer holds for a resolvable unknown outcome; retained custody that cannot be resolved is covered without a mount by store_commit.rs an_unknown_outcome_under_a_moved_head_stays_retained and by layerfs-control mount_control.rs an_original_local_unknown_blocks_another_commit_and_normal_unmount. The module header notes F3's new end and where the nothing-published case is staged. Production LOC: 207,195 -> 207,195 (delta 0) core 40,989 -> 40,989 (0) engine 96,515 -> 96,515 (0) control 59,366 -> 59,366 (0) api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent cecee1eaab and the staged tree (test-only change) Co-Authored-By: Claude Opus 5.5 --- .../tests/mounted_commit_failures.rs | 285 +++++------------- 1 file changed, 75 insertions(+), 210 deletions(-) diff --git a/engine/crates/layerfs-daemon/tests/mounted_commit_failures.rs b/engine/crates/layerfs-daemon/tests/mounted_commit_failures.rs index 2e4a395214..81c04244cf 100644 --- a/engine/crates/layerfs-daemon/tests/mounted_commit_failures.rs +++ b/engine/crates/layerfs-daemon/tests/mounted_commit_failures.rs @@ -11,7 +11,9 @@ //! - F2: the same real held writer, taken around the real `commit_branch` //! by the external catalog wrapper of `support/history_boundary.rs`. //! - F3: external catalog boundary scope; not a kernel SQLite I/O failure. The -//! wrapper performs the real publication and reports an unknown outcome. +//! wrapper performs the real publication and reports an unknown outcome; +//! the next Commit request's one resolution finds that Commit as the head +//! and installs it (finding #5). //! - F4: external catalog boundary scope. The wrapper performs the real //! publication and then reserves every free admission registration of the //! local owner through its public `submit_when_available`, submitting @@ -33,7 +35,8 @@ //! that was attempted and failed is not staged anywhere. //! - F3 covers only the world where the publication happened and its //! acknowledgement was lost. An unknown outcome where nothing was published -//! is not staged. +//! (resolved by folding the capture back) is staged without a mount, in +//! `store_commit.rs`. //! //! Product expectations are collected and reported after the mount has been //! torn down, so a deviation still leaves its whole evidence and no mount. @@ -59,8 +62,7 @@ mod mounted; mod rig; use history_boundary::{Boundary, ObservedHistory}; use layerfs_bridge::control::{ - Activity, ControlCode, ControlRefusal, MountPhase, ReadyMount, Reply, Request, WorkspaceStatus, - WorkspaceToken, + Activity, ReadyMount, Reply, Request, WorkspaceStatus, WorkspaceToken, }; use layerfs_content::{ContentError, ObjectId}; use layerfs_daemon::{ @@ -83,14 +85,12 @@ use rig::{base_tree, bash_in, host, passed, root}; use std::{ cell::Cell, fmt::Debug, - fs, path::Path, process::Command as Process, sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }, - time::{Duration, Instant}, }; /// External storage boundary scope: test code at the public pack persistence @@ -209,7 +209,6 @@ head -c 6291456 /dev/urandom > made/big.bin "#; const AFTER: &str = "made/after-failure.txt"; const FIRST: &[u8] = b"written after the failed Commit\n"; -const SECOND: &[u8] = b"and after the refused unmount\n"; /// A bounded description of an original value for an evidence line. fn brief(value: &impl Debug) -> String { @@ -273,16 +272,6 @@ enum Staging { /// `storage_boundary::PublishBoundary` around the real writer. Publication, } -/// Why a failure's custody stays, which decides what the retained tail -/// expects of the driver's local resolution and of the Branch. -#[derive(Clone, Copy, Eq, PartialEq)] -enum Kept { - /// The publication happened; the driver attempted no local resolution. - Published, - /// Nothing was published; the driver's one local resolution was itself - /// refused before effect. - ResolutionRefused, -} /// One installed Normal Store, opened once and kept open, and one real /// kernel serving assembly over it: `Harness::new`, as `rig::Rig` uses it. struct Fx { @@ -471,14 +460,6 @@ fn quiet(harness: &Harness, token: WorkspaceToken) { settled }); } -/// A refusal for retained original custody, made before any effect. -fn refused(result: Result, what: &str) -> ControlRefusal { - match result { - Err(Failure::Custody(refusal)) => *refusal, - Ok(done) => panic!("{what}: admitted past retained custody: {:?}", done.reply), - Err(other) => panic!("{what}: {}", brief(&other)), - } -} /// The same mount after the failure: the view is what it was before the /// Commit, and one more write by externally launched bash is served and read /// back. Returns the tree with that write. @@ -922,22 +903,14 @@ impl Case { drop(mounted); checks.done(name); } - /// A failure whose custody stays: the failure and the engine name the - /// same reader and owner, later Commit and normal unmount are refused - /// Unknown before any effect, the mount keeps serving, and an independent - /// observation of the Branch settles nothing. The test then detaches the - /// kernel mount itself. - fn retained_tail( - mut self, - left: Left, - failure: Box, - activity: Activity, - why: Kept, - ) { + /// An unknown publication outcome whose Commit did land (finding #5): + /// custody stays after the failure (`Uncertain`, both owners kept) and + /// the mount keeps serving; the next Commit request runs the one + /// resolution, which reads the head, finds exactly this Commit and + /// installs it, so that Commit is admitted, publishes over it (no second + /// publication of the same changes) and is exact; unmount is normal. + fn resolved_tail(mut self, left: Left, failure: Box) { let name = self.name; - let token = self.token(); - let _request = left.request(); - let directory = self.ready.directory.clone(); let mount = root(&self.ready).to_path_buf(); expect!( self.checks, @@ -947,119 +920,44 @@ impl Case { ); expect!( self.checks, - !left.settled - && left.local.is_none() - && left.local_error.is_some() == (why == Kept::ResolutionRefused), - "{name}: nothing local is resolved: settled={} local={:?} local_error={:?}", + !left.settled && left.local.is_none() && left.local_error.is_none(), + "{name}: nothing local is resolved by the failure: settled={} local={:?} local_error={:?}", left.settled, left.local, left.local_error ); expect!( self.checks, - left.namespace.as_ref().is_some_and(Owners::kept), + left.namespace.as_ref().is_some_and(Owners::kept) + && failure + .namespace + .as_ref() + .is_some_and(CapturedConstruction::retained), "{name}: an unsettled failure keeps the reader and the operation owner: {:?}", left.namespace ); - expect!( - self.checks, - failure - .namespace - .as_ref() - .is_some_and(CapturedConstruction::retained), - "{name}: the original failure carries the retained owners" - ); - let _kept = left - .namespace - .as_ref() - .map(|owners| (owners.reader, owners.operation)); - + drop(failure); let status = self.status(); let captured = status.local.as_ref().and_then(|local| local.captured); expect!( self.checks, - status.activity == activity - && status.published == left.published + status.activity == Activity::Uncertain + && status.published.is_none() && status.binding == self.bound.binding && captured == Some(left.capture.generation.number()), "{name}: registry after the failure: activity={:?} published={:?} captured={captured:?}", status.activity, status.published ); - let after = still_serving(&mount, &self.before, name); println!( "{name} MOUNT same_view_after_failure=true new_write_served=true paths={}", after.len() ); - // A later Commit is refused before any effect: no new capture, no - // registry change, the same owners in the engine. - let same = |a: &WorkspaceStatus, b: &WorkspaceStatus| { - a.epoch == b.epoch - && a.activity == b.activity - && a.published == b.published - && a.binding == b.binding - && a.local == b.local - }; - let before_commit = self.status(); - let commit = refused(self.fx.harness.try_commit(token), "a later Commit"); - let _after_commit = self.status(); - expect!( - self.checks, - commit.code == ControlCode::Unknown && commit.published == left.published, - "{name}: a later Commit is refused Unknown with the known publication: {commit:?}" - ); - - // Normal unmount is refused the same way and detaches nothing. - let unmount = refused(self.fx.harness.try_unmount(token), "normal unmount"); - let after_unmount = self.status(); - let phase = after_unmount.kernel.as_ref().map(|kernel| kernel.phase); - expect!( - self.checks, - unmount.code == ControlCode::Unknown && unmount.published == left.published, - "{name}: normal unmount is refused Unknown: {unmount:?}" - ); - expect!( - self.checks, - same(&before_commit, &after_unmount) - && phase == Some(MountPhase::Ready) - && mount_entry(&directory).is_some(), - "{name}: the refused unmount had an effect: phase={phase:?} mounted={}", - mount_entry(&directory).is_some() - ); - println!( - "{name} REFUSALS later_commit=code:{:?},phase:{},published:{} unmount=code:{:?},phase:{} epoch_unchanged={} captured_unchanged={} kernel_phase={phase:?} mount_table_entry=present", - commit.code, - commit.phase, - commit.published.is_some(), - unmount.code, - unmount.phase, - before_commit.epoch == after_unmount.epoch, - before_commit.local == after_unmount.local - ); - // The mount goes on serving reads and writes under retained custody. - passed( - &bash_in( - COMMAND, - &mount, - &format!( - "set -euo pipefail; printf 'and after the refused unmount\\n' >> {AFTER}; cat README.md target/debug/app > /dev/null" - ), - ), - "write after the refused unmount", - ); - assert_eq!( - fs::read(mount.join(AFTER)).unwrap(), - [FIRST, SECOND].concat() - ); - println!("{name} MOUNT serves_reads_and_writes_under_retained_custody=true"); - - // Observations that do not go through this Workspace: a separate - // read-only session of the Store and, after a publication, a fresh - // bind of the Branch. A published candidate is the Branch root and - // its tree is the captured frontier; otherwise the Branch is what - // this Workspace bound. + // An independent session: the Branch head is one Commit of the + // candidate root, published once, over the bound head. + let candidate = left.candidate.expect("the staged candidate"); let observer = SqliteHandles::open_read_only( self.fx.fixture.config.clone(), installed::BINDING, @@ -1071,99 +969,65 @@ impl Case { .branch_snapshot(self.fx.harness.branch) .unwrap() .unwrap(); + let landed = observed + .branch + .head_commit + .and_then(|id| observer.history.commit(id).unwrap()); drop(observer); - let branch = match why { - Kept::Published => { - let candidate = left.candidate.expect("the staged candidate"); - expect!( - self.checks, - observed.effective_root == candidate - && observed.branch.head_commit.is_some() - && candidate != self.bound.binding.effective_root, - "{name}: an independent session reads the candidate as the Branch root: observed={:?} candidate={candidate:?}", - observed.effective_root - ); - let published = self.fx.published(candidate); - assert_same( - &self.before, - &published, - &format!("{name}: the published candidate, fresh bind"), - ); - format!( - "independent_session_root=candidate head={:?} fresh_bind_root=candidate fresh_bind_paths={}", - observed.branch.head_commit, - published.len() - ) - } - Kept::ResolutionRefused => { - expect!( - self.checks, - left.candidate.is_none() - && observed.effective_root == self.bound.binding.effective_root - && observed.branch.head_commit == self.bound.binding.branch.head_commit, - "{name}: an independent session reads the bound Branch unchanged: observed={:?} head={:?} candidate={:?}", - observed.effective_root, - observed.branch.head_commit, - left.candidate - ); - format!( - "independent_session_root=bound_root_unchanged head={:?} candidate={:?}", - observed.branch.head_commit, left.candidate - ) - } - }; - // No observation settles the original failure. - let observed_status = self.status(); expect!( self.checks, - observed_status.activity == activity - && observed_status.published == left.published - && observed_status.binding == self.bound.binding - && observed_status.epoch == before_commit.epoch, - "{name}: an observation settled the original failure: activity={:?} published={:?} epoch={}", - observed_status.activity, - observed_status.published, - observed_status.epoch + landed.as_ref().is_some_and(|record| record.root == candidate + && record.parent == self.bound.binding.branch.head_commit), + "{name}: the head is the landed Commit over the bound head: {landed:?} candidate={candidate:?}" ); - println!( - "{name} OBSERVED {branch} original_failure_settled_by_observation=false activity={:?}", - observed_status.activity + let published = self.fx.published(candidate); + assert_same( + &self.before, + &published, + &format!("{name}: the landed candidate, fresh bind"), ); - // Teardown by the test. The product refuses normal unmount for this - // custody and has no forced unmount: one plain umount(8), launched - // and reaped here, detaches the kernel mount. The registry entry and - // its session are then dropped with the serving assembly. - quiet(&self.fx.harness, token); - let detached = Process::new("umount").arg(&directory).output().unwrap(); - assert!(detached.status.success(), "{detached:?}"); - assert!(mount_entry(&directory).is_none()); - let deadline = Instant::now() + Duration::from_secs(3); - let (loops, phase) = loop { - let kernel = self.fx.harness.status(token).kernel.unwrap(); - let loops = kernel - .work - .map_or((0, 0), |work| (work.loops_exited, work.loops_configured)); - if (loops.0 == loops.1 && loops.1 != 0) || Instant::now() >= deadline { - break (loops, kernel.phase); - } - std::thread::sleep(Duration::from_millis(5)); - }; + // The next Commit request resolves the custody and is admitted: it + // publishes the write made since, over the landed Commit, and + // installs exactly the tree the mount shows. + let head = landed.map(|record| record.id); + let later = self.later_exact(&mount, head); + expect!( + self.checks, + later + .as_ref() + .is_some_and(|record| record.root != candidate), + "{name}: the later Commit carries the write made after the failure: {later:?}" + ); + passed( + &bash_in( + COMMAND, + &mount, + "set -euo pipefail; cat README.md target/debug/app > /dev/null", + ), + "reads after the resolution", + ); println!( - "{name} TEARDOWN by_test=plain umount(8) of {directory} status={:?} mount_table_entry=gone receive_loops_exited={}/{} registry_phase_after={phase:?} product_unmount=refused forced_unmount=none deviations={}", - detached.status, - loops.0, - loops.1, - self.checks.0.len() + "{name} RESOLVED landed={head:?} later_parent=landed later_root_differs={} mount_served_throughout=true", + later.as_ref().is_some_and(|record| record.root != candidate) ); + + let unmounted = self.unmount(); + let directory = self.ready.directory.clone(); + if mount_entry(&directory).is_some() { + let done = Process::new("umount").arg(&directory).output().unwrap(); + println!( + "{name} TEARDOWN by_test=plain umount(8) status={:?}", + done.status + ); + } let Self { fx, mounted, checks, .. } = self; - drop(failure); - fx.finish(false); + fx.finish(unmounted); drop(mounted); checks.done(name); } @@ -1226,9 +1090,10 @@ fn f2_store_busy_at_publication_is_settled_and_releases_both_owners() { /// F3. Lost History acknowledgement. External catalog boundary scope; not a /// kernel SQLite I/O failure: the wrapper performs the real publication and -/// then reports an unknown outcome. +/// then reports an unknown outcome. Custody stays until the next Commit +/// request, whose one resolution finds the landed Commit and installs it. #[test] -fn f3_unknown_history_outcome_keeps_custody_and_the_mount_still_serves() { +fn f3_unknown_history_outcome_is_resolved_by_the_next_commit_and_the_mount_still_serves() { let mut case = Case::start( "F3", "external catalog boundary scope; not a kernel SQLite I/O failure (support/history_boundary.rs Boundary::LostAcknowledgement: real publication, then UnknownOutcome)", @@ -1246,7 +1111,7 @@ fn f3_unknown_history_outcome_keeps_custody_and_the_mount_still_serves() { left.phase, left.published ); - case.retained_tail(left, failure, Activity::Uncertain, Kept::Published); + case.resolved_tail(left, failure); } /// F5. A definite failure inside the producer: real Store Busy. A change