From ff8d68fa0b92de30bf002f54e0ee539f82a31e6e Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 17:19:40 +0800 Subject: [PATCH 1/6] fix(sandbox): worker place evidence and a tombstone on every removal path Gaps left after #783 (missing evidence stays "no proof", never death): - Worker-route Sandboxes now record place evidence. `sandbox.create` sends the machine name and the generation the home record minted with the create (`Call::Create.place`, frame fields `place_machine`/`generation`); the worker writes them into its own record after the start (`files::save_place`, best effort, never over a record that has a generation), so `mount_place` there returns them and the daemon's bind records the generation token. A worker's root keeps no machine record, so its mounts still carry no incarnation (none is guessed). - Every removal of a Sandbox's home record writes the retirement tombstone first, best effort, reporting a failed write in `left`: `sandbox.remove` on the forgotten, stopped, already-gone and unstarted paths and `forget` (`retire_home`, which writes the home's tombstone for a worker's Sandbox), `lifecycle::reclaim`, and the close's forget paths. A worker's root is not a home: `record::retire` writes nothing there. - One tombstone per name: once a recreated Sandbox's started record is written, the name's older tombstone of the same home goes (`record::drop_retired`); the newer record proves the old generation's mounts dead by itself. A tombstone that is not older is kept. - `machine.remove` keeps deleting `machine//` with its tombstones; it is refused while a Store or Sandbox uses the machine, and the decision is documented in `record/tombstone.rs`. Tests: new `place_evidence` (worker place, no tombstone in a worker root, recreate drops the older tombstone); `half_created` asserts the unstarted removal's tombstone; `host_frame` round-trips a create with a place. Production LOC: 214,060 -> 214,149 (delta +89) scope: tools/production_loc.py (repo-pinned counter), first-parent tree vs committed tree reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Co-Authored-By: Claude Opus 5.5 --- control/crates/layerfs-sandbox/src/create.rs | 11 +- .../crates/layerfs-sandbox/src/dispatch.rs | 4 +- control/crates/layerfs-sandbox/src/files.rs | 19 +++ .../crates/layerfs-sandbox/src/host/call.rs | 8 +- .../crates/layerfs-sandbox/src/host/frame.rs | 9 +- .../crates/layerfs-sandbox/src/lifecycle.rs | 63 ++++++--- .../crates/layerfs-sandbox/src/record/mod.rs | 4 +- .../layerfs-sandbox/src/record/sandbox.rs | 20 ++- .../layerfs-sandbox/src/record/tombstone.rs | 73 ++++++++-- control/crates/layerfs-sandbox/src/remove.rs | 30 +++- .../layerfs-sandbox/tests/half_created.rs | 9 +- .../layerfs-sandbox/tests/host_frame.rs | 6 +- .../layerfs-sandbox/tests/installed_repair.rs | 2 +- .../layerfs-sandbox/tests/place_evidence.rs | 130 ++++++++++++++++++ .../layerfs-sandbox/tests/retired_docker.rs | 2 +- 15 files changed, 343 insertions(+), 47 deletions(-) create mode 100644 control/crates/layerfs-sandbox/tests/place_evidence.rs diff --git a/control/crates/layerfs-sandbox/src/create.rs b/control/crates/layerfs-sandbox/src/create.rs index c328958291..4d15f69ce0 100644 --- a/control/crates/layerfs-sandbox/src/create.rs +++ b/control/crates/layerfs-sandbox/src/create.rs @@ -154,8 +154,14 @@ pub fn create( let _sandbox = record::lock(&home, name)?; record.clone().with_op(&op).write(&home)?; } + // a worker keeps its own record of the Sandbox: it is sent the machine + // and generation minted here, which the mounts it places then carry + let place = (record.generation()).map(|g| (machine.to_owned(), g.to_owned())); let asked = Asked { - call: Call::Create { platform: None }, + call: Call::Create { + platform: None, + place, + }, message: Message::Absent, image: request.image.clone(), start: Some((0, total(request.mount))), @@ -176,6 +182,9 @@ pub fn create( record = direct::save(&home, record, opened)?; } record.write(&home)?; + // the started record's newer generation proves the retired one's + // mounts dead by itself: the name's older tombstone goes + record::drop_retired(&home, &record); if !request.mount { events.phase("start", Some(1), Some(1), Vec::new()); } diff --git a/control/crates/layerfs-sandbox/src/dispatch.rs b/control/crates/layerfs-sandbox/src/dispatch.rs index 61097f4b23..fdef55f8d9 100644 --- a/control/crates/layerfs-sandbox/src/dispatch.rs +++ b/control/crates/layerfs-sandbox/src/dispatch.rs @@ -22,7 +22,9 @@ pub fn call(host: Host, call: Call) -> Outcome { // the operator view of control admission and retained failures // (#540): a bounded read model, never a product operation Call::Capacity => capacity(&host), - Call::Create { platform } => crate::lifecycle::create(&host, platform.as_deref()), + Call::Create { platform, place } => { + crate::lifecycle::create(&host, platform.as_deref(), place.as_ref()) + } Call::Close { force, held } => { crate::lifecycle::close(&host, force, held.as_deref().unwrap_or_default()) } diff --git a/control/crates/layerfs-sandbox/src/files.rs b/control/crates/layerfs-sandbox/src/files.rs index c02b2fa49a..0675cb2303 100644 --- a/control/crates/layerfs-sandbox/src/files.rs +++ b/control/crates/layerfs-sandbox/src/files.rs @@ -118,6 +118,25 @@ pub fn save_sandbox( let record = record.with_start(format!("{store}/{}", state.project), facts, daemon); record.write_in(directory) } +/// Writes the machine and generation a worker's caller minted (`place`) +/// into the worker's own record of Sandbox `name` in `directory`, so the +/// mounts it places carry them (#783 gap 1). A record that names a +/// generation already (on `native`, the home's own) is left as it is. Best +/// effort: a record left without them only means its mounts carry no place +/// evidence, and missing evidence is never death. +pub fn save_place(directory: &Path, name: &str, (machine, generation): &(String, String)) { + let _ = (|| -> Result<()> { + let _sandbox = crate::record::lock_in(directory, name)?; + let Some(record) = SandboxRecord::read_in(directory, name)? else { + return Ok(()); + }; + if record.generation().is_some() { + return Ok(()); + } + record.with_place(machine, generation).write_in(directory) + })(); +} + /// The kernel route a running Sandbox's Workspaces use: loopback NFS for a /// native (macOS) one, FUSE for every other. pub fn route(runtime: &Sandbox) -> &'static str { diff --git a/control/crates/layerfs-sandbox/src/host/call.rs b/control/crates/layerfs-sandbox/src/host/call.rs index d23b0e5a11..591f1fdad9 100644 --- a/control/crates/layerfs-sandbox/src/host/call.rs +++ b/control/crates/layerfs-sandbox/src/host/call.rs @@ -139,7 +139,13 @@ impl Message { pub enum Call { /// `sandbox.create`; the image travels in [`Deploy`]. `platform` is a /// caller's named platform (#529), checked against the deployment. - Create { platform: Option }, + /// `place` is the machine name and Sandbox generation the caller's home + /// record minted: a worker writes them into its own record, so the + /// mounts it places carry them (a mount there reads no home record). + Create { + platform: Option, + place: Option<(String, String)>, + }, /// `sandbox.close(force)`; `held` names Workspaces the caller records /// (a Sandbox it reaches directly, #535 G4). Close { diff --git a/control/crates/layerfs-sandbox/src/host/frame.rs b/control/crates/layerfs-sandbox/src/host/frame.rs index f463cb51f4..2428db622f 100644 --- a/control/crates/layerfs-sandbox/src/host/frame.rs +++ b/control/crates/layerfs-sandbox/src/host/frame.rs @@ -68,8 +68,12 @@ fn fields(call: &Call, sent: &Message, sandbox: Option<&str>) -> Vec<(&'static s let mut fields = Vec::new(); let mut said = false; match call { - Call::Create { platform } => { - fields.extend(platform.as_deref().map(|p| ("platform", text(p)))) + Call::Create { platform, place } => { + fields.extend(platform.as_deref().map(|p| ("platform", text(p)))); + if let Some((machine, generation)) = place { + fields.push(("place_machine", text(machine))); + fields.push(("generation", text(generation))); + } } Call::Close { force, held } => { fields.push(("force", SdkValue::Bool(*force))); @@ -245,6 +249,7 @@ fn call(op: Op, more: &SdkValue) -> Call { match op { Op::SandboxCreate => Call::Create { platform: text("platform"), + place: text("place_machine").zip(text("generation")), }, Op::SandboxClose => Call::Close { force: more.get_bool("force"), diff --git a/control/crates/layerfs-sandbox/src/lifecycle.rs b/control/crates/layerfs-sandbox/src/lifecycle.rs index adbab098f1..ea5e16800d 100644 --- a/control/crates/layerfs-sandbox/src/lifecycle.rs +++ b/control/crates/layerfs-sandbox/src/lifecycle.rs @@ -223,9 +223,11 @@ pub fn start( /// as `sandbox remove` forgets it (D-8). `deploy.sandbox` names its backend, `native` or /// `namespaces`; a native one's `image` is `local`. `platform` (#529) is /// checked against that backend and recorded. +/// `place`, the machine and generation the caller's home minted, goes into +/// a worker's own record once the Sandbox started ([`crate::files::save_place`]). /// The only call that starts a Sandbox. Failures are `Failed` or /// `Unknown`, never retried. -pub fn create(host: &Host, named: Option<&str>) -> Outcome { +pub fn create(host: &Host, named: Option<&str>, place: Option<&(String, String)>) -> Outcome { // the platform is checked against the deployment before any effect (#529) let deploy = host .deploy() @@ -259,7 +261,11 @@ pub fn create(host: &Host, named: Option<&str>) -> Outcome { } None => {} } - start((host, &platform), &directory, store) + let state = start((host, &platform), &directory, store)?; + if let Some(place) = place { + crate::files::save_place(&directory, &state.id, place); + } + Ok(state) })(); let state = match made { Ok(state) => state, @@ -318,10 +324,12 @@ pub fn close(host: &Host, force: bool, held: &[String]) -> Outcome { )); }; if recorded.retired() { + let _ = retired(host, &id); return forget(&id, &directory, &recorded); } if let Some(why) = crate::reopen::unread(&recorded) { - return forget_unread(&id, &directory, &recorded, &why); + let unretired = retired(host, &id); + return forget_unread(&id, &directory, &recorded, &why, unretired); } let state = match crate::registry::sandbox_live(host) { Ok(state) => state, @@ -400,12 +408,7 @@ pub fn close(host: &Host, force: bool, held: &[String]) -> Outcome { // before the record (the folder) goes. It is best effort: a missing // tombstone is only "no proof of death", so the close goes on, still // ends the mount intents and reports the failure in `left`. - let unretired = match crate::record::SandboxRecord::read(&host.home, &id) { - Ok(Some(record)) => crate::record::retire(&host.home, &record).err(), - Ok(None) => None, - Err(refusal) => Some(refusal), - } - .map(|refusal| not_retired(&id, &refusal.message)); + let unretired = retired(host, &id); let pg = (host.store_record.as_ref()) .is_some_and(|r| r.kind().ok() == Some(layerfs_store::record::StoreKind::Postgresql)); let (left, handed) = match (pg, &host.postgresql) { @@ -449,14 +452,23 @@ pub fn close(host: &Host, force: bool, held: &[String]) -> Outcome { } /// The `left` sentence of a close whose retired tombstone of Sandbox `id` -/// was not written for reason `why`. Nothing is unsafe about it: without a -/// tombstone, admission has no proof the Sandbox is gone, so a mount intent -/// it held and that was not ended stays live until its owner settles it. +/// was not written for reason `why` ([`crate::record::unretired`]). pub(crate) fn not_retired(id: &str, why: &str) -> SdkValue { - SdkValue::text(format!( - "Sandbox {id}'s retired tombstone was not written ({why}): a mount intent it held \ - that was not ended is not proven dead" - )) + SdkValue::text(crate::record::unretired(id, why)) +} + +/// Writes the retirement tombstone of Sandbox `id` from its record in +/// `host`'s home, best effort, before that record goes: `left`'s sentence +/// when it was not written. On a worker's root there is no home record to +/// retire ([`crate::record::retire`] writes none there): the caller writes the +/// home's tombstone when its `sandbox.remove` removes its own record. +fn retired(host: &Host, id: &str) -> Option { + match crate::record::SandboxRecord::read(&host.home, id) { + Ok(Some(record)) => crate::record::retire(&host.home, &record).err(), + Ok(None) => None, + Err(refusal) => Some(refusal), + } + .map(|refusal| not_retired(id, &refusal.message)) } /// The Branch and Workspace identity of each of `mounted` this process @@ -505,18 +517,24 @@ fn forget(id: &str, directory: &Path, recorded: &DaemonRecord) -> Outcome { /// its identity cannot be checked, so nothing is signalled. Its folder goes /// under its guard, and the answer (`Forgotten`, with `left`) says what may /// remain: its daemon or init process and its run folder. -fn forget_unread(id: &str, directory: &Path, recorded: &DaemonRecord, why: &str) -> Outcome { +/// `unretired` is the sentence of a retirement tombstone that was not +/// written, which `left` carries too. +fn forget_unread( + id: &str, + directory: &Path, + recorded: &DaemonRecord, + why: &str, + unretired: Option, +) -> Outcome { let _guard = layerfs_store::project::discovery::guard(directory)?; discard(directory, recorded)?; std::fs::remove_dir_all(directory).map_err(failed)?; layerfs_home::home::generation::moved_above(directory); + let left = std::iter::once(SdkValue::text(unread_left(recorded, why))).chain(unretired); Ok(SdkValue::map([ ("kind", SdkValue::text("Forgotten")), ("sandbox", SdkValue::text(id)), - ( - "left", - SdkValue::List(vec![SdkValue::text(unread_left(recorded, why))]), - ), + ("left", SdkValue::List(left.collect())), ])) } @@ -587,6 +605,9 @@ pub fn reclaim(host: &Host, container: &str, stopped: bool) -> Outcome { .delete() .map_err(values::wire)?; } + // its runtime is gone: the home record's tombstone first, best effort + // (the close that reclaimed it answers `NoSuchSandbox`, with no `left`) + let _ = retired(host, id); lock(&SANDBOXES)?.remove(&directory); std::fs::remove_dir_all(&directory).map_err(failed)?; layerfs_home::home::generation::moved_above(&directory); diff --git a/control/crates/layerfs-sandbox/src/record/mod.rs b/control/crates/layerfs-sandbox/src/record/mod.rs index a5ae3f9144..66645620e7 100644 --- a/control/crates/layerfs-sandbox/src/record/mod.rs +++ b/control/crates/layerfs-sandbox/src/record/mod.rs @@ -13,5 +13,7 @@ mod workspace; pub use daemon::{Carrier, DaemonRecord, Forward, Local}; pub use sandbox::{lock, lock_in, mount_place, sandbox, sandboxes, SandboxRecord}; -pub use tombstone::{retire, retire_in, SandboxTombstone}; +pub use tombstone::{ + drop_retired, retire, retire_in, retire_reported, unretired, SandboxTombstone, +}; pub use workspace::WorkspaceRecord; diff --git a/control/crates/layerfs-sandbox/src/record/sandbox.rs b/control/crates/layerfs-sandbox/src/record/sandbox.rs index 2f04f8195e..1d756d264b 100644 --- a/control/crates/layerfs-sandbox/src/record/sandbox.rs +++ b/control/crates/layerfs-sandbox/src/record/sandbox.rs @@ -272,6 +272,14 @@ impl SandboxRecord { self } + /// The record naming the machine it runs on and the generation its + /// caller's home minted: what a worker's own record of it keeps. + pub fn with_place(mut self, machine: &str, generation: &str) -> Self { + self.fields.set(Field::Machine(machine.to_owned())); + self.fields.set(Field::Generation(generation.to_owned())); + self + } + /// The intent the record holds, if any. pub fn op(&self) -> Option { self.fields @@ -540,11 +548,13 @@ impl SandboxRecord { } /// The place a mount of Sandbox `name` records: the record in `directory` -/// names the machine it runs on and the generation its create minted, and the -/// machine record under the same `home` names that machine's current ordered -/// incarnation. A record this side cannot read supplies no authority (no -/// proof, never death): the names alone, and admission falls back to the -/// owner evidence. +/// names the machine it runs on and the generation its create minted (a +/// worker's own record keeps the values its caller sent with the create), +/// and the machine record under the same `home` names that machine's current +/// ordered incarnation (a worker's root keeps no machine record, so its +/// mounts carry no incarnation). A record this side cannot read supplies no +/// authority (no proof, never death): the names alone, and admission falls +/// back to the owner evidence. pub fn mount_place(home: &Path, directory: &Path, name: &str) -> Result { let record = SandboxRecord::read_in(directory, name)?; let machine = record.as_ref().map(|record| record.machine().to_owned()); diff --git a/control/crates/layerfs-sandbox/src/record/tombstone.rs b/control/crates/layerfs-sandbox/src/record/tombstone.rs index adad0572d6..e329514e0b 100644 --- a/control/crates/layerfs-sandbox/src/record/tombstone.rs +++ b/control/crates/layerfs-sandbox/src/record/tombstone.rs @@ -1,12 +1,27 @@ //! Retired Sandbox tombstones: `machine//sandbox-retired/.json`. //! -//! A close, force close, remove or reclaim writes the tombstone **before** it -//! deletes the Sandbox record, so a crash leaves the record or both, never -//! neither. The path is outside `sandbox/`, so a Sandbox listing never -//! mistakes a tombstone for a Sandbox. The tombstone names the generation the -//! close retired; a Sandbox recreated under the same name mints a new, greater -//! generation, so the old tombstone never retires it. A missing tombstone and -//! a missing record are both "no proof", never death. +//! Every removal of a Sandbox's home record writes the tombstone **before** it +//! deletes that record, best effort: a close or force close on `native`, a +//! reclaim of a runtime that ended by itself, a forget, and `sandbox.remove` +//! on every route (normal, forgotten, unstarted), which writes the home's +//! tombstone for a worker's Sandbox. A crash leaves the record or both, never +//! neither; a write that fails is reported in `left` and the removal goes on, +//! since a missing tombstone is only "no proof". The path is outside +//! `sandbox/`, so a Sandbox listing never mistakes a tombstone for a Sandbox. +//! +//! A tombstone is a home record: the place view reads the caller's home, so a +//! worker's root (which no view reads) gets none, and its caller writes the +//! home's. It names the generation the removal retired; a Sandbox recreated +//! under the same name mints a new, greater generation, so the old tombstone +//! never retires it, and once that record is written the old tombstone goes +//! ([`drop_retired`]): the newer record proves the older generation's mounts +//! dead by itself, so one name keeps at most one tombstone and none while it +//! is in use. `machine.remove` deletes `machine//` with its +//! tombstones: it is refused while a Store or Sandbox uses the machine, and a +//! mount intent placed there then has no Sandbox evidence (no proof, never +//! death) until a machine of that name starts again (its newer incarnation +//! proves the old placements dead) or the operator repairs it. A missing +//! tombstone and a missing record are both "no proof", never death. use super::sandbox::SandboxRecord; use layerfs_bridge::control::{SdkRefusal, SdkValue}; use layerfs_home::home::{self, paths, read_record, write_entity}; @@ -65,11 +80,15 @@ impl SandboxTombstone { /// Writes `record`'s tombstone under `home` before its record is deleted. /// A record without a generation or machine has nothing a tombstone could -/// name, so there is nothing to write. +/// name, and a worker's root is no home (no place view reads it), so there +/// is nothing to write. pub fn retire(home: &Path, record: &SandboxRecord) -> Result<()> { let Some(generation) = record.generation() else { return Ok(()); }; + if layerfs_home::home::guest::is_root(home) { + return Ok(()); + } let machine = record.machine(); if generation.is_empty() || machine.is_empty() { return Ok(()); @@ -91,3 +110,41 @@ pub fn retire_in(home: &Path, directory: &Path, name: &str) -> Result<()> { None => Ok(()), } } + +/// [`retire`], best effort: the sentence a removal reports in `left` when the +/// tombstone was not written, else `None`. The removal goes on either way. +pub fn retire_reported(home: &Path, record: &SandboxRecord) -> Option { + let refusal = retire(home, record).err()?; + Some(unretired(record.name(), &refusal.message)) +} + +/// The `left` sentence of a removal whose retired tombstone of Sandbox `name` +/// was not written for reason `why`. Nothing is unsafe about it: without a +/// tombstone, admission has no proof the Sandbox is gone, so a mount intent +/// it held and that was not ended stays live until its owner settles it. +pub fn unretired(name: &str, why: &str) -> String { + format!( + "Sandbox {name}'s retired tombstone was not written ({why}): a mount intent it held \ + that was not ended is not proven dead" + ) +} + +/// Deletes the tombstone of `record`'s name once `record` (a Sandbox +/// recreated under it) is written with a newer generation of the same home: +/// that record proves the retired generation's mounts dead by itself +/// (`RecordedOlder`), so the tombstone adds nothing. A tombstone that is not +/// older (a restore, another home's value, an unreadable file) is kept. Best +/// effort: a tombstone left behind is only one more file for the name. +pub fn drop_retired(home: &Path, record: &SandboxRecord) { + let Some(generation) = record.generation() else { + return; + }; + let (machine, name) = (record.machine(), record.name()); + let Ok(Some(tombstone)) = SandboxTombstone::read(home, machine, name) else { + return; + }; + let order = layerfs_history::compare_place(&tombstone.generation, generation); + if order == layerfs_history::PlaceOrder::RecordedOlder { + let _ = std::fs::remove_file(paths::sandbox_tombstone(home, machine, name)); + } +} diff --git a/control/crates/layerfs-sandbox/src/remove.rs b/control/crates/layerfs-sandbox/src/remove.rs index 9646264cb0..02b583a41a 100644 --- a/control/crates/layerfs-sandbox/src/remove.rs +++ b/control/crates/layerfs-sandbox/src/remove.rs @@ -229,17 +229,20 @@ pub fn remove(home: &Path, events: &mut Events<'_>, request: &RemoveRequest) -> Ok(value) if value.get_text("kind") == Some("Forgotten") && value.get("left").is_some() => { phase(events, "delete", None); direct::release(&home, &record); + let unretired = retire_home(&home, &record, &dir); remove_folder(&dir)?; done(events); let left = match value.get("left") { Some(SdkValue::List(items)) => texts(items).map(str::to_owned).collect(), _ => Vec::new(), }; + let left = left.into_iter().chain(unretired).collect(); Ok(Removed::AlreadyGone { left }) } Ok(value) => { phase(events, "delete", None); direct::release(&home, &record); + let unretired = retire_home(&home, &record, &dir); remove_folder(&dir)?; let unmounted = match value.get("unknown") { Some(SdkValue::List(paths)) => texts(paths).map(&handle_of).collect(), @@ -256,6 +259,7 @@ pub fn remove(home: &Path, events: &mut Events<'_>, request: &RemoveRequest) -> } _ => Vec::new(), }; + let left = left.into_iter().chain(unretired).collect(); done(events); Ok(Removed::Stopped { unmounted, left }) } @@ -263,9 +267,10 @@ pub fn remove(home: &Path, events: &mut Events<'_>, request: &RemoveRequest) -> Err(refusal) if refusal.code == "NoSuchSandbox" => { phase(events, "delete", None); direct::release(&home, &record); + let left = retire_home(&home, &record, &dir).into_iter().collect(); remove_folder(&dir)?; done(events); - Ok(Removed::AlreadyGone { left: Vec::new() }) + Ok(Removed::AlreadyGone { left }) } // its outcome is not known: the record stays with the intent, // uncertain, until another `sandbox.remove` clears it @@ -415,6 +420,7 @@ fn forget( let _sandbox = record::lock(home, name)?; direct::release(home, &record); } + let unretired = retire_home(home, &record, &dir); remove_folder(&dir)?; done(events); let kept = left.map(|left| { @@ -424,7 +430,10 @@ fn forget( ) }); Ok(Removed::AlreadyGone { - left: std::iter::once(first).chain(kept).collect(), + left: std::iter::once(first) + .chain(kept) + .chain(unretired) + .collect(), }) } @@ -510,10 +519,25 @@ fn may_run(record: &SandboxRecord) -> bool { /// live create. fn remove_unstarted(home: &Path, record: &SandboxRecord) -> Result { let unresolved = (record.op()).is_some_and(|op| op.standing() == Standing::Unresolved); - remove_folder(&record.dir(home))?; + let dir = record.dir(home); + let unretired = retire_home(home, record, &dir); + remove_folder(&dir)?; let mut left = Vec::new(); if unresolved { left.push("its create's outcome was unknown: a Sandbox it may have started on its machine is not recorded here".to_owned()); } + left.extend(unretired); Ok(Removed::AlreadyGone { left }) } + +/// Writes the home's retirement tombstone of Sandbox `record` before its home +/// record (folder `dir`) goes: best effort, its failure a sentence of `left`. +/// This is the tombstone of a worker's Sandbox, whose worker writes none. A +/// folder already gone was removed by the Sandbox's own side on `native`, +/// which wrote the tombstone first. +fn retire_home(home: &Path, record: &SandboxRecord, dir: &Path) -> Option { + match dir.exists() { + true => record::retire_reported(home, record), + false => None, + } +} diff --git a/control/crates/layerfs-sandbox/tests/half_created.rs b/control/crates/layerfs-sandbox/tests/half_created.rs index 2da8b06087..ec50ce84e2 100644 --- a/control/crates/layerfs-sandbox/tests/half_created.rs +++ b/control/crates/layerfs-sandbox/tests/half_created.rs @@ -131,13 +131,16 @@ fn an_unstarted_sandbox_on_a_machine_is_closed_by_its_worker_or_kept() { ); // a create that ended while it claimed the name started nothing: its - // records go, as before + // records go, as before, and the home keeps the tombstone of the + // generation it minted (#783 gap 2: every removal path writes it) + let generation = "p1:aa11.sandbox:0000000000000010:aa"; write_record( &paths::sandbox_record(&home, "s2"), &SdkValue::map([ ("name", t("s2")), ("project", t("shop/api")), ("machine", t("dev")), + ("generation", t(generation)), ("op", ended_create("claim")), ]), ) @@ -147,6 +150,10 @@ fn an_unstarted_sandbox_on_a_machine_is_closed_by_its_worker_or_kept() { Ok(Removed::AlreadyGone { .. }) )); assert!(!paths::sandbox_dir(&home, "s2").exists()); + let tombstone = read_record(&paths::sandbox_tombstone(&home, "dev", "s2")) + .unwrap() + .expect("the removal's tombstone"); + assert_eq!(tombstone.get_text("generation"), Some(generation)); std::fs::remove_dir_all(home).unwrap(); } diff --git a/control/crates/layerfs-sandbox/tests/host_frame.rs b/control/crates/layerfs-sandbox/tests/host_frame.rs index 21c7be2bbb..26c9e96a6a 100644 --- a/control/crates/layerfs-sandbox/tests/host_frame.rs +++ b/control/crates/layerfs-sandbox/tests/host_frame.rs @@ -72,7 +72,11 @@ fn a_frame_keeps_the_untyped_request_s_fields_and_order() { #[test] fn a_frame_reads_back_to_its_request() { let calls = [ - Call::Create { platform: None }, + // a worker's create carries the caller's machine and generation + Call::Create { + platform: None, + place: Some(("box".to_owned(), "p1:aa11.sandbox:10:aa".to_owned())), + }, Call::Close { force: true, held: None, diff --git a/control/crates/layerfs-sandbox/tests/installed_repair.rs b/control/crates/layerfs-sandbox/tests/installed_repair.rs index 576ec8bbf2..71c66667b5 100644 --- a/control/crates/layerfs-sandbox/tests/installed_repair.rs +++ b/control/crates/layerfs-sandbox/tests/installed_repair.rs @@ -84,7 +84,7 @@ fn sandbox_create_repairs_an_incomplete_sqlite_project_record() { }; // the repair happens before launch; a host that can launch a daemon // starts one, which is removed again - match lifecycle::create(&host, None) { + match lifecycle::create(&host, None, None) { Ok(_) => { lifecycle::close(&host, true, &[]).expect("the started Sandbox is removed"); } diff --git a/control/crates/layerfs-sandbox/tests/place_evidence.rs b/control/crates/layerfs-sandbox/tests/place_evidence.rs new file mode 100644 index 0000000000..eed4fc6ec7 --- /dev/null +++ b/control/crates/layerfs-sandbox/tests/place_evidence.rs @@ -0,0 +1,130 @@ +//! Place evidence on the Sandbox side (#783 gaps 1–3): a worker's own record +//! keeps the machine and generation its caller minted, so its mounts carry +//! them; a tombstone is written on the removal paths and goes once the name +//! is recreated with a newer generation. Missing evidence is never death. +use layerfs_bridge::control::SdkValue; +use layerfs_home::json::parse; +use layerfs_home::op::Op; +use layerfs_sandbox::record::{mount_place, retire, SandboxRecord, SandboxTombstone}; +use std::path::PathBuf; + +/// A fresh folder of its own under the temp directory: a worker's root +/// (not a home) unless `home` opens it as one. +fn scratch(tag: &str, home: bool) -> PathBuf { + let root = std::env::temp_dir().join(format!("lfs-place-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + if home { + layerfs_home::home::layout::open(&root).expect("a new home"); + } + root +} + +#[test] +fn a_worker_record_keeps_the_callers_place_and_its_mounts_read_it() { + let root = scratch("worker", false); + let directory = root.join("sandbox").join("t1"); + std::fs::create_dir_all(&directory).unwrap(); + // the worker's record as its start writes it: no machine, no generation + SandboxRecord::from_record( + "t1", + parse(r#"{"name":"t1","project":"shop/api","backend":"namespaces"}"#).unwrap(), + ) + .write_in(&directory) + .unwrap(); + let before = mount_place(&root, &directory, "t1").unwrap(); + assert_eq!(before.generation, None, "no evidence before the place"); + assert_eq!(before.machine, None); + + let generation = "p1:aa11.sandbox:0000000000000010:aa".to_owned(); + layerfs_sandbox::files::save_place(&directory, "t1", &("box".to_owned(), generation.clone())); + let placed = mount_place(&root, &directory, "t1").unwrap(); + assert_eq!(placed.sandbox.as_deref(), Some("t1")); + assert_eq!(placed.machine.as_deref(), Some("box")); + assert_eq!(placed.generation.as_deref(), Some(generation.as_str())); + // a worker's root keeps no machine record: no incarnation is guessed + assert_eq!(placed.machine_incarnation, None); + + // a record naming a generation already (native's home record) is left + let other = ( + "other".to_owned(), + "p1:aa11.sandbox:0000000000000020:bb".to_owned(), + ); + layerfs_sandbox::files::save_place(&directory, "t1", &other); + let kept = SandboxRecord::read_in(&directory, "t1").unwrap().unwrap(); + assert_eq!(kept.generation(), Some(generation.as_str())); + assert_eq!(kept.machine(), "box"); + let _ = std::fs::remove_dir_all(&root); +} + +/// The tombstone is a home record: a worker's root, which no place view +/// reads, gets none (its caller writes the home's), while a home does. +#[test] +fn a_tombstone_is_written_in_a_home_and_never_in_a_worker_root() { + let record = SandboxRecord::from_record( + "t1", + parse( + r#"{"name":"t1","machine":"box","generation":"p1:aa11.sandbox:0000000000000010:aa"}"#, + ) + .unwrap(), + ); + let root = scratch("root", false); + layerfs_home::home::guest::serve_root(&root); + retire(&root, &record).unwrap(); + assert!(!layerfs_home::home::paths::sandbox_tombstone(&root, "box", "t1").exists()); + let _ = std::fs::remove_dir_all(&root); + + let home = scratch("home", true); + retire(&home, &record).unwrap(); + let tombstone = SandboxTombstone::read(&home, "box", "t1").unwrap().unwrap(); + assert_eq!(tombstone.generation, "p1:aa11.sandbox:0000000000000010:aa"); + let _ = std::fs::remove_dir_all(&home); +} + +/// A Sandbox recreated under a retired name mints a newer generation; once +/// it is recorded the old tombstone goes (the newer record proves the old +/// generation's mounts dead by itself), so tombstones do not pile up. +#[test] +fn a_recreated_name_drops_its_older_tombstone() { + let home = scratch("recreate", true); + let id = layerfs_home::home::opened(&home).unwrap().id; + let old = format!("p1:{id}.sandbox:0000000000000010:aa"); + SandboxTombstone { + name: "t1".to_owned(), + machine: "box".to_owned(), + generation: old.clone(), + retired_ms: 1, + } + .write(&home) + .unwrap(); + let op = Op::begin("sandbox.create", "claim", SdkValue::Null).unwrap(); + let record = SandboxRecord::creating(&home, "t1", "shop/api", "box", &op).unwrap(); + // a tombstone newer than the record (a restore) is kept + let newer = format!("p1:{id}.sandbox:{:016}:bb", u64::MAX / 4); + SandboxTombstone { + name: "t1".to_owned(), + machine: "box".to_owned(), + generation: newer.clone(), + retired_ms: 2, + } + .write(&home) + .unwrap(); + layerfs_sandbox::record::drop_retired(&home, &record); + let kept = SandboxTombstone::read(&home, "box", "t1").unwrap().unwrap(); + assert_eq!(kept.generation, newer, "a newer tombstone stays"); + + // the older one goes + SandboxTombstone { + name: "t1".to_owned(), + machine: "box".to_owned(), + generation: old, + retired_ms: 1, + } + .write(&home) + .unwrap(); + layerfs_sandbox::record::drop_retired(&home, &record); + assert!(SandboxTombstone::read(&home, "box", "t1") + .unwrap() + .is_none()); + let _ = std::fs::remove_dir_all(&home); +} diff --git a/control/crates/layerfs-sandbox/tests/retired_docker.rs b/control/crates/layerfs-sandbox/tests/retired_docker.rs index d94cf3a38c..81c25aae31 100644 --- a/control/crates/layerfs-sandbox/tests/retired_docker.rs +++ b/control/crates/layerfs-sandbox/tests/retired_docker.rs @@ -155,7 +155,7 @@ fn a_create_of_the_same_name_forgets_a_retired_docker_record() { }), ..host(&root) }; - let refusal = layerfs_sandbox::lifecycle::create(&host, None).unwrap_err(); + let refusal = layerfs_sandbox::lifecycle::create(&host, None, None).unwrap_err(); assert_ne!(refusal.code, "Exists", "{}", refusal.message); assert!( matches!(refusal.code.as_str(), "InvalidInput" | "Unsupported"), From 75b000d2d6e398bb97d773d0a4155533084b7d23 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 17:25:53 +0800 Subject: [PATCH 2/6] fix(persistence): bound the done audit per Branch; PostgreSQL release and compaction parity - An operator release that retains a `done` row now deletes the oldest done rows of the same scope (a mount's Branch) beyond the newest 100 (`DONE_RETAINED`), in the release's transaction (`gc_intent_done_cap.sql`). No schema change: no index, table or column; the scope's rows are found through the existing UNIQUE (scope_kind, scope_id, owner_boot) index, and only `state = 'done'` rows are matched. `gc_intent_release_done` answers the row's scope. - PostgreSQL `release_done` answers what the retain itself answered, so a second (or concurrent) release is `false`/`NotFound` as on SQLite, and only a row this release retained has its session keys released. - PostgreSQL compaction no longer touches a retained done row: its `compaction_intent` read, the status read and both cleanup deletes filter `state <> 'done'`. Tests: `gc_intent_done` gains a cap test (101 rows -> the newest 100 of the Branch; another Branch's row stays). Production LOC: 214,149 -> 214,167 (delta +18) scope: tools/production_loc.py (repo-pinned counter), first-parent tree vs committed tree reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Co-Authored-By: Claude Opus 5.5 --- .../queries/history/gc_intent_done_cap.sql | 14 +++++ .../history/gc_intent_release_done.sql | 5 +- .../src/backend/postgresql/compact/cleanup.rs | 6 +- .../src/backend/postgresql/status.rs | 2 +- .../src/backend/sqlite/session/query.rs | 3 + .../src/history/admission.rs | 1 + .../src/history/admission/authority.rs | 24 ++++++-- .../tests/gc_intent_done.rs | 59 +++++++++++++++++++ 8 files changed, 103 insertions(+), 11 deletions(-) create mode 100644 engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_cap.sql diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_cap.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_cap.sql new file mode 100644 index 0000000000..00d509d355 --- /dev/null +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_cap.sql @@ -0,0 +1,14 @@ +-- Bounds the retained `done` audit of one scope (a mount's Branch): after a +-- release retains a row, the oldest done rows of that scope beyond the newest +-- $3 are deleted. No new index, table or column: the scope's rows are found +-- through the existing UNIQUE (scope_kind, scope_id, owner_boot) index, and a +-- live or uncertain intent is never matched (`state = 'done'`). Portable to +-- PostgreSQL, as the other intent statements are. +DELETE FROM gc_intent +WHERE state = 'done' AND scope_kind = $1 AND scope_id = $2 + AND op_id NOT IN ( + SELECT op_id FROM gc_intent + WHERE state = 'done' AND scope_kind = $1 AND scope_id = $2 + ORDER BY updated_ms DESC, op_id DESC + LIMIT $3 + ); diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_release_done.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_release_done.sql index 9df1a3ccf2..508435b239 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_release_done.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_release_done.sql @@ -3,7 +3,8 @@ -- the action/operator/op evidence. Admission queries filter `state <> 'done'`; -- `gc_intent_done` is the only read that sees the retained row. A row already -- retained is not matched again, so a second release reports it gone instead --- of rewriting the audit line. +-- of rewriting the audit line. It answers the row's scope, which +-- `gc_intent_done_cap` then bounds. UPDATE gc_intent SET state = 'done', uncertain = FALSE, @@ -12,4 +13,4 @@ SET state = 'done', evidence = $1, updated_ms = $2 WHERE op_id = $3 AND state <> 'done' -RETURNING op_id; +RETURNING scope_kind, scope_id; diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/compact/cleanup.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/compact/cleanup.rs index da1a9b3bb1..cf1dba3c79 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/compact/cleanup.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/compact/cleanup.rs @@ -222,7 +222,7 @@ pub(crate) fn compaction_intent( stage(session, |tx| { let rows = tx.query( &format!( - "SELECT op_id FROM {schema}.gc_intent WHERE kind='compaction' ORDER BY updated_ms LIMIT 1" + "SELECT op_id FROM {schema}.gc_intent WHERE kind='compaction' AND state <> 'done' ORDER BY updated_ms LIMIT 1" ), Vec::new(), )?; @@ -304,7 +304,7 @@ pub(crate) fn settle_leftover( clear_round(session, schema)?; stage(session, |tx| { tx.batch(&format!( - "DELETE FROM {schema}.gc_intent WHERE kind='compaction'" + "DELETE FROM {schema}.gc_intent WHERE kind='compaction' AND state <> 'done'" ))?; Ok(()) })?; @@ -711,7 +711,7 @@ pub(crate) fn cleanup( } else { stage(session, |tx| { tx.batch(&format!( - "DELETE FROM {schema}.gc_intent WHERE kind='compaction'" + "DELETE FROM {schema}.gc_intent WHERE kind='compaction' AND state <> 'done'" ))?; Ok(()) })?; diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/status.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/status.rs index 9daeee4535..b23eda01c4 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/status.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/status.rs @@ -207,7 +207,7 @@ pub fn compact_status( LEFT JOIN {table}.gc_op o ON o.id=1 \ LEFT JOIN LATERAL (SELECT op_id,owner_runtime,owner_boot,state,\ phase,generation,artifact,updated_ms \ - FROM {table}.gc_intent WHERE kind='compaction' \ + FROM {table}.gc_intent WHERE kind='compaction' AND state <> 'done' \ ORDER BY updated_ms LIMIT 1) i ON TRUE" ); let rows = match client.query(&sql, &[]) { diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/session/query.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/session/query.rs index 57cc94393d..1aa6dae6ff 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/session/query.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/session/query.rs @@ -276,6 +276,9 @@ pub(crate) fn history(key: &str) -> Result<&'static str, BackendError> { "gc_intent_done_delete" => Ok(include_str!( "../../../../sql/sqlite/queries/history/gc_intent_done_delete.sql" )), + "gc_intent_done_cap" => Ok(include_str!( + "../../../../sql/sqlite/queries/history/gc_intent_done_cap.sql" + )), "gc_branch_stack_any" => Ok(include_str!( "../../../../sql/sqlite/queries/history/gc_branch_stack_any.sql" diff --git a/engine/crates/layerfs-persistence/src/history/admission.rs b/engine/crates/layerfs-persistence/src/history/admission.rs index 202a1b9579..2a8d72debe 100644 --- a/engine/crates/layerfs-persistence/src/history/admission.rs +++ b/engine/crates/layerfs-persistence/src/history/admission.rs @@ -75,6 +75,7 @@ const DONE: &str = "gc_intent_done"; const DONE_BRANCH: &str = "gc_intent_done_branch"; const DONE_INSERT: &str = "gc_intent_done_insert"; const DONE_DELETE: &str = "gc_intent_done_delete"; +const DONE_CAP: &str = "gc_intent_done_cap"; const BRANCH_STACK: &str = "gc_branch_stack_any"; const EPOCH_LOCK: &str = "gc_epoch_lock"; diff --git a/engine/crates/layerfs-persistence/src/history/admission/authority.rs b/engine/crates/layerfs-persistence/src/history/admission/authority.rs index 9df260eb50..2bcce13674 100644 --- a/engine/crates/layerfs-persistence/src/history/admission/authority.rs +++ b/engine/crates/layerfs-persistence/src/history/admission/authority.rs @@ -28,14 +28,26 @@ pub(crate) fn release(provider: &HistoryProvider, op_id: &[u8; 16]) -> HistoryRe } } +/// The retained `done` rows one scope (a mount's Branch) keeps: retaining a +/// new one deletes the oldest beyond this many, in the same transaction, so +/// the audit stays bounded without a schema change. +pub const DONE_RETAINED: i64 = 100; + /// Retains one released intent as the durable `done` audit row. The owner /// columns are cleared so the unique owner key cannot block a later mount; /// admission queries filter `state <> 'done'`, and `gc_intent_done` is the -/// only read that sees the row. Returns `false` when the op has no intent, so -/// a concurrent repair does not invent one. +/// only read that sees the row. The scope's oldest done rows beyond +/// [`DONE_RETAINED`] go. Returns `false` when the op has no live intent (none, +/// or one already retained), so a concurrent or repeated repair invents none. fn retain_done_in(tx: &Transaction<'_>, op_id: &[u8; 16], evidence: &str) -> HistoryResult { let rows = tx.query(RELEASE_DONE, params![evidence, now_ms(), op_id.as_slice()])?; - Ok(!rows.is_empty()) + let Some(row) = rows.first() else { + return Ok(false); + }; + let scope_kind: String = cell(row, 0)?; + let scope_id: Option> = cell(row, 1)?; + tx.query(DONE_CAP, params![scope_kind, scope_id, DONE_RETAINED])?; + Ok(true) } /// [`release`] for the operator repair: it keeps the released row as the @@ -49,13 +61,15 @@ pub(crate) fn release_done( match &provider.engine { Engine::Sqlite(_) => provider.write(|tx| retain_done_in(tx, op_id, evidence)), Engine::Postgres(session) => { + // a second release finds no live intent and answers `false` + // (`NotFound` to the caller), as SQLite does; only a row this + // release retained has its session keys released let found = provider.write(|tx| { let Some(intent) = get_in(tx, op_id)? else { return Ok(None); }; let keys = keys_for_release(tx, provider.catalog_id, &intent)?; - retain_done_in(tx, op_id, evidence)?; - Ok(Some(keys)) + Ok(retain_done_in(tx, op_id, evidence)?.then_some(keys)) })?; let retained = found.is_some(); if let Some(ReleaseKeys { keys }) = found { diff --git a/engine/crates/layerfs-persistence/tests/gc_intent_done.rs b/engine/crates/layerfs-persistence/tests/gc_intent_done.rs index 7655635323..9e07077dc1 100644 --- a/engine/crates/layerfs-persistence/tests/gc_intent_done.rs +++ b/engine/crates/layerfs-persistence/tests/gc_intent_done.rs @@ -457,3 +457,62 @@ fn place_tokens_round_trip_through_evidence_and_live_statements_keep_a_done_row( .unwrap(); assert_eq!(tokens(&history), (None, None)); } + +/// #783 gap 3: one Branch's retained `done` audit is bounded with no schema +/// change. A release that retains a row deletes that Branch's oldest done +/// rows beyond the newest 100 (`DONE_RETAINED`); another Branch's rows and +/// live intents are untouched. +#[test] +fn a_release_keeps_at_most_the_newest_done_rows_of_its_branch() { + const RETAINED: usize = 100; + let temp = Temp::new("gc-done-audit-cap"); + let history = catalog(&temp); + let (_, branch) = project(&history); + let path = temp.join("store.sqlite"); + for body in 1..=RETAINED as u8 { + done_row(&path, branch, body, "release", i64::from(body)); + } + // another Branch's done row is not this Branch's to bound + let other = branch_id(2); + history + .fork(&layerfs_history::records::ForkRequest { + stack: stack(1), + branch: other, + name: name("other"), + source: layerfs_history::records::ForkSource::Layer( + history.layer_stack(stack(1)).unwrap().unwrap().head_layer, + ), + }) + .unwrap(); + done_row(&path, other, 250, "release other", 0); + let mounted = GcIntent::shared( + op(200), + GcIntentKind::Mount, + GcScopeKind::Branch, + branch.as_slice(), + ) + .in_project(stack(1).as_slice()) + .named(Some("proj"), Some("work")) + .placed(Some([200; 32]), Some("box"), Some("box")) + .owned(Some("pid:1@0"), Some("boot:1")); + history.gc_register(&mounted).unwrap(); + history.gc_mark_uncertain(&op(200)).unwrap(); + assert!(history.gc_release_done(&op(200), "release").unwrap()); + + // the test rows all record the names proj/work: count by Branch scope + let connection = rusqlite::Connection::open(&path).unwrap(); + let kept = |scope: BranchId| -> Vec> { + let mut statement = connection + .prepare("SELECT op_id FROM gc_intent WHERE state = 'done' AND scope_id = ?1") + .unwrap(); + let rows = statement + .query_map([scope.as_slice()], |row| row.get(0)) + .unwrap(); + rows.map(Result::unwrap).collect() + }; + let work = kept(branch); + assert_eq!(work.len(), RETAINED, "the Branch keeps its newest rows"); + assert!(!work.contains(&op(1).to_vec()), "the oldest went"); + assert!(work.contains(&op(2).to_vec()) && work.contains(&op(200).to_vec())); + assert_eq!(kept(other).len(), 1, "another Branch's row stays"); +} From c0b3e2971bea6ddb828b074a439d22b1cb372c93 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 17:45:25 +0800 Subject: [PATCH 3/6] feat(gc): a real liveness verdict, the 2.0 repair call surface, leftovers removed Item 4, a real `safe` verdict: - New read `HistoryCatalog::gc_liveness(intents)` (persistence: `admission::liveness`, store-service: `admission::liveness`): the owner check first, then the place view scoped on the thread, exactly as an admitting removal judges a conflict. One read transaction, no write. - `list`/`preview` rows carry `liveness` (`live`, `uncertain`, `dead`) and `safe` = not `live`, instead of `safe = uncertain` and a prose `reason`. - `settle` refuses a holder still `live` with `InUse` (fix: the same line with `--force`) unless `--force`, or `--legacy` for a row without evidence. - A worker's `store.repair` is sent the calling home's place view and installs it, as Store calls do. Item 6, the call surface (2.0 conventions): - `store.repair_mount_holders(project, branch, action, { op, legacy, force, operator, limit, cursor })`: a `/` Project argument instead of a Store name plus a project name; `list`, `preview` and `audit` page by `limit` (1-1000, default 100) and `cursor` (carrying project, Branch and action) and answer `{ action, items, next_cursor }`; ops answer `{ action, op, state }` with state words. - The repair moved out of `layerfs-store/src/service.rs` into `layerfs-store/src/repair.rs`: one `Repair` request (frame codec shared by the local and worker routes) replaces the ten-argument functions and their `too_many_arguments` allows; `control::store::repair` takes a `RepairRequest`. - `project.mount_holders` appears in no doc or source (the doctor check is `store.mount_holders`), so nothing to drop or build. Item 7, leftovers with no product caller: - removed `gc_record_done`/`record_done`/`gc_intent_done_insert.sql`, `gc_prune_done`/`prune_done`/`gc_intent_done_delete.sql`, `Param::OptionalI64` and its binders, `admission::audit_value` (replaced by the per-row `done_value`), and the lease wording plus the unused `now_ms` argument of `PlaceAuthority::liveness` and `PlaceView`. Docs: `store.md` section rewritten; GC spec place-writer, audit and repair bullets; runbook audit line. Tests deleted (they drove removed APIs): `gc_intent_done` `preview_retains_a_done_row_without_an_operation` and `a_prune_deletes_only_the_named_done_rows`. Tests changed: `gc_calls`, `cli/gc`, `store_repair_worker`, `store_repair_live`, `repair_postgresql` (new call shape; settle guard and cursor paging asserted), `authority` (no `now_ms`). New: `gc_place_view` liveness test. Production LOC: 214,167 -> 214,170 (delta +3) scope: tools/production_loc.py (repo-pinned counter), first-parent tree vs committed tree reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Co-Authored-By: Claude Opus 5.5 --- .../src/store/repair_mount_holders.rs | 69 ++-- api/crates/layerfs-api/tests/gc_calls.rs | 62 +++- api/crates/layerfs-cli/tests/gc.rs | 15 +- control/crates/layerfs-control/src/store.rs | 151 +++++--- .../layerfs-control/src/worker_server/ops.rs | 48 +-- .../tests/store_repair_live.rs | 30 +- .../tests/store_repair_worker.rs | 76 ++-- control/crates/layerfs-store/src/lib.rs | 1 + control/crates/layerfs-store/src/repair.rs | 351 ++++++++++++++++++ control/crates/layerfs-store/src/service.rs | 258 ------------- .../layerfs-store/tests/repair_postgresql.rs | 133 +++---- .../layerfs-history/src/contract/authority.rs | 19 +- .../layerfs-history/src/contract/catalog.rs | 29 +- .../crates/layerfs-history/tests/authority.rs | 10 +- .../docs/issues/project-41/LayerFS-GC-spec.md | 48 ++- core/docs/issues/project-41/gc-runbook.md | 2 +- docs/architecture/api/sdk/store.md | 61 +-- .../queries/history/gc_intent_done_delete.sql | 6 - .../queries/history/gc_intent_done_insert.sql | 9 - .../queries/history/gc_intent_release.sql | 2 +- .../src/backend/postgresql/session/query.rs | 1 - .../src/backend/records.rs | 1 - .../src/backend/sqlite/session/query.rs | 6 - .../src/backend/sqlite/session/rows.rs | 1 - .../src/history/admission.rs | 59 +-- .../src/history/admission/authority.rs | 23 +- .../src/history/admission/place.rs | 4 +- .../src/history/bindings.rs | 5 - .../src/history/catalog.rs | 12 +- .../tests/gc_intent_done.rs | 94 ----- .../tests/gc_place_view.rs | 34 ++ .../src/history/admission.rs | 63 ++-- 32 files changed, 835 insertions(+), 848 deletions(-) create mode 100644 control/crates/layerfs-store/src/repair.rs delete mode 100644 engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_delete.sql delete mode 100644 engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_insert.sql diff --git a/api/crates/layerfs-api/src/store/repair_mount_holders.rs b/api/crates/layerfs-api/src/store/repair_mount_holders.rs index dc23efc3c4..b723968f1c 100644 --- a/api/crates/layerfs-api/src/store/repair_mount_holders.rs +++ b/api/crates/layerfs-api/src/store/repair_mount_holders.rs @@ -1,65 +1,50 @@ //! `store.repair_mount_holders`: explicit first-class repair of one Branch's //! mount admissions, on the machine whose worker holds a SQLite Store and in -//! this process for a PostgreSQL Store. List and preview write nothing: they -//! answer the typed holder view, preview with what release would do for each -//! holder; settle/release name one op; `audit` reads the bounded retained done -//! rows of that Branch. Release retains the row as the durable operator audit -//! and records the operator label; every call is also in the home's -//! `trace/calls.jsonl` call log. +//! this process for a PostgreSQL Store. `list` and `preview` write nothing: +//! one page of holders, each with its row `state` and the `liveness` +//! admission would give it now; `settle` refuses a holder still `live` +//! unless forced; `release` retains a settled row as the durable done audit +//! and records the operator label; `audit` pages the Branch's retained rows. +//! Every call is also in the home's `trace/calls.jsonl` call log. use crate::calls::table::{ a, call, opt, Call, - Kind::{Bool, Int, Name, Text}, + Kind::{Bool, Int, Name, Project, Text}, }; -use crate::calls::Context; +use crate::calls::{Context, Paging}; use layerfs_bridge::control::SdkValue; -use layerfs_home::names::StoreName; -use layerfs_home::outcome::{refused, Outcome}; +use layerfs_control::store::RepairRequest; +use layerfs_home::outcome::Outcome; pub(crate) const CALL: Call = call( "store", "repair_mount_holders", - &[ - a("name", Name), - a("project", Name), - a("branch", Name), - a("action", Name), - ], + &[a("project", Project), a("branch", Name), a("action", Name)], &[ opt("op", Text), opt("legacy", Bool), + opt("force", Bool), opt("operator", Text), - opt("page", Int), opt("limit", Int), + opt("cursor", Text).redact(), ], "list, preview, settle, release or audit mount holders (operator)", run, -); +) +.paged(Paging::Cursor); fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { - let name = StoreName::parse(args.get_text("name").unwrap_or(""))?; - let project = args.get_text("project").unwrap_or("").to_owned(); - let branch = args.get_text("branch").unwrap_or("").to_owned(); - let action = args.get_text("action").unwrap_or("preview").to_owned(); - let op = match args.get_text("op") { - None | Some("") => None, - Some(text) => Some( - layerfs_bridge::sdk_values::unhex(text) - .and_then(|bytes| bytes.try_into().ok()) - .ok_or_else(|| refused("InvalidInput", "op must be 16 bytes of hex"))?, - ), + let text = |name: &str| args.get_text(name).map(str::to_owned); + let request = RepairRequest { + project: text("project").unwrap_or_default(), + branch: text("branch").unwrap_or_default(), + action: text("action").unwrap_or_default(), + op: text("op"), + legacy: matches!(args.get("legacy"), Some(SdkValue::Bool(true))), + force: matches!(args.get("force"), Some(SdkValue::Bool(true))), + operator: text("operator"), + limit: args.get_int("limit"), + cursor: text("cursor"), }; - let legacy = matches!(args.get("legacy"), Some(SdkValue::Bool(true))); - let operator = args.get_text("operator").unwrap_or(""); - let page = args - .get_int("page") - .and_then(|page| u32::try_from(page).ok()) - .unwrap_or(0); - let limit = args - .get_int("limit") - .and_then(|limit| u32::try_from(limit).ok()) - .unwrap_or(100); let (home, _) = context.parts(); - layerfs_control::store::repair( - home, &name, &project, &branch, &action, op, legacy, operator, page, limit, - ) + layerfs_control::store::repair(home, &request) } diff --git a/api/crates/layerfs-api/tests/gc_calls.rs b/api/crates/layerfs-api/tests/gc_calls.rs index 60ca93e2b3..b4ebb56384 100644 --- a/api/crates/layerfs-api/tests/gc_calls.rs +++ b/api/crates/layerfs-api/tests/gc_calls.rs @@ -870,8 +870,7 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { let legacy_op = "31".repeat(16); let repair = |action: &str, op: Option<&str>, legacy: bool| { let mut fields = vec![ - ("name", t("shop")), - ("project", t("api")), + ("project", t("shop/api")), ("branch", t("main")), ("action", t(action)), ]; @@ -892,13 +891,12 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { "store.repair_mount_holders", &repair("preview", None, false), ); - let Some(SdkValue::List(holders)) = preview.get("holders") else { + let Some(SdkValue::List(holders)) = preview.get("items") else { panic!("preview holders: {preview:?}"); }; assert_eq!(holders.len(), 2, "{preview:?}"); assert_eq!(preview.get_text("action"), Some("preview")); - assert_eq!(preview.get("op"), Some(&SdkValue::Null)); - assert_eq!(preview.get("audit"), Some(&SdkValue::Null)); + assert_eq!(preview.get("next_cursor"), Some(&SdkValue::Null)); // Preview is read-only: the Branch's intents are as registered, and no // retained row was written. let intents = with_service(&open, |service| { @@ -932,6 +930,10 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { Some("generation:1") ); assert_eq!(live_row.get("legacy"), Some(&SdkValue::Bool(false))); + // nothing proves its owner gone: the row still looks live + assert_eq!(live_row.get_text("liveness"), Some("live")); + assert_eq!(live_row.get("safe"), Some(&SdkValue::Bool(false))); + assert!(live_row.get("reason").is_none(), "state words, no prose"); let legacy_row = holders .iter() .find(|row| row.get_text("op") == Some(legacy_op.as_str())) @@ -952,17 +954,23 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { ); assert_eq!(code, "InvalidInput", "{message}"); - ok( + // a holder that still looks live is settled only when forced + let (code, message) = refused( &home, "store.repair_mount_holders", &repair("settle", Some(&live_op), false), ); + assert_eq!(code, "InUse", "{message}"); + let mut forced = repair("settle", Some(&live_op), false); + forced.push(("force", SdkValue::Bool(true))); + let settled = ok(&home, "store.repair_mount_holders", &forced); + assert_eq!(settled.get_text("state"), Some("uncertain"), "{settled:?}"); let preview = ok( &home, "store.repair_mount_holders", &repair("preview", None, false), ); - let Some(SdkValue::List(holders)) = preview.get("holders") else { + let Some(SdkValue::List(holders)) = preview.get("items") else { panic!("preview holders: {preview:?}"); }; let settled_row = holders @@ -993,7 +1001,7 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { &repair("preview", None, false), ); assert!( - matches!(preview.get("holders"), Some(SdkValue::List(rows)) if rows.is_empty()), + matches!(preview.get("items"), Some(SdkValue::List(rows)) if rows.is_empty()), "{preview:?}" ); @@ -1030,16 +1038,38 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { evidence.contains(&format!("action=release;operator=alice;op={live_op}")), "{evidence}" ); - assert!(matches!(audit.get("has_more"), Some(SdkValue::Bool(false)))); + assert_eq!(audit.get("next_cursor"), Some(&SdkValue::Null), "{audit:?}"); - // Paging is bounded by the call, not by the caller. - let mut paged = repair("audit", None, false); - paged.push(("limit", SdkValue::Int(i64::from(u32::MAX)))); - let paged = ok(&home, "store.repair_mount_holders", &paged); - assert!( - matches!(paged.get("limit"), Some(SdkValue::Int(limit)) if *limit == i64::from(layerfs_history::MAXIMUM_AUDIT_PAGE)), - "{paged:?}" + // Paging is by `limit` and `cursor`: one row a page, the cursor carries + // the project, Branch and action, and another action's cursor is refused. + let mut first = repair("audit", None, false); + first.push(("limit", SdkValue::Int(1))); + let first = ok(&home, "store.repair_mount_holders", &first); + let Some(cursor) = first.get_text("next_cursor").map(str::to_owned) else { + panic!("a first page of one names the next: {first:?}"); + }; + let mut second = repair("audit", None, false); + second.push(("limit", SdkValue::Int(1))); + second.push(("cursor", t(&cursor))); + let second = ok(&home, "store.repair_mount_holders", &second); + let op_of = |page: &SdkValue| match page.get("items") { + Some(SdkValue::List(rows)) if rows.len() == 1 => rows[0].get_text("op").map(str::to_owned), + other => panic!("one row: {other:?}"), + }; + assert_ne!(op_of(&first), op_of(&second), "the second page moves on"); + assert_eq!( + second.get("next_cursor"), + Some(&SdkValue::Null), + "{second:?}" ); + let mut crossed = repair("preview", None, false); + crossed.push(("cursor", t(&cursor))); + let (code, message) = refused(&home, "store.repair_mount_holders", &crossed); + assert_eq!(code, "InvalidInput", "{message}"); + let mut too_many = repair("audit", None, false); + too_many.push(("limit", SdkValue::Int(i64::from(u32::MAX)))); + let (code, message) = refused(&home, "store.repair_mount_holders", &too_many); + assert_eq!(code, "InvalidInput", "{message}"); // A refused call changes nothing. let (code, message) = refused( diff --git a/api/crates/layerfs-cli/tests/gc.rs b/api/crates/layerfs-cli/tests/gc.rs index b533960fef..bd803e89f7 100644 --- a/api/crates/layerfs-cli/tests/gc.rs +++ b/api/crates/layerfs-cli/tests/gc.rs @@ -36,7 +36,7 @@ const CALLS: &[(&[&str], &str, &str)] = &[ ), ( &["store", "repair-mount-holders"], - "layerfs store repair-mount-holders ", + "layerfs store repair-mount-holders ", "list, preview, settle, release or audit mount holders (operator)", ), ]; @@ -112,12 +112,11 @@ fn wrong_arity_and_options_are_usage_errors() { &["store", "compact", "shop", "extra"], &["store", "compact", "shop", "--force"], &["store", "repair-mount-holders"], - &["store", "repair-mount-holders", "shop", "app", "main"], + &["store", "repair-mount-holders", "shop/app", "main"], &[ "store", "repair-mount-holders", - "shop", - "app", + "shop/app", "main", "preview", "extra", @@ -125,11 +124,10 @@ fn wrong_arity_and_options_are_usage_errors() { &[ "store", "repair-mount-holders", - "shop", - "app", + "shop/app", "main", "preview", - "--force", + "--prune", ], ]; for words in wrong { @@ -154,8 +152,7 @@ fn well_formed_lines_reach_the_library() { &[ "store", "repair-mount-holders", - "shop", - "app", + "shop/app", "main", "preview", ], diff --git a/control/crates/layerfs-control/src/store.rs b/control/crates/layerfs-control/src/store.rs index bb08bbc3c8..395163aafd 100644 --- a/control/crates/layerfs-control/src/store.rs +++ b/control/crates/layerfs-control/src/store.rs @@ -7,7 +7,6 @@ //! reaches it as a Sandbox call would. use crate::inventory; use layerfs_bridge::control::{SdkRefusal, SdkValue}; -use layerfs_bridge::sdk_values::hex; use layerfs_home::events::Events; use layerfs_home::names::{MachineName, StoreName}; use layerfs_home::outcome::shell_word; @@ -69,62 +68,118 @@ pub fn compact(home: &Path, events: &mut Events<'_>, name: &StoreName) -> Outcom }) } +/// `store.repair_mount_holders(project, branch, action, { op, legacy, +/// force, operator, limit, cursor })` as the call surface takes it. +#[derive(Clone, Debug, Default)] +pub struct RepairRequest { + /// The project, `/`. + pub project: String, + /// The Branch whose mount holders it repairs. + pub branch: String, + /// `list`, `preview`, `settle`, `release`, `settle_legacy` or `audit`. + pub action: String, + /// The holder `settle` and `release` act on, as hex. + pub op: Option, + /// `settle` only a row without owner or place evidence. + pub legacy: bool, + /// `settle` a holder that still looks live. + pub force: bool, + /// The operator label a release records. + pub operator: Option, + /// The rows of one page (`list`, `preview`, `audit`). + pub limit: Option, + /// The `next_cursor` of the page before. + pub cursor: Option, +} + +/// The call a repair cursor belongs to. +const REPAIR: &str = "store.repair_mount_holders"; + /// `store.repair_mount_holders`: first-class explicit operator repair of -/// one Branch's mount intents. List and preview write nothing (preview says -/// what release would do for each holder); settle/release act on one explicit -/// op; release retains the row as the durable done audit; `audit` reads the -/// retained rows of that Branch. -/// Nothing is automatic. A SQLite -/// Store on another machine is repaired by that machine's worker -/// (`store.repair`), so the live Docker Store is reachable; a PostgreSQL -/// Store runs here, as its calls do. -#[allow(clippy::too_many_arguments)] -pub fn repair( - home: &Path, - name: &StoreName, - project: &str, - branch: &str, - action: &str, - op: Option<[u8; 16]>, - legacy: bool, - operator: &str, - page: u32, - limit: u32, -) -> Outcome { +/// one Branch's mount intents ([`layerfs_store::repair`]). `list` and +/// `preview` page the holders, each with its row `state` and the +/// `liveness` admission would give it now; `settle` refuses a holder still +/// `live` unless forced; `release` retains a settled row as the durable done +/// audit; `audit` pages the Branch's retained rows. The cursor carries the +/// project, Branch and action. Nothing is automatic. A SQLite Store on +/// another machine is repaired by that machine's worker (`store.repair`), +/// sent this home's place view; a PostgreSQL Store runs here, as its calls +/// do. +pub fn repair(home: &Path, request: &RepairRequest) -> Outcome { + let limit = layerfs_home::cursor::limit(REPAIR, request.limit, 100)?; + let filters = [ + ("project", SdkValue::text(&request.project)), + ("branch", SdkValue::text(&request.branch)), + ("action", SdkValue::text(&request.action)), + ]; + let carried = (request.cursor.as_deref()) + .map(|made| layerfs_home::cursor::resume(REPAIR, made, &filters)) + .transpose()?; + let target = layerfs_store::resolve::target(home, &request.project)?; + let sent = layerfs_store::repair::Repair { + project: target.project.clone(), + branch: request.branch.clone(), + action: request.action.clone(), + op: layerfs_store::repair::op_of(request.op.as_deref())?, + legacy: request.legacy, + force: request.force, + operator: request.operator.clone().unwrap_or_default(), + after: carried.as_ref().map(|carried| carried.place().clone()), + limit: limit as u32, + }; // The host holds the Store's lease while it repairs or sends the call, // as `store_call` does: a Store an operation is moving is left. - let (_lease, record) = layerfs_store::lease::claim(home, name.as_str())?; - let store_ref = record.store_ref()?; - let executor = place::plan(home, store_ref)?; - match executor { + let (_lease, record) = layerfs_store::lease::claim(home, &target.store)?; + let answer = match place::plan(home, record.store_ref()?)? { Executor::Local => { - let open = OpenArgs::of_record(home, name.as_str(), &record)?; - layerfs_store::service::repair_mount_holders_at( - &open, project, branch, action, op, legacy, operator, page, limit, - ) + let open = OpenArgs::of_record(home, &target.store, &record)?; + layerfs_store::repair::repair_at(&open, &sent) } Executor::Worker(mut worker) => { - let fields = vec![ - ("store".to_owned(), SdkValue::text(name.as_str())), + let mut fields = vec![ + ("store".to_owned(), SdkValue::text(&target.store)), ("store_record".to_owned(), record.to_record().clone()), - ("project".to_owned(), SdkValue::text(project)), - ("branch".to_owned(), SdkValue::text(branch)), - ("action".to_owned(), SdkValue::text(action)), - ( - "op".to_owned(), - op.map_or(SdkValue::Null, |op| SdkValue::text(hex(&op))), - ), - ("legacy".to_owned(), SdkValue::Bool(legacy)), - ("operator".to_owned(), SdkValue::text(operator)), - ("page".to_owned(), SdkValue::Int(i64::from(page))), - ("limit".to_owned(), SdkValue::Int(i64::from(limit))), ]; - // no repair action compares a place (it names its op), so the - // frame carries no place view - let request = SdkValue::Map(fields); - worker.call("store.repair", request, &mut |_: SdkValue| {}) + fields.extend(sent.to_fields()); + // list, preview and settle judge holders with this home's places + if let Some(view) = layerfs_store::place_view::encoded_from_home(home) { + fields.push(("place_view".to_owned(), view)); + } + worker.call("store.repair", SdkValue::Map(fields), &mut |_: SdkValue| {}) } - } + }; + let answer = answer.map_err(|refusal| match refusal.code.as_str() { + "InUse" => with_fix( + refusal, + format!( + "layerfs store repair-mount-holders {} {} settle --op {} --force", + shell_word(&request.project), + shell_word(&request.branch), + request.op.as_deref().unwrap_or_default() + ), + ), + _ => refusal, + })?; + Ok(paged(answer, &filters)) +} + +/// A repair answer with its `next` place made the `next_cursor` the caller +/// takes back; an answer that is no page is as the Store side gave it. +fn paged(answer: SdkValue, filters: &[(&str, SdkValue)]) -> SdkValue { + let SdkValue::Map(fields) = answer else { + return answer; + }; + let fields = (fields.into_iter()) + .map(|(name, value)| match (name.as_str(), value) { + ("next", SdkValue::Null) => ("next_cursor".to_owned(), SdkValue::Null), + ("next", place) => ( + "next_cursor".to_owned(), + SdkValue::Text(layerfs_home::cursor::make(REPAIR, place, filters)), + ), + (_, value) => (name, value), + }) + .collect(); + SdkValue::Map(fields) } /// Who uses a Store or a project, read from the Sandbox records. diff --git a/control/crates/layerfs-control/src/worker_server/ops.rs b/control/crates/layerfs-control/src/worker_server/ops.rs index fcb8dc7696..d935acd2c0 100644 --- a/control/crates/layerfs-control/src/worker_server/ops.rs +++ b/control/crates/layerfs-control/src/worker_server/ops.rs @@ -191,46 +191,17 @@ pub(super) fn run( }) } // the operator's repair of one Branch's mount holders on the Store - // under this worker's root: `{ store, store_record, project, branch, - // action, op?, legacy, operator?, page?, limit? }`. List and preview - // write nothing: they answer the typed holders, each with what release - // would do. settle/release act on one explicit op (`legacy` settles - // only a row without owner or place evidence); release retains the - // row as the durable done audit; `audit` reads the Branch's retained - // rows. The call log records every action. + // under this worker's root: `{ store, store_record, place_view?, + // }`. `list`, `preview` and + // `settle` judge each holder with the caller's place view, installed + // here as a Store call's is; the rest is `layerfs_store::repair`. "store.repair" => { let store = args .get_text("store") .ok_or_else(|| refused("InvalidInput", "a Store repair names its Store"))? .to_owned(); layerfs_home::names::StoreName::parse(&store)?; - let project = args - .get_text("project") - .ok_or_else(|| refused("InvalidInput", "a Store repair names its project"))?; - let branch = args - .get_text("branch") - .ok_or_else(|| refused("InvalidInput", "a Store repair names its Branch"))?; - let action = args - .get_text("action") - .ok_or_else(|| refused("InvalidInput", "a Store repair names its action"))?; - let op = match args.get_text("op") { - None | Some("") => None, - Some(text) => Some( - layerfs_bridge::sdk_values::unhex(text) - .and_then(|bytes| bytes.try_into().ok()) - .ok_or_else(|| refused("InvalidInput", "op must be 16 bytes of hex"))?, - ), - }; - let legacy = matches!(args.get("legacy"), Some(SdkValue::Bool(true))); - let operator = args.get_text("operator").unwrap_or(""); - let page = args - .get_int("page") - .and_then(|page| u32::try_from(page).ok()) - .unwrap_or(0); - let limit = args - .get_int("limit") - .and_then(|limit| u32::try_from(limit).ok()) - .unwrap_or(100); + let request = layerfs_store::repair::Repair::read(&args)?; let file = layerfs_home::home::paths::store_file(root, &store); let open = layerfs_store::open_args::OpenArgs { home: Some(root.to_path_buf()), @@ -240,9 +211,12 @@ pub(super) fn run( store_record: args.get("store_record").cloned(), postgresql: None, }; - layerfs_store::service::repair_mount_holders_at( - &open, project, branch, action, op, legacy, operator, page, limit, - ) + let place = layerfs_store_service::history::admission::decode_place_view( + args.get("place_view"), + ); + layerfs_store_service::history::admission::with_place_view(place, || { + layerfs_store::repair::repair_at(&open, &request) + }) } // one step of a Store move, remove or create, or a live read's, on // this machine diff --git a/control/crates/layerfs-control/tests/store_repair_live.rs b/control/crates/layerfs-control/tests/store_repair_live.rs index a4d774b003..cf539e31c0 100644 --- a/control/crates/layerfs-control/tests/store_repair_live.rs +++ b/control/crates/layerfs-control/tests/store_repair_live.rs @@ -212,6 +212,9 @@ fn seed(home: &Path) { .unwrap(); } +/// One repair of `branch` on the worker. A settle here is forced: these +/// holders name owners nothing on this host can judge, and the operator +/// confirmed them gone (the guard itself is `store_repair_worker`'s). fn repair( placed: &worker_store::Placed, branch: &str, @@ -219,24 +222,23 @@ fn repair( op: Option, legacy: bool, ) -> SdkValue { - let name = StoreName::parse("shop").unwrap(); - layerfs_control::store::repair( - &placed.home, - &name, - "app", - branch, - action, - op.map(|op| [op; 16]), + let request = layerfs_control::store::RepairRequest { + project: "shop/app".to_owned(), + branch: branch.to_owned(), + action: action.to_owned(), + op: op.map(op_hex), legacy, - "alice", - 0, - 100, - ) - .unwrap_or_else(|refusal| panic!("{action} {branch}: {refusal:?}")) + force: action == "settle", + operator: Some("alice".to_owned()), + limit: None, + cursor: None, + }; + layerfs_control::store::repair(&placed.home, &request) + .unwrap_or_else(|refusal| panic!("{action} {branch}: {refusal:?}")) } fn holders(value: &SdkValue) -> &[SdkValue] { - match value.get("holders") { + match value.get("items") { Some(SdkValue::List(holders)) => holders, other => panic!("no holder list: {other:?}"), } diff --git a/control/crates/layerfs-control/tests/store_repair_worker.rs b/control/crates/layerfs-control/tests/store_repair_worker.rs index 19d0910eca..8539ea663c 100644 --- a/control/crates/layerfs-control/tests/store_repair_worker.rs +++ b/control/crates/layerfs-control/tests/store_repair_worker.rs @@ -8,6 +8,8 @@ mod worker_store; use layerfs_bridge::control::SdkValue; +use layerfs_bridge::sdk_values::hex; +use layerfs_control::store::RepairRequest; use layerfs_history::records::{GcIntent, GcIntentKind, GcScopeKind}; use layerfs_history::{HistoryName, NamedSnapshot, PlaceAuthority}; use layerfs_home::names::StoreName; @@ -113,25 +115,27 @@ fn serve(listener: std::net::TcpListener, root: PathBuf) { }); } -fn repair(placed: &worker_store::Placed, action: &str, op: Option, legacy: bool) -> SdkValue { - let name = StoreName::parse("shop").unwrap(); - layerfs_control::store::repair( - &placed.home, - &name, - "app", - "main", - action, - op.map(|op| [op; 16]), +fn request(action: &str, op: Option, legacy: bool) -> RepairRequest { + RepairRequest { + project: "shop/app".to_owned(), + branch: "main".to_owned(), + action: action.to_owned(), + op: op.map(|op| hex(&[op; 16])), legacy, - "alice", - 0, - 100, - ) - .unwrap_or_else(|refusal| panic!("{action}: {refusal:?}")) + force: false, + operator: Some("alice".to_owned()), + limit: None, + cursor: None, + } +} + +fn repair(placed: &worker_store::Placed, action: &str, op: Option, legacy: bool) -> SdkValue { + layerfs_control::store::repair(&placed.home, &request(action, op, legacy)) + .unwrap_or_else(|refusal| panic!("{action}: {refusal:?}")) } fn holders(value: &SdkValue) -> &[SdkValue] { - match value.get("holders") { + match value.get("items") { Some(SdkValue::List(holders)) => holders, other => panic!("no holder list: {other:?}"), } @@ -181,7 +185,7 @@ fn repair_previews_settles_and_releases_through_the_worker() { // Preview over the worker answers the typed view and writes nothing. let preview = repair(&placed, "preview", None, false); - assert_eq!(preview.get("audit"), Some(&SdkValue::Null), "{preview:?}"); + assert_eq!(preview.get_text("action"), Some("preview"), "{preview:?}"); let audit = repair(&placed, "audit", None, false); assert!( matches!(audit.get("items"), Some(SdkValue::List(rows)) if rows.is_empty()), @@ -194,6 +198,9 @@ fn repair_previews_settles_and_releases_through_the_worker() { .find(|row| row.get_text("op") == Some("21".repeat(16).as_str())) .expect("the live holder"); assert_eq!(live.get_text("state"), Some("live")); + // nothing proves its owner gone: it still looks live, so not safe + assert_eq!(live.get_text("liveness"), Some("live")); + assert_eq!(live.get("safe"), Some(&SdkValue::Bool(false))); assert_eq!(live.get_text("sandbox"), Some("box")); assert_eq!(live.get_text("machine_incarnation"), Some("worker:1")); assert_eq!(live.get_text("sandbox_generation"), Some("generation:1")); @@ -204,23 +211,28 @@ fn repair_previews_settles_and_releases_through_the_worker() { .expect("the legacy holder"); assert_eq!(legacy.get("legacy"), Some(&SdkValue::Bool(true))); - // Release without settle is refused; settle marks the one named op. - let name = StoreName::parse("shop").unwrap(); - let refused = layerfs_control::store::repair( - &placed.home, - &name, - "app", - "main", - "release", - Some([0x21; 16]), - false, - "alice", - 0, - 100, - ) - .unwrap_err(); + // Release without settle is refused; a settle of a holder that still + // looks live is refused `InUse` unless forced, and marks the one op. + let refused = + layerfs_control::store::repair(&placed.home, &request("release", Some(0x21), false)) + .unwrap_err(); assert_eq!(refused.code, "Conflict", "{refused:?}"); - repair(&placed, "settle", Some(0x21), false); + let refused = + layerfs_control::store::repair(&placed.home, &request("settle", Some(0x21), false)) + .unwrap_err(); + assert_eq!(refused.code, "InUse", "{refused:?}"); + assert!( + refused + .detail + .get_text("fix") + .is_some_and(|fix| fix.ends_with("--force")), + "{refused:?}" + ); + let forced = RepairRequest { + force: true, + ..request("settle", Some(0x21), false) + }; + layerfs_control::store::repair(&placed.home, &forced).expect("a forced settle"); let preview = repair(&placed, "preview", None, false); let settled = holders(&preview) .iter() diff --git a/control/crates/layerfs-store/src/lib.rs b/control/crates/layerfs-store/src/lib.rs index 75693f4611..1e92087f75 100644 --- a/control/crates/layerfs-store/src/lib.rs +++ b/control/crates/layerfs-store/src/lib.rs @@ -37,6 +37,7 @@ pub mod project; #[doc(hidden)] pub mod record; mod related; +pub mod repair; pub mod report; #[doc(hidden)] pub mod resolve; diff --git a/control/crates/layerfs-store/src/repair.rs b/control/crates/layerfs-store/src/repair.rs new file mode 100644 index 0000000000..b4f1396bc6 --- /dev/null +++ b/control/crates/layerfs-store/src/repair.rs @@ -0,0 +1,351 @@ +//! `store.repair_mount_holders` where the Store's calls run: in this process +//! for a PostgreSQL Store or a SQLite Store on this computer, or in the +//! machine's worker (`store.repair`) for a SQLite Store there. The caller's +//! side resolves the project and the cursor ([`Repair`] is what crosses); +//! this side reads the Branch's mount intents, judges each with the same +//! owner check and place view admission uses, and acts on one explicit op. +//! +//! `list` and `preview` write nothing: one page of holders by op, each with +//! its row `state` (`live`, `uncertain`) and the `liveness` admission would +//! give it now (`live`, `uncertain`, `dead`). `settle` marks one op uncertain +//! and refuses a holder that still looks `live` unless forced; `release` +//! retains a settled row as the durable `done` audit; `settle_legacy` marks +//! only rows without owner or place evidence; `audit` reads one page of the +//! Branch's retained rows. Nothing is automatic. +use crate::open_args::OpenArgs; +use crate::service::{branch_named, with_service}; +use layerfs_bridge::control::{SdkRefusal, SdkValue}; +use layerfs_bridge::sdk_values::{hex, unhex}; +use layerfs_history::{GcIntent, GcIntentKind, GcScopeKind, Liveness, MountHolderView}; +use layerfs_home::outcome::{failed, refused}; +use layerfs_store_service::history::admission; + +type Result = std::result::Result; + +/// The actions the call takes. +pub const ACTIONS: [&str; 6] = [ + "list", + "preview", + "settle", + "release", + "settle_legacy", + "audit", +]; + +/// One repair as the side that holds the Store runs it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Repair { + /// The project's name in its Store. + pub project: String, + /// The Branch whose mount holders it repairs. + pub branch: String, + /// One of [`ACTIONS`]. + pub action: String, + /// The holder `settle` and `release` act on. + pub op: Option<[u8; 16]>, + /// `settle` only a row without owner or place evidence. + pub legacy: bool, + /// `settle` a holder that still looks `live`. + pub force: bool, + /// The operator label a release records (empty: `local`). + pub operator: String, + /// Where the page starts, from the caller's cursor: the last holder op + /// listed (`list`, `preview`) or the audit page (`audit`). + pub after: Option, + /// The rows of one page. + pub limit: u32, +} + +impl Repair { + /// The request as a worker frame's fields. + #[must_use] + pub fn to_fields(&self) -> Vec<(String, SdkValue)> { + let text = |value: &str| SdkValue::text(value); + vec![ + ("project".to_owned(), text(&self.project)), + ("branch".to_owned(), text(&self.branch)), + ("action".to_owned(), text(&self.action)), + ( + "op".to_owned(), + self.op.map_or(SdkValue::Null, |op| text(&hex(&op))), + ), + ("legacy".to_owned(), SdkValue::Bool(self.legacy)), + ("force".to_owned(), SdkValue::Bool(self.force)), + ("operator".to_owned(), text(&self.operator)), + ("after".to_owned(), self.after.clone().unwrap_or_default()), + ("limit".to_owned(), SdkValue::Int(i64::from(self.limit))), + ] + } + + /// The request a worker frame's `args` carry; a missing name or a + /// malformed op is `InvalidInput`. + pub fn read(args: &SdkValue) -> Result { + let named = |name: &str| { + args.get_text(name) + .map(str::to_owned) + .ok_or_else(|| refused("InvalidInput", format!("a Store repair names its {name}"))) + }; + Ok(Self { + project: named("project")?, + branch: named("branch")?, + action: named("action")?, + op: op_of(args.get_text("op"))?, + legacy: args.get_bool("legacy"), + force: args.get_bool("force"), + operator: args.get_text("operator").unwrap_or("").to_owned(), + after: args.get("after").filter(|v| **v != SdkValue::Null).cloned(), + limit: (args.get_int("limit")) + .and_then(|limit| u32::try_from(limit).ok()) + .unwrap_or(100), + }) + } +} + +/// A holder op as given: 16 bytes of hex, or none. +pub fn op_of(text: Option<&str>) -> Result> { + match text { + None | Some("") => Ok(None), + Some(text) => unhex(text) + .and_then(|bytes| bytes.try_into().ok()) + .map(Some) + .ok_or_else(|| refused("InvalidInput", "op must be 16 bytes of hex")), + } +} + +/// Runs `request` on the Store `open` names, with the place view of its +/// caller's home (or the one a worker frame installed): `{ action, items, +/// next }` for a page (`next`, the place the next page starts from, or null), +/// `{ action, op, state }` for an op, `{ action, settled }` for +/// `settle_legacy`. +pub fn repair_at(open: &OpenArgs, request: &Repair) -> Result { + if !ACTIONS.contains(&request.action.as_str()) { + return Err(refused( + "InvalidInput", + format!("action must be one of {}", ACTIONS.join(", ")), + )); + } + if request.action == "audit" { + return audit(open, request); + } + let branch = branch_named(open, &request.project, &request.branch)?; + crate::place_view::scoped(open, || { + with_service(open, |service| holders(service, branch, request)) + }) +} + +/// One page of the Branch's retained `done` rows, oldest first; the page +/// number travels in the cursor. +fn audit(open: &OpenArgs, request: &Repair) -> Result { + let page = match &request.after { + Some(SdkValue::Int(page)) => u32::try_from(*page).unwrap_or(0), + _ => 0, + }; + with_service(open, |service| { + let read = admission::done_intents_branch( + service.store.history(), + &request.project, + &request.branch, + page, + request.limit, + ) + .map_err(failed)?; + let items = read.items.iter().map(admission::done_value).collect(); + let next = match read.has_more { + true => SdkValue::Int(i64::from(page) + 1), + false => SdkValue::Null, + }; + Ok(SdkValue::map([ + ("action", SdkValue::text("audit")), + ("items", SdkValue::List(items)), + ("next", next), + ])) + }) +} + +/// The actions on the Branch's live mount intents. +fn holders( + service: &layerfs_store_service::StoreService, + branch: layerfs_history::BranchId, + request: &Repair, +) -> Result { + let catalog = service.store.history(); + let mut mounts: Vec = (catalog.gc_intents(GcScopeKind::Branch, branch.as_slice())) + .map_err(failed)? + .into_iter() + .filter(|intent| intent.kind == GcIntentKind::Mount) + .collect(); + mounts.sort_by_key(|intent| intent.op_id); + let action = request.action.as_str(); + if matches!(action, "list" | "preview") { + return page(catalog, &mounts, request); + } + if action == "settle_legacy" { + let mut settled = 0i64; + for intent in mounts.iter().filter(|i| MountHolderView::of(i).legacy()) { + catalog.gc_mark_uncertain(&intent.op_id).map_err(failed)?; + settled += 1; + } + return Ok(SdkValue::map([ + ("action", SdkValue::text(action)), + ("settled", SdkValue::Int(settled)), + ])); + } + let op = request + .op + .ok_or_else(|| refused("InvalidInput", format!("{action} needs the holder op")))?; + let shown = hex(&op); + let found = (mounts.iter().find(|intent| intent.op_id == op)).ok_or_else(|| { + refused( + "NotFound", + format!("no mount holder {shown} at this Branch"), + ) + })?; + let state = match action { + "settle" => { + settle(catalog, found, request)?; + "uncertain" + } + _ => { + if !found.uncertain { + return Err(refused( + "Conflict", + format!("mount holder {shown} is not settled: settle it before release"), + )); + } + let operator = operator_label(&request.operator)?; + let evidence = format!("action=release;operator={operator};op={shown}"); + if !catalog.gc_release_done(&op, &evidence).map_err(failed)? { + return Err(refused( + "NotFound", + format!("mount holder {shown} was already released"), + )); + } + "done" + } + }; + Ok(SdkValue::map([ + ("action", SdkValue::text(action)), + ("op", SdkValue::text(shown)), + ("state", SdkValue::text(state)), + ])) +} + +/// Marks `found` uncertain. A holder the owner check and place view still +/// find `live` is refused `InUse` unless forced; `--legacy` settles only a +/// row without owner or place evidence, which nothing can judge. +fn settle( + catalog: &dyn layerfs_history::HistoryCatalog, + found: &GcIntent, + request: &Repair, +) -> Result<()> { + let legacy = MountHolderView::of(found).legacy(); + if request.legacy && !legacy { + return Err(refused( + "InvalidInput", + "this holder has owner or place evidence; --legacy settles only legacy rows", + )); + } + if !(request.force || request.legacy) { + let judged = admission::liveness(catalog, std::slice::from_ref(found)).map_err(failed)?; + if judged.first() == Some(&Liveness::Live) { + return Err(refused( + "InUse", + format!( + "mount holder {} still looks live: nothing proves its owner gone; \ + settle it with --force once you know it is", + hex(&found.op_id) + ), + )); + } + } + catalog.gc_mark_uncertain(&found.op_id).map_err(failed) +} + +/// One page of holders after the cursor's op, each judged now. +fn page( + catalog: &dyn layerfs_history::HistoryCatalog, + mounts: &[GcIntent], + request: &Repair, +) -> Result { + let after = match &request.after { + Some(SdkValue::Text(text)) => op_of(Some(text))?, + _ => None, + }; + let mut left = mounts + .iter() + .filter(|intent| after.is_none_or(|after| intent.op_id > after)); + let shown: Vec = left + .by_ref() + .take(request.limit as usize) + .cloned() + .collect(); + let next = match (left.next(), shown.last()) { + (Some(_), Some(last)) => SdkValue::text(hex(&last.op_id)), + _ => SdkValue::Null, + }; + let judged = admission::liveness(catalog, &shown).map_err(failed)?; + let items = (shown.iter().zip(judged)) + .map(|(intent, liveness)| holder_row(&MountHolderView::of(intent), liveness)) + .collect(); + Ok(SdkValue::map([ + ("action", SdkValue::text(&request.action)), + ("items", SdkValue::List(items)), + ("next", next), + ])) +} + +/// The word a [`Liveness`] is shown as. +#[must_use] +pub fn liveness_word(liveness: Liveness) -> &'static str { + match liveness { + Liveness::Live => "live", + Liveness::Uncertain => "uncertain", + Liveness::Dead => "dead", + } +} + +/// One holder row: the typed view, its row `state`, the `liveness` judged +/// now and `safe` (true unless it still looks live: settle needs no force). +fn holder_row(holder: &MountHolderView, liveness: Liveness) -> SdkValue { + let text = |value: Option<&str>| SdkValue::opt_text(value); + let workspace = holder.workspace.map(|ws| hex(&ws)); + SdkValue::map([ + ("op", SdkValue::text(hex(&holder.op))), + ("branch", text(holder.branch.as_deref())), + ("project", text(holder.project.as_deref())), + ("workspace", text(workspace.as_deref())), + ("sandbox", text(holder.sandbox.as_deref())), + ("machine", text(holder.machine.as_deref())), + ("owner_runtime", text(holder.owner_runtime.as_deref())), + ("owner_boot", text(holder.owner_boot.as_deref())), + ( + "machine_incarnation", + text(holder.machine_incarnation.as_deref()), + ), + ( + "sandbox_generation", + text(holder.sandbox_generation.as_deref()), + ), + ("state", SdkValue::text(holder.state())), + ("liveness", SdkValue::text(liveness_word(liveness))), + ("safe", SdkValue::Bool(liveness != Liveness::Live)), + ("legacy", SdkValue::Bool(holder.legacy())), + ]) +} + +/// The operator label a release records. An absent label is the local +/// operator; a label is at most 128 characters without control characters. +/// It is not an authenticated principal, only the name the caller gives. +fn operator_label(operator: &str) -> Result<&str> { + let operator = operator.trim(); + if operator.is_empty() { + return Ok("local"); + } + if operator.len() > 128 || operator.chars().any(char::is_control) { + return Err(refused( + "InvalidInput", + "operator must be at most 128 characters without control characters", + )); + } + Ok(operator) +} diff --git a/control/crates/layerfs-store/src/service.rs b/control/crates/layerfs-store/src/service.rs index 50695d1915..e03f7beaf8 100644 --- a/control/crates/layerfs-store/src/service.rs +++ b/control/crates/layerfs-store/src/service.rs @@ -17,8 +17,6 @@ //! again. use crate::open_args::{OpenArgs, ROUTING}; use layerfs_bridge::control::{SdkCall, SdkRefusal, SdkValue}; -use layerfs_bridge::sdk_values::hex; -use layerfs_history::MountHolderView; use layerfs_home::helpers::lock; use layerfs_home::outcome::{failed, refused, Outcome}; use layerfs_store_service::{OpenRefusal, StoreService}; @@ -277,259 +275,3 @@ pub fn reconcile_machine( } } } - -/// Resolves Branch `branch` of `project` in the Store `open` names, then runs -/// [`repair_mount_holders`] on it: the one implementation behind a local call -/// and a worker's `store.repair` operation. -/// The operator options travel as the call's own fields; keeping them -/// explicit is the call surface, not a bundle of unrelated state. -#[allow(clippy::too_many_arguments)] -pub fn repair_mount_holders_at( - open: &OpenArgs, - project: &str, - branch: &str, - action: &str, - op: Option<[u8; 16]>, - legacy: bool, - operator: &str, - page: u32, - limit: u32, -) -> Result { - if action == "audit" { - return done_audit(open, project, branch, page, limit); - } - let resolved = branch_named(open, project, branch)?; - repair_mount_holders( - open, resolved, project, branch, action, op, legacy, operator, page, limit, - ) -} - -/// One bounded page of the retained `done` audit of one Branch, oldest -/// first. The live holder queries filter done rows; this is the only repair -/// action that reads them, and it reads only the Branch it names. It changes -/// no intent. -pub fn done_audit( - args: &OpenArgs, - project: &str, - branch: &str, - page: u32, - limit: u32, -) -> Result { - with_service(args, |service| { - let page = layerfs_store_service::history::admission::done_intents_branch( - service.store.history(), - project, - branch, - page, - limit, - ) - .map_err(failed)?; - Ok(layerfs_store_service::history::admission::audit_value( - &page, - )) - }) -} - -/// First-class operator repair of the mount intents held at one Branch. -/// `preview` lists them; `settle`/`release` act on one explicit `op`; -/// `settle_legacy` marks only rows without owner or place evidence. The call -/// runs through the Store catalog, so a PostgreSQL Store and a worker-hosted -/// SQLite Store behave the same way. Never automatic; a live-looking holder -/// is never released by preview. -/// -/// Release retains the `gc_intent` row in state `done` with the action, -/// operator label and op in `evidence`, and clears the owner columns. List -/// and preview write nothing; preview answers what release would do for each -/// holder. Settle changes the row to uncertain and is in the home's -/// `trace/calls.jsonl` call log only. The `audit` action reads the Branch's -/// retained done rows in bounded pages. -#[allow(clippy::too_many_arguments)] -pub fn repair_mount_holders( - args: &OpenArgs, - branch: layerfs_history::BranchId, - project: &str, - branch_name: &str, - action: &str, - op: Option<[u8; 16]>, - legacy: bool, - operator: &str, - page: u32, - limit: u32, -) -> Result { - with_service(args, |service| { - let catalog = service.store.history(); - let scoped = catalog - .gc_intents(layerfs_history::GcScopeKind::Branch, branch.as_slice()) - .map_err(failed)?; - let mounts: Vec = scoped - .into_iter() - .filter(|intent| intent.kind == layerfs_history::GcIntentKind::Mount) - .collect(); - // The typed, read-only view every branch below reports: it carries - // the place and lease authority the row recorded, and building it - // changes nothing. - let holders: Vec = mounts.iter().map(MountHolderView::of).collect(); - let holder = |op: &[u8; 16]| mounts.iter().find(|intent| &intent.op_id == op); - match action { - "list" => Ok(SdkValue::map([ - ("holders", holder_rows(&holders)), - ("legacy", SdkValue::Bool(legacy)), - ("action", SdkValue::text("list")), - ("op", SdkValue::Null), - ("audit", SdkValue::Null), - ])), - // Preview is read-only: it answers what release would do for each - // holder (`safe`, `reason`) and writes nothing; the call log - // records the call. - "preview" => Ok(SdkValue::map([ - ("holders", holder_rows(&holders)), - ("legacy", SdkValue::Bool(legacy)), - ("action", SdkValue::text("preview")), - ("op", SdkValue::Null), - ("audit", SdkValue::Null), - ])), - "settle" | "release" => { - let op = op.ok_or_else(|| { - refused("InvalidInput", format!("{action} needs the holder op")) - })?; - let found = holder(&op).ok_or_else(|| { - refused( - "NotFound", - format!("no mount holder {} at this Branch", hex(&op)), - ) - })?; - if legacy && !MountHolderView::of(found).legacy() { - return Err(refused( - "InvalidInput", - "this holder has owner or place evidence; --legacy settles only legacy rows", - )); - } - if action == "settle" { - catalog.gc_mark_uncertain(&op).map_err(failed)?; - return Ok(SdkValue::map([ - ("action", SdkValue::text(action)), - ("op", SdkValue::text(hex(&op))), - ("audit", SdkValue::text("call-log")), - ])); - } - if !found.uncertain { - return Err(refused( - "Conflict", - "settle the holder before release; preview and settle are the two explicit steps", - )); - } - // The operator audit is the retained row itself: release - // keeps it in `done` with the action, operator and op in - // `evidence`, and clears the owner columns. The call log - // still records the call. - let operator = operator_label(operator)?; - let evidence = format!("action=release;operator={operator};op={}", hex(&op)); - if !catalog.gc_release_done(&op, &evidence).map_err(failed)? { - return Err(refused( - "NotFound", - format!("the mount holder {} was already released", hex(&op)), - )); - } - Ok(SdkValue::map([ - ("action", SdkValue::text("release")), - ("op", SdkValue::text(hex(&op))), - ("audit", SdkValue::text("gc_intent")), - ])) - } - "audit" => { - let page = layerfs_store_service::history::admission::done_intents_branch( - catalog, - project, - branch_name, - page, - limit, - ) - .map_err(failed)?; - Ok(layerfs_store_service::history::admission::audit_value( - &page, - )) - } - "settle_legacy" => { - let mut settled = 0u64; - for holder in &holders { - if holder.legacy() { - catalog.gc_mark_uncertain(&holder.op).map_err(failed)?; - settled += 1; - } - } - Ok(SdkValue::map([ - ("action", SdkValue::text("settle_legacy")), - ("settled", SdkValue::Int(settled as i64)), - ("audit", SdkValue::text("call-log")), - ])) - } - _ => Err(refused( - "InvalidInput", - "action must be preview, settle, release, settle_legacy or audit", - )), - } - }) -} - -/// The operator label a release records. An absent label is the local -/// operator; a label is at most 128 characters without control characters. -/// It is not an authenticated principal, only the name the caller gives. -fn operator_label(operator: &str) -> Result<&str, SdkRefusal> { - let operator = operator.trim(); - if operator.is_empty() { - return Ok("local"); - } - if operator.len() > 128 || operator.chars().any(char::is_control) { - return Err(refused( - "InvalidInput", - "operator must be at most 128 characters without control characters", - )); - } - Ok(operator) -} - -fn holder_rows(holders: &[MountHolderView]) -> SdkValue { - SdkValue::List( - holders - .iter() - .map(|holder| { - let workspace = holder.workspace.map(|ws| hex(&ws)); - SdkValue::map([ - ("op", SdkValue::text(hex(&holder.op))), - ("branch", SdkValue::opt_text(holder.branch.as_deref())), - ("project", SdkValue::opt_text(holder.project.as_deref())), - ("workspace", SdkValue::opt_text(workspace.as_deref())), - ("sandbox", SdkValue::opt_text(holder.sandbox.as_deref())), - ("machine", SdkValue::opt_text(holder.machine.as_deref())), - ( - "owner_runtime", - SdkValue::opt_text(holder.owner_runtime.as_deref()), - ), - ( - "owner_boot", - SdkValue::opt_text(holder.owner_boot.as_deref()), - ), - ( - "machine_incarnation", - SdkValue::opt_text(holder.machine_incarnation.as_deref()), - ), - ( - "sandbox_generation", - SdkValue::opt_text(holder.sandbox_generation.as_deref()), - ), - ("state", SdkValue::text(holder.state())), - ("legacy", SdkValue::Bool(holder.legacy())), - ("safe", SdkValue::Bool(holder.uncertain)), - ( - "reason", - SdkValue::text(if holder.uncertain { - "uncertain: the owner is already settled; release is available" - } else { - "live: the owner still holds the admission; settle it first" - }), - ), - ]) - }) - .collect(), - ) -} diff --git a/control/crates/layerfs-store/tests/repair_postgresql.rs b/control/crates/layerfs-store/tests/repair_postgresql.rs index 714cd96e08..9607b1c469 100644 --- a/control/crates/layerfs-store/tests/repair_postgresql.rs +++ b/control/crates/layerfs-store/tests/repair_postgresql.rs @@ -12,13 +12,14 @@ use layerfs_bridge::control::SdkValue; use layerfs_history::records::{GcIntent, GcIntentKind, GcScopeKind}; use layerfs_history::{HistoryCatalogConfig, PlaceAuthority}; use layerfs_home::home; -use layerfs_home::names::StoreName; +use layerfs_home::names::ProjectRef; use layerfs_persistence::{PostgresHandles, PostgresSelection}; use layerfs_storage::StoragePolicy; use layerfs_store::open_args::OpenArgs; -use layerfs_store::project::add::{add_project, ProjectAdd}; +use layerfs_store::project::family::{init, ProjectInit}; use layerfs_store::record::StoreRecord; -use layerfs_store::service::{branch_named, repair_mount_holders_at, with_service}; +use layerfs_store::repair::{repair_at, Repair}; +use layerfs_store::service::{branch_named, with_service}; use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; @@ -129,7 +130,7 @@ fn mount(branch: &[u8], stack: &[u8], op: u8) -> GcIntent { } fn holders(value: &SdkValue) -> &[SdkValue] { - match value.get("holders") { + match value.get("items") { Some(SdkValue::List(rows)) => rows, other => panic!("no holder list: {other:?}"), } @@ -162,15 +163,18 @@ fn operator_repair_round_trips_on_postgresql() { .with("binding", SdkValue::Bytes(BINDING.to_vec())) .with("cursor", SdkValue::Bytes(vec![71; 32])); record.write(&home).unwrap(); - add_project(&ProjectAdd { - home: home.clone(), - store: StoreName::parse("pgs").unwrap(), - name: "app".to_owned(), - source: folder("app"), - timeout_ms: Some(60_000), - store_record: None, - }) - .unwrap(); + let mut sink = |_| {}; + let mut events = layerfs_home::events::Events::new(&mut sink); + init( + &home, + &mut events, + &ProjectInit { + project: ProjectRef::parse("pgs/app").unwrap(), + folder: folder("app").display().to_string(), + timeout: Some(60_000), + }, + ) + .expect("project.init on the PostgreSQL Store"); let record = StoreRecord::read(&home, "pgs").unwrap().unwrap(); let open = OpenArgs::of_record(&home, "pgs", &record).unwrap(); let branch = branch_named(&open, "app", "main").unwrap(); @@ -194,11 +198,22 @@ fn operator_repair_round_trips_on_postgresql() { }) .unwrap(); - let preview = repair_mount_holders_at( - &open, "app", "main", "preview", None, false, "alice", 0, 100, - ) - .expect("preview"); - assert_eq!(preview.get("audit"), Some(&SdkValue::Null), "{preview:?}"); + let repair = |action: &str, op: Option, force: bool| { + repair_at( + &open, + &Repair { + project: "app".to_owned(), + branch: "main".to_owned(), + action: action.to_owned(), + op: op.map(|op| [op; 16]), + force, + operator: "alice".to_owned(), + limit: 100, + ..Repair::default() + }, + ) + }; + let preview = repair("preview", None, false).expect("preview"); let rows = holders(&preview); assert_eq!(rows.len(), 2, "{rows:?}"); let row = rows @@ -206,82 +221,30 @@ fn operator_repair_round_trips_on_postgresql() { .find(|row| row.get_text("op") == Some("21".repeat(16).as_str())) .expect("the live holder"); assert_eq!(row.get_text("state"), Some("live")); + // a shared Store proves no owner gone from here: it still looks live + assert_eq!(row.get_text("liveness"), Some("live")); + assert_eq!(row.get("safe"), Some(&SdkValue::Bool(false))); assert_eq!(row.get_text("machine_incarnation"), Some("worker:1")); assert_eq!(row.get_text("sandbox_generation"), Some("generation:1")); assert_eq!(row.get("legacy"), Some(&SdkValue::Bool(false))); - let refused = repair_mount_holders_at( - &open, - "app", - "main", - "release", - Some([0x21; 16]), - false, - "alice", - 0, - 100, - ) - .unwrap_err(); + let refused = repair("release", Some(0x21), false).unwrap_err(); assert_eq!(refused.code, "Conflict", "{refused:?}"); - repair_mount_holders_at( - &open, - "app", - "main", - "settle", - Some([0x21; 16]), - false, - "alice", - 0, - 100, - ) - .expect("settle"); - repair_mount_holders_at( - &open, - "app", - "main", - "release", - Some([0x21; 16]), - false, - "alice", - 0, - 100, - ) - .expect("release"); - let settled = repair_mount_holders_at( - &open, - "app", - "main", - "settle_legacy", - None, - false, - "alice", - 0, - 100, - ) - .expect("settle_legacy"); + let refused = repair("settle", Some(0x21), false).unwrap_err(); + assert_eq!(refused.code, "InUse", "a live-looking holder: {refused:?}"); + repair("settle", Some(0x21), true).expect("a forced settle"); + repair("release", Some(0x21), false).expect("release"); + // a second release answers NotFound, as on SQLite (#783 gap 5) + let again = repair("release", Some(0x21), false).unwrap_err(); + assert_eq!(again.code, "NotFound", "{again:?}"); + let settled = repair("settle_legacy", None, false).expect("settle_legacy"); assert_eq!(settled.get_int("settled"), Some(1)); - repair_mount_holders_at( - &open, - "app", - "main", - "release", - Some([0x31; 16]), - false, - "alice", - 0, - 100, - ) - .expect("release the legacy holder"); - let preview = repair_mount_holders_at( - &open, "app", "main", "preview", None, false, "alice", 0, 100, - ) - .expect("preview"); + repair("release", Some(0x31), false).expect("release the legacy holder"); + let preview = repair("preview", None, false).expect("preview"); assert!(holders(&preview).is_empty()); // The two releases retained their rows as the PostgreSQL Store's durable // operator audit; the audit read does not resolve a Branch first. - let audit = - repair_mount_holders_at(&open, "app", "main", "audit", None, false, "alice", 0, 100) - .expect("audit"); + let audit = repair("audit", None, false).expect("audit"); let Some(SdkValue::List(items)) = audit.get("items") else { panic!("audit items: {audit:?}"); }; diff --git a/core/crates/layerfs-history/src/contract/authority.rs b/core/crates/layerfs-history/src/contract/authority.rs index fe964e69cc..42a22f920c 100644 --- a/core/crates/layerfs-history/src/contract/authority.rs +++ b/core/crates/layerfs-history/src/contract/authority.rs @@ -16,7 +16,7 @@ use std::collections::BTreeMap; -/// The durable place and lease evidence carried beside a mount intent. +/// The durable place evidence carried beside a mount intent. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct PlaceAuthority { /// The worker generation that placed the mount. @@ -224,16 +224,15 @@ pub fn compare_place(recorded: &str, current: &str) -> PlaceOrder { } impl PlaceAuthority { - /// Classifies the owner for `now_ms` against the current place values - /// `place`, when the adapter can see any. + /// Classifies the owner against the current place values `place`, when + /// the adapter can see any. /// - /// Place death wins over lease state: a machine incarnation or Sandbox - /// generation the current record proves older than itself is - /// [`Liveness::Dead`] even if the lease is stale. An expired lease - /// without place death is [`Liveness::Uncertain`], never - /// [`Liveness::Dead`], because a slow owner is not a dead owner. Missing - /// place evidence is no proof: only the lease decides. - pub fn liveness(&self, _now_ms: i64, place: Option<&PlaceRecord>) -> Liveness { + /// A machine incarnation or Sandbox generation the current record proves + /// older than the recorded one is [`Liveness::Dead`]; a recorded value + /// newer than the current one (a restore) or unordered against it is + /// [`Liveness::Uncertain`]. Missing place evidence, or another home's + /// value, is no proof: [`Liveness::Live`]. + pub fn liveness(&self, place: Option<&PlaceRecord>) -> Liveness { if let Some(place) = place { if let (Some(recorded), Some(current)) = ( self.machine_incarnation.as_deref(), diff --git a/core/crates/layerfs-history/src/contract/catalog.rs b/core/crates/layerfs-history/src/contract/catalog.rs index e7e9100828..2d62d1c1be 100644 --- a/core/crates/layerfs-history/src/contract/catalog.rs +++ b/core/crates/layerfs-history/src/contract/catalog.rs @@ -586,6 +586,16 @@ pub trait HistoryCatalog: Send + Sync { Err(crate::error::HistoryError::Unsupported("GC admission")) } + /// What admission would say of each of `intents` now, in order: the + /// owner evidence first, then the place view the caller installed for + /// this thread, exactly as an admitting removal judges a conflicting + /// intent. A read; it changes nothing. The operator repair's `list` and + /// `preview` report it and its `settle` refuses a holder still `Live` + /// unless forced. The default refuses. + fn gc_liveness(&self, _intents: &[GcIntent]) -> HistoryResult> { + Err(crate::error::HistoryError::Unsupported("GC admission")) + } + /// One bounded page of retained `done` admission rows, oldest first, for /// the operator audit. `page` is zero-based and `limit` is clamped to /// [`crate::records::MAXIMUM_AUDIT_PAGE`]. The live admission queries @@ -607,25 +617,6 @@ pub trait HistoryCatalog: Send + Sync { ) -> HistoryResult { Err(crate::error::HistoryError::Unsupported("GC done audit")) } - - /// Writes one retained `done` admission row directly, the release/done - /// row path without a live intent to release: `state = 'done'`, no owner - /// columns, no place authority, and `evidence` naming the operator action - /// and label. `intent.op_id` is the row's operation identity. It is the - /// durable operator preview (`action=preview`, no operation) and never - /// enters admission, whose queries filter `state <> 'done'`. The default - /// refuses: a provider that keeps no `done` rows cannot promise the audit. - fn gc_record_done(&self, _intent: &GcIntent, _evidence: &str) -> HistoryResult { - Err(crate::error::HistoryError::Unsupported("GC done audit")) - } - - /// Deletes the retained `done` rows the operator exported by `op_ids`, - /// and only those: each row must still be in state `done`, so a prune - /// never removes a live intent. Answers how many rows went. The default - /// refuses; a provider that keeps no `done` rows has nothing to prune. - fn gc_prune_done(&self, _op_ids: &[[u8; 16]]) -> HistoryResult { - Err(crate::error::HistoryError::Unsupported("GC done audit")) - } } impl std::fmt::Debug for HistoryCatalogConfig { diff --git a/core/crates/layerfs-history/tests/authority.rs b/core/crates/layerfs-history/tests/authority.rs index d50e3da80a..b9d5dd138b 100644 --- a/core/crates/layerfs-history/tests/authority.rs +++ b/core/crates/layerfs-history/tests/authority.rs @@ -68,13 +68,13 @@ fn tokens_of_different_homes_are_foreign_and_never_dead() { }; // Another home's values are no evidence: the holder stays live, as with // no place evidence at all. - assert_eq!(mount.liveness(0, Some(&other_home)), Liveness::Live); + assert_eq!(mount.liveness(Some(&other_home)), Liveness::Live); // The same home's newer start still proves the older placement dead. let same_home = PlaceRecord { machine_incarnation: Some(homed("aa11", "worker", 2, "bb")), ..PlaceRecord::default() }; - assert_eq!(mount.liveness(0, Some(&same_home)), Liveness::Dead); + assert_eq!(mount.liveness(Some(&same_home)), Liveness::Dead); } #[test] @@ -108,17 +108,17 @@ fn a_tombstone_newer_than_the_live_generation_is_uncertain() { }; // Only the tombstone of this very generation retires the live record. assert_eq!( - mount.liveness(0, Some(&place(generation.clone()))), + mount.liveness(Some(&place(generation.clone()))), Liveness::Dead ); // A newer tombstone beside an equal record (a clock step): uncertain. assert_eq!( - mount.liveness(0, Some(&place(homed("aa11", "sandbox", 9, "bb")))), + mount.liveness(Some(&place(homed("aa11", "sandbox", 9, "bb")))), Liveness::Uncertain ); // An older tombstone names an earlier Sandbox of the same name. assert_eq!( - mount.liveness(0, Some(&place(homed("aa11", "sandbox", 1, "bb")))), + mount.liveness(Some(&place(homed("aa11", "sandbox", 1, "bb")))), Liveness::Live ); } diff --git a/core/docs/issues/project-41/LayerFS-GC-spec.md b/core/docs/issues/project-41/LayerFS-GC-spec.md index 9359c84862..6fd8c73eff 100644 --- a/core/docs/issues/project-41/LayerFS-GC-spec.md +++ b/core/docs/issues/project-41/LayerFS-GC-spec.md @@ -498,12 +498,22 @@ malformed one decodes as no token: missing evidence is no proof, never death then records the new ordered `incarnation` in the home `MachineRecord` before the worker serves; the worker-start reconcile settles only the rows of that machine that are dead and not uncertain. Mount registration settles - nothing. A Sandbox remove (normal or forced) writes the generation's - tombstone under `machine//sandbox-retired/` once the runtime is - stopped and before its home record goes; a failed tombstone write does not - stop the removal (a missing tombstone is only no proof). A placed mount - records the place values the daemon's caller read from the home records, - and its project and Branch names. + nothing. Every removal of a Sandbox's home record (a close or force close, + a reclaim of a runtime that ended by itself, a forget, and `sandbox.remove` + on every route, which writes the home's tombstone for a worker's Sandbox) + writes the generation's tombstone under `machine//sandbox-retired/` + before that record goes; a failed tombstone write does not stop the removal + (a missing tombstone is only no proof) and is reported in `left`. A worker's + root is no home and gets no tombstone. Once a recreated Sandbox's started + record names a newer generation of the same home, the name's older + tombstone is deleted (the newer record proves the old generation's mounts + dead by itself), so a name keeps at most one. `machine.remove`, refused + while a Store or Sandbox uses the machine, deletes `machine//` with + its tombstones. A placed mount records the place values the daemon's caller + read from the home records, and its project and Branch names. A worker's + Sandbox record carries the machine name and the generation its caller's + home minted, sent with the create, so its mounts record the generation; a + worker's root keeps no machine record, so they record no incarnation. - **Audit.** An operator release keeps the intent as a `gc_intent` `done` row instead of deleting it: the action, the operator label and the op are in `evidence` (replacing the live row's place tokens), the owner columns are @@ -512,19 +522,27 @@ malformed one decodes as no token: missing evidence is no proof, never death (`Copy::Done`). The owner's own release, an uncertain mark and a retried registration never delete or revive a `done` row. A separate read (`WHERE state = 'done'`, scoped by the recorded project and Branch names, - ordered by `updated_ms, op_id`, paged) exposes them. `list`, `preview` and - `audit` write nothing. + ordered by `updated_ms, op_id`, paged) exposes them. A release that retains + a row deletes the oldest done rows of the same Branch beyond the newest 100 + in its transaction, with no schema change (the existing unique index finds + the Branch's rows). A second release of one op answers `NotFound` on both + Store kinds, and PostgreSQL compaction never reads or deletes a done row. + `list`, `preview` and `audit` write nothing. - **Operator repair reachability and the typed holder view.** `store.repair_mount_holders` runs where the Store's calls run: a SQLite Store on another machine repairs through that machine's worker (`store.repair`), and a PostgreSQL Store repairs in the calling process. - `list` and `preview` answer the same typed holder view (`MountHolderView`: - owner, place, generation and state) on every route, and the doctor's - read-only `store.diagnose` forwards those fields from a worker. The - Store-wide compact barrier is retained: a live or uncertain holder still - refuses `store.compact`; an owner the owner evidence proves dead is adopted - and the rebuild proceeds. Lease renewal, fencing and a jsonl audit archive - are deferred (#775). + It takes `/`, the Branch and the action, and pages `list`, + `preview` and `audit` by `limit` and `cursor`. `list` and `preview` answer + the same typed holder view (`MountHolderView`: owner, place, generation and + state) on every route, with the `liveness` admission would give each holder + now (owner check, then the calling home's place view, sent to a worker with + the call) and `safe` (not `live`); `settle` refuses a holder still `live` + unless forced. The doctor's read-only `store.diagnose` forwards those fields + from a worker. The Store-wide compact barrier is retained: a live or + uncertain holder still refuses `store.compact`; an owner the owner evidence + proves dead is adopted and the rebuild proceeds. A jsonl audit archive is + deferred (#775). - Compaction writes its `gc_intent` operation row **before** its first checkpoint; the row lives in `.compact` during build/verify, moves to the live Store after install, and is cleared at settle. `none` writes diff --git a/core/docs/issues/project-41/gc-runbook.md b/core/docs/issues/project-41/gc-runbook.md index 75f3d863f3..5ee790d7a3 100644 --- a/core/docs/issues/project-41/gc-runbook.md +++ b/core/docs/issues/project-41/gc-runbook.md @@ -151,7 +151,7 @@ installed → it records the outcome. A dead owner's op is adopted; only a live re-run `layerfs store compact ` to adopt. For a lost PG swap reply, use §2 on a second connection. 3. Before manual steps, back up (`backup.create` on SQLite; server backup on PG) and record generation `G`, op id, artifact name. 4. Compare artifact/schema with the op; leave anything a record names to the next compact (`G` removes, `G+1` records). -5. Never hand-edit `gc_intent`, `gc_dead`, markers or `project_epoch`; never unlink `-wal`/`-shm`; never drop a schema `gc_op` names. The retained `done` audit rows are read with `layerfs store repair-mount-holders audit` (scoped to that Branch); the jsonl `archive`/`--prune` export is deferred (#775), and nothing deletes a done row automatically. +5. Never hand-edit `gc_intent`, `gc_dead`, markers or `project_epoch`; never unlink `-wal`/`-shm`; never drop a schema `gc_op` names. The retained `done` audit rows are read with `layerfs store repair-mount-holders / audit` (scoped to that Branch, paged by `--limit`/`--cursor`); a Branch keeps its newest 100 done rows (a release deletes the oldest beyond them), and the jsonl archive export is deferred (#775). 6. To re-use a name after a removal, re-create after the frontier (or after a rebuild frees it); don't delete markers. Escalate if old content must be restored. ## 7. Branch retirement (`branch.remove`, live since 2026-11-15) diff --git a/docs/architecture/api/sdk/store.md b/docs/architecture/api/sdk/store.md index 65388ef97f..04a580c7fe 100644 --- a/docs/architecture/api/sdk/store.md +++ b/docs/architecture/api/sdk/store.md @@ -41,7 +41,7 @@ The `store` calls: list and read Stores, create a sqlite Store, connect a Postgr | [`store.update`](#storeupdate) | PostgreSQL | `{ ok }` | `admin` | | [`store.move`](#storemove) | sqlite | `{ moved_bytes }` | `admin` | | [`store.remove`](#storeremove) | sqlite | `{ ok }`, or `{ left }` | `admin` | -| [`store.repair_mount_holders`](#storerepair_mount_holders) | both | holders, one settled/released op, or a bounded done-audit page | `admin` | +| [`store.repair_mount_holders`](#storerepair_mount_holders) | both | a page of holders or done rows (`items`, `next_cursor`), or one settled/released op | `admin` | | [`store.compact`](#storecompact) | both | `{ freed_bytes }` | `admin` | | [`store.doctor`](#storedoctor) | both | the doctor report | `admin` | @@ -608,39 +608,52 @@ $ layerfs store remove nope Explicit, operator-only repair of the mount admissions held at one Branch. Nothing is automatic: list, preview and audit write nothing, the doctor only -reports the same rows without releasing them, and no action deletes a row. +reports the same rows without releasing them, and no action deletes a live +row. ```text -CLI layerfs store repair-mount-holders [--op HEX] [--legacy] [--operator NAME] [--page N] [--limit N] +CLI layerfs store repair-mount-holders [--op HEX] [--legacy] [--force] [--operator NAME] [--limit 100] [--cursor C] ``` -The action is one of: +| Argument | Kind | Rule | +| --- | --- | --- | +| `project` | project | `/` | +| `branch` | name | the Branch whose holders are repaired; `audit` reads the rows recorded under this name, so a removed Branch's rows stay readable | +| `action` | name | `list`, `preview`, `settle`, `release`, `settle_legacy` or `audit` | +| `op` option | text | the holder `settle` and `release` act on: 16 bytes of hex | +| `legacy` option | bool | `settle` only a row without owner or place evidence | +| `force` option | bool | `settle` a holder that still looks `live` | +| `operator` option | text | the label a release records: at most 128 characters, no control characters; empty is `local`; not an authenticated principal | +| `limit` option | int | rows of one page (`list`, `preview`, `audit`): 1 to 1000, default 100 | +| `cursor` option | text | the `next_cursor` of the page before; it carries the project, Branch and action | | Action | Effect | | --- | --- | -| `list` | lists the typed holder view (op, project, Branch, Workspace, Sandbox, machine, place authority, state, legacy, `safe`, `reason`); read-only, writes nothing | -| `preview` | lists the same typed view, each row's `safe` and `reason` saying what `release` would do; read-only, writes nothing | -| `settle` | marks exactly `--op` uncertain; a later call reports `Unresolved`, never `Busy` | -| `release` | needs the preceding settle; retains the row in state `done` with `action=release;operator=NAME;op=HEX` in `evidence` (replacing the `place:v1;...` place tokens a live row keeps there) and clears the owner columns, so the unique owner key cannot block a remount; the owner's own release, a later settle or a retried registration never deletes or revives that row | -| `settle_legacy` | marks only rows with missing owner or place evidence | -| `audit` | one bounded page of the named project/Branch's retained `done` rows, oldest first (`--page`, `--limit`, clamped to 1000); changes nothing. The scope is the recorded project and Branch names, so a removed Branch's retained rows stay readable | - -Every holder row carries `safe` and `reason`: `safe` means the row is -uncertain (settled), so `release` is available; it is not a liveness verdict, -and the operator confirms the holder is gone before releasing. A live row -still holds the admission and must be settled first. Release answers `{ action: "release", op, audit: "gc_intent" }`; -preview answers the holders plus `{ action: "preview", op: null, audit: null -}`; list answers the holders alone; list, preview, settle and `settle_legacy` -are in the home's `trace/calls.jsonl` call log only. `--operator` is the local name -the caller gives (at most 128 characters, no control characters; empty is -`local`): it is not an authenticated principal. On a SQLite Store the call runs -on the machine that holds the file through its worker; a PostgreSQL Store runs -in the calling process. +| `list` | one page of holders by op, read-only | +| `preview` | the same page (what `settle` and `release` would act on), read-only | +| `settle` | marks exactly `--op` uncertain, answering `{ action, op, state: "uncertain" }`; a holder whose `liveness` is `live` is refused `InUse` unless `--force` (or `--legacy` for a row without evidence); a later call reports `Unresolved`, never `Busy` | +| `release` | needs the preceding settle; retains the row in state `done` with `action=release;operator=NAME;op=HEX` in `evidence` (replacing the `place:v1;...` place tokens a live row keeps there) and clears the owner columns, so the unique owner key cannot block a remount, answering `{ action, op, state: "done" }`. A Branch keeps its newest 100 done rows: a release deletes the oldest beyond them | +| `settle_legacy` | marks only rows with missing owner or place evidence: `{ action, settled }` | +| `audit` | one page of the Branch's retained `done` rows, oldest first; changes nothing | + +A page answers `{ action, items, next_cursor }`. Each holder row carries the +typed view (`op`, `project`, `branch`, `workspace`, `sandbox`, `machine`, +`owner_runtime`, `owner_boot`, `machine_incarnation`, `sandbox_generation`, +`legacy`) and three state words: `state`, the row's own state (`live`, or +`uncertain` once settled); `liveness`, what admission would say of it now +from the owner check and this home's place view (`live`, `uncertain` or +`dead`; a shared PostgreSQL Store proves no death from a place, so its rows +are at most `uncertain` there); and `safe`, true unless it still looks +`live`. A worker's call is sent the place view of the calling home. Every +call is in the home's `trace/calls.jsonl` call log. On a SQLite Store the call +runs on the machine that holds the file through its worker; a PostgreSQL Store +runs in the calling process. | Error | When | | --- | --- | -| `InvalidInput` | an unknown action; a missing or malformed `--op`; a bad operator label | -| `NotFound` | no mount holder with that op at the Branch (for a release: already released) | +| `InvalidInput` | an unknown action; a missing or malformed `--op`; a bad operator label; a `limit` out of range; a cursor of another action, project or Branch | +| `NotFound` | no mount holder with that op at the Branch (for a release: already released, on either Store kind) | +| `InUse` | `settle` of a holder that still looks `live`; `fix: … settle --op HEX --force` | | `Conflict` | release before settle | | `Unavailable`, `Unknown` | the owning worker is not reachable or its answer was lost | diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_delete.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_delete.sql deleted file mode 100644 index 29f6144ae1..0000000000 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_delete.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Delete exactly one row the operator exported: `state = 'done'` keeps a live --- intent out of the archive's prune even if its op id were named, and --- `RETURNING` proves whether the row was still there. Portable to PostgreSQL. -DELETE FROM gc_intent -WHERE state = 'done' AND op_id = $1 -RETURNING op_id; diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_insert.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_insert.sql deleted file mode 100644 index a4c382100f..0000000000 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_done_insert.sql +++ /dev/null @@ -1,9 +0,0 @@ --- The durable operator preview row: a `done` row written without a live --- intent to release. The owner and place columns stay NULL and `evidence` --- holds the audit text (never a `place:v1` value), so the unique owner key --- never blocks a later mount and admission, which filters `state <> 'done'`, --- never sees it. `gc_intent_done` is the bounded read that does. Portable to --- PostgreSQL, as the other intent statements are. -INSERT INTO gc_intent (op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, evidence, updated_ms) -VALUES ($1, $2, $3, $4, NULL, NULL, NULL, $5, $6, NULL, NULL, 'done', FALSE, $7, $8, $9) -RETURNING op_id; diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_release.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_release.sql index 5bd14604a7..9fa8ad744f 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_release.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_release.sql @@ -1,3 +1,3 @@ -- The owner's own release deletes its live row; a retained `done` audit row --- is never deleted here (`gc_intent_done_delete` is the operator's prune). +-- is never deleted here (`gc_intent_done_cap` bounds a Branch's done rows). DELETE FROM gc_intent WHERE op_id = $1 AND state <> 'done' RETURNING op_id; diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/session/query.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/session/query.rs index da45e1d5df..1c776656ce 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/session/query.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/session/query.rs @@ -24,7 +24,6 @@ pub(crate) fn bind(param: Param, ty: &Type) -> Result<(Bound, u64), BackendError Param::Bytes(v) => (v.len() as u64, v).into_bound(), Param::OptionalBytes(v) => (v.as_ref().map_or(0, Vec::len) as u64, v).into_bound(), Param::OptionalText(v) => (v.as_ref().map_or(0, String::len) as u64, v).into_bound(), - Param::OptionalI64(v) => (if v.is_some() { 8u64 } else { 0 }, v).into_bound(), }) } diff --git a/engine/crates/layerfs-persistence/src/backend/records.rs b/engine/crates/layerfs-persistence/src/backend/records.rs index 1fb7c9dcc0..cff17f7f9e 100644 --- a/engine/crates/layerfs-persistence/src/backend/records.rs +++ b/engine/crates/layerfs-persistence/src/backend/records.rs @@ -6,7 +6,6 @@ pub(crate) enum Param { Bytes(Vec), OptionalBytes(Option>), OptionalText(Option), - OptionalI64(Option), } #[derive(Clone, Debug)] pub(crate) enum Value { diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/session/query.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/session/query.rs index 1aa6dae6ff..0777375953 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/session/query.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/session/query.rs @@ -270,12 +270,6 @@ pub(crate) fn history(key: &str) -> Result<&'static str, BackendError> { "gc_intent_done_branch" => Ok(include_str!( "../../../../sql/sqlite/queries/history/gc_intent_done_branch.sql" )), - "gc_intent_done_insert" => Ok(include_str!( - "../../../../sql/sqlite/queries/history/gc_intent_done_insert.sql" - )), - "gc_intent_done_delete" => Ok(include_str!( - "../../../../sql/sqlite/queries/history/gc_intent_done_delete.sql" - )), "gc_intent_done_cap" => Ok(include_str!( "../../../../sql/sqlite/queries/history/gc_intent_done_cap.sql" )), diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/session/rows.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/session/rows.rs index 080ab94644..92dc22349d 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/session/rows.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/session/rows.rs @@ -11,7 +11,6 @@ pub(crate) fn bind(p: Param) -> SqlValue { Param::Bytes(v) => SqlValue::Blob(v), Param::OptionalBytes(v) => v.map(SqlValue::Blob).unwrap_or(SqlValue::Null), Param::OptionalText(v) => v.map(SqlValue::Text).unwrap_or(SqlValue::Null), - Param::OptionalI64(v) => v.map(SqlValue::Integer).unwrap_or(SqlValue::Null), } } pub(crate) fn blob<'a>(row: &'a Row<'_>, index: usize) -> Result<&'a [u8], BackendError> { diff --git a/engine/crates/layerfs-persistence/src/history/admission.rs b/engine/crates/layerfs-persistence/src/history/admission.rs index 2a8d72debe..c10123a755 100644 --- a/engine/crates/layerfs-persistence/src/history/admission.rs +++ b/engine/crates/layerfs-persistence/src/history/admission.rs @@ -14,9 +14,9 @@ //! `PlaceView` the control layer supplies (and, for a name the view does not //! carry, from the current records the admitted call itself carries). The //! control layer reads its home once for the call; this engine opens no home -//! file. A recorded value older than the current one is dead even with a live -//! lease; a recorded value newer than the current one (a home restore) is -//! uncertain, never dead; a value another home minted is uncertain. The +//! file. A recorded value older than the current one is dead; a recorded +//! value newer than the current one (a home restore) is uncertain, never +//! dead; a value another home minted is no evidence. The //! owner's namespace/boot evidence always applies as it did before place //! evidence existed: an owner it proves gone is dead, and place evidence only //! adds proofs of death. A mount registration settles only the conflicting @@ -52,7 +52,7 @@ mod authority; mod place; mod removal; mod session; -pub(crate) use authority::{reconcile_machine, release, release_done}; +pub(crate) use authority::{liveness, reconcile_machine, release, release_done}; pub(crate) use place::PlaceView; pub use place::{has_place_view, with_place_view}; pub(crate) use removal::{delete_stack, intents, remove_branch, remove_path}; @@ -73,8 +73,6 @@ const ALL_STORE: &str = "gc_intent_all_store"; const MACHINE_INTENTS: &str = "gc_intent_list_machine"; const DONE: &str = "gc_intent_done"; const DONE_BRANCH: &str = "gc_intent_done_branch"; -const DONE_INSERT: &str = "gc_intent_done_insert"; -const DONE_DELETE: &str = "gc_intent_done_delete"; const DONE_CAP: &str = "gc_intent_done_cap"; const BRANCH_STACK: &str = "gc_branch_stack_any"; @@ -380,7 +378,7 @@ impl OwnerView { /// Adopts the rows whose place authority proves them dead and that are not /// uncertain: their operation cannot still be running, so their intent is -/// deleted and does not hold the scope. A live place with an expired lease is +/// deleted and does not hold the scope. A place the view finds uncertain is /// kept and reported `Unresolved`; an uncertain row stays until its owner /// settles it. fn settle_dead( @@ -837,53 +835,6 @@ impl HistoryProvider { } } -/// Writes one retained `done` row directly: the release/done path without a -/// live intent. The owner and place columns stay NULL, so the row never -/// blocks a mount, and admission filters `state <> 'done'`. -fn record_done_in(tx: &Transaction<'_>, intent: &GcIntent, evidence: &str) -> HistoryResult { - let rows = tx.query( - DONE_INSERT, - params![ - intent.op_id.to_vec(), - intent.kind.as_str(), - intent.scope_kind.as_str(), - intent.scope_id.clone(), - intent.project.clone(), - intent.branch.clone(), - intent.phase.clone(), - evidence, - now_ms(), - ], - )?; - Ok(!rows.is_empty()) -} - -/// [`record_done_in`] for one Store write transaction: the durable preview -/// audit row. -pub(crate) fn record_done( - provider: &HistoryProvider, - intent: &GcIntent, - evidence: &str, -) -> HistoryResult { - provider.write(|tx| record_done_in(tx, intent, evidence)) -} - -/// Deletes the retained `done` rows the operator exported, and only those: -/// each delete names one op and keeps filtering `state = 'done'`, so a live -/// intent is never removed by a prune. Answers how many rows went. -pub(crate) fn prune_done(provider: &HistoryProvider, op_ids: &[[u8; 16]]) -> HistoryResult { - provider.write(|tx| { - let mut removed = 0u64; - for op_id in op_ids { - let rows = tx.query(DONE_DELETE, [op_id.as_slice()])?; - if !rows.is_empty() { - removed += 1; - } - } - Ok(removed) - }) -} - /// One bounded page of retained `done` audit rows, oldest first. The live /// admission queries filter `state <> 'done'`; this read is the only one that /// sees them, and it never changes a row. diff --git a/engine/crates/layerfs-persistence/src/history/admission/authority.rs b/engine/crates/layerfs-persistence/src/history/admission/authority.rs index 2bcce13674..dc5eead5c1 100644 --- a/engine/crates/layerfs-persistence/src/history/admission/authority.rs +++ b/engine/crates/layerfs-persistence/src/history/admission/authority.rs @@ -80,12 +80,29 @@ pub(crate) fn release_done( } } +/// What admission would say of each of `intents` now: the owner evidence, +/// then the place view scoped on this thread merged with each intent's own +/// place, as [`PlaceView::liveness`] judges a conflict. One read transaction; +/// nothing is written. +pub(crate) fn liveness( + provider: &HistoryProvider, + intents: &[GcIntent], +) -> HistoryResult> { + let postgres = postgres(provider); + provider.read(|tx| { + let owners = OwnerView::now(); + (intents.iter()) + .map(|intent| PlaceView::for_intent(intent).liveness(tx, intent, postgres, &owners)) + .collect() + }) +} + /// Settles the intents at `machine` its new ordered incarnation proves dead. /// /// One write transaction: no other machine's rows are read, and only a dead -/// intent that is not uncertain is released. An expired lease is uncertain, -/// never dead, and a recorded incarnation newer than `incarnation` (a home -/// restore) is kept uncertain like an unordered value that differs. +/// intent that is not uncertain is released. A recorded incarnation newer +/// than `incarnation` (a home restore) is kept uncertain like an unordered +/// value that differs. pub(crate) fn reconcile_machine( provider: &HistoryProvider, machine: &str, diff --git a/engine/crates/layerfs-persistence/src/history/admission/place.rs b/engine/crates/layerfs-persistence/src/history/admission/place.rs index 970bf0bc5f..5c2dfaa3b2 100644 --- a/engine/crates/layerfs-persistence/src/history/admission/place.rs +++ b/engine/crates/layerfs-persistence/src/history/admission/place.rs @@ -63,7 +63,6 @@ fn scoped() -> Option { /// (control's home records) merged with the place the admitted call itself /// carries. Cached once, so every conflicting intent costs one comparison. pub(crate) struct PlaceView { - now_ms: i64, supplied: Option, fallback_machine: Option, fallback_incarnation: Option, @@ -74,7 +73,6 @@ pub(crate) struct PlaceView { impl PlaceView { fn current(supplied: Option<&SuppliedPlaceView>) -> Self { Self { - now_ms: now_ms(), supplied: supplied.cloned().or_else(scoped), fallback_machine: None, fallback_incarnation: None, @@ -178,7 +176,7 @@ impl PlaceView { true => self.record(intent), false => None, }; - Ok(match authority.liveness(self.now_ms, place.as_ref()) { + Ok(match authority.liveness(place.as_ref()) { Liveness::Dead if shared_store => Liveness::Uncertain, verdict => verdict, }) diff --git a/engine/crates/layerfs-persistence/src/history/bindings.rs b/engine/crates/layerfs-persistence/src/history/bindings.rs index 333a673e21..a3a14c4d08 100644 --- a/engine/crates/layerfs-persistence/src/history/bindings.rs +++ b/engine/crates/layerfs-persistence/src/history/bindings.rs @@ -36,11 +36,6 @@ impl From> for Param { Self::OptionalText(v) } } -impl From> for Param { - fn from(v: Option) -> Self { - Self::OptionalI64(v) - } -} impl From<&str> for Param { fn from(v: &str) -> Self { Self::Text(v.to_owned()) diff --git a/engine/crates/layerfs-persistence/src/history/catalog.rs b/engine/crates/layerfs-persistence/src/history/catalog.rs index 3b2a46a332..ab0b214eb9 100644 --- a/engine/crates/layerfs-persistence/src/history/catalog.rs +++ b/engine/crates/layerfs-persistence/src/history/catalog.rs @@ -318,6 +318,10 @@ impl HistoryCatalog for HistoryProvider { super::admission::mark_uncertain(self, op_id) } + fn gc_liveness(&self, intents: &[GcIntent]) -> HistoryResult> { + super::admission::liveness(self, intents) + } + fn gc_remove_branch( &self, branch: BranchId, @@ -362,14 +366,6 @@ impl HistoryCatalog for HistoryProvider { super::admission::done_intents_branch(self, project, branch, page, limit) } - fn gc_record_done(&self, intent: &GcIntent, evidence: &str) -> HistoryResult { - super::admission::record_done(self, intent, evidence) - } - - fn gc_prune_done(&self, op_ids: &[[u8; 16]]) -> HistoryResult { - super::admission::prune_done(self, op_ids) - } - fn gc_reconcile_machine(&self, machine: &str, incarnation: &str) -> HistoryResult { super::admission::reconcile_machine(self, machine, incarnation) } diff --git a/engine/crates/layerfs-persistence/tests/gc_intent_done.rs b/engine/crates/layerfs-persistence/tests/gc_intent_done.rs index 9e07077dc1..cd99bae780 100644 --- a/engine/crates/layerfs-persistence/tests/gc_intent_done.rs +++ b/engine/crates/layerfs-persistence/tests/gc_intent_done.rs @@ -202,100 +202,6 @@ fn a_done_row_is_never_a_live_holder() { .expect("the done row does not hold"); } -/// The durable preview: the same retained-row columns as a release, with -/// `action=preview`, the operator label and no operation. It is invisible to -/// the live admission read and does not block a later mount. -#[test] -fn preview_retains_a_done_row_without_an_operation() { - let temp = Temp::new("gc-done-audit-preview"); - let history = catalog(&temp); - let (_, branch) = project(&history); - let preview = GcIntent::shared( - op(30), - GcIntentKind::Mount, - GcScopeKind::Branch, - branch.as_slice(), - ) - .named(Some("proj"), Some("work")); - assert!(history - .gc_record_done(&preview, "action=preview;operator=alice") - .unwrap()); - assert!(history - .gc_intents(GcScopeKind::Branch, branch.as_slice()) - .unwrap() - .is_empty()); - - let page = history.gc_done_intents(0, 10).unwrap(); - assert_eq!(page.items.len(), 1, "{page:?}"); - let row = &page.items[0]; - assert_eq!(row.op_id, op(30)); - assert_eq!(row.kind, GcIntentKind::Mount); - assert_eq!(row.scope_id.as_slice(), branch.as_slice()); - assert_eq!(row.project.as_deref(), Some("proj")); - assert_eq!(row.branch.as_deref(), Some("work")); - assert_eq!(row.phase, None); - assert_eq!( - row.evidence.as_deref(), - Some("action=preview;operator=alice") - ); - assert_eq!(row.machine, None); - assert_eq!(row.sandbox, None); - - let mount = GcIntent::shared( - op(31), - GcIntentKind::Mount, - GcScopeKind::Branch, - branch.as_slice(), - ) - .in_project(stack(1).as_slice()) - .named(Some("proj"), Some("work")) - .placed(Some([31; 32]), Some("box"), Some("box")) - .owned(Some("runtime-private"), Some("boot-private")); - history - .gc_register(&mount) - .expect("the preview row's cleared owner key does not hold"); -} - -/// A prune deletes exactly the exported done rows it names; a live intent -/// named by the same call is not a done row and stays. -#[test] -fn a_prune_deletes_only_the_named_done_rows() { - let temp = Temp::new("gc-done-audit-prune"); - let history = catalog(&temp); - let (_, branch) = project(&history); - let path = temp.join("store.sqlite"); - done_row(&path, branch, 1, "release one", 10); - done_row(&path, branch, 2, "release two", 20); - done_row(&path, branch, 3, "release three", 30); - let live = GcIntent::shared( - op(4), - GcIntentKind::Mount, - GcScopeKind::Branch, - branch.as_slice(), - ) - .in_project(stack(1).as_slice()) - .named(Some("proj"), Some("work")) - .placed(Some([4; 32]), Some("box"), Some("box")) - .owned(Some("runtime-private"), Some("boot-private")); - history.gc_register(&live).unwrap(); - - let removed = history - .gc_prune_done(&[op(1), op(3), op(4), op(9)]) - .unwrap(); - assert_eq!(removed, 2, "only the named done rows go"); - let page = history.gc_done_intents(0, 10).unwrap(); - assert_eq!(page.items.len(), 1, "{page:?}"); - assert_eq!(page.items[0].op_id, op(2)); - assert_eq!( - history - .gc_intents(GcScopeKind::Branch, branch.as_slice()) - .unwrap() - .len(), - 1, - "the live intent stays" - ); -} - /// The operator audit is scoped to the Branch it names: a done row of one /// Branch never appears in another Branch's page, even at the same Store. #[test] diff --git a/engine/crates/layerfs-persistence/tests/gc_place_view.rs b/engine/crates/layerfs-persistence/tests/gc_place_view.rs index 19e105924c..4e6f2c46bf 100644 --- a/engine/crates/layerfs-persistence/tests/gc_place_view.rs +++ b/engine/crates/layerfs-persistence/tests/gc_place_view.rs @@ -226,3 +226,37 @@ fn another_homes_place_of_the_same_name_is_never_dead() { 1 ); } + +/// #783 gap 4: the operator's liveness read judges a holder as admission +/// would, from the owner check and the scoped view, and changes nothing: +/// live with no view, dead once the view's tombstone retires its generation. +#[test] +fn liveness_reads_the_scoped_view_and_changes_nothing() { + let temp = Temp::new("gc-place-liveness"); + let history = catalog(&temp); + let (_, branch) = project(&history); + let generation = token("sandbox", 10, "a"); + let holder = mount(branch, 0x41, &generation); + history.gc_register(&holder).unwrap(); + + let judged = history.gc_liveness(std::slice::from_ref(&holder)).unwrap(); + assert_eq!( + judged, + vec![layerfs_history::Liveness::Live], + "no view: no proof" + ); + + let mut view = PlaceView::new(); + view.set_machine("box", token("worker", 20, "a")); + view.set_sandbox_retired("box", "box-1", generation); + let judged = with_place_view(Some(view), || { + history.gc_liveness(std::slice::from_ref(&holder)).unwrap() + }); + assert_eq!(judged, vec![layerfs_history::Liveness::Dead]); + // a read: the holder is still registered, not uncertain + let left = history + .gc_intents(GcScopeKind::Branch, branch.as_slice()) + .unwrap(); + assert_eq!(left.len(), 1); + assert!(!left[0].uncertain); +} diff --git a/engine/crates/layerfs-store-service/src/history/admission.rs b/engine/crates/layerfs-store-service/src/history/admission.rs index 54b0807ff6..d76746bc0e 100644 --- a/engine/crates/layerfs-store-service/src/history/admission.rs +++ b/engine/crates/layerfs-store-service/src/history/admission.rs @@ -390,6 +390,15 @@ pub fn reconcile_machine( catalog.gc_reconcile_machine(machine, incarnation) } +/// What admission would say of each of `intents` now (owner evidence, then +/// the place view installed on this thread), in order. Changes nothing. +pub fn liveness( + catalog: &dyn HistoryCatalog, + intents: &[GcIntent], +) -> HistoryResult> { + catalog.gc_liveness(intents) +} + /// One bounded page of retained `done` admission rows, for the operator /// audit. This is the only read that sees a done row; admission and preview /// keep filtering them out. @@ -414,48 +423,20 @@ pub fn done_intents_branch( catalog.gc_done_intents_branch(project, branch, page, limit) } -/// Writes one retained `done` row directly, for the operator preview audit: -/// the release/done row path without a live intent. The owner and place -/// columns stay NULL and admission keeps filtering `state <> 'done'`. -pub fn record_done( - catalog: &dyn HistoryCatalog, - intent: &GcIntent, - evidence: &str, -) -> HistoryResult { - catalog.gc_record_done(intent, evidence) -} - -/// Deletes the retained `done` rows the operator exported. Only rows still -/// in state `done` are removed; the answer counts them. -pub fn prune_done(catalog: &dyn HistoryCatalog, op_ids: &[[u8; 16]]) -> HistoryResult { - catalog.gc_prune_done(op_ids) -} - -/// The wire answer of one audit page. -pub fn audit_value(page: &GcAuditPage) -> SdkValue { - let item = |row: &GcIntentDone| { - SdkValue::map([ - ("op", SdkValue::text(hex16(&row.op_id))), - ("kind", SdkValue::text(row.kind.as_str())), - ("scope_kind", SdkValue::text(row.scope_kind.as_str())), - ("scope_id", SdkValue::text(hex16(&row.scope_id))), - ("project", SdkValue::opt_text(row.project.as_deref())), - ("branch", SdkValue::opt_text(row.branch.as_deref())), - ("machine", SdkValue::opt_text(row.machine.as_deref())), - ("sandbox", SdkValue::opt_text(row.sandbox.as_deref())), - ("phase", SdkValue::opt_text(row.phase.as_deref())), - ("evidence", SdkValue::opt_text(row.evidence.as_deref())), - ("updated_ms", SdkValue::Int(row.updated_ms)), - ]) - }; +/// The wire answer of one retained `done` row of the operator audit. +pub fn done_value(row: &GcIntentDone) -> SdkValue { SdkValue::map([ - ( - "items", - SdkValue::List(page.items.iter().map(item).collect()), - ), - ("page", SdkValue::Int(i64::from(page.page))), - ("limit", SdkValue::Int(i64::from(page.limit))), - ("has_more", SdkValue::Bool(page.has_more)), + ("op", SdkValue::text(hex16(&row.op_id))), + ("kind", SdkValue::text(row.kind.as_str())), + ("scope_kind", SdkValue::text(row.scope_kind.as_str())), + ("scope_id", SdkValue::text(hex16(&row.scope_id))), + ("project", SdkValue::opt_text(row.project.as_deref())), + ("branch", SdkValue::opt_text(row.branch.as_deref())), + ("machine", SdkValue::opt_text(row.machine.as_deref())), + ("sandbox", SdkValue::opt_text(row.sandbox.as_deref())), + ("phase", SdkValue::opt_text(row.phase.as_deref())), + ("evidence", SdkValue::opt_text(row.evidence.as_deref())), + ("updated_ms", SdkValue::Int(row.updated_ms)), ]) } From 986d3b82feea6a324ddbe0e9d97ef48e05480e67 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 17:50:54 +0800 Subject: [PATCH 4/6] test(store): the PostgreSQL repair test sets up through project.init `repair_postgresql` now creates its project with `project.init` (the call-surface route) instead of `add_project`, so it writes the record shape `store.connect` writes: the address alone plus a saved login. It asserts the 2.0 repair surface on PostgreSQL: rows at most `live` with `safe` false, a settle of a live-looking holder refused `InUse` until forced, and a second release `NotFound` as on SQLite. Run against a private postgres:17 server (trust auth, amcheck). Production LOC: 214,170 -> 214,170 (delta 0) scope: tools/production_loc.py (repo-pinned counter), first-parent tree vs committed tree reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Co-Authored-By: Claude Opus 5.5 --- .../layerfs-store/tests/repair_postgresql.rs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/control/crates/layerfs-store/tests/repair_postgresql.rs b/control/crates/layerfs-store/tests/repair_postgresql.rs index 9607b1c469..7337658410 100644 --- a/control/crates/layerfs-store/tests/repair_postgresql.rs +++ b/control/crates/layerfs-store/tests/repair_postgresql.rs @@ -159,7 +159,27 @@ fn operator_repair_round_trips_on_postgresql() { let home = tempdir("home"); home::ensure(&home).unwrap(); - let record = StoreRecord::connected("pgs", &url, "layerfs", "local", None) + // `store.connect`'s record shape with its saved login, which + // `project.init` dials with: the address alone in the record (the URL + // after its user part), the user and password saved (a trust-auth server + // takes any password) + let read: postgres::Config = url.parse().expect("LAYERFS_TEST_POSTGRES_URL is a URL"); + let user = read.get_user().unwrap_or("postgres"); + let password = read.get_password().map_or("unused".to_owned(), |password| { + String::from_utf8(password.to_vec()).expect("a UTF-8 password") + }); + layerfs_store::postgresql::login::save(&home, "pg", user, &password).unwrap(); + let address = match layerfs_store::postgresql::connect::holds_login(&url) { + false => url.clone(), + true => { + let (scheme, after) = url.split_once("://").expect("a postgres:// URL"); + format!( + "{scheme}://{}", + after.split_once('@').map_or(after, |(_, at)| at) + ) + } + }; + let record = StoreRecord::connected("pgs", &address, "layerfs", "local", Some("pg")) .with("binding", SdkValue::Bytes(BINDING.to_vec())) .with("cursor", SdkValue::Bytes(vec![71; 32])); record.write(&home).unwrap(); From 58716c80f023821d5d5789b11e66219be7b7b872 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 17:58:16 +0800 Subject: [PATCH 5/6] fix(sandbox): the caller's place always wins in a worker's Sandbox record `files::save_place` skipped a worker record that already named a generation. A record an interrupted removal left behind (no daemon, so the create proceeds and `save_sandbox` keeps its fields) could then name an older generation than the home's new record: mounts would record that older value, and the home's view would judge them retired (dead) while live, worse than the base. The caller's machine and generation now replace any other values; on `native` the record is the home's own and already names them, so nothing is written. Tests: `place_evidence` asserts an older leftover generation is replaced. Production LOC: 214,170 -> 214,170 (delta 0) scope: tools/production_loc.py (repo-pinned counter), first-parent tree vs committed tree reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Co-Authored-By: Claude Opus 5.5 --- control/crates/layerfs-sandbox/src/files.rs | 13 ++++++++----- .../layerfs-sandbox/tests/place_evidence.rs | 16 +++++++++------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/control/crates/layerfs-sandbox/src/files.rs b/control/crates/layerfs-sandbox/src/files.rs index 0675cb2303..fa836cd6d7 100644 --- a/control/crates/layerfs-sandbox/src/files.rs +++ b/control/crates/layerfs-sandbox/src/files.rs @@ -120,17 +120,20 @@ pub fn save_sandbox( } /// Writes the machine and generation a worker's caller minted (`place`) /// into the worker's own record of Sandbox `name` in `directory`, so the -/// mounts it places carry them (#783 gap 1). A record that names a -/// generation already (on `native`, the home's own) is left as it is. Best -/// effort: a record left without them only means its mounts carry no place -/// evidence, and missing evidence is never death. +/// mounts it places carry them (#783 gap 1). The caller's values always win: +/// a record an interrupted removal left behind may name an older generation, +/// and a mount recording that one would look retired beside the home's +/// newer record. On `native` the record is the home's own and already names +/// them (nothing is written). Best effort: a record left without them only +/// means its mounts carry no place evidence, and missing evidence is never +/// death. pub fn save_place(directory: &Path, name: &str, (machine, generation): &(String, String)) { let _ = (|| -> Result<()> { let _sandbox = crate::record::lock_in(directory, name)?; let Some(record) = SandboxRecord::read_in(directory, name)? else { return Ok(()); }; - if record.generation().is_some() { + if record.generation() == Some(generation) && record.machine() == machine { return Ok(()); } record.with_place(machine, generation).write_in(directory) diff --git a/control/crates/layerfs-sandbox/tests/place_evidence.rs b/control/crates/layerfs-sandbox/tests/place_evidence.rs index eed4fc6ec7..1d6eb915b2 100644 --- a/control/crates/layerfs-sandbox/tests/place_evidence.rs +++ b/control/crates/layerfs-sandbox/tests/place_evidence.rs @@ -45,15 +45,17 @@ fn a_worker_record_keeps_the_callers_place_and_its_mounts_read_it() { // a worker's root keeps no machine record: no incarnation is guessed assert_eq!(placed.machine_incarnation, None); - // a record naming a generation already (native's home record) is left - let other = ( - "other".to_owned(), + // a record an interrupted removal left with an older generation takes + // the caller's newer one: a mount recording the old one would look + // retired beside the home's newer record + let newer = ( + "box".to_owned(), "p1:aa11.sandbox:0000000000000020:bb".to_owned(), ); - layerfs_sandbox::files::save_place(&directory, "t1", &other); - let kept = SandboxRecord::read_in(&directory, "t1").unwrap().unwrap(); - assert_eq!(kept.generation(), Some(generation.as_str())); - assert_eq!(kept.machine(), "box"); + layerfs_sandbox::files::save_place(&directory, "t1", &newer); + let replaced = SandboxRecord::read_in(&directory, "t1").unwrap().unwrap(); + assert_eq!(replaced.generation(), Some(newer.1.as_str())); + assert_eq!(replaced.machine(), "box"); let _ = std::fs::remove_dir_all(&root); } From 1b17dbb3c3564d1acc679b67f4c122a3dab7aa37 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 18:03:35 +0800 Subject: [PATCH 6/6] fix(store): a full last audit page names no next cursor The persistence page reports `has_more` whenever a page is full, so the repair audit handed out a cursor to an empty page after a full last page. The audit now reads one row at the next page's offset and names the next page only when one follows. Caught by `gc_calls` on Linux. Production LOC: 214,170 -> 214,181 (delta +11) scope: tools/production_loc.py (repo-pinned counter), first-parent tree vs committed tree reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Co-Authored-By: Claude Opus 5.5 --- control/crates/layerfs-store/src/repair.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/control/crates/layerfs-store/src/repair.rs b/control/crates/layerfs-store/src/repair.rs index b4f1396bc6..b9a23eb112 100644 --- a/control/crates/layerfs-store/src/repair.rs +++ b/control/crates/layerfs-store/src/repair.rs @@ -150,7 +150,21 @@ fn audit(open: &OpenArgs, request: &Repair) -> Result { ) .map_err(failed)?; let items = read.items.iter().map(admission::done_value).collect(); - let next = match read.has_more { + // a full page names a next one only when a row follows it: the read + // of one row at the next page's offset (with a limit of one, the + // page number is the offset) + let more = read.has_more + && !admission::done_intents_branch( + service.store.history(), + &request.project, + &request.branch, + (page + 1).saturating_mul(read.limit), + 1, + ) + .map_err(failed)? + .items + .is_empty(); + let next = match more { true => SdkValue::Int(i64::from(page) + 1), false => SdkValue::Null, };