From b07327ba1f1e0258740d23aa155d7e9ff3a42aa0 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 02:12:57 +0800 Subject: [PATCH] fix(store): review follow-ups to #751 project-record repair MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of #751 (merged as fae5488566) found these; each is fixed here. - project doctor: a SQLite project's record must be complete only where this process runs the Store's calls. A worker's Sandboxes read the entry that worker keeps, so a host stub there is not a project.record fault. A failed project.record no longer skips project.listed or the --full project.data walk. - sandbox.create: the repair is decided by the record (no manifest, no installed, or bytes that do not decode), not by one refusal message, and is best effort: a repair that fails or cannot complete the record leaves the call's own refusal as it was. The repaired record is decoded in hand (discovery::project_of) instead of reading the entry again. - store.move: a record the record phase leaves incomplete is a line of log/repair.jsonl (call, store, project, why) instead of a silent drop. - project.init on a worker: a manifest/installed pair that is not a complete Disposable pair (restored::complete) is left out and logged in log/repair.jsonl, for a move or Sandbox create to complete. - restore and record repair share one Store scan, restored::found_in. Tests: doctor_targets checks project.listed still runs after a project.record failure; project_family checks store.move logs a record it cannot rebuild; installed_repair removes a Sandbox it did start instead of requiring create to fail; restored_records follows repair_project's new return (the written record). No tests deleted. Ran (TMPDIR=/tmp, 120 s limit each): restored_records 7, installed_repair 1, doctor_targets 7, project_family 7, backup_family 5, project_doctor_full 3, project_init_worker 7, store_family 5 (1 ignored), store_transfer_crash 6, layerfs-control doctor 12, project_delete_worker 14, store_transfer_recovery 4, restore_install 3: all pass. fmt, Clippy (-D warnings) on layerfs-store/-sandbox/-control/-api and the product boundary guard pass. Not run: a doctor of a project whose Store is on a ready worker machine (needs a running VM), a restore from a bucket. Docs: doctor, home, sandboxes, projects, sqlite-and-postgresql. Durable: NOT_RUN — disabled by owner until explicit reauthorization. Production LOC: 206,108 -> 206,163 (delta +55) core 40,988 -> 40,988 (0) engine 95,845 -> 95,845 (0) control 58,950 -> 59,005 (+55) layerfs-store +48, layerfs-control +8, layerfs-sandbox -1 api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent fae5488566 and the staged tree Co-Authored-By: Claude Opus 5.5 --- .../layerfs-api/tests/doctor_targets.rs | 8 + .../layerfs-api/tests/project_family.rs | 23 +++ .../src/doctor/project_target.rs | 34 ++-- .../crates/layerfs-sandbox/src/lifecycle.rs | 72 +++++---- .../layerfs-sandbox/tests/installed_repair.rs | 16 +- .../layerfs-store/src/backup/restore.rs | 27 +--- .../layerfs-store/src/backup/restored.rs | 150 +++++++++++------- .../layerfs-store/src/project/discovery.rs | 16 ++ .../layerfs-store/src/project/family.rs | 44 +++-- .../src/sqlite/transfer/phases.rs | 47 +++++- .../layerfs-store/tests/restored_records.rs | 2 +- docs/architecture/control/doctor/README.md | 2 +- docs/architecture/control/home/README.md | 6 +- docs/architecture/control/sandboxes/README.md | 2 +- .../control/stores-and-projects/projects.md | 2 +- .../sqlite-and-postgresql.md | 3 +- 16 files changed, 297 insertions(+), 157 deletions(-) diff --git a/api/crates/layerfs-api/tests/doctor_targets.rs b/api/crates/layerfs-api/tests/doctor_targets.rs index 4713874950..afe30804b0 100644 --- a/api/crates/layerfs-api/tests/doctor_targets.rs +++ b/api/crates/layerfs-api/tests/doctor_targets.rs @@ -552,6 +552,14 @@ fn a_sqlite_project_without_a_manifest_fails_project_doctor() { && f.get_text("severity") == Some("error")), "full={full}: {report:?}" ); + // the record's failure hides no other check: the Store's list is + // still checked + let rows = list(report.get("tree").unwrap(), "checks"); + assert!( + rows.iter() + .any(|row| row.get_text("check") == Some("project.listed")), + "full={full}: {report:?}" + ); } // PostgreSQL project records hold no manifest; project.record still passes. diff --git a/api/crates/layerfs-api/tests/project_family.rs b/api/crates/layerfs-api/tests/project_family.rs index e5120ca7c0..756590e9e4 100644 --- a/api/crates/layerfs-api/tests/project_family.rs +++ b/api/crates/layerfs-api/tests/project_family.rs @@ -834,12 +834,35 @@ fn move_skips_unreadable_project_record_and_still_repairs_incomplete_ones() { let damaged_path = paths::project_record(&home, "shop", "damaged"); std::fs::write(&damaged_path, b"{").unwrap(); write_legacy_stub(11111); + // a record of a stack the Store does not hold cannot be rebuilt: the + // move still ends, and says so in log/repair.jsonl + let orphan_path = paths::project_record(&home, "shop", "orphan"); + home::private_dir(orphan_path.parent().unwrap()).unwrap(); + write_record( + &orphan_path, + &SdkValue::map([ + ("v", SdkValue::Int(1)), + ("name", t("orphan")), + ("stack", t("0101010101010101010101010101010101")), + ("created", SdkValue::Int(1)), + ]), + ) + .unwrap(); ok( &home, "store.move", &[("store", t("shop")), ("machine", t("box"))], ); + let repair_log = std::fs::read_to_string(paths::log_dir(&home).join("repair.jsonl")).unwrap(); + assert!( + repair_log + .lines() + .any(|line| line.contains("\"project\":\"orphan\"") + && line.contains("\"call\":\"store.move\"")), + "{repair_log}" + ); + assert!(!repair_log.contains("\"legacy\""), "{repair_log}"); let store_rec = layerfs_api::home::read_record(&paths::store_record(&home, "shop")) .unwrap() .unwrap(); diff --git a/control/crates/layerfs-control/src/doctor/project_target.rs b/control/crates/layerfs-control/src/doctor/project_target.rs index 88081501d8..6fd6e205e4 100644 --- a/control/crates/layerfs-control/src/doctor/project_target.rs +++ b/control/crates/layerfs-control/src/doctor/project_target.rs @@ -62,23 +62,22 @@ pub(super) fn run(probe: &Probe<'_>, node: &mut Node) { }); match recorded { Ok((record, Some(project))) => { - let needs_manifest = matches!(record.store_ref(), Ok(StoreRef::Sqlite { .. })) - && project - .op() - .is_none_or(|op| op.name() != layerfs_store::project::op::INIT); - if needs_manifest && !layerfs_store::backup::restored::complete(&project) { + if opened_here(probe.home, &record, &project) + && !layerfs_store::backup::restored::complete(&project) + { checks.fail( RECORD, format!( - "project {handle}'s record has no complete manifest (a Sandbox cannot open it)" + "project {handle}'s record has no complete manifest (a Sandbox on this computer cannot open it)" ), ); } else { checks.pass(RECORD, "the project and its Store are on record"); - let stack = listed(probe, (&record, &project), handle, &mut checks); - if let (Some(stack), true) = (stack, probe.full) { - data(probe, &record, stack, &mut checks); - } + } + // the Store's list and data are checked whatever the record holds + let stack = listed(probe, (&record, &project), handle, &mut checks); + if let (Some(stack), true) = (stack, probe.full) { + data(probe, &record, stack, &mut checks); } } Ok((_, None)) => { @@ -89,6 +88,21 @@ pub(super) fn run(probe: &Probe<'_>, node: &mut Node) { checks.fill(node, probe.checks, probe.budget.expired()); } +/// Whether a Sandbox of `project` opens its Store from this home's record: +/// a sqlite Store whose calls run in this process, with no Init under way. +/// A worker's Sandbox reads the entry that worker keeps, which its own Init +/// wrote complete (#749), so a host record without one is not a fault there. +fn opened_here(home: &Path, store: &StoreRecord, project: &ProjectRecord) -> bool { + matches!(store.store_ref(), Ok(StoreRef::Sqlite { .. })) + && project + .op() + .is_none_or(|op| op.name() != layerfs_store::project::op::INIT) + && matches!( + place::on_machine_read(home, &store.machine().unwrap_or_default()), + Ok(Executor::Local) + ) +} + /// `project.listed`: the Store's own list holds the project its record /// names, by its stack id, or by its name for a record without one. The /// stack the list names, when it does. diff --git a/control/crates/layerfs-sandbox/src/lifecycle.rs b/control/crates/layerfs-sandbox/src/lifecycle.rs index 2c0bcde9da..733485a547 100644 --- a/control/crates/layerfs-sandbox/src/lifecycle.rs +++ b/control/crates/layerfs-sandbox/src/lifecycle.rs @@ -132,42 +132,23 @@ fn installed(host: &Host) -> Result { let name = &host.project; let identity = layerfs_store::identity::identity(&host.open_args())?; layerfs_store::identity::sqlite_only(&identity, "a Sandbox of a Store file")?; - let project = match layerfs_store::project::discovery::project( + let found = layerfs_store::project::discovery::project( Some(&host.home), Some(&host.store), Some(&host.project), - ) { - Ok(project) => project, - Err(refusal) - if refusal.code == "NoSuchProject" - && refusal.message == "no complete project manifest" => - { - let repaired = host - .open_args() - .store_path() - .ok() - .filter(|path| path.is_file()) - .map(|path| { - layerfs_store::backup::restored::repair_project( - &host.home, - &host.store, - &host.project, - identity, - &path, - ) - }) - .transpose()? - .unwrap_or(false); - if !repaired { - return Err(refusal); - } - layerfs_store::project::discovery::project( - Some(&host.home), - Some(&host.store), - Some(&host.project), - )? + ); + // a record without a complete `manifest` and `installed` (#749: one an + // older worker Init wrote) is rebuilt from the Store file here, once; + // a repair that cannot complete it leaves the refusal as it was + let project = match found { + Ok(project) if project.installed.is_some() => project, + Err(refusal) if !matches!(refusal.code.as_str(), "NoSuchProject" | "Failed") => { + return Err(refusal) } - Err(refusal) => return Err(refusal), + found => match repaired(host, identity) { + Some(project) => project, + None => found?, + }, }; let Some(installed) = project.installed.clone() else { return Err(refused( @@ -178,6 +159,33 @@ fn installed(host: &Host) -> Result { Ok(OpenedStore::File(Box::new((project, installed)))) } +/// The project of `host`, its record completed from the Store file this +/// kernel holds ([`restored::repair_project`]); `None` when there is no such +/// file, the record needs no repair or the repair does not complete it. +/// +/// [`restored::repair_project`]: layerfs_store::backup::restored::repair_project +fn repaired( + host: &Host, + identity: layerfs_store::identity::Identity, +) -> Option { + let file = host.open_args().store_path().ok().filter(|p| p.is_file())?; + let record = layerfs_store::backup::restored::repair_project( + &host.home, + &host.store, + &host.project, + identity, + &file, + ) + .ok()??; + layerfs_store::project::discovery::project_of( + Some(&host.home), + Some(&host.store), + Some(&host.project), + record.to_record(), + ) + .ok() +} + /// Starts the Sandbox the call names (`sandbox`) as its deployment says /// (`deploy.sandbox`: native or namespaces), its daemon on `store`. Called /// under the guard of its folder `directory`, so no other call on it runs diff --git a/control/crates/layerfs-sandbox/tests/installed_repair.rs b/control/crates/layerfs-sandbox/tests/installed_repair.rs index 764674b58c..939cd443fe 100644 --- a/control/crates/layerfs-sandbox/tests/installed_repair.rs +++ b/control/crates/layerfs-sandbox/tests/installed_repair.rs @@ -81,11 +81,17 @@ fn sandbox_create_repairs_an_incomplete_sqlite_project_record() { message: Message::Absent, started: None, }; - let err = lifecycle::create(&host, None).unwrap_err(); - assert_ne!( - err.code, "NoSuchProject", - "must heal manifest instead of failing NoSuchProject: {err:?}" - ); + // the repair happens before launch; a host that can launch a daemon + // starts one, which is removed again + match lifecycle::create(&host, None) { + Ok(_) => { + lifecycle::close(&host, true, &[]).expect("the started Sandbox is removed"); + } + Err(err) => assert_ne!( + err.code, "NoSuchProject", + "must heal manifest instead of failing NoSuchProject: {err:?}" + ), + } let repaired = ProjectRecord::read(&home, "shop", "api").unwrap().unwrap(); assert_eq!(repaired.created(), Some(&SdkValue::Int(55))); assert!(restored::complete(&repaired)); diff --git a/control/crates/layerfs-store/src/backup/restore.rs b/control/crates/layerfs-store/src/backup/restore.rs index 159b131726..94001cd17e 100644 --- a/control/crates/layerfs-store/src/backup/restore.rs +++ b/control/crates/layerfs-store/src/backup/restore.rs @@ -2,7 +2,7 @@ use super::family::write_link; use super::progress::Shown; use super::record::{BucketRecord, StoreLink}; -use super::restored::{records, Found, Main, Restored}; +use super::restored::{records, Found, Restored}; use crate::get::hex_text; use crate::identity::{Identity, Kind}; use crate::intent; @@ -12,7 +12,6 @@ use crate::Related; use layerfs_bridge::control::{SdkRefusal, SdkValue}; use layerfs_bridge::sdk_values::hex; use layerfs_bucket::backup as remote; -use layerfs_history::{HistoryName, NamedSnapshot}; use layerfs_home::events::Events; use layerfs_home::home::flock::{try_lock, unlock}; use layerfs_home::home::{self, paths}; @@ -449,30 +448,10 @@ fn projects_in(home: &Path, store: &str, record: &StoreRecord, file: &Path) -> R ..Default::default() }; crate::service::with_service(&open, |service| { - // the project's own line of Layers: `main`, through its name index - let main = - HistoryName::new(layerfs_store_service::history::branch::MAIN).map_err(failed)?; + // each project's own line of Layers: `main`, through its name index let projects = service .store - .published(|history| { - let mut found = Vec::new(); - for stack in layerfs_project::store::projects(history)? { - let snapshot = match history.branch_snapshot_named(&stack.name, &main)? { - NamedSnapshot::Found(snapshot) => Some(Main { - stack: snapshot.branch.stack, - branch: snapshot.branch.id, - root: snapshot.base_root.to_bytes(), - }), - NamedSnapshot::NoStack | NamedSnapshot::NoBranch => None, - }; - found.push(Found { - name: stack.name.as_str().to_owned(), - stack: SdkValue::text(hex(&stack.id.to_bytes())), - main: snapshot, - }); - } - Ok(found) - }) + .published(super::restored::found_in) .map_err(failed)?; Ok(Listing { projects, diff --git a/control/crates/layerfs-store/src/backup/restored.rs b/control/crates/layerfs-store/src/backup/restored.rs index 43cba713aa..960caec1f8 100644 --- a/control/crates/layerfs-store/src/backup/restored.rs +++ b/control/crates/layerfs-store/src/backup/restored.rs @@ -8,7 +8,9 @@ use crate::record::StoreRecord; use layerfs_bridge::control::{SdkRefusal, SdkValue}; use layerfs_bridge::provision::{StoreManifest, StoreProfile}; use layerfs_bridge::sdk_values::hex; -use layerfs_history::{BranchId, HistoryCatalog, HistoryName, LayerStackId, NamedSnapshot}; +use layerfs_history::{ + BranchId, HistoryCatalog, HistoryName, HistoryResult, LayerStackId, NamedSnapshot, +}; use layerfs_home::home::{self, paths}; use layerfs_home::outcome::{failed, refused}; use std::path::{Path, PathBuf}; @@ -188,26 +190,14 @@ pub fn complete(record: &ProjectRecord) -> bool { decodes("manifest") && decodes("installed") } -/// Reads the live projects and SQLite version of the local SQLite Store at -/// `file` through a read-only diagnostic handle so the file's bytes and WAL -/// stay untouched. -pub fn projects_in_diagnostic(file: &Path, identity: &Identity) -> Result<(Vec, String)> { - layerfs_store_service::kernel_guard::check(file) - .map_err(|reason| refused("Unsupported", reason.0))?; - let handles = layerfs_persistence::SqliteHandles::open_diagnostic( - file, - &identity.binding, - identity.cursor_key, - ) - .map_err(|error| refused("Unavailable", crate::words::persistence(&error)))?; - let main = HistoryName::new(layerfs_store_service::history::branch::MAIN).map_err(failed)?; +/// The projects Store history `history` holds, each with its `main` +/// Branch when it has one: what a restore and a record repair rebuild +/// records from. +pub fn found_in(history: &dyn HistoryCatalog) -> HistoryResult> { + let main = HistoryName::new(layerfs_store_service::history::branch::MAIN)?; let mut found = Vec::new(); - for stack in layerfs_project::store::projects(&handles.history).map_err(failed)? { - let snapshot = match handles - .history - .branch_snapshot_named(&stack.name, &main) - .map_err(failed)? - { + for stack in layerfs_project::store::projects(history)? { + let snapshot = match history.branch_snapshot_named(&stack.name, &main)? { NamedSnapshot::Found(snapshot) => Some(Main { stack: snapshot.branch.stack, branch: snapshot.branch.id, @@ -221,9 +211,28 @@ pub fn projects_in_diagnostic(file: &Path, identity: &Identity) -> Result<(Vec Result<(Vec, String)> { + layerfs_store_service::kernel_guard::check(file) + .map_err(|reason| refused("Unsupported", reason.0))?; + let handles = layerfs_persistence::SqliteHandles::open_diagnostic( + file, + &identity.binding, + identity.cursor_key, + ) + .map_err(|error| refused("Unavailable", crate::words::persistence(&error)))?; + let found = found_in(&handles.history).map_err(failed)?; Ok((found, handles.profile().sqlite_version.clone())) } +/// The record `name` would be completed to: `existing` with the `manifest` +/// and `installed` its listed project rebuilds, when the Store lists it +/// with a `main` Branch of the recorded stack. `Ok(None)` when it does not. fn match_rebuilt( store: &str, restored: &Restored, @@ -244,36 +253,57 @@ fn match_rebuilt( Ok(Some(existing.with_fields_of(&rebuilt))) } +/// A record repair needs: it holds no `op` and is not [`complete`]. +fn needs_repair(record: &ProjectRecord) -> bool { + record.op().is_none() && !complete(record) +} + /// Rebuilds `manifest` and `installed` on existing incomplete SQLite project /// records of Store `store` under `home` from the local `file`. Records that -/// are already complete or hold an `op` are left alone; when none need repair, -/// `file` is not opened. +/// are already complete or hold an `op` are left alone, as is one whose +/// `record.json` does not read; when none need repair, `file` is not opened. +/// Returns each record it left incomplete, with why, so the caller can say +/// so: a failure here never fails the call that asked for it. pub fn complete_existing( home: &Path, store: &str, record: &StoreRecord, file: &Path, -) -> Result<()> { +) -> Vec<(String, String)> { let entries = match paths::names(&paths::store_dir(home, store).join("project")) { Ok(names) => names, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(failed(error)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Vec::new(), + Err(error) => return vec![(String::new(), error.to_string())], }; - let mut incomplete = Vec::new(); - for name in entries { - let Ok(Some(existing)) = ProjectRecord::read(home, store, &name) else { - continue; - }; - if existing.op().is_none() && !complete(&existing) { - incomplete.push(name); - } - } + let incomplete: Vec = entries + .into_iter() + .filter(|name| { + ProjectRecord::read(home, store, name) + .is_ok_and(|r| r.as_ref().is_some_and(needs_repair)) + }) + .collect(); if incomplete.is_empty() { - return Ok(()); + return Vec::new(); } + complete_all(home, store, record, file, &incomplete).unwrap_or_else(|refusal| { + (incomplete.into_iter()) + .map(|name| (name, refusal.message.clone())) + .collect() + }) +} + +/// [`complete_existing`] of the records `incomplete` names, once the Store +/// file is read. +fn complete_all( + home: &Path, + store: &str, + record: &StoreRecord, + file: &Path, + incomplete: &[String], +) -> Result> { let identity = crate::identity::identity_in(record)?; if identity.kind != Kind::Sqlite { - return Ok(()); + return Ok(Vec::new()); } let (found, sqlite) = projects_in_diagnostic(file, &identity)?; let restored = Restored { @@ -282,37 +312,40 @@ pub fn complete_existing( sqlite, }; let _lock = home::lock::take(home)?; + let mut left = Vec::new(); for name in incomplete { - let Ok(Some(existing)) = ProjectRecord::read(home, store, &name) else { - continue; + let existing = match ProjectRecord::read(home, store, name) { + Ok(Some(existing)) if needs_repair(&existing) => existing, + _ => continue, }; - if existing.op().is_some() || complete(&existing) { - continue; - } - if let Ok(Some(updated)) = match_rebuilt(store, &restored, &found, &name, existing) { - let _ = updated.write(home); - } + let why = match match_rebuilt(store, &restored, &found, name, existing) { + Ok(Some(updated)) => match updated.write(home) { + Ok(()) => continue, + Err(refusal) => refusal.message, + }, + Ok(None) => format!("Store {store} has no main Branch of its stack"), + Err(refusal) => refusal.message, + }; + left.push((name.clone(), why)); } - Ok(()) + Ok(left) } /// Completes one existing incomplete SQLite project record `project` of -/// Store `store` from the local `file`; returns whether the record was written. +/// Store `store` from the local `file`; returns the record it wrote, or +/// `None` when the record needs no repair or cannot be rebuilt. pub fn repair_project( home: &Path, store: &str, project: &str, identity: Identity, file: &Path, -) -> Result { +) -> Result> { if identity.kind != Kind::Sqlite { - return Ok(false); + return Ok(None); } - let Some(existing) = ProjectRecord::read(home, store, project)? else { - return Ok(false); - }; - if existing.op().is_some() || complete(&existing) { - return Ok(false); + if !ProjectRecord::read(home, store, project)?.is_some_and(|r| needs_repair(&r)) { + return Ok(None); } let (found, sqlite) = projects_in_diagnostic(file, &identity)?; let restored = Restored { @@ -321,15 +354,12 @@ pub fn repair_project( sqlite, }; let _lock = home::lock::take(home)?; - let Some(existing) = ProjectRecord::read(home, store, project)? else { - return Ok(false); + let Some(existing) = ProjectRecord::read(home, store, project)?.filter(needs_repair) else { + return Ok(None); }; - if existing.op().is_some() || complete(&existing) { - return Ok(false); - } let Some(updated) = match_rebuilt(store, &restored, &found, project, existing)? else { - return Ok(false); + return Ok(None); }; updated.write(home)?; - Ok(true) + Ok(Some(updated)) } diff --git a/control/crates/layerfs-store/src/project/discovery.rs b/control/crates/layerfs-store/src/project/discovery.rs index 7a5015d723..cc10607d2b 100644 --- a/control/crates/layerfs-store/src/project/discovery.rs +++ b/control/crates/layerfs-store/src/project/discovery.rs @@ -275,6 +275,22 @@ pub fn project(home: Option<&Path>, store: Option<&str>, name: Option<&str>) -> let path = project_dir(home, store, name)?; let value = layerfs_home::home::read_record(&path.join("record.json"))? .ok_or_else(|| refused("NoSuchProject", "no project record"))?; + decoded(&path, &value) +} + +/// [`project`] from its record `value`, already in hand (a record a repair +/// just wrote, #749), with no second read of its entry. +pub fn project_of( + home: Option<&Path>, + store: Option<&str>, + name: Option<&str>, + value: &SdkValue, +) -> Result { + decoded(&project_dir(home, store, name)?, value) +} + +/// The project whose entry is `path` and whose record is `value`. +fn decoded(path: &Path, value: &SdkValue) -> Result { let decode = |name| match value.get(name) { Some(SdkValue::Bytes(bytes)) => StoreManifest::decode(bytes).map_err(failed), _ => Err(refused("NoSuchProject", "no complete project manifest")), diff --git a/control/crates/layerfs-store/src/project/family.rs b/control/crates/layerfs-store/src/project/family.rs index fee73601e9..820dc44b8c 100644 --- a/control/crates/layerfs-store/src/project/family.rs +++ b/control/crates/layerfs-store/src/project/family.rs @@ -17,7 +17,6 @@ use crate::record::{StoreRecord, StoreRef}; use crate::resolve; use crate::sqlite::family::progress; use layerfs_bridge::control::SdkValue; -use layerfs_bridge::provision::StoreManifest; use layerfs_home::events::Events; use layerfs_home::names::{ProjectRef, StoreName}; use layerfs_home::op::FIELD; @@ -287,16 +286,41 @@ fn init_on_worker( refusal })?; let stack = added.get("stack").cloned().unwrap_or_default(); - let mut project = ProjectRecord::initialised(store, name, stack); - if let (Some(SdkValue::Bytes(m)), Some(SdkValue::Bytes(i))) = - (added.get("manifest"), added.get("installed")) - { - if StoreManifest::decode(m).is_ok() && StoreManifest::decode(i).is_ok() { - project = project - .with("manifest", SdkValue::Bytes(m.clone())) - .with("installed", SdkValue::Bytes(i.clone())); + // the worker's `manifest` and `installed` complete the record (#749); + // a worker that sends none (an older build) or sends ones that are not + // a complete Disposable pair leaves it for a move or a Sandbox create + // to complete from the Store file, the latter logged: the project is + // already in the Store, so the Init does not fail over it + let initialised = ProjectRecord::initialised(store, name, stack); + let project = match (added.get("manifest"), added.get("installed")) { + (None, None) => initialised, + (manifest, installed) => { + let full = (initialised.clone()) + .with("manifest", manifest.cloned().unwrap_or_default()) + .with("installed", installed.cloned().unwrap_or_default()); + if crate::backup::restored::complete(&full) { + full + } else { + let _ = layerfs_home::home::log_line( + &home, + "repair.jsonl", + &SdkValue::map([ + ("at", SdkValue::Int(layerfs_home::home::now_ms())), + ("call", SdkValue::text("project.init")), + ("store", SdkValue::text(store.as_str())), + ("project", SdkValue::text(name)), + ( + "message", + SdkValue::text( + "the worker's manifest and installed manifest are not a complete Disposable pair; the record keeps neither", + ), + ), + ]), + ); + initialised + } } - } + }; progress(events, "record", None); { let _lock = layerfs_home::home::lock::take(&home)?; diff --git a/control/crates/layerfs-store/src/sqlite/transfer/phases.rs b/control/crates/layerfs-store/src/sqlite/transfer/phases.rs index 514fd636a9..ddbc497191 100644 --- a/control/crates/layerfs-store/src/sqlite/transfer/phases.rs +++ b/control/crates/layerfs-store/src/sqlite/transfer/phases.rs @@ -228,6 +228,44 @@ fn enter( at(phase, advance(&home, name, op, phase)) } +/// Completes the incomplete project records of Store `name` from the Store +/// file on this kernel (#749), before a worker's copy and the entries it +/// keeps are retired. Best effort: a record left incomplete does not fail +/// the move, which has installed the Store already; each is a line of +/// `log/repair.jsonl`, naming the project (none when the Store's records +/// were not read at all) and why. +fn complete_records(home: &Path, name: &str, call: &str) { + let left = match StoreRecord::of(home, name) { + Ok(record) => crate::backup::restored::complete_existing( + home, + name, + &record, + &home::paths::store_file(home, name), + ), + Err(refusal) => vec![(String::new(), refusal.message)], + }; + for (project, why) in left { + let _ = home::log_line( + home, + "repair.jsonl", + &SdkValue::map([ + ("at", SdkValue::Int(home::now_ms())), + ("call", SdkValue::text(call)), + ("store", SdkValue::text(name)), + ( + "project", + if project.is_empty() { + SdkValue::Null + } else { + SdkValue::text(project) + }, + ), + ("message", SdkValue::text(why)), + ]), + ); + } +} + fn phases( home: &Path, events: &mut Events<'_>, @@ -333,14 +371,7 @@ fn phases( // use on `to` and a copy the next move deletes first enter(&home, events, op, name, "record", None)?; if matches!(source, Executor::Local) || matches!(target, Executor::Local) { - if let Ok(local_record) = StoreRecord::of(&home, name) { - let _ = crate::backup::restored::complete_existing( - &home, - name, - &local_record, - &home::paths::store_file(&home, name), - ); - } + complete_records(&home, name, op.name()); } let last = SdkValue::map([ ("call", SdkValue::text(op.name())), diff --git a/control/crates/layerfs-store/tests/restored_records.rs b/control/crates/layerfs-store/tests/restored_records.rs index 14b1667585..ac0f9646cb 100644 --- a/control/crates/layerfs-store/tests/restored_records.rs +++ b/control/crates/layerfs-store/tests/restored_records.rs @@ -307,7 +307,7 @@ fn repair_project_completes_an_incomplete_record_from_sqlite_store() { &paths::store_file(&home, STORE), ) .unwrap(); - assert!(repaired); + assert!(repaired.is_some_and(|record| layerfs_store::backup::restored::complete(&record))); let project = discovery::project(Some(&home), Some(STORE), Some(PROJECT)) .expect("repaired record opens in Sandbox"); assert!(project.installed.is_some()); diff --git a/docs/architecture/control/doctor/README.md b/docs/architecture/control/doctor/README.md index d1a06ed46b..978808ae48 100644 --- a/docs/architecture/control/doctor/README.md +++ b/docs/architecture/control/doctor/README.md @@ -182,7 +182,7 @@ Under a machine that is not ready only `store.record` is made: the rest are | Check | What is observed | Source | | --- | --- | --- | -| `project.record` | The project's record and its Store's record read; for a SQLite Store without a `project.init` `op`, `manifest` and `installed` decode with `Disposable` | [`project_target.rs`](../../../../control/crates/layerfs-control/src/doctor/project_target.rs), [`restored.rs`](../../../../control/crates/layerfs-store/src/backup/restored.rs) | +| `project.record` | The project's record and its Store's record read; for a SQLite Store whose calls run in this process, with no `project.init` `op`, `manifest` and `installed` decode with `Disposable` (a Store on a worker is exempt: that worker's Sandboxes read the entry it keeps). A failure here does not stop `project.listed` or `project.data` | [`project_target.rs`](../../../../control/crates/layerfs-control/src/doctor/project_target.rs), [`restored.rs`](../../../../control/crates/layerfs-store/src/backup/restored.rs) | | `project.listed` | The Store's own list (read where its calls run) holds the record's stack id, or its name for a record without one. Not listed: a notice, `fix` `layerfs project delete `, which removes such an entry. A Store this host cannot open or whose file is gone, and a worker that does not answer (`machine`, `not_answering`), block it | [`project_target.rs`](../../../../control/crates/layerfs-control/src/doctor/project_target.rs), [`live.rs`](../../../../control/crates/layerfs-store/src/project/live.rs) | | `project.data` (`--full` only) | Everything main's head and each live Branch's head reach, read and checked once per project in one pinned read view: each tree's namespace qualified, each object located, reconstructed, admitted and its children's context checked, as the whole-Store scan checks its rows ([Store diagnostics](../../engine/store/diagnostics.md#one-projects-data)). sqlite on this kernel and PostgreSQL in this process; sqlite on a machine through its worker's `store.diagnose` with `cut: project`, its `data` events passed back. The first 64 problems are findings (an unreadable object `not_checked` `lost`), the rest one counted finding | [`project_target.rs`](../../../../control/crates/layerfs-control/src/doctor/project_target.rs), [`diagnostic.rs`](../../../../control/crates/layerfs-store/src/diagnostic.rs) | diff --git a/docs/architecture/control/home/README.md b/docs/architecture/control/home/README.md index d5f5d909bc..baa417444d 100644 --- a/docs/architecture/control/home/README.md +++ b/docs/architecture/control/home/README.md @@ -40,8 +40,8 @@ says how the first call creates one and why a folder that is not a LayerFS workspace//exec/.json one per running command backup//record.json provider, url, prefix, region, access key id secret//.json 0600: saved logins (auth), bucket keys - log/ uncertain.jsonl; leases, exec .jsonl and - their .1.jsonl; rotate.lock + log/ uncertain.jsonl; leases, exec, repair .jsonl + and their .1.jsonl; rotate.lock trace/calls.jsonl the call log; calls.1.jsonl calls.lock /layerfs/data/ a machine's data root: its worker's root @@ -410,7 +410,7 @@ independent of `LAYERFS_TRACE`. | PostgreSQL Store with no saved login (`auth`) | `InvalidInput`, fix `layerfs store save-auth --user --password-stdin && layerfs store update --auth `; a named login not saved is `NotFound` | [`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) `dial`, `read` | | A folder that is not a LayerFS 2.0 home (a `layerfs.json` of another layout, or anything but `layerfs.lock`, the integration folders and `.DS_Store` with no `layerfs.json`) | `Unsupported`, fix `mv .old && layerfs home init`; nothing written ([Opening a home](#opening-a-home)) | [`home/layout.rs`](../../../../control/crates/layerfs-home/src/home/layout.rs) `foreign` | | Call log size | rotates past 16 MiB to the one `calls.1.jsonl` under a non-blocking `flock` on `calls.lock`; `home.clear_log` waits for that lock, truncates in place and removes the rotated file | [`logs.rs`](../../../../control/crates/layerfs-home/src/logs.rs) | -| Other log sizes | One rule: past 16 MiB a log moves once to its `.1` name, replacing the one before. `log/*.jsonl` (`leases`, and `exec` on the side that keeps the command records): a writer opens, appends one line and closes, and a log then past the size is renamed to `.1.jsonl` under a non-blocking `flock` on `log/rotate.lock`; a writer that does not get the lock skips it. `log/uncertain.jsonl` never rotates: it is the only record of uncertain outcomes. `machine//forward.log` is checked when a forward starts: it is copied to `forward.1.log` and emptied in place, never renamed, since the machine's other forwards hold it open ([forwards](../machines/workers-and-reach.md#forwards)). A machine's `/layerfs/data/log/worker.log` is renamed to `worker.1.log` only when a worker starts, never while one runs ([workers](../machines/workers-and-reach.md#the-workers-log)). A Sandbox's `daemon.log` is new with its run folder and goes with it: it is never rotated and there is no `daemon.1.log` ([Backends](../sandboxes/backends.md#local-one-daemon-process-on-this-kernel)) | [`home/records.rs`](../../../../control/crates/layerfs-home/src/home/records.rs) `log_line`, [`log_file.rs`](../../../../engine/crates/layerfs-bridge/src/log_file.rs), [`setup/forward.rs`](../../../../control/crates/layerfs-platform/src/setup/forward.rs), [`setup/worker.rs`](../../../../control/crates/layerfs-platform/src/setup/worker.rs) `log_start` | +| Other log sizes | One rule: past 16 MiB a log moves once to its `.1` name, replacing the one before. `log/*.jsonl` (`leases`, `repair`, and `exec` on the side that keeps the command records): a writer opens, appends one line and closes, and a log then past the size is renamed to `.1.jsonl` under a non-blocking `flock` on `log/rotate.lock`; a writer that does not get the lock skips it. `log/uncertain.jsonl` never rotates: it is the only record of uncertain outcomes. `machine//forward.log` is checked when a forward starts: it is copied to `forward.1.log` and emptied in place, never renamed, since the machine's other forwards hold it open ([forwards](../machines/workers-and-reach.md#forwards)). A machine's `/layerfs/data/log/worker.log` is renamed to `worker.1.log` only when a worker starts, never while one runs ([workers](../machines/workers-and-reach.md#the-workers-log)). A Sandbox's `daemon.log` is new with its run folder and goes with it: it is never rotated and there is no `daemon.1.log` ([Backends](../sandboxes/backends.md#local-one-daemon-process-on-this-kernel)) | [`home/records.rs`](../../../../control/crates/layerfs-home/src/home/records.rs) `log_line`, [`log_file.rs`](../../../../engine/crates/layerfs-bridge/src/log_file.rs), [`setup/forward.rs`](../../../../control/crates/layerfs-platform/src/setup/forward.rs), [`setup/worker.rs`](../../../../control/crates/layerfs-platform/src/setup/worker.rs) `log_start` | | `home.log` page | default 200, at most 1000 lines, and at most 64 KiB of rows before it ends early with a cursor; a cursor carries its call and filters (another call's, or one given with different filters, is `InvalidInput`); a cursor after a rotation or clear is stale (`InvalidInput`); a torn line is counted in `skipped` | same | ## Demonstration diff --git a/docs/architecture/control/sandboxes/README.md b/docs/architecture/control/sandboxes/README.md index 10bcfc02ac..791b62282c 100644 --- a/docs/architecture/control/sandboxes/README.md +++ b/docs/architecture/control/sandboxes/README.md @@ -52,7 +52,7 @@ runtime owns command launch, streams, exit status and cancel | Behaviour | Detail | Source | | --- | --- | --- | | Choose the backend | `deploy.sandbox` (`LAYERFS_SANDBOX`) is `native` (macOS) or `namespaces` (Linux). Unset or `docker` names the retired docker backend and is refused; `native` on Linux and `namespaces` off Linux are refused; all before any effect. | [`runtime.rs`](../../../../control/crates/layerfs-sandbox/src/runtime.rs) `backend` | -| `sandbox.create` | Under the Sandbox folder's guard: a started record is `Exists` (a record of the retired docker backend is cleared first). If an existing SQLite project record without an `op` lacks a complete `manifest`/`installed`, it is rebuilt read-only from the local Store file before launch (`restored::repair_project`). Builds a fresh `DaemonSetup` (listen `127.0.0.1:0`, keys, kernel route, overlay template, mount home, command identity, limits), launches once and waits up to 30 s for the daemon's listen line. A sqlite Store's directory is bound in; a PostgreSQL Store's server is reach-checked first. | [`lifecycle.rs`](../../../../control/crates/layerfs-sandbox/src/lifecycle.rs) `create`, `setup`, `installed`; [`launch/local.rs`](../../../../control/crates/layerfs-sandbox/src/launch/local.rs); [`launch/provider.rs`](../../../../control/crates/layerfs-sandbox/src/launch/provider.rs); [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) `reach_check` | +| `sandbox.create` | Under the Sandbox folder's guard: a started record is `Exists` (a record of the retired docker backend is cleared first). If an existing SQLite project record without an `op` lacks a complete `manifest`/`installed`, it is rebuilt read-only from the local Store file before launch (`restored::repair_project`), once and best effort: a repair that does not complete it leaves the call's refusal as it was. Builds a fresh `DaemonSetup` (listen `127.0.0.1:0`, keys, kernel route, overlay template, mount home, command identity, limits), launches once and waits up to 30 s for the daemon's listen line. A sqlite Store's directory is bound in; a PostgreSQL Store's server is reach-checked first. | [`lifecycle.rs`](../../../../control/crates/layerfs-sandbox/src/lifecycle.rs) `create`, `setup`, `installed`; [`launch/local.rs`](../../../../control/crates/layerfs-sandbox/src/launch/local.rs); [`launch/provider.rs`](../../../../control/crates/layerfs-sandbox/src/launch/provider.rs); [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) `reach_check` | | Command identity | Linux: uid 501, gid 20. macOS: the caller's own uid and gid. | [`lifecycle.rs`](../../../../control/crates/layerfs-sandbox/src/lifecycle.rs) `setup`, [`launch/local.rs`](../../../../control/crates/layerfs-sandbox/src/launch/local.rs) | | Launch on the kernel | `Runtime::launch_with_binds` starts the daemon once in a private directory and returns the owner; a failure after an effect returns it in `LaunchFailure::instance` for one stop and one delete. | [`runtime.rs`](../../../../control/crates/layerfs-sandbox-backend/src/runtime.rs), [Backends](backends.md) | | Reopen | A later call reopens the Sandbox by its recorded runtime (`native` or `namespaces`); `Runtime::reopen` checks the recorded process identity and starts nothing. A daemon found gone or stopped is `NoSuchSandbox`, with every Workspace it held lost. | [`reopen.rs`](../../../../control/crates/layerfs-sandbox/src/reopen.rs), [`registry.rs`](../../../../control/crates/layerfs-sandbox/src/registry.rs) `sandbox_live` | diff --git a/docs/architecture/control/stores-and-projects/projects.md b/docs/architecture/control/stores-and-projects/projects.md index 8229be7a7c..2852d935be 100644 --- a/docs/architecture/control/stores-and-projects/projects.md +++ b/docs/architecture/control/stores-and-projects/projects.md @@ -42,7 +42,7 @@ runs and how the folder gets there. | Rule | Detail | Source | | --- | --- | --- | | Live add | Init adds a folder as a new project to an existing Store through its writer; it does not seal | [`family.rs`](../../../../control/crates/layerfs-store/src/project/family.rs), [`add.rs`](../../../../control/crates/layerfs-store/src/project/add.rs) | -| Where | where the Store's calls run: this process for PostgreSQL and a `Local` sqlite machine, else the machine's worker; the folder is always on the caller's host, and a worker Init returns `manifest` and `installed` so the caller's project record is complete | same | +| Where | where the Store's calls run: this process for PostgreSQL and a `Local` sqlite machine, else the machine's worker; the folder is always on the caller's host, and a worker Init returns `manifest` and `installed` so the caller's project record is complete; a pair that is not a complete Disposable one is left out and logged in `log/repair.jsonl`, for a move or Sandbox create to complete | same | | Time limit | default 1 hour (`timeout` in ms) | same, `INIT_TIMEOUT_MS` | | Progress | `{phase, done, total}`: `check`, `send` (bytes, worker route only), `install`, `record` | same | | Lease | this process holds the Store's lease for the whole Init, on every route | same | diff --git a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md index 4b90ec086d..27061cafe1 100644 --- a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md +++ b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md @@ -42,7 +42,8 @@ own operation verify target: the copy's bytes, sha256 and heads are the snapshot's install (op written uncertain first) rename incoming -> store.sqlite record incomplete SQLite project records without an `op` are completed - read-only from the local `store.sqlite` (`restored::complete_existing`); + read-only from the local `store.sqlite` (`restored::complete_existing`), + best effort: each one left incomplete is a line of log/repair.jsonl; record names the new machine; last_transfer {.., retired:false} retire delete the source's copy; retired: true; op dropped ```