From 941f66d43d536b0cc3999306e9455af4915e1b8e Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 16:05:28 +0800 Subject: [PATCH 01/16] revert(workspace): move the read-ahead window change out of the GC PR The `Streams::follow` change follows any same-root window with `until > start` without checking the window's start, so a second pass over a file inherits the first pass's end and gets no read-ahead. It is also unrelated to GC authority and attributed to the wrong base commit (d19d98f138 is a GC mark change). It goes to #779 with its own FUSE measurement; this restores the base `client.rs`. Production LOC: 214,081 -> 214,073 (delta -8) 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 --- engine/crates/layerfs-workspace/src/base/client.rs | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/engine/crates/layerfs-workspace/src/base/client.rs b/engine/crates/layerfs-workspace/src/base/client.rs index 7aa915be6e..6296f6edac 100644 --- a/engine/crates/layerfs-workspace/src/base/client.rs +++ b/engine/crates/layerfs-workspace/src/base/client.rs @@ -79,18 +79,7 @@ impl Streams { .0 .iter() .position(|last| last.root == root && last.next == start); - let until = match found { - Some(index) => Some(self.0.remove(index).until), - // A concurrent request may continue inside a window another - // request already fetched: follow that window instead of opening - // a new one, so its tail is not demanded again. - None => self - .0 - .iter() - .filter(|stream| stream.root == root && stream.until > start) - .map(|stream| stream.until) - .max(), - }; + let until = found.map(|index| self.0.remove(index).until); self.0.push(Ahead { root, next: end, From 77af6743015a9a261a0ca8d4496a3eb443c19f1b Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 16:05:43 +0800 Subject: [PATCH 02/16] chore: restore base tests and drop stray files from the GC PR - Restore engine/crates/layerfs-persistence/tests/postgresql_gc_fence.rs (base T6 admission and T6.5 project_epoch writer-fence tests on PostgreSQL; it was deleted with the lease/fence trim but tests neither). - Restore the `project.get` read in api/crates/layerfs-api/tests/ machine_no_start.rs (a stopped machine answers it from records). - Remove the personal merge-tool config `.lww`. - Remove core/docs/issues/project-41/{lean-coordination,lean-gap-closure, lean-verification,mount-authority-lease}.md: the documentation policy allows only the GC spec in that directory, and they describe deferred lease/archive work as implemented. Production LOC: 214,073 -> 214,073 (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 --- .lww | 4 - .../layerfs-api/tests/machine_no_start.rs | 1 + .../issues/project-41/lean-coordination.md | 24 - .../issues/project-41/lean-gap-closure.md | 70 -- .../issues/project-41/lean-verification.md | 85 -- .../project-41/mount-authority-lease.md | 354 ------- .../tests/postgresql_gc_fence.rs | 977 ++++++++++++++++++ 7 files changed, 978 insertions(+), 537 deletions(-) delete mode 100644 .lww delete mode 100644 core/docs/issues/project-41/lean-coordination.md delete mode 100644 core/docs/issues/project-41/lean-gap-closure.md delete mode 100644 core/docs/issues/project-41/lean-verification.md delete mode 100644 core/docs/issues/project-41/mount-authority-lease.md create mode 100644 engine/crates/layerfs-persistence/tests/postgresql_gc_fence.rs diff --git a/.lww b/.lww deleted file mode 100644 index 28fc1927d4..0000000000 --- a/.lww +++ /dev/null @@ -1,4 +0,0 @@ -%include .gitignore -# The Git index is regenerated by every git command; keep the newer side -# whole instead of conflicting on the binary file. -/.git/index diff --git a/api/crates/layerfs-api/tests/machine_no_start.rs b/api/crates/layerfs-api/tests/machine_no_start.rs index 0de8ec970d..bbed32ab0a 100644 --- a/api/crates/layerfs-api/tests/machine_no_start.rs +++ b/api/crates/layerfs-api/tests/machine_no_start.rs @@ -101,6 +101,7 @@ fn every_read(home: &Path) { ("store.get", vec![("store", "shop")]), ("store.get", vec![("store", "shop"), ("with", "live")]), ("project.list", vec![]), + ("project.get", vec![("project", "shop/api")]), ("sandbox.list", vec![]), ("backup.list", vec![]), ] { diff --git a/core/docs/issues/project-41/lean-coordination.md b/core/docs/issues/project-41/lean-coordination.md deleted file mode 100644 index f41cc3ca03..0000000000 --- a/core/docs/issues/project-41/lean-coordination.md +++ /dev/null @@ -1,24 +0,0 @@ -# Lean model coordination - -## Dependency - -The Lean model (`formal/lean/gc-admission/`, issue #769 / #74) must follow the **final -`p4-closure` behavior**, not only the p4-integration tree. - -`p4-closure` (subagent `5bcb81cc`) adds: - -| Gap | Behavior the Lean model must include | -| --- | --- | -| G1 | the optional `home` path on the Store record's `machines.` entries; the bounded, ordered cross-home `PlaceView` merge; an unreachable home contributes no proof | -| G2 | the `store.repair_mount_holders` `archive` transition (+ `--prune`): export done rows to `gc-audit.jsonl`, no automatic delete | -| G4 | `preview` writes a retained `gc_intent` done row (`action = "preview"`) | - -## Status - -- The Lean plan (`3a7650ad`, `p4-lean-proof`) is in progress; it records this dependency - and is **blocked on `5bcb81cc`** for the final `State`/`Transitions`/`Invariants`. -- When `p4-closure` is final and, if merged, the PR #73 tree is rebuilt, update the Lean - model (the `machines..home` state, the `archive` transition, the preview done row) - before starting the proofs. -- The invariant set (8) and the `step_preserves` shape stay; only the state/transitions - gain the new fields/actions. diff --git a/core/docs/issues/project-41/lean-gap-closure.md b/core/docs/issues/project-41/lean-gap-closure.md deleted file mode 100644 index 4d01b32666..0000000000 --- a/core/docs/issues/project-41/lean-gap-closure.md +++ /dev/null @@ -1,70 +0,0 @@ -# Lean phase-3 gap closure - -The lean phase-3 GC authority is done for the core (0 new tables, 4 `gc_intent` -columns, ordered `MachineRecord.incarnation` / `SandboxRecord.generation`, -machine-level tombstone, retained `gc_intent` `done` row audit, compact -`Copy::Done`, per-machine 2.0 conversion). This note closes the four residual -gaps, all with lean (no new Store table). - -## G1. Shared-PostgreSQL cross-home proof - -Today `control::layerfs-store::place_view::from_home` reads only the caller's -home; on a shared PostgreSQL Store, another machine's rows stay -conservative-live. - -Lean closure: the Store record's `machines.` entry may record that -machine's own **`home` path**, an optional record field (no new table). The -control layer builds the PlaceView from the caller's home and every recorded -`home` it can read: each home's `MachineRecord.incarnation`, -`SandboxRecord.generation` and `machine//sandbox-retired/*.json` are -merged into one bounded view, ordered by the ordered token and capped at 4096 -places. An unreachable, relative or unrecorded home contributes no proof. The -worker/PG admission carries this merged view (the existing `place_view` -frame); no new table. - -Acceptance: a shared-PG Store with two machine homes proves the older -incarnation dead across homes; a Store whose second home is offline stays -conservative-live; the bound (4096 places) holds. - -## G2. Done-row audit retention - -Today done rows accumulate and no archive exists (design row 20, Low). - -Lean closure: add `store.repair_mount_holders` action `archive` that exports -the bounded done rows (default all, page-limited) to -`/log/gc-audit.jsonl` and then, only with an explicit `--prune`, -deletes the exported rows. Default is export-only, no auto-delete. Optional -later: a `(scope_kind, scope_id, state)` partial index; not required now. - -Acceptance: archive writes a JSONL and keeps the rows; `--prune` removes only -the exported pages; admission is unaffected. - -## G3. 2.0 conversion - -`tools/store_gc_convert.py` already implements the per-machine conversion -(copy the machine incarnation and Sandbox tombstones, export old audit rows -to JSONL, `--gone` for a missing machine, drop the three old tables only after -every machine converts, never touch the source file). Remaining work: a test -on a real old-format Store fixture and a documented operator runbook (the -`gc-runbook.md` already describes it). - -Acceptance: a 3-table Store fixture converts to the lean schema; `--gone` -covers a missing machine; the source is unchanged. - -## G4. Durable preview row - -Today preview is call-log only (design row 8, Medium). - -Lean closure: make `preview` write a retained `gc_intent` `done` row with -`action = "preview"`, `op = null`, the operator label and no owner columns, -reusing the release/done row path; no new table, no admission change. - -Acceptance: preview leaves a done row readable by the bounded `gc_intent_done` -read; repeated previews are idempotent per call; admission still filters -`state <> 'done'`. - -## Out of scope - -The live 6 branches / 331 retired reclamation is an operator run (settle, -release, `branch.remove`, `store.compact`), not code. The shared-PG operators -still declare `--gone` machines explicitly. diff --git a/core/docs/issues/project-41/lean-verification.md b/core/docs/issues/project-41/lean-verification.md deleted file mode 100644 index 5527c6de25..0000000000 --- a/core/docs/issues/project-41/lean-verification.md +++ /dev/null @@ -1,85 +0,0 @@ -# Lean verification of the GC / mount-admission lifecycle - -## Scope and verdict - -The lifecycle (Sandbox create/mount/unmount/close/force/remove × Store GC -`branch.remove`/`store.compact` × Machine incarnation/restart × Workspace mount -registration) is a state machine with a small set of safety invariants. Lean 4 can -formalize and prove the **abstract design** invariants (Level 2). It cannot prove the -Rust implementation (Level 3+) or the DB/FUSE/network semantics (Level 4). - -## The five levels (re-checked) - -| Level | Content | Work | Assurance | Do? | -| --- | --- | --- | --- | --- | -| 0 | spec only (types/state, no proofs) | days (~100–300 lines) | design clarified, no machine check | yes | -| 1 | executable model + property tests (`#eval`/`Plausible`) | 1–2 weeks | holds on tested states | yes | -| 2 | abstract model + safety invariants proven | 4–8 weeks (a first complete model + 8 invariants, with Lean experience) | design-level proofs | yes (recommended) | -| 3 | refinement (Rust ↔ Lean; Aeneas/Verus) | 1–3 person-months | code-level, only pure core functions | optional | -| 4 | end-to-end (DB transactions, crash, concurrency, FUSE) | years (seL4/CompCert scale) | strongest | no | - -Corrections to the earlier sketch: -- The Level 2 estimate of 2–6 weeks was optimistic; 4–8 weeks is realistic, and the - model will be revised while proving. -- "Liveness" is only weak: the operator is the only escape. "No automatic release" is - a **safety** property, not liveness. -- Level 3 with Aeneas/Verus is practical only for the pure functions - (`settle_place`, the ordered compare, the PlaceView merge); the async/worker/DB - parts are not. -- The model must abstract the transaction as atomic: a `Step` either commits or not. - -## The model (Level 0–2) - -### State - -- `Intent`: `state : Op | Done | Uncertain`, `op`, `ownerBoot`, `machineInc`, - `sandboxGen`, `leaseExpires`, `fence`, `evidence` -- `Machine`: `incarnation : Option Ordered` (the ordered token) -- `Sandbox`: `generation : Option Ordered`, `tombstone : Bool` -- `Store`: `branches`, `intents`, `retired` -- the machine / Sandbox / Store-GC lifecycles - -### Transitions - -Sandbox create/mount/unmount/close/force/remove; machine restart/restore; admission -(the place compare); `branch.remove`; `store.compact`; operator -preview/settle/release/archive. - -### The invariants - -1. A live mount is never reclaimed by `branch.remove`/`store.compact`. -2. Settle/release only on a provably Dead or explicitly Uncertain row. -3. Missing / old / unordered evidence is never Dead. -4. Ordered rule: current newer ⇒ Dead; current older ⇒ Uncertain; equal ⇒ Live. -5. Compact barrier: a live intent blocks `store.compact`. -6. Fence: a stale fencing token cannot release the row. -7. Audit: a retained `done` row survives `store.compact` (`Copy::Done`). -8. The operator is the only path to end an unprovable row (no automatic release). - -### Proof shape - -`theorem step_preserves (h : Inv s) : Inv (step op s)`, case analysis per transition; -`omega` for the ordered compare; the DB transaction assumed atomic. - -## What Lean does NOT cover - -- The Rust implementation (Level 3 only for the pure core functions) -- SQLite/PostgreSQL transactions, crash recovery, WAL -- Concurrency/linearizability of worker restarts -- FUSE/kernel behavior -- The live Store operator run (settle/release the 6, `store.compact` the 331) - -## Plan - -1. Lean 4 model + the 8 invariants (Level 0–2), reviewed against the design. -2. Property tests in Lean; align them with the Rust property/integration tests. -3. Optional Level 3 for `settle_place` and the PlaceView merge. -4. Document the mapping in `mount-authority-lease.md`. - -## Relation to the lean phase-3 design - -The lean design (0 new tables, 4 `gc_intent` columns, ordered -`MachineRecord.incarnation` / `SandboxRecord.generation`, machine-level tombstone, -retained `done` row audit, `Copy::Done`, per-machine 2.0 conversion) is the subject -of the invariants. Lean verifies the design; the Rust tests + FUSE verify the -implementation; the live operator run is out of scope. diff --git a/core/docs/issues/project-41/mount-authority-lease.md b/core/docs/issues/project-41/mount-authority-lease.md deleted file mode 100644 index 1463b43f92..0000000000 --- a/core/docs/issues/project-41/mount-authority-lease.md +++ /dev/null @@ -1,354 +0,0 @@ - - -# Mount admission authority, leasing, and recovery - -> **Iterative review branch:** `design-review`, forked from `design-phase1` head -> `12941806`. The phase-1 bridge is implemented on `design-phase1`; this copy -> records the converged phase-1/phase-3 split, the live-6 reality, and the -> VM/container authority split. The source is the `design-gc-authority` copy of -> this document. - -> **Status:** phase-3 implementation in progress (`p3-schema` -> -> `p3-intent` -> `p3-admission` -> `p3-writers` + `p3-lease` -> `p3-repair`). -> The additive schema, the typed contract, the place-first admission rule, the -> place writers (machine incarnation, Sandbox tombstone, worker-start reconcile), -> the lease heartbeat and the durable audit are implemented. The operator repair -> reaches a worker-hosted SQLite Store and a PostgreSQL Store through one typed -> holder view, and the Store-wide compact barrier is retained with tests. Mount -> intents do not yet carry a Sandbox generation, no call renews a lease and no -> production mount sets one, and the live-6 settlement remains open (§9). -> Target: the `gc_intent` `Mount` admission lock and the GC recovery path, -> layerfs-project#41. Read -> `LayerFS-GC-spec.md` (§4.4, §5, §10) and `gc-runbook.md` (§2, §4) first. -> Owner: LayerFS GC owner. This document supersedes the "close/by-sandbox release" -> idea (RV5 FAIL-1/2) and is the essential layer beneath the safe partial commits -> 17370050f4 / 7ab1040594 / 41788e2c25. - -## 1. The problem in one paragraph - -A `Mount` is a **durable, Branch-scoped Store admission lock**: `mount_intent` writes a -`gc_intent` row of kind `mount` (`engine/crates/layerfs-store-service/src/history/admission.rs:164`, -registered by `store/bind.rs:127`) whose owner is an **ephemeral Sandbox daemon**. Its -liveness authority is the holder process's **PID namespace + boot** (`OwnerView::dead`, -`engine/crates/layerfs-persistence/src/history/admission.rs:251-300`): local SQLite adopts -an intent from an earlier boot, but another PID namespace, a shared PostgreSQL Store, or -missing/unparsable owner evidence stays **conservatively LIVE forever**. There is no -lease, expiry, heartbeat, or fencing. `branch.remove` and `store.compact` refuse while a -mount exists (`classify`, same file:360-374; GC spec §5, line 428: **any** mount blocks a -Store-wide compact), so one unprovable Branch lock blocks **all** reclamation — the live -state (6 branches blocked, 331 retired, compact blocked) is the evidence. The only escape -is the operator's `gc_mark_uncertain` + `gc_release` (admission comment; GC runbook §2), -which is raw SQL, out of band, and not a first-class call. - -**Essential vs safe partial.** 17370050f4/7ab1040594/41788e2c25 are a *safe partial*: -7ab's forced remove ends **only the mount intents its own known Workspaces held** by -workspace id (`control/crates/layerfs-sandbox/src/mount_intents.rs`); it explicitly -refuses a folder/by-sandbox sweep and reports `left`. 41788's doctor -`mount_holders` (`control/crates/layerfs-control/src/doctor/mount_holders.rs`) *surfaces* -unmatched holders and reclaims only **recorded** Sandbox/Workspace mounts; its first line -is the design constraint: *"Missing records are evidence of a blocker, never authority to -release an admission."* None of them releases a live-owned forgotten Sandbox, a -private/place-null mount, or an ownerless/legacy row. They fix observation and the -graceful/forced path; they do not fix the authority/lease gap below. - -## 2. Goals, non-goals, invariants - -Goals: -- A provable owner death ends the lock automatically, per place, without an operator. -- An unprovable/ownerless lock has a **bounded**, auditable recovery path (first-class, - not raw SQL), and never auto-releases a possibly live mount. -- SQLite and shared PostgreSQL both work; the schema change is additive. -- One Store writer; no global sweeps; the forced-remove own-intent model stays. - -Non-goals: -- Not a folder/by-sandbox release (RV5 rejected; missing records are not authority). -- Not loosening the Store-wide compact barrier by default (see §4). -- Not changing the own-intent forced-remove model; not auto-releasing live private mounts. - -Invariants: -1. **Safety first:** a mount that may be live is never released automatically. -2. **Place is authority:** where a place exists, the machine incarnation and Sandbox - lifecycle decide liveness; the caller's namespace is only a fallback. -3. **No sweep:** only the owner, the place authority, or an explicit operator repair ends - an intent; every end is auditable. -4. **Additive, compat:** existing Stores keep working; old rows are migrated to - `uncertain`/legacy and need an explicit settle. - -## 3. Design - -### 3.1 Durable place / incarnation authority - -Record the authority on the mount intent and make admission consult it: - -| Field | Where | Purpose | -| --- | --- | --- | -| `machine_incarnation` | `gc_intent` (new), `MachineRecord`, worker start | Identifies the kernel/worker generation that placed the mount. A mount from an older incarnation of a machine is provably dead. | -| `sandbox_generation` | `gc_intent` (new), `SandboxRecord` (new), durable tombstone | Identifies the Sandbox incarnation; a tombstone/retired generation proves the Sandbox gone even after its home record is deleted. | -| `workspace_id` / `branch` | existing `gc_intent.workspace` / `branch` + `project` | The own-intent end key (7ab's `mount_intents::end`); never a path/folder. | -| `owner_runtime` / `owner_boot` | existing `gc_intent` | The fallback evidence for private/place-null mounts; unchanged. | - -Schema: additive columns on `gc_intent` (see `engine/crates/layerfs-persistence/sql/sqlite/gc.sql` -and `sql/postgresql/gc.sql`; the `GcIntent` struct at -`core/crates/layerfs-history/src/contract/records.rs:750`, builders `placed`/`owned` -at 847/861). A `machine_incarnation` authority row (per machine) and a -`sandbox_tombstone` marker (`sandbox`, `machine`, `generation`, `retired_ms`) follow the -existing `branch_retired`/`layer_stack_retired` marker pattern (GC spec §4.4). - -Admission (`OwnerView::dead` / `settleable` / `settle_dead` in -`engine/crates/layerfs-persistence/src/history/admission.rs:251-380`) becomes: - -1. If `owner_runtime`/`owner_boot` are present and the owner is provably dead by the - existing same-boot/same-namespace/local-SQLite rules: dead (unchanged). -2. Else, if the mount has a `machine_incarnation` and the Store's machine authority says - the machine's current incarnation differs: **dead** (this covers another PID - namespace and a rebooted machine; no `/proc` probing). -3. Else, if the mount's `sandbox_generation` is absent from the Sandbox authority or a - tombstone marks it retired at that machine incarnation: **dead** (the Sandbox is gone; - `missing records` are not proof, the **tombstone** is). -4. Else, if the place is shared PostgreSQL: compare the Store's per-machine incarnation - row; a machine's older incarnation is dead; another live machine's current incarnation - stays live. **No global sweep.** -5. Else (private/place-null/legacy): fall back to owner evidence; if still unprovable, - the lease/repair path (§3.2/§3.3), never auto-release. - -Worker-start reconcile: at machine-worker start (the launch/listen path that logs -`layerfs worker: launched`; `control/crates/layerfs-machine/...`), a **bounded, per-machine** -reconcile scans `gc_intent` where `machine = this` and `machine_incarnation` is older than -the current one (or the Sandbox tombstone says gone) and ends them once, with an audit row. -It never touches another machine's rows and never sweeps by folder. For local SQLite this -is the same adoption the current `dead` does for old boots, made explicit and audited; for -shared PG it is per-machine, keyed by the Store's incarnation row. - -Code touchpoints: -- `core/crates/layerfs-history/src/contract/records.rs` `GcIntent` fields/builders, - `MountHolders`/`GcHolder`. -- `engine/crates/layerfs-store-service/src/history/admission.rs` `mount_intent`, - `release_or_mark`; `store/bind.rs` register. -- `engine/crates/layerfs-persistence/src/history/admission.rs` `OwnerView::dead`, - `settleable`, `settle_dead`, `classify`; `owner_dead`. -- `engine/crates/layerfs-persistence/sql/{sqlite,postgresql}/gc.sql` and the `add_gc` - migration; `records`/`status` serialization. -- `control/crates/layerfs-machine/src/record.rs` + worker start (incarnation); - `control/crates/layerfs-sandbox/src/record` + remove/close (generation/tombstone). -- `control/crates/layerfs-sandbox/src/mount_intents.rs` (7ab own-intent end; keep it as - the graceful/forced path; the authority is the Store-side complement). -- `engine/crates/layerfs-daemon/src/control/registry.rs:157` `close_bound` (normal end). - -### 3.2 Lease / expiry / fencing for ownerless / place-null / private / legacy — deferred (#775) - -> **Deferred (#775).** This trimmed PR ships the ordered place authority -> (`machine_incarnation` + `sandbox_generation`) and the durable tombstone -> only. Lease expiry, heartbeat renewal, fencing tokens and the cross-home -> merge are deferred; the rationale below is kept for the follow-up. - -Add `lease_expires_ms` (and a fencing token, reuse `op_id`/generation) to `gc_intent` (or -a `gc_lease` side table). The owner (daemon or private Store-call workspace) renews the -lease on a heartbeat while it holds the mount. Admission treats an **expired lease as -uncertain, not dead by default**: a slow owner is not a dead owner. A first-class repair -(§3.3) or a policy-configured grace may release it. The fencing token prevents a -resurrected old owner from renewing/releasing a newer lease. - -SQLite: leases are local to the machine; the worker start can expire old leases safely -(same machine). PostgreSQL: the lease row is in the Store; a live owner on another machine -renews it; a machine's old leases expire only with its incarnation authority; no global -sweep. Migration: rows with no lease/place (including the live 6) are marked -`uncertain`/`legacy` and require an explicit settle; they are never auto-released. - -### 3.3 First-class recovery (not raw SQL) - -> The shipped subset of the recovery call is `list`, `preview`, `settle`, -> `release`, `settle_legacy` and a Branch-scoped `audit`. The jsonl -> `archive`/`--prune` export is deferred (#775). - -New Store-side call (proposed): `store repair mount-holders` (CLI/SDK), plus the -`gc_release` primitives behind it: - -- `--preview` lists holders (op, branch, workspace, sandbox, machine, owner evidence, - state/uncertain) — the same `mounts_detail` that already exists - (`engine/crates/layerfs-store-service/src/history/lookup.rs:70/142`), exposed in the - public short form and the doctor (41788). -- `--settle` marks a holder `uncertain`/`legacy` with an audit row; `--release` ends it - only after the preview, with an audit row; both idempotent, one writer, backup guidance. - Requires the operator role; the doctor reports but never auto-releases. -- The GC runbook's `gc_mark_uncertain`/`gc_release` becomes the implementation of this - call (no hand-edited `gc_intent`). The "Historical mount holders" procedure becomes the - call's manual mode. -- For the live 6: type them first with a **read-only** `gc_intent` query (owner_runtime, - owner_boot, sandbox/machine, state/uncertain; the runbook query) — the rows are - plausibly live-owned forgotten-sandbox/legacy, not proven stale. Then `--settle` / - `--release`; then `branch.remove` the 6 and `store.compact` the 331. -- Never auto-release a live/unproven admission; the repair is explicit and audited. - -### 3.4 The Store-wide compact barrier - -Current: `store.compact` refuses on **any** mount Store-wide (GC spec §5, line 428). This -is a correctness barrier for a single-generation Store rebuild: a live mount may hold a -Store reader/snapshot, and the rebuild/verify must not race it. - -Options: -- **A (recommended):** keep the barrier; make dead mounts clearable via §3.1/§3.2/§3.3. - The barrier is not the root; the leaked lock is. No policy change. -- **B:** scope compaction admission to the branches/layers the compact would reclaim, so - a mount of an unrelated Branch does not block. This needs a proof that the rebuild does - not read/race the mounted Branch (read-only mounts, snapshots); high risk, not in this - design. -- **C:** generation-based compaction (a new Store generation; mounts keep the old - generation; the old is retained). A larger redesign; out of scope. - -The essential point: with a sound place authority/lease and a first-class repair, A is -sufficient; until then, the barrier amplifies any leak. Revisit B only with a documented -read-only mount/generation model. - -### 3.5 Observability (secondary, but do it first) - -`MountsActive` already builds holders (`mounts_detail`, `lookup.rs:70/142`), but the -public short form omits `detail` (`api/crates/layerfs-api/src/calls/refusal.rs` -`value(refusal, detail=false)`; the Node SDK keeps `refusal.detail` only if the addon -sends it). Fix: include `detail.holders` for `MountsActive`/`InUse` (or make the CLI/SDK -request `--detail`); the daemon `control/failure.rs:162` drop is the daemon-control path, -not the live `branch.remove` path. Doctor 41788 surfaces the same rows. This is an -observability bug, not the lock lifetime; it is cheap and unblocks diagnosis. - -## 4. Tests - -Add or extend (the project's test layout): -- `engine/crates/layerfs-persistence/tests/admission.rs`: machine-incarnation death; - Sandbox tombstone; old boot; shared-PG per-machine; missing evidence; lease expiry; - never auto-release live. -- `engine/crates/layerfs-store-service/tests/admission.rs`: `mount_intent` place fields; - worker reconcile; `settle_dead`; `release_or_mark`. -- `api/crates/layerfs-api/tests/gc_calls.rs`: the forgotten-sandbox case - (`a_live_mount_intent_of_a_forgotten_sandbox_keeps_holding_the_store`, line ~387-409 at - ed9118) after the authority/repair; `branch.remove`; `store.compact`; the 6/331 shape; - `mount_holders`; `store repair` preview/settle/release; audit; idempotency. -- `control/crates/layerfs-control/tests/doctor_*`: `mount_holders` warning/fix; repair. -- `control/crates/layerfs-sandbox/tests`: forced-remove own intents; `left`; no folder - sweep; `WasGone`; same-boot lost Sandbox. -- `engine/crates/layerfs-persistence/tests/sqlite_compact_matrix.rs` and - `postgresql_gc_*`: mount + compact; authority; pre-GC migration. -- Scenarios: live private mount; same-boot lost sandbox; old-boot adoption; legacy/ - ownerless; shared PG; worker restart; compaction after repair; migration; no sweep. -- Build/test in a Workspace; note the current Sandbox network limitation (crates.io - index/fuser git timeout) in the test report. - -## 5. Compatibility and rollout - -- Additive schema (the GC runbook: additive migrations, no down migration; `add_gc`); - SQLite and PostgreSQL; old clients refuse/ignore new columns safely; one writer. -- Deployed ed9118: the live CLI/bundle/worker/SDK are all ed9118; the project tree at - 4e65ebbae is older; host HEAD f06180c5 has 7ab/41788. The design targets the source; - deploying 7ab/41788 alone does not release the 6. -- The live 6/331: the read-only query + the repair/migration is the operational path; - the authority prevents recurrence; the compact reclaims the 331 after the 6 are ended. -- Phases (converged review): - 1. **Phase 1 bridge (implemented)**: observability (short-form holders + doctor 41788) - and the explicit local-SQLite, per-Branch `store.repair_mount_holders` - preview/settle/release/settle_legacy. No schema; no automatic release. It does not - by itself reach a worker-hosted Docker SQLite Store or a PostgreSQL Store. - 3. **Phase 3 essential**: place/incarnation authority; caller namespace/boot fallback; - lease/fencing; additive schema/migration; worker/PG repair + audit; compact barrier - retained; tests/rollout/reclaim. The old phase-2 and phase-4 details are folded into - phase 3, not dropped. - 5. Compact barrier decision (retain A; revisit B/C only with a generation/read-only - mount design). - 6. Tests/rollout. -- The safe partial 7ab/41788 can land first (observation/own-intent); the essential - authority/lease/repair follows. - -## 6. Risks and open questions - -- Machine incarnation source: kernel boot id vs worker incarnation; native/macOS vs - docker kernel; shared PG per-machine authority; clock/expiry false death. -- Sandbox tombstone durability: home record vs Store marker; the removed sandboxes (the - live 6) have no tombstone; the migration must not treat missing records as death. -- Private/place-null mounts: owner evidence only; lease policy (uncertain vs release); - fencing; ownerless legacy. -- The operator/audit/backup path; the read-only `gc_intent` query policy; the 6 type - (live-owned vs legacy) must be proven before the repair. -- The compact barrier: retain vs scope vs generation; the Store rebuild/reader race. -- Schema/migration on PostgreSQL; the `UNIQUE(scope_kind, scope_id, owner_boot)` with - new columns; old clients; the ed9118/legacy rows. -- The `mount_intents::end` own-intent model and `sandbox.remove` (root permission) are - separate; do not conflate with the authority. -- The project tree's older `api` layout may lack the current `refusal.rs`/`mount_holders` - paths; port the partial first or map the equivalent path when implementing. - -## 7. First implementation step - -If only one thing lands next: **observability + the explicit repair/migration -bridge (phase 1)**. It is cheap, safe, and makes the essential work measurable; it does -not by itself unblock a worker-hosted Docker SQLite Store or a shared PostgreSQL Store. -The live 6 are on the Docker worker; phase 1 runs only where the local SQLite Store file -is reachable. Phase 3 (worker/PG repair plus place authority/lease) is required to -release them; the authority prevents recurrence, and the compact reclaims the 331 after -the 6 are ended. - -## 8. References - -- `core/docs/issues/project-41/LayerFS-GC-spec.md` §4.4, §5 (line 428), §10. -- `core/docs/issues/project-41/gc-runbook.md` §2 (operator), §4 (limits). -- `core/crates/layerfs-history/src/contract/records.rs:750` `GcIntent`; `placed`/`owned` - 847/861. -- `engine/crates/layerfs-persistence/src/history/admission.rs` `OwnerView`/`dead` - 251-300, `settle_dead` 342, `classify` 360, `conflicts` 452. -- `engine/crates/layerfs-store-service/src/history/admission.rs:164` `mount_intent`; - `store/bind.rs:127`; `history/lookup.rs:70/142` `mounts_detail`. -- `engine/crates/layerfs-persistence/sql/sqlite/gc.sql`, `sql/postgresql/gc.sql` - (`gc_intent` columns); `engine/crates/layerfs-daemon/src/control/registry.rs:157`. -- `control/crates/layerfs-sandbox/src/close.rs` (`WasGone`); `.../mount_intents.rs` - (7ab, not in this tree); `control/crates/layerfs-control/src/doctor/mount_holders.rs` - (41788); `api/crates/layerfs-api/src/calls/refusal.rs` (short form; upstream path). -- Live evidence: 6 stuck branches, 331 retired, compact blocked; ed9118 test - `api/crates/layerfs-api/tests/gc_calls.rs` ~387-409. - -## 9. Converged phase 1 / phase 3 (iterative review) - -**Phase 1 bridge (implemented on `design-phase1`).** The short form and doctor 41788 -surface holders without releasing anything. The explicit operator call -`store.repair_mount_holders` is local SQLite only and per Branch: `preview` changes no -intent; `settle` marks one named `op` uncertain; `release` requires that same named `op` -to be uncertain already, so settle and release are two explicit steps (preview, settle, -release); and `settle_legacy` marks only rows with no owner or place evidence. It is not -automatic and does not touch the live Store. Phase 1 audit is the CLI call log plus the -`gc_intent` state change; the durable operator audit row is phase 3 and is not claimed -here. Phase 3 keeps that row as a retained `gc_intent` `done` row (the action, the operator -label and the bounded evidence), and a fenced heartbeat extends a lease without ever -shortening it; the preview is the CLI call log only. The GC spec §5.1 records both. The phase-1 call cannot reach the live Docker worker -Store from a host home, so it is a bridge and proof, not the operational release of the -6. - -**Phase 3 essential.** The place authority is the primary liveness proof: -`machine_incarnation`, `sandbox_generation` and a durable `sandbox_tombstone`; admission -consults place first and falls back to the existing caller PID-namespace/boot evidence -only for private/place-null rows. A dead place ends the intent; an absent home record is -never death. Lease expiry is **uncertain**, never auto-dead; the owner renews, and a -fencing token (reusing `op_id`/generation) prevents an old owner from renewing or -releasing a newer lease. The schema is additive on SQLite and PostgreSQL; old rows are -marked uncertain/legacy and require an explicit settle. The operator call is extended to -the worker Store and PostgreSQL through one typed holder view, with a durable audit row; -the doctor still only reports, and its worker-side read forwards the same authority -fields. The Store-wide compact barrier is retained and tested against a live and an -uncertain authority. - -**VM/container split.** On native, the kernel boot/incarnation is the place authority. On -Docker/VM, the worker/container generation is the authority, not the host kernel boot: a -restarted worker or VM proves an old placement dead even when the host kernel did not -reboot. A shared PostgreSQL Store carries a per-machine incarnation row; another live -machine current incarnation stays live, and there is no global sweep. The caller PID -namespace is only a fallback for place-null/private intents; another namespace is never -assumed dead. - -**Live 6/331.** The 6 are plausibly live-owned forgotten Docker worker mounts, not proven -legacy. Phase 3 first types them with a read-only `gc_intent` query, then settles/releases -them with operator authority on the worker Store; only then can `branch.remove` end the -6 and `store.compact` reclaim the 331. Phase 1 alone cannot do this. - -**Remaining essential gaps.** The worker-start reconcile and the machine-incarnation -and Sandbox-tombstone writers are in place (`p3-writers`); operator repair reaches a -worker-hosted SQLite Store and a PostgreSQL Store, the typed holder view covers the -worker path, and the Store-wide compact barrier is retained with tests (`p3-repair`). -Mount intents still do not carry a Sandbox generation (the daemon and forced-remove -plumbing), no call renews a lease and no production mount sets one, and the live-6/331 -settlement has not been run. The phase-1 bridge never releases a live-looking holder -automatically. - diff --git a/engine/crates/layerfs-persistence/tests/postgresql_gc_fence.rs b/engine/crates/layerfs-persistence/tests/postgresql_gc_fence.rs new file mode 100644 index 0000000000..5edfe9ccdb --- /dev/null +++ b/engine/crates/layerfs-persistence/tests/postgresql_gc_fence.rs @@ -0,0 +1,977 @@ +//! PostgreSQL runtime evidence for the GC admission and epoch paths that +//! shipped compile-only: T6's `gc_intent` admission and T6.5's writer-side +//! `project_epoch` fence, including the `SELECT ... FOR SHARE` re-check. +//! +//! The tests drive `PostgresHandles` through the public `HistoryCatalog` +//! methods. A trigger stands in for a removal marker that bumps the epoch +//! inside the writer's own transaction, which is exactly where the fence's +//! re-read runs; a deleted epoch row stands in for a compacted-away project. +//! +//! Needs `LAYERFS_TEST_POSTGRES_URL`; NOT_RUN without it. +mod support; + +use layerfs_history::error::{HistoryError, Missing}; +use layerfs_history::records::{ + ForkRequest, ForkSource, GcDeletion, GcIntent, GcIntentKind, GcScopeKind, PathRemovalKind, + PathRemovalRequest, +}; +use layerfs_history::{CatalogId, HistoryCatalog, LayerStackId}; +use support::pg::{ + commit, commit_request, counts, epoch, layer_request, merge_request, project, publish, url, + Schema, +}; +use support::root; +use support::{branch_id, name}; + +const CURSOR: [u8; 32] = [78; 32]; + +/// Every test opens its own catalog identity, as a real Store does: the +/// PostgreSQL advisory keys are database-wide, so two tests that shared a +/// binding could see each other's intents while running in parallel. The +/// process id keeps a second run of this file on the same database from +/// sharing them too. +fn binding(tag: &str) -> Vec { + format!("postgresql-gc-fence-{tag}-{}", std::process::id()).into_bytes() +} + +fn op(tag: u8) -> [u8; 16] { + [tag; 16] +} + +fn mount( + stack: layerfs_history::LayerStackId, + branch: layerfs_history::BranchId, + tag: u8, +) -> GcIntent { + GcIntent::shared( + op(tag), + GcIntentKind::Mount, + GcScopeKind::Branch, + branch.as_slice(), + ) + .in_project(stack.as_slice()) + .named(Some("proj"), Some("work")) + .placed( + Some([tag; 32]), + Some(&format!("sandbox-{tag}")), + Some(&format!("machine-{tag}")), + ) + .owned(Some("runtime-a"), Some(&format!("boot-{tag}"))) +} + +fn init(stack: layerfs_history::LayerStackId, tag: u8) -> GcIntent { + GcIntent::shared( + op(tag), + GcIntentKind::Init, + GcScopeKind::Project, + stack.as_slice(), + ) + .named(Some("proj"), None) + .with_phase(Some("init")) + .owned(Some("runtime-a"), Some(&format!("boot-{tag}"))) +} + +fn merge(stack: layerfs_history::LayerStackId, tag: u8) -> GcIntent { + GcIntent::shared( + op(tag), + GcIntentKind::Merge, + GcScopeKind::Project, + stack.as_slice(), + ) + .named(Some("proj"), Some("merged")) + .with_phase(Some("merge")) + .owned(Some("runtime-a"), Some(&format!("boot-{tag}"))) +} + +fn removal(stack: layerfs_history::LayerStackId, body: u8) -> GcIntent { + GcIntent::operation( + op(body), + GcIntentKind::Removal, + GcScopeKind::Project, + stack.as_slice(), + ) + .named(Some("proj"), None) +} + +fn path_request(stack: layerfs_history::LayerStackId) -> PathRemovalRequest { + PathRemovalRequest { + stack, + path: b"a.txt".to_vec(), + removed_ms: 1_000, + } +} + +fn hex16(bytes: &[u8; 16]) -> String { + let mut out = String::with_capacity(32); + for byte in bytes { + out.push_str(&format!("{byte:02x}")); + } + out +} + +/// A trigger that bumps the project epoch before each inserted row, standing +/// in for a removal marker that wins the race inside the writer's transaction. +fn bump_trigger(admin: &mut postgres::Client, table: &str) { + admin + .batch_execute(&format!( + "CREATE OR REPLACE FUNCTION g6a_epoch_race() RETURNS trigger LANGUAGE plpgsql AS $$ \ + BEGIN UPDATE project_epoch SET epoch=epoch+1 WHERE layer_stack_id=NEW.layer_stack_id; RETURN NEW; END $$; \ + CREATE TRIGGER g6a_epoch_race BEFORE INSERT ON \"{table}\" FOR EACH ROW \ + EXECUTE FUNCTION g6a_epoch_race();" + )) + .unwrap(); +} + +fn drop_trigger(admin: &mut postgres::Client) { + admin + .batch_execute( + "DROP TRIGGER IF EXISTS g6a_epoch_race ON \"commit\"; \ + DROP TRIGGER IF EXISTS g6a_epoch_race ON layer; \ + DROP FUNCTION IF EXISTS g6a_epoch_race();", + ) + .unwrap(); +} + +#[test] +fn a_normal_commit_publish_and_merge_leave_the_epoch_alone() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_normal"); + let binding = binding("fence_normal"); + let handles = schema.create(&binding, CURSOR); + let (shop, work, genesis) = project(&handles.history, 1); + + let first = commit(&handles.history, work, 5); + assert_eq!( + epoch(&mut schema.admin(), shop), + 0, + "a Commit does not bump the epoch" + ); + let layer = publish(&handles.history, shop, work); + assert_eq!(layer.parent, Some(genesis)); + assert_eq!( + epoch(&mut schema.admin(), shop), + 0, + "a published Layer does not bump it" + ); + let merged = handles + .history + .merge_branch(&merge_request( + &handles.history, + shop, + work, + first.id, + genesis, + 60, + )) + .unwrap(); + assert_eq!(merged.branch.name.as_str(), "merged"); + assert_eq!( + epoch(&mut schema.admin(), shop), + 0, + "a merge does not bump it" + ); + assert_eq!(counts(&mut schema.admin()), (2, 2)); +} + +#[test] +fn a_missing_epoch_row_refuses_every_writer_with_conflict() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_missing"); + let binding = binding("fence_missing"); + let handles = schema.create(&binding, CURSOR); + let (shop, work, genesis) = project(&handles.history, 1); + let first = commit(&handles.history, work, 5); + let side_request = merge_request(&handles.history, shop, work, first.id, genesis, 61); + let before = counts(&mut schema.admin()); + + schema + .admin() + .execute( + "DELETE FROM project_epoch WHERE layer_stack_id=$1", + &[&shop.as_slice()], + ) + .unwrap(); + + let refused = handles + .history + .commit_branch(&commit_request(&handles.history, work, root(6))) + .unwrap_err(); + assert!( + matches!(refused, HistoryError::Conflict("project epoch")), + "{refused:?}" + ); + let refused = handles + .history + .add_layer(&layer_request(&handles.history, shop, work)) + .unwrap_err(); + assert!( + matches!(refused, HistoryError::Conflict("project epoch")), + "{refused:?}" + ); + let refused = handles.history.merge_branch(&side_request).unwrap_err(); + assert!( + matches!(refused, HistoryError::Conflict("project epoch")), + "{refused:?}" + ); + + assert_eq!(counts(&mut schema.admin()), before, "no partial write"); + let snapshot = handles.history.branch_snapshot(work).unwrap().unwrap(); + assert_eq!(snapshot.branch.head_commit, Some(first.id)); + assert_eq!( + handles + .history + .layer_stack(shop) + .unwrap() + .unwrap() + .head_layer, + genesis + ); + assert!(handles.history.branch(merged_branch()).unwrap().is_none()); +} + +/// The Branch id `merge_request` creates for the merge. +fn merged_branch() -> layerfs_history::BranchId { + layerfs_history::BranchId::from_authority([9; 16]) +} + +#[test] +fn an_epoch_change_during_a_commit_is_detected_and_rolled_back() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_trigger_commit"); + let binding = binding("fence_trigger_commit"); + let handles = schema.create(&binding, CURSOR); + let (shop, work, _genesis) = project(&handles.history, 1); + + bump_trigger(&mut schema.admin(), "commit"); + let refused = handles + .history + .commit_branch(&commit_request(&handles.history, work, root(5))) + .unwrap_err(); + assert!( + matches!(refused, HistoryError::Conflict("project epoch")), + "{refused:?}" + ); + assert_eq!(counts(&mut schema.admin()).0, 0, "the Commit rolled back"); + assert_eq!( + epoch(&mut schema.admin(), shop), + 0, + "the fake bump rolled back too" + ); + assert!(handles + .history + .branch(work) + .unwrap() + .unwrap() + .head_commit + .is_none()); + + drop_trigger(&mut schema.admin()); + let record = commit(&handles.history, work, 5); + assert_eq!(record.stack, shop); + assert_eq!(epoch(&mut schema.admin(), shop), 0); + assert_eq!( + handles.history.branch(work).unwrap().unwrap().head_commit, + Some(record.id) + ); +} + +#[test] +fn an_epoch_change_during_a_publish_is_detected_and_rolled_back() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_trigger_layer"); + let binding = binding("fence_trigger_layer"); + let handles = schema.create(&binding, CURSOR); + let (shop, work, genesis) = project(&handles.history, 1); + let _first = commit(&handles.history, work, 5); + let before = counts(&mut schema.admin()); + + bump_trigger(&mut schema.admin(), "layer"); + let refused = handles + .history + .add_layer(&layer_request(&handles.history, shop, work)) + .unwrap_err(); + assert!( + matches!(refused, HistoryError::Conflict("project epoch")), + "{refused:?}" + ); + assert_eq!(counts(&mut schema.admin()), before, "the Layer rolled back"); + assert_eq!(epoch(&mut schema.admin(), shop), 0); + assert_eq!( + handles + .history + .layer_stack(shop) + .unwrap() + .unwrap() + .head_layer, + genesis + ); + + drop_trigger(&mut schema.admin()); + let layer = publish(&handles.history, shop, work); + assert_eq!(layer.parent, Some(genesis)); + assert_eq!(counts(&mut schema.admin()).1, before.1 + 1); +} + +#[test] +fn an_epoch_change_during_a_merge_is_detected_and_rolled_back() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_trigger_merge"); + let binding = binding("fence_trigger_merge"); + let handles = schema.create(&binding, CURSOR); + let (shop, work, genesis) = project(&handles.history, 1); + let first = commit(&handles.history, work, 5); + let request = merge_request(&handles.history, shop, work, first.id, genesis, 62); + let before = counts(&mut schema.admin()); + + bump_trigger(&mut schema.admin(), "commit"); + let refused = handles.history.merge_branch(&request).unwrap_err(); + assert!( + matches!(refused, HistoryError::Conflict("project epoch")), + "{refused:?}" + ); + assert_eq!(counts(&mut schema.admin()), before, "the merge rolled back"); + assert_eq!(epoch(&mut schema.admin(), shop), 0); + assert!(handles.history.branch(merged_branch()).unwrap().is_none()); + + drop_trigger(&mut schema.admin()); + let merged = handles.history.merge_branch(&request).unwrap(); + assert_eq!(merged.branch.name.as_str(), "merged"); + assert_eq!(counts(&mut schema.admin()).0, before.0 + 1); +} + +#[test] +fn a_mount_blocks_all_three_removals_until_released() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "admission_mount"); + let binding = binding("admission_mount"); + let handles = schema.create(&binding, CURSOR); + let (project_id, branch, _genesis) = project(&handles.history, 1); + let mount = mount(project_id, branch, 1); + handles.history.gc_register(&mount).unwrap(); + + let refusal = handles + .history + .gc_remove_branch(branch, 1_000, &removal(project_id, 2)) + .unwrap_err(); + let HistoryError::MountsActive(state) = &refusal else { + panic!("{refusal:?}"); + }; + assert_eq!(state.holders.len(), 1); + assert_eq!(state.holders[0].kind, GcIntentKind::Mount); + assert_eq!(state.holders[0].sandbox.as_deref(), Some("sandbox-1")); + assert_eq!(state.holders[0].machine.as_deref(), Some("machine-1")); + assert_eq!( + state.holders[0].workspace.as_deref(), + Some("01".repeat(32).as_str()) + ); + assert_eq!(state.holders[0].op, hex16(&op(1))); + + assert!(matches!( + handles + .history + .gc_delete_stack(project_id, 1_000, &removal(project_id, 3)) + .unwrap_err(), + HistoryError::MountsActive(_) + )); + assert!(matches!( + handles + .history + .gc_remove_path(&path_request(project_id), &removal(project_id, 4)) + .unwrap_err(), + HistoryError::MountsActive(_) + )); + + let listed = handles + .history + .gc_intents(GcScopeKind::Branch, branch.as_slice()) + .unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].kind, GcIntentKind::Mount); + handles.history.gc_release(&op(1)).unwrap(); + assert!(handles + .history + .gc_intents(GcScopeKind::Branch, branch.as_slice()) + .unwrap() + .is_empty()); + handles.history.gc_release(&op(1)).unwrap(); + + let outcome = handles + .history + .gc_remove_path(&path_request(project_id), &removal(project_id, 4)) + .unwrap(); + assert_eq!(outcome.kind, PathRemovalKind::Removed); + assert_eq!(epoch(&mut schema.admin(), project_id), 1); + handles + .history + .gc_remove_branch(branch, 2_000, &removal(project_id, 2)) + .unwrap(); + assert_eq!(epoch(&mut schema.admin(), project_id), 2); + assert!(matches!( + handles + .history + .gc_delete_stack(project_id, 3_000, &removal(project_id, 3)) + .unwrap(), + GcDeletion::Marked { deleted_ms: 3_000 } + )); + assert_eq!(epoch(&mut schema.admin(), project_id), 3); +} + +#[test] +fn init_and_merge_are_project_holders() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "admission_shared"); + let binding = binding("admission_shared"); + let handles = schema.create(&binding, CURSOR); + let (project_id, _branch, _genesis) = project(&handles.history, 1); + + handles.history.gc_register(&init(project_id, 5)).unwrap(); + let refusal = handles + .history + .gc_delete_stack(project_id, 1_000, &removal(project_id, 6)) + .unwrap_err(); + let HistoryError::BusyOp(state) = &refusal else { + panic!("an Init is a Busy operation, not a mount: {refusal:?}"); + }; + assert_eq!(state.kind, GcIntentKind::Init); + assert_eq!(state.phase.as_deref(), Some("init")); + handles.history.gc_release(&op(5)).unwrap(); + + handles.history.gc_register(&merge(project_id, 7)).unwrap(); + let refusal = handles + .history + .gc_remove_path(&path_request(project_id), &removal(project_id, 8)) + .unwrap_err(); + let HistoryError::BusyOp(state) = &refusal else { + panic!("a merge is a Busy operation, not a mount: {refusal:?}"); + }; + assert_eq!(state.kind, GcIntentKind::Merge); + assert_eq!(state.phase.as_deref(), Some("merge")); + handles.history.gc_release(&op(7)).unwrap(); + + handles + .history + .gc_remove_path(&path_request(project_id), &removal(project_id, 8)) + .unwrap(); +} + +#[test] +fn a_live_operation_is_busy_and_an_uncertain_owner_is_unresolved() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "admission_op"); + let binding = binding("admission_op"); + let handles = schema.create(&binding, CURSOR); + let (project_id, branch, _genesis) = project(&handles.history, 1); + let catalog = CatalogId::derive(&binding).unwrap(); + let compaction = GcIntent::operation( + op(9), + GcIntentKind::Compaction, + GcScopeKind::Store, + catalog.as_slice(), + ) + .owned(Some("runtime-a"), Some("boot-9")) + .with_phase(Some("mark")); + handles.history.gc_register(&compaction).unwrap(); + + let refusal = handles + .history + .gc_remove_branch(branch, 1_000, &removal(project_id, 10)) + .unwrap_err(); + let HistoryError::BusyOp(state) = &refusal else { + panic!("{refusal:?}"); + }; + assert_eq!(state.kind, GcIntentKind::Compaction); + assert_eq!(state.entity, "store"); + assert_eq!(state.phase.as_deref(), Some("mark")); + assert_eq!(state.op, hex16(&op(9))); + + assert!(matches!( + handles + .history + .gc_register(&mount(project_id, branch, 11)) + .unwrap_err(), + HistoryError::BusyOp(_) + )); + + handles.history.gc_mark_uncertain(&op(9)).unwrap(); + let refusal = handles + .history + .gc_remove_branch(branch, 1_000, &removal(project_id, 10)) + .unwrap_err(); + assert!(matches!(refusal, HistoryError::Unresolved(_))); + + handles.history.gc_release(&op(9)).unwrap(); + handles + .history + .gc_remove_branch(branch, 2_000, &removal(project_id, 10)) + .unwrap(); +} + +#[test] +fn a_removal_first_refuses_the_later_commit_and_writes_nothing() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_removal_first"); + let binding = binding("fence_removal_first"); + let handles = schema.create(&binding, CURSOR); + let (shop, work, _genesis) = project(&handles.history, 1); + let _first = commit(&handles.history, work, 5); + let before = counts(&mut schema.admin()); + + // Capture the request while the Branch is still visible; the removal then + // wins, and the filtered Branch resolution hides the retired Branch before + // the fence opens, so the write is refused and leaves no Commit behind. + let request = commit_request(&handles.history, work, root(6)); + handles.history.mark_branch_removed(work, 1_000).unwrap(); + assert_eq!( + epoch(&mut schema.admin(), shop), + 1, + "the marker bumped the epoch once" + ); + + let refused = handles.history.commit_branch(&request).unwrap_err(); + assert!( + matches!( + refused, + HistoryError::Missing(Missing::Branch) | HistoryError::Conflict("project epoch") + ), + "{refused:?}" + ); + assert_eq!(counts(&mut schema.admin()), before); +} + +/// Runs `run` while this test holds `project_epoch` against readers, waits +/// until the writer blocks on that lock (its fence read), then retires `stack` +/// in the holding transaction before releasing it. The writer's resource +/// pre-read and its fence read therefore straddle a committed removal — the +/// exact window the fix closes. +fn retire_under_fence(schema: &Schema, stack: LayerStackId, run: F) -> T +where + F: FnOnce() -> T + Send + 'static, + T: Send + 'static, +{ + let mut admin = schema.admin(); + admin + .batch_execute("BEGIN; LOCK TABLE project_epoch IN ACCESS EXCLUSIVE MODE") + .expect("hold the epoch against readers"); + let writer = std::thread::spawn(run); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + loop { + let waiting: i64 = admin + .query_one( + "SELECT count(*) FROM pg_locks l \ + WHERE l.relation = 'project_epoch'::regclass AND NOT l.granted", + &[], + ) + .expect("lock waiters") + .get(0); + if waiting > 0 { + break; + } + assert!( + std::time::Instant::now() < deadline, + "the writer never reached its fence read" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + admin + .execute( + "INSERT INTO layer_stack_retired(layer_stack_id, deleted_ms) VALUES ($1, 1)", + &[&stack.as_slice()], + ) + .expect("retire the stack"); + admin + .execute( + "INSERT INTO branch_retired(branch_id, removed_ms) \ + SELECT branch_id, 1 FROM branch WHERE layer_stack_id = $1 \ + ON CONFLICT DO NOTHING", + &[&stack.as_slice()], + ) + .expect("retire the branches"); + admin + .execute( + "UPDATE project_epoch SET epoch = epoch + 1 WHERE layer_stack_id = $1", + &[&stack.as_slice()], + ) + .expect("bump the epoch"); + admin.batch_execute("COMMIT").expect("release the epoch"); + writer.join().expect("the writer thread") +} + +fn branch_rows(schema: &Schema) -> i64 { + schema + .admin() + .query_one("SELECT count(*) FROM branch", &[]) + .unwrap() + .get(0) +} + +/// Branch rows a caller can still see: `branch.remove` is a soft marker, so a +/// retired Branch keeps its row until compaction. +fn live_branch_rows(schema: &Schema) -> i64 { + schema + .admin() + .query_one( + "SELECT count(*) FROM branch b \ + WHERE NOT EXISTS (SELECT 1 FROM branch_retired r WHERE r.branch_id = b.branch_id)", + &[], + ) + .unwrap() + .get(0) +} + +/// Finding 4: the fence opens before the Branch read, so a Branch retired +/// between the write's resource read and its fence is visible on the re-read. +/// Reading the Branch first let the Commit land on a retired Branch. +#[test] +fn a_commit_retired_in_the_fence_window_never_lands() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_window_commit"); + let binding = binding("fence_window_commit"); + let handles = std::sync::Arc::new(schema.create(&binding, CURSOR)); + let (shop, work, _genesis) = project(&handles.history, 1); + let _first = commit(&handles.history, work, 5); + let request = commit_request(&handles.history, work, root(6)); + let before = counts(&mut schema.admin()); + + let writer = handles.clone(); + let refused = retire_under_fence(&schema, shop, move || { + writer.history.commit_branch(&request) + }) + .expect_err("a Commit cannot land on a Branch retired in the window"); + assert!( + matches!(refused, HistoryError::Missing(Missing::Branch)), + "{refused:?}" + ); + assert_eq!( + counts(&mut schema.admin()), + before, + "no Commit row was written" + ); +} + +/// The same window on the Layer publication: the stack is re-read after the +/// fence, so a retired stack is `Missing` instead of being extended. +#[test] +fn a_publish_retired_in_the_fence_window_never_lands() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_window_publish"); + let binding = binding("fence_window_publish"); + let handles = std::sync::Arc::new(schema.create(&binding, CURSOR)); + let (shop, work, _genesis) = project(&handles.history, 1); + let _first = commit(&handles.history, work, 5); + let request = layer_request(&handles.history, shop, work); + let before = counts(&mut schema.admin()); + + let writer = handles.clone(); + let refused = retire_under_fence(&schema, shop, move || writer.history.add_layer(&request)) + .expect_err("a Layer cannot extend a stack retired in the window"); + assert!(matches!(refused, HistoryError::Missing(_)), "{refused:?}"); + assert_eq!( + counts(&mut schema.admin()), + before, + "no Layer row was written" + ); +} + +#[test] +fn a_merge_retired_in_the_fence_window_never_starts() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_window_merge"); + let binding = binding("fence_window_merge"); + let handles = std::sync::Arc::new(schema.create(&binding, CURSOR)); + let (shop, work, genesis) = project(&handles.history, 1); + let first = commit(&handles.history, work, 5); + let request = merge_request(&handles.history, shop, work, first.id, genesis, 60); + let before = counts(&mut schema.admin()); + + let writer = handles.clone(); + let refused = retire_under_fence(&schema, shop, move || writer.history.merge_branch(&request)) + .expect_err("a merge cannot start on a stack retired in the window"); + assert!(matches!(refused, HistoryError::Missing(_)), "{refused:?}"); + assert_eq!( + counts(&mut schema.admin()), + before, + "no merge Commit or Branch was written" + ); +} + +#[test] +fn a_fork_retired_in_the_fence_window_never_starts() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_window_fork"); + let binding = binding("fence_window_fork"); + let handles = std::sync::Arc::new(schema.create(&binding, CURSOR)); + let (shop, _work, genesis) = project(&handles.history, 1); + let request = ForkRequest { + stack: shop, + branch: branch_id(7), + name: name("late"), + source: ForkSource::Layer(genesis), + }; + let before = branch_rows(&schema); + + let writer = handles.clone(); + let refused = retire_under_fence(&schema, shop, move || writer.history.fork(&request)) + .expect_err("a fork cannot start on a stack retired in the window"); + assert!(matches!(refused, HistoryError::Missing(_)), "{refused:?}"); + assert_eq!(branch_rows(&schema), before, "no Branch row was written"); +} + +/// Finding 4: fork now takes the project fence at all; a project whose epoch +/// row is gone is `Conflict`, like every other writer. +#[test] +fn a_fork_without_a_project_epoch_is_conflict() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_fork_missing"); + let binding = binding("fence_fork_missing"); + let handles = schema.create(&binding, CURSOR); + let (shop, _work, genesis) = project(&handles.history, 1); + let request = ForkRequest { + stack: shop, + branch: branch_id(7), + name: name("late"), + source: ForkSource::Layer(genesis), + }; + schema + .admin() + .execute( + "DELETE FROM project_epoch WHERE layer_stack_id=$1", + &[&shop.as_slice()], + ) + .unwrap(); + let refused = handles.history.fork(&request).unwrap_err(); + assert!( + matches!(refused, HistoryError::Conflict("project epoch")), + "{refused:?}" + ); +} + +/// Finding 11: `project.delete` takes the Store key shared and only its own +/// project key exclusively. A mount of another project must not refuse it, and +/// the removal must still refuse a mount of its own project. +#[test] +fn a_project_removal_does_not_take_the_store_key_exclusively() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "keys_project"); + let binding = binding("keys_project"); + let handles = schema.create(&binding, CURSOR); + let (shop_a, work_a, _) = project(&handles.history, 1); + let (shop_b, _work_b, _) = project(&handles.history, 2); + + // A live mount in project A takes the Store key shared. Project names are + // unique in a Store, so the two projects carry different names. + let mount_a = mount(shop_a, work_a, 1).named(Some("project-a"), Some("work-a")); + handles.history.gc_register(&mount_a).unwrap(); + // Deleting project B registers Store shared + project B exclusive. + let removal_b = removal(shop_b, 2).named(Some("project-b"), None); + handles.history.gc_register(&removal_b).unwrap(); + // The removal's own project is excluded... + let mount_b = mount(shop_b, branch_id(2), 3).named(Some("project-b"), Some("work-b")); + assert!(matches!( + handles.history.gc_register(&mount_b).unwrap_err(), + HistoryError::BusyOp(_) | HistoryError::Busy + )); + // ...but another project's mount is not: the Store key stayed shared. + let mount_a2 = mount(shop_a, work_a, 4).named(Some("project-a"), Some("work-a")); + handles.history.gc_register(&mount_a2).unwrap(); + // The delete itself still admits with the other project mounted. + let marked = handles + .history + .gc_delete_stack(shop_b, 1_000, &removal_b) + .unwrap(); + assert!(matches!(marked, GcDeletion::Marked { deleted_ms: 1_000 })); + handles.history.gc_release(&op(1)).unwrap(); + handles.history.gc_release(&op(2)).unwrap(); + handles.history.gc_release(&op(4)).unwrap(); +} + +/// Finding 8: PostgreSQL checks `catalog_incarnation` in every write +/// transaction, so a session opened at `G` cannot publish at `G` after a swap +/// has installed `G + 1`. The refused transaction writes nothing, and a fresh +/// open at the installed generation works. +#[test] +fn a_write_from_a_session_opened_before_the_swap_is_stale() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_generation"); + let binding = binding("fence_generation"); + let handles = schema.create(&binding, CURSOR); + let (shop, work, _) = project(&handles.history, 1); + let first = commit(&handles.history, work, 5); + // The client reads at `G` build the request before the swap, as a real + // caller does; the write that runs after it is the one under test. + let request = commit_request(&handles.history, work, root(6)); + let before = counts(&mut schema.admin()); + + // Stand in for compaction's Phase B swap: install `G + 1`. + schema + .admin() + .execute( + "UPDATE history_meta SET catalog_incarnation=catalog_incarnation+1 WHERE id=1", + &[], + ) + .unwrap(); + + let refused = handles.history.commit_branch(&request).unwrap_err(); + assert!( + matches!(refused, HistoryError::StaleStore), + "a Commit at the old generation is StaleStore: {refused:?}" + ); + let refused = handles + .history + .fork(&ForkRequest { + stack: shop, + branch: branch_id(9), + name: name("stale"), + source: ForkSource::Commit { + branch: work, + commit: first.id, + }, + }) + .unwrap_err(); + assert!( + matches!(refused, HistoryError::StaleStore), + "a fork at the old generation is StaleStore: {refused:?}" + ); + assert_eq!(counts(&mut schema.admin()), before, "nothing was written"); + + // Reopening at the installed generation is the documented recovery. + let fresh = schema.open(&binding, CURSOR).unwrap(); + let landed = fresh + .history + .commit_branch(&commit_request(&fresh.history, work, root(6))) + .unwrap(); + assert!(matches!( + landed, + layerfs_history::records::CommitOutcome::Committed { .. } + )); +} + +/// F44R2-1: the same generation fence guards reads. A session opened at `G` +/// cannot render a project or a Branch at `G` after a swap installed `G + 1`: +/// the `Mode::Read` transaction and the single-statement reads join +/// `history_meta.catalog_incarnation` and answer `StaleStore`, and a fresh +/// open at the installed generation reads them. +#[test] +fn a_read_from_a_session_opened_before_the_swap_is_stale() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "fence_read_generation"); + let binding = binding("fence_read_generation"); + let handles = schema.create(&binding, CURSOR); + let (shop, work, _) = project(&handles.history, 1); + commit(&handles.history, work, 5); + + // Stand in for compaction's Phase B swap: install `G + 1`. + schema + .admin() + .execute( + "UPDATE history_meta SET catalog_incarnation=catalog_incarnation+1 WHERE id=1", + &[], + ) + .unwrap(); + + // A read transaction: the check rides in its BEGIN batch. + let refused = handles.history.layer_stack(shop).unwrap_err(); + assert!( + matches!(refused, HistoryError::StaleStore), + "a project read at the old generation is StaleStore: {refused:?}" + ); + // A single-statement read that resolves a Branch and its roots. + let refused = handles.history.branch_snapshot(work).unwrap_err(); + assert!( + matches!(refused, HistoryError::StaleStore), + "a Branch snapshot at the old generation is StaleStore: {refused:?}" + ); + // The by-name one-statement read joins the same generation column. + let refused = handles + .history + .branch_snapshot_named(&name("project-1"), &name("work")) + .unwrap_err(); + assert!( + matches!(refused, HistoryError::StaleStore), + "a named Branch snapshot at the old generation is StaleStore: {refused:?}" + ); + + // Reopening at the installed generation is the documented recovery. + let fresh = schema.open(&binding, CURSOR).unwrap(); + assert!(fresh.history.layer_stack(shop).unwrap().is_some()); + assert!(fresh.history.branch_snapshot(work).unwrap().is_some()); +} + +/// Two concurrent `branch.remove` calls in one project take the same epoch +/// row. The marker transaction locks it `FOR UPDATE` first, so the second +/// waits for the first and then bumps the value it read; both removals land +/// with one epoch bump each instead of a `40P01` deadlock on a shared-lock +/// upgrade. +#[test] +fn two_concurrent_branch_removes_in_one_project_are_ordered() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "concurrent_removal"); + let binding = binding("concurrent_removal"); + let first = schema.create(&binding, CURSOR); + let (project_id, work, genesis) = project(&first.history, 1); + let other = branch_id(2); + first + .history + .fork(&ForkRequest { + stack: project_id, + branch: other, + name: name("other"), + source: ForkSource::Layer(genesis), + }) + .unwrap(); + let second = schema.open(&binding, CURSOR).expect("a second session"); + let (left, right) = std::thread::scope(|scope| { + let left = scope.spawn(|| { + first + .history + .gc_remove_branch(work, 1_000, &removal(project_id, 40)) + }); + let right = scope.spawn(|| { + second + .history + .gc_remove_branch(other, 2_000, &removal(project_id, 41)) + }); + (left.join().unwrap(), right.join().unwrap()) + }); + for result in [&left, &right] { + match result { + Ok(()) => {} + // A bounded lane wait is a definite typed refusal, never a panic. + Err(HistoryError::Busy) => {} + Err(other) => panic!("a removal refusal must be typed: {other:?}"), + } + } + assert_eq!(epoch(&mut schema.admin(), project_id), 2); + assert_eq!(live_branch_rows(&schema), 0, "both Branches are retired"); +} + +/// A shared Store may be admitted from another machine whose boot and PID +/// namespace this one cannot observe, so a recorded owner on another boot +/// stays conservatively live: it is reported as a holder and never adopted, +/// until its owner releases it. (A local SQLite Store adopts the same row; +/// see `admission.rs#an_earlier_boot_is_settled_on_a_local_store`.) +#[test] +fn another_boot_stays_conservatively_live_on_a_shared_store() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "other_boot"); + let binding = binding("other_boot"); + let handles = schema.create(&binding, CURSOR); + let (project_id, branch, _genesis) = project(&handles.history, 1); + let mount = mount(project_id, branch, 50).owned(Some("pid:1@1@ns:1"), Some("boot:0:test:50")); + handles.history.gc_register(&mount).unwrap(); + let refusal = handles + .history + .gc_remove_branch(branch, 1_000, &removal(project_id, 51)) + .unwrap_err(); + let HistoryError::MountsActive(state) = &refusal else { + panic!("a shared Store keeps an unobservable owner live: {refusal:?}"); + }; + assert_eq!(state.holders.len(), 1); + assert_eq!(state.holders[0].op, hex16(&op(50))); + + handles.history.gc_release(&op(50)).unwrap(); + handles + .history + .gc_remove_branch(branch, 2_000, &removal(project_id, 52)) + .unwrap(); + assert_eq!(epoch(&mut schema.admin(), project_id), 1); +} From 5c3671ffa5d27a5d28842e3b9c5704a6b4b08fc0 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 16:24:40 +0800 Subject: [PATCH 03/16] fix(control): best-effort tombstone, place view only for admitting calls, read-only preview Three regressions against the base, in the control layer: - Sandbox close and forced close: a failed retired-tombstone write (or a failed record read before it) no longer aborts the removal after the runtime is confirmed stopped. The removal goes on, still ends the mount intents and removes the record, and reports the unwritten tombstone as a `left` sentence (`lifecycle::not_retired`). A missing tombstone only means "no proof of death". - The home place view (every machine record, Sandbox record and tombstone) is no longer read on every Store call. `with_service` and `open::run` no longer build it; only the calls whose admission compares placed mount intents do: `branch.remove` and `project.remove_file` (`place_view::admits`, local and worker frames), project delete (local admit/mark via `place_view::scoped`; worker frames unchanged) and the machine start reconcile. Reads, listings, file writes and merges build and send none: their shared intents conflict only with operation intents, which carry no place. The repair call no longer sends a view: none of its actions compares a place. The mount path's own place values are unchanged. - `store.repair_mount_holders ... preview` is read-only: it writes no retained `done` row and answers `audit: null`; each holder's `safe` and `reason` say what release would do. Docs, call help and worker op text updated. Also removes PR dead code that failed `clippy -D warnings`: the unused doctor `mount_holders` STORE/PROJECT/result/local/audit items, and unused test helpers/imports (`future_ms`, `audit_items`, `branch_named`, `HistoryError`) in the repair tests. Tests: gc_calls, store_repair_live, store_repair_worker and repair_postgresql now expect no preview rows (preview leaves gc_intent and the audit unchanged); new half_created `a_forced_remove_goes_on_when_its_tombstone_cannot_be_written`; new layerfs-store `place_view_scope`. No test deleted. Production LOC: 214081 -> 214030 (delta -51) scope: tools/production_loc.py (repo-pinned counter), first-parent tree vs committed tree control 62950 -> 62899; core, engine, api unchanged reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Co-Authored-By: Claude Opus 5.5 --- .../src/store/repair_mount_holders.rs | 13 ++-- api/crates/layerfs-api/tests/gc_calls.rs | 72 +++++++---------- .../src/doctor/mount_holders.rs | 52 ------------- control/crates/layerfs-control/src/store.rs | 14 ++-- .../layerfs-control/src/worker_server/ops.rs | 22 +++--- .../tests/store_repair_live.rs | 61 ++++----------- .../tests/store_repair_worker.rs | 22 ++---- control/crates/layerfs-sandbox/src/force.rs | 12 +-- .../crates/layerfs-sandbox/src/lifecycle.rs | 23 +++++- .../layerfs-sandbox/tests/half_created.rs | 45 +++++++++++ control/crates/layerfs-store/src/call.rs | 12 ++- control/crates/layerfs-store/src/open.rs | 16 ++-- .../crates/layerfs-store/src/place_view.rs | 41 +++++++--- .../layerfs-store/src/project/delete.rs | 40 ++++++---- control/crates/layerfs-store/src/service.rs | 77 +++++++------------ .../layerfs-store/tests/place_view_scope.rs | 70 +++++++++++++++++ .../layerfs-store/tests/repair_postgresql.rs | 17 +--- docs/architecture/api/sdk/store.md | 10 +-- 18 files changed, 319 insertions(+), 300 deletions(-) create mode 100644 control/crates/layerfs-store/tests/place_view_scope.rs 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 daae5f618b..dc23efc3c4 100644 --- a/api/crates/layerfs-api/src/store/repair_mount_holders.rs +++ b/api/crates/layerfs-api/src/store/repair_mount_holders.rs @@ -1,12 +1,11 @@ //! `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. Preview changes no live admission, -//! answers the typed holder view and writes its own retained done row -//! (`action=preview`, no operation); 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: 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. use crate::calls::table::{ a, call, opt, Call, Kind::{Bool, Int, Name, Text}, diff --git a/api/crates/layerfs-api/tests/gc_calls.rs b/api/crates/layerfs-api/tests/gc_calls.rs index d697fd8dba..60ca93e2b3 100644 --- a/api/crates/layerfs-api/tests/gc_calls.rs +++ b/api/crates/layerfs-api/tests/gc_calls.rs @@ -7,7 +7,7 @@ use layerfs_history::records::{GcIntent, GcIntentKind, GcScopeKind}; use layerfs_history::PlaceAuthority; use layerfs_store::open_args::OpenArgs; use layerfs_store::record::StoreRecord; -use layerfs_store::service::{branch_named, with_service}; +use layerfs_store::service::with_service; use layerfs_store_service::history::lookup; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; @@ -810,16 +810,8 @@ fn a_bare_project_name_is_refused_by_every_project_call() { std::fs::remove_dir_all(home).unwrap(); } -fn future_ms() -> i64 { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("the clock is after the epoch") - .as_millis(); - i64::try_from(now).expect("the clock fits an i64") + 60_000 -} - /// `store.repair_mount_holders` is the explicit two-step operator repair: -/// preview answers the typed holder view and changes no intent; release needs +/// preview answers the typed holder view and writes nothing; release needs /// a preceding settle; `settle_legacy` marks only rows with no owner or place /// evidence; release retains the row as the durable done audit, and the audit /// action reads it back in bounded pages. @@ -906,7 +898,29 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { 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_text("audit"), Some("gc_intent")); + assert_eq!(preview.get("audit"), 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| { + (service.store.history()) + .gc_intents(GcScopeKind::Branch, branch.as_slice()) + .map_err(lookup::history) + }) + .unwrap(); + assert_eq!(intents.len(), 2, "{intents:?}"); + assert!( + intents.iter().all(|intent| !intent.uncertain), + "{intents:?}" + ); + let audit = ok( + &home, + "store.repair_mount_holders", + &repair("audit", None, false), + ); + assert!( + matches!(audit.get("items"), Some(SdkValue::List(rows)) if rows.is_empty()), + "preview wrote a row: {audit:?}" + ); let live_row = holders .iter() .find(|row| row.get_text("op") == Some(live_op.as_str())) @@ -984,9 +998,7 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { ); // Both releases retained their row as the durable operator audit, and - // every preview retained its own done row: the release rows keep the op, - // the preview rows are the operator action with no op. Admission still - // filters every done row. + // the three previews wrote none. Admission still filters every done row. let audit = ok( &home, "store.repair_mount_holders", @@ -1003,17 +1015,7 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { }) .collect(); assert_eq!(released.len(), 2, "{audit:?}"); - let previews: Vec<_> = rows - .iter() - .filter(|row| row.get_text("evidence") == Some("action=preview;operator=alice")) - .collect(); - assert_eq!(previews.len(), 3, "{audit:?}"); - for row in &previews { - assert_eq!(row.get("phase"), Some(&SdkValue::Null)); - assert_eq!(row.get_text("op").map(str::len), Some(32)); - assert_eq!(row.get_text("kind"), Some("mount")); - assert_eq!(row.get_text("scope_kind"), Some("branch")); - } + assert_eq!(rows.len(), 2, "only the releases are retained: {audit:?}"); let released = released .iter() .find(|row| row.get_text("op") == Some(live_op.as_str())) @@ -1063,23 +1065,3 @@ fn store_repair_mount_holders_is_an_explicit_two_step_operator_call() { std::fs::remove_dir_all(home).unwrap(); let _ = std::fs::remove_dir_all(folder); } - -/// The bounded read of the Store's retained done rows, as the audit action -/// answers it. -fn audit_items(home: &Path) -> Vec { - let audit = ok( - home, - "store.repair_mount_holders", - &[ - ("name", t("shop")), - ("project", t("api")), - ("branch", t("main")), - ("action", t("audit")), - ], - ); - match audit.get("items") { - Some(SdkValue::List(items)) => items.clone(), - other => panic!("audit items: {other:?}"), - } -} - diff --git a/control/crates/layerfs-control/src/doctor/mount_holders.rs b/control/crates/layerfs-control/src/doctor/mount_holders.rs index a82c996476..ffd7369a88 100644 --- a/control/crates/layerfs-control/src/doctor/mount_holders.rs +++ b/control/crates/layerfs-control/src/doctor/mount_holders.rs @@ -6,59 +6,8 @@ use layerfs_home::{home::paths, names::SandboxName, outcome::refused}; use layerfs_sandbox::record::{SandboxRecord, WorkspaceRecord}; use std::path::Path; -pub(super) const STORE: &str = "store.mount_holders"; -pub(super) const PROJECT: &str = "project.mount_holders"; pub(super) const AUDIT: &str = "store.gc_audit"; -pub(super) fn result( - home: &Path, - store: &str, - shared: bool, - check: &str, - result: Result, - checks: &mut Checks, -) { - match result { - Ok(rows) => report(home, store, shared, check, Some(&rows), checks), - Err(error) => checks.unknown(check, error.message), - } -} - -/// The local SQLite path: read the rows and report them against this home. -pub(super) fn local( - home: &Path, - store: &str, - name: &str, - identity: &layerfs_store::identity::Identity, - checks: &mut Checks, -) { - let path = paths::store_file(home, name); - result( - home, - store, - false, - STORE, - layerfs_store::diagnostic::mount_holders(&path, identity), - checks, - ); -} - -/// The local SQLite path: one bounded page of the retained `done` -/// operator-audit rows, read on a diagnostic open. The doctor only reports -/// them; it never releases or settles one. -pub(super) fn audit( - home: &Path, - name: &str, - identity: &layerfs_store::identity::Identity, - checks: &mut Checks, -) { - let path = paths::store_file(home, name); - audit_result( - layerfs_store::diagnostic::done_audit(&path, identity, 0, 16), - checks, - ); -} - /// The worker's forwarded `store.gc_audit` event, or the local result: a /// read that answers is evidence, never a warning; a read that fails is /// `unknown`, so it cannot turn into a release. @@ -153,4 +102,3 @@ pub(super) fn report( ); } } - diff --git a/control/crates/layerfs-control/src/store.rs b/control/crates/layerfs-control/src/store.rs index 7eb2bf5720..bb08bbc3c8 100644 --- a/control/crates/layerfs-control/src/store.rs +++ b/control/crates/layerfs-control/src/store.rs @@ -70,9 +70,10 @@ pub fn compact(home: &Path, events: &mut Events<'_>, name: &StoreName) -> Outcom } /// `store.repair_mount_holders`: first-class explicit operator repair of -/// one Branch's mount intents. Preview lists them and writes its own retained -/// done row; settle/release act on one explicit op; release retains the row as -/// the durable done audit; `audit` reads the retained rows of that Branch. +/// 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 @@ -103,7 +104,7 @@ pub fn repair( ) } Executor::Worker(mut worker) => { - let mut fields = vec![ + let fields = vec![ ("store".to_owned(), SdkValue::text(name.as_str())), ("store_record".to_owned(), record.to_record().clone()), ("project".to_owned(), SdkValue::text(project)), @@ -118,9 +119,8 @@ pub fn repair( ("page".to_owned(), SdkValue::Int(i64::from(page))), ("limit".to_owned(), SdkValue::Int(i64::from(limit))), ]; - if let Some(place) = layerfs_store::place_view::encoded_from_home(home) { - fields.push(("place_view".to_owned(), place)); - } + // 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| {}) } diff --git a/control/crates/layerfs-control/src/worker_server/ops.rs b/control/crates/layerfs-control/src/worker_server/ops.rs index cd7e4acd87..fcb8dc7696 100644 --- a/control/crates/layerfs-control/src/worker_server/ops.rs +++ b/control/crates/layerfs-control/src/worker_server/ops.rs @@ -192,11 +192,12 @@ 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? }`. Preview changes no intent: it - // lists the typed holders and the call log records the read. - // settle/release/settle_legacy act on one explicit op or the legacy - // rows; release retains the row as the durable done audit, and the - // call log records every action. + // 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. "store.repair" => { let store = args .get_text("store") @@ -239,14 +240,9 @@ pub(super) fn run( store_record: args.get("store_record").cloned(), postgresql: None, }; - 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::service::repair_mount_holders_at( - &open, project, branch, action, op, legacy, operator, page, limit, - ) - }) + layerfs_store::service::repair_mount_holders_at( + &open, project, branch, action, op, legacy, operator, page, limit, + ) } // 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 d7dd7db60c..837e8bca93 100644 --- a/control/crates/layerfs-control/tests/store_repair_live.rs +++ b/control/crates/layerfs-control/tests/store_repair_live.rs @@ -12,7 +12,6 @@ mod worker_store; use layerfs_bridge::control::{SdkCall, SdkRefusal, SdkValue}; -use layerfs_history::error::HistoryError; use layerfs_history::records::{GcIntent, GcIntentKind, GcScopeKind}; use layerfs_history::PlaceAuthority; use layerfs_home::events::Events; @@ -54,16 +53,6 @@ fn source(tag: &str) -> PathBuf { directory } -fn future_ms() -> i64 { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("the clock is after the epoch") - .as_millis(); - // An hour: seeding the 331 retired Branches must never let a lease the - // test calls live expire underneath it. - i64::try_from(now).expect("the clock fits an i64") + 3_600_000 -} - fn text(value: &str) -> SdkValue { SdkValue::text(value) } @@ -183,7 +172,6 @@ fn seed(home: &Path) { .named(Some("app"), Some(&name)), }; history.gc_register(&intent).unwrap(); - } // The 331 already retired behind the six: fork, a wholly dead pack, @@ -555,7 +543,7 @@ fn the_live_six_of_three_hundred_thirty_one_is_repaired_removed_and_reclaimed() ); // The operator's per-Branch preview answers the same typed view and - // settles nothing. + // writes nothing. for tag in FIRST..FIRST + 6 { let name = format!("stuck-{}", tag - FIRST); let preview = repair(&placed, &name, "preview", None, false); @@ -617,7 +605,7 @@ fn the_live_six_of_three_hundred_thirty_one_is_repaired_removed_and_reclaimed() assert_eq!(holders(&preview).len(), 0, "{name}: {preview:?}"); } // The audit is scoped to the Branch it names: each Branch's page holds - // exactly its own two preview rows and one release row. + // exactly its own release row; its two previews wrote none. for tag in FIRST..FIRST + 6 { let name = format!("stuck-{}", tag - FIRST); let audit = repair(&placed, &name, "audit", None, false); @@ -638,28 +626,21 @@ fn the_live_six_of_three_hundred_thirty_one_is_repaired_removed_and_reclaimed() .is_some_and(|evidence| evidence.contains("action=release;operator=alice;op=")) }) .count(); - let previews = rows - .iter() - .filter(|row| row.get_text("evidence") == Some("action=preview;operator=alice")) - .count(); assert_eq!(releases, 1, "{name}: {audit:?}"); - assert_eq!(previews, 2, "{name}: {audit:?}"); + assert_eq!(rows.len(), 1, "{name}: {audit:?}"); } - // 3c. The doctor's worker-side audit is the same bounded page (16 rows at - // limit 16) over the same retained rows, as evidence; it releases nothing. + // 3c. The doctor's worker-side audit is the same bounded page (limit 16) + // over the same retained rows, as evidence; it releases nothing. The six + // releases are every retained row. let doctor = diagnostic_audit(&placed); let Some(SdkValue::List(rows)) = doctor.get("items") else { panic!("doctor audit items: {doctor:?}"); }; - assert_eq!( - rows.len(), - 16, - "the worker audit page is bounded: {doctor:?}" - ); + assert_eq!(rows.len(), 6, "{doctor:?}"); assert_eq!( doctor.get("has_more"), - Some(&SdkValue::Bool(true)), + Some(&SdkValue::Bool(false)), "{doctor:?}" ); let releases = rows @@ -669,12 +650,7 @@ fn the_live_six_of_three_hundred_thirty_one_is_repaired_removed_and_reclaimed() .is_some_and(|evidence| evidence.starts_with("action=release;")) }) .count(); - let previews = rows - .iter() - .filter(|row| row.get_text("evidence") == Some("action=preview;operator=alice")) - .count(); assert_eq!(releases, 6, "{doctor:?}"); - assert_eq!(previews, 10, "{doctor:?}"); // 4. The six now remove, and their names stay retired until compaction. for tag in FIRST..FIRST + 6 { @@ -714,17 +690,13 @@ fn the_live_six_of_three_hundred_thirty_one_is_repaired_removed_and_reclaimed() // durable operator audit. Preview still filters them. let preview = repair(&placed, "main", "preview", None, false); assert_eq!(holders(&preview).len(), 0, "no holder remains"); - // The audit is scoped: main has only the preview this step wrote, and - // each repaired Branch keeps its own six rows through the rebuild. + // The audit is scoped: main has no row (its preview wrote none), and + // each repaired Branch keeps its own release row through the rebuild. let audit = repair(&placed, "main", "audit", None, false); let Some(SdkValue::List(rows)) = audit.get("items") else { panic!("audit items: {audit:?}"); }; - assert_eq!(rows.len(), 1, "main's audit is the preview it wrote: {audit:?}"); - assert_eq!( - rows[0].get_text("evidence"), - Some("action=preview;operator=alice") - ); + assert!(rows.is_empty(), "main's preview wrote a row: {audit:?}"); for tag in FIRST..FIRST + 6 { let name = format!("stuck-{}", tag - FIRST); let audit = repair(&placed, &name, "audit", None, false); @@ -738,12 +710,11 @@ fn the_live_six_of_three_hundred_thirty_one_is_repaired_removed_and_reclaimed() .is_some_and(|evidence| evidence.starts_with("action=release;")) }) .count(); - let previews = rows - .iter() - .filter(|row| row.get_text("evidence") == Some("action=preview;operator=alice")) - .count(); - assert_eq!(releases, 1, "the compaction kept {name}'s release: {audit:?}"); - assert_eq!(previews, 2, "the compaction kept {name}'s previews: {audit:?}"); + assert_eq!( + releases, 1, + "the compaction kept {name}'s release: {audit:?}" + ); + assert_eq!(rows.len(), 1, "{name}: {audit:?}"); } placed.remove(); diff --git a/control/crates/layerfs-control/tests/store_repair_worker.rs b/control/crates/layerfs-control/tests/store_repair_worker.rs index 41be3a533a..19d0910eca 100644 --- a/control/crates/layerfs-control/tests/store_repair_worker.rs +++ b/control/crates/layerfs-control/tests/store_repair_worker.rs @@ -35,14 +35,6 @@ fn source(tag: &str) -> PathBuf { directory } -fn future_ms() -> i64 { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("the clock is after the epoch") - .as_millis(); - i64::try_from(now).expect("the clock fits an i64") + 60_000 -} - fn mount(stack: &[u8], branch: &[u8], op: u8) -> GcIntent { GcIntent::shared( [op; 16], @@ -187,8 +179,14 @@ fn repair_previews_settles_and_releases_through_the_worker() { assert_eq!(live.get_text("machine_incarnation"), Some("worker:1")); assert_eq!(live.get_text("state"), Some("live")); - // Preview over the worker answers the typed view and settles nothing. + // 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:?}"); + let audit = repair(&placed, "audit", None, false); + assert!( + matches!(audit.get("items"), Some(SdkValue::List(rows)) if rows.is_empty()), + "preview wrote a row: {audit:?}" + ); let rows = holders(&preview); assert_eq!(rows.len(), 2); let live = rows @@ -260,10 +258,6 @@ fn repair_previews_settles_and_releases_through_the_worker() { let evidence = row.get_text("evidence").expect("evidence"); assert!(evidence.contains("operator=alice"), "{row:?}"); } - let previews: Vec<_> = rows - .iter() - .filter(|row| row.get_text("evidence") == Some("action=preview;operator=alice")) - .collect(); - assert_eq!(previews.len(), 4, "every worker preview: {audit:?}"); + assert_eq!(rows.len(), 2, "no worker preview wrote a row: {audit:?}"); placed.remove(); } diff --git a/control/crates/layerfs-sandbox/src/force.rs b/control/crates/layerfs-sandbox/src/force.rs index e37a1e3c84..1d3cfb32b9 100644 --- a/control/crates/layerfs-sandbox/src/force.rs +++ b/control/crates/layerfs-sandbox/src/force.rs @@ -102,11 +102,13 @@ pub fn close(host: &Host, held: &[String]) -> Outcome { None => Err(format!("no Sandbox {id} is recorded")), }; // the runtime is confirmed stopped: write the durable home tombstone - // before the record (the folder) goes; a failed write keeps the record - if let Some(record) = &record { - crate::record::retire(&host.home, record).map_err(after_stop)?; - } - let left = crate::mount_intents::end(open.as_ref().map_err(String::as_str), &bound); + // before the record (the folder) goes, best effort as a close does + // (`crate::lifecycle::not_retired`): a failed write is reported in `left` + let unretired = (record.as_ref()) + .and_then(|record| crate::record::retire(&host.home, record).err()) + .map(|refusal| crate::lifecycle::not_retired(&id, &refusal.message)); + let mut left = crate::mount_intents::end(open.as_ref().map_err(String::as_str), &bound); + left.extend(unretired); // the table is whole after a holder's panic (layerfs-project#177) crate::registry::SANDBOXES .lock() diff --git a/control/crates/layerfs-sandbox/src/lifecycle.rs b/control/crates/layerfs-sandbox/src/lifecycle.rs index b23f603ee6..adbab098f1 100644 --- a/control/crates/layerfs-sandbox/src/lifecycle.rs +++ b/control/crates/layerfs-sandbox/src/lifecycle.rs @@ -397,10 +397,15 @@ pub fn close(host: &Host, force: bool, held: &[String]) -> Outcome { // to the caller, which runs PostgreSQL Store calls and ends them // (`mount_intents::end_handed`); what records less is reported here // The runtime is confirmed stopped: write the durable home tombstone - // before the record (the folder) goes; a failed write keeps the record. - if let Some(record) = crate::record::SandboxRecord::read(&host.home, &id)? { - crate::record::retire(&host.home, &record)?; + // 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 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) { @@ -422,6 +427,7 @@ pub fn close(host: &Host, force: bool, held: &[String]) -> Outcome { None, ), }; + let left = left.into_iter().chain(unretired).collect(); lock(&SANDBOXES)?.remove(&directory); std::fs::remove_dir_all(&directory).map_err(failed)?; layerfs_home::home::generation::moved_above(&directory); @@ -442,6 +448,17 @@ 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. +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" + )) +} + /// The Branch and Workspace identity of each of `mounted` this process /// holds, read before a forced close drains them; a `held` path it does /// not hold is listed with neither, so its answer says so. diff --git a/control/crates/layerfs-sandbox/tests/half_created.rs b/control/crates/layerfs-sandbox/tests/half_created.rs index 84f70dff0c..2da8b06087 100644 --- a/control/crates/layerfs-sandbox/tests/half_created.rs +++ b/control/crates/layerfs-sandbox/tests/half_created.rs @@ -247,3 +247,48 @@ fn a_half_created_native_sandbox_has_its_daemon_stopped_or_kept() { assert!(!paths::sandbox_dir(&home, "s1").exists()); std::fs::remove_dir_all(home).unwrap(); } + +/// The retired tombstone is best effort: a forced remove whose tombstone +/// cannot be written (here its `sandbox-retired` folder is a file) still +/// stops the daemon, ends what it holds and removes the record, and reports +/// the unwritten tombstone in `left`. A missing tombstone is only "no proof +/// of death". +#[cfg(target_os = "macos")] +#[test] +fn a_forced_remove_goes_on_when_its_tombstone_cannot_be_written() { + use layerfs_bridge::process::LocalProcess; + let home = new_home("unretired"); + let mut kept = stand_in(); + let folder = half_created(&home, "s1", kept.id()); + let record = read_record(&paths::sandbox_record(&home, "s1")) + .unwrap() + .unwrap(); + let record = home::with_field(record, "generation", t("p1:sandbox:0000000000000001:00")); + write_record(&paths::sandbox_record(&home, "s1"), &record).unwrap(); + let retired = paths::sandbox_retired_dir(&home, "native"); + std::fs::create_dir_all(retired.parent().unwrap()).unwrap(); + std::fs::write(&retired, b"not a folder").unwrap(); + let daemon = LocalProcess::observe(kept.id()).unwrap(); + + match removed(&home, "s1", true) { + Ok(Removed::Stopped { unmounted, left }) => { + assert!(unmounted.is_empty(), "{unmounted:?}"); + assert_eq!(left.len(), 1, "{left:?}"); + assert!( + left[0].contains("retired tombstone was not written"), + "{left:?}" + ); + } + Ok(Removed::AlreadyGone { left }) => panic!("taken as gone: {left:?}"), + Err(refusal) => panic!("the unwritten tombstone aborted the remove: {refusal:?}"), + } + let _ = kept.wait(); + assert!(!daemon.alive(), "its daemon still runs"); + assert!(!folder.exists(), "its run folder stays"); + assert!( + !paths::sandbox_dir(&home, "s1").exists(), + "its record stays" + ); + assert!(retired.is_file()); + std::fs::remove_dir_all(home).unwrap(); +} diff --git a/control/crates/layerfs-store/src/call.rs b/control/crates/layerfs-store/src/call.rs index 00736f3689..0b04632179 100644 --- a/control/crates/layerfs-store/src/call.rs +++ b/control/crates/layerfs-store/src/call.rs @@ -49,13 +49,11 @@ pub fn store_call( Executor::Worker(mut worker) => { // the host process holds the lease while it sends the call let _lease = lease; - let request = frame( - method, - with_project(args, target), - target, - &record, - crate::place_view::encoded_from_home(&home), - ); + // only an admitting call carries the caller's place view + let place = (crate::place_view::admits(method)) + .then(|| crate::place_view::encoded_from_home(&home)) + .flatten(); + let request = frame(method, with_project(args, target), target, &record, place); worker.call("store.call", request, &mut |event| events.event(event)) } } diff --git a/control/crates/layerfs-store/src/open.rs b/control/crates/layerfs-store/src/open.rs index 6c851b84bd..0bc890adf3 100644 --- a/control/crates/layerfs-store/src/open.rs +++ b/control/crates/layerfs-store/src/open.rs @@ -48,16 +48,14 @@ static SETTLED: Condvar = Condvar::new(); /// The Store stays open while it runs. pub fn run(op: &str, open: &OpenArgs, args: SdkValue, lease: Option) -> Outcome { let running = Running(enter(open, lease, 1)?); - // The bounded places this home can speak for, read once for the call. The - // engine never opens a home record; a worker call installs its own view - // before this, and that view is kept. - let place = match layerfs_store_service::history::admission::has_place_view() { - true => None, - false => crate::place_view::from_open(open), + // An admitting call reads the bounded places this home can speak for, + // once; no other call reads the home (`place_view::admits`). The engine + // never opens a home record; a worker call installs its own view before + // this, and that view is kept. + let outcome = match crate::place_view::admits(op) { + true => crate::place_view::scoped(open, || direct::call(op, open, args)), + false => direct::call(op, open, args), }; - let outcome = layerfs_store_service::history::admission::with_place_view(place, || { - direct::call(op, open, args) - }); drop(running); outcome } diff --git a/control/crates/layerfs-store/src/place_view.rs b/control/crates/layerfs-store/src/place_view.rs index 85eeb7e46e..6225ef21f9 100644 --- a/control/crates/layerfs-store/src/place_view.rs +++ b/control/crates/layerfs-store/src/place_view.rs @@ -1,11 +1,18 @@ //! The bounded place view the control layer builds from its home. //! //! Admission on the engine side never reads a home file. The control layer -//! reads the place records it can see once per Store call and hands the engine -//! a bounded map: each machine's current `MachineRecord.incarnation`, each -//! Sandbox's current generation, and every machine-level `sandbox-retired` +//! reads the place records it can see once per admitting Store call and hands +//! the engine a bounded map: each machine's current `MachineRecord.incarnation`, +//! each Sandbox's current generation, and every machine-level `sandbox-retired` //! tombstone. A name missing from the view is no proof, never death. //! +//! Only a call whose admission compares placed mount intents reads it: an +//! exclusive operation's admission (a Branch removal, a project's file +//! removal, a project delete) and a machine's start reconcile ([`admits`]). +//! Every other Store call (reads, listings, file writes, merges) builds and +//! sends none: their admission meets only operation intents, which carry no +//! place, so a view could not change it. +//! //! The view is bounded by the places the home actually records; it never //! scans a Store, a Workspace or a content pack. use crate::open_args::OpenArgs; @@ -15,6 +22,28 @@ use layerfs_home::home::{paths, read_record}; use layerfs_machine::record::MachineRecord; use std::path::Path; +/// The public Store methods whose engine admission compares placed mount +/// intents with the view: the exclusive removals. A shared intent (a file +/// write's private Workspace, a merge) conflicts only with operation intents, +/// which record no place. +pub const ADMITTING: [&str; 2] = ["branch.remove", "project.remove_file"]; + +/// Whether Store method `method` reads the place view ([`ADMITTING`]). +#[must_use] +pub fn admits(method: &str) -> bool { + ADMITTING.contains(&method) +} + +/// Runs `work` with the place view of `open`'s home installed, unless a +/// caller (a worker frame) installed one already: one admitting call's read. +pub fn scoped(open: &OpenArgs, work: impl FnOnce() -> R) -> R { + let place = match layerfs_store_service::history::admission::has_place_view() { + true => None, + false => from_open(open), + }; + layerfs_store_service::history::admission::with_place_view(place, work) +} + /// Builds the bounded place view from the caller's home alone. /// /// A missing home, a machine without a record and a Sandbox without a record @@ -65,12 +94,6 @@ pub fn encoded_from_home(home: &Path) -> Option { from_home(home).map(|view| layerfs_store_service::history::admission::encode_place_view(&view)) } -/// [`encoded_from_home`] for a Store call's [`OpenArgs`]. -#[must_use] -pub fn encoded_from_open(open: &OpenArgs) -> Option { - from_open(open).map(|view| layerfs_store_service::history::admission::encode_place_view(&view)) -} - /// The tombstones dir holds, as (Sandbox name, retired generation). A /// tombstone without a generation names nothing admission can compare. fn tombstones(dir: &Path) -> Vec<(String, String)> { diff --git a/control/crates/layerfs-store/src/project/delete.rs b/control/crates/layerfs-store/src/project/delete.rs index 7b070c5182..513b35ef41 100644 --- a/control/crates/layerfs-store/src/project/delete.rs +++ b/control/crates/layerfs-store/src/project/delete.rs @@ -600,20 +600,25 @@ struct Local { impl Effects for Local { fn admit(&mut self, stack: LayerStackId, op: [u8; 16], project: &str) -> Result { let intent = store_admission::project_removal_at(stack, op, Some(project)); - service::with_service(&self.open, |service| { - match service.store.history().gc_register(&intent) { - Ok(()) => Ok(Admission::new(stack, op)), - // A provider without admission cannot exclude a removal; the - // marker's own admission still runs, as it did before T6. - Err(HistoryError::Unsupported(_)) => Ok(Admission::new(stack, op)), - Err(error) => Err(lookup::history_in( - error, - GcScopeKind::Project, - project, - None, - Some(&op), - )), - } + // the removal's admission compares placed mount intents with the + // caller's place view, as `Remote` sends it + let open = &self.open; + crate::place_view::scoped(open, || { + service::with_service(open, |service| { + match service.store.history().gc_register(&intent) { + Ok(()) => Ok(Admission::new(stack, op)), + // A provider without admission cannot exclude a removal; the + // marker's own admission still runs, as it did before T6. + Err(HistoryError::Unsupported(_)) => Ok(Admission::new(stack, op)), + Err(error) => Err(lookup::history_in( + error, + GcScopeKind::Project, + project, + None, + Some(&op), + )), + } + }) }) } @@ -646,8 +651,11 @@ impl Effects for Local { admission.op, Some(self.project.as_str()), ); - service::with_service(&self.open, |service| { - delete_stack_with(&service.store, admission.stack, deleted_ms, &intent) + let open = &self.open; + crate::place_view::scoped(open, || { + service::with_service(open, |service| { + delete_stack_with(&service.store, admission.stack, deleted_ms, &intent) + }) }) } diff --git a/control/crates/layerfs-store/src/service.rs b/control/crates/layerfs-store/src/service.rs index 6c8853fb71..50695d1915 100644 --- a/control/crates/layerfs-store/src/service.rs +++ b/control/crates/layerfs-store/src/service.rs @@ -126,13 +126,7 @@ pub fn with_service( work: impl FnOnce(&Arc) -> Result, ) -> Result { acquire(args)?; - let result = service(args).and_then(|service| { - let place = match layerfs_store_service::history::admission::has_place_view() { - true => None, - false => crate::place_view::from_open(args), - }; - layerfs_store_service::history::admission::with_place_view(place, || work(&service)) - }); + let result = service(args).and_then(|service| work(&service)); let released = release(args); let value = result?; released?; @@ -253,16 +247,19 @@ pub fn reconcile_machine( match crate::place::plan(home, store_ref)? { crate::place::Executor::Local => { let args = OpenArgs::of_record(home, store, &record)?; - with_service(&args, |service| { - layerfs_store_service::history::admission::reconcile_machine( - service.store.history(), - machine, - incarnation, - ) - .map(|reconcile| { - layerfs_store_service::history::admission::reconcile_value(&reconcile) + // the reconcile compares placed mount intents: it reads the view + crate::place_view::scoped(&args, || { + with_service(&args, |service| { + layerfs_store_service::history::admission::reconcile_machine( + service.store.history(), + machine, + incarnation, + ) + .map(|reconcile| { + layerfs_store_service::history::admission::reconcile_value(&reconcile) + }) + .map_err(layerfs_store_service::history::lookup::history) }) - .map_err(layerfs_store_service::history::lookup::history) }) } crate::place::Executor::Worker(mut worker) => { @@ -341,12 +338,11 @@ pub fn done_audit( /// 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. Preview -/// writes its own retained `done` row the same way, with `action=preview`, -/// the operator label and no operation; it changes no live intent. 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. +/// 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, @@ -382,33 +378,16 @@ pub fn repair_mount_holders( ("op", SdkValue::Null), ("audit", SdkValue::Null), ])), - "preview" => { - // Preview changes no live intent, but the operator action is - // durable: it writes a retained `done` row through the same - // release/done columns, with the operator label and no - // operation (`evidence` has no `op=`). The row never admits - // (admission filters `state <> 'done'`) and the bounded - // `gc_intent_done` read reports it. - let operator = operator_label(operator)?; - let mut op = [0u8; 16]; - op.copy_from_slice(&layerfs_home::helpers::random()?[..16]); - let evidence = format!("action=preview;operator={operator}"); - let intent = layerfs_history::GcIntent::shared( - op, - layerfs_history::GcIntentKind::Mount, - layerfs_history::GcScopeKind::Branch, - branch.as_slice(), - ) - .named(Some(project), Some(branch_name)); - catalog.gc_record_done(&intent, &evidence).map_err(failed)?; - Ok(SdkValue::map([ - ("holders", holder_rows(&holders)), - ("legacy", SdkValue::Bool(legacy)), - ("action", SdkValue::text("preview")), - ("op", SdkValue::Null), - ("audit", SdkValue::text("gc_intent")), - ])) - } + // 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")) diff --git a/control/crates/layerfs-store/tests/place_view_scope.rs b/control/crates/layerfs-store/tests/place_view_scope.rs new file mode 100644 index 0000000000..2de6b7e329 --- /dev/null +++ b/control/crates/layerfs-store/tests/place_view_scope.rs @@ -0,0 +1,70 @@ +//! Only the Store calls whose admission compares placed mount intents read +//! the caller's home place view (`place_view::admits`): the exclusive +//! removals. Reads, listings, file writes and merges never build or send it, +//! and the view a worker frame or a caller installed is kept, never replaced. +use layerfs_history::PlaceView; +use layerfs_store::open_args::OpenArgs; +use layerfs_store::place_view::{admits, scoped}; +use layerfs_store_service::history::admission::{has_place_view, with_place_view}; + +#[test] +fn only_the_exclusive_removals_read_the_place_view() { + for method in ["branch.remove", "project.remove_file"] { + assert!(admits(method), "{method}"); + } + for method in [ + "store.stats", + "project.stats", + "project.list_branches", + "branch.fork", + "branch.list_commits", + "branch.get_commit", + "branch.merge", + "branch.publish", + "branch.diff_commits", + "branch.diff_branches", + "commit.diff", + "fs.read", + "fs.revision", + "fs.list", + "fs.stat", + "fs.grep", + "fs.glob", + "fs.diff_files", + "fs.blame", + "fs.write", + "fs.edit", + "fs.mkdir", + "fs.rm", + "fs.cp", + "fs.mv", + "fs.apply", + ] { + assert!( + !admits(method), + "{method} must not read the home place view" + ); + } +} + +#[test] +fn an_admitting_call_reads_its_home_once_and_keeps_an_installed_view() { + let home = std::env::temp_dir().join(format!("lfs-place-scope-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&home); + std::fs::create_dir_all(home.join("machine")).unwrap(); + let open = OpenArgs { + home: Some(home.clone()), + ..OpenArgs::default() + }; + // a home with no place evidence installs nothing + assert!(!scoped(&open, has_place_view)); + // a worker frame's view stays installed: the call does not replace it + let mut view = PlaceView::new(); + view.set_machine("box", "p1:worker:0000000000000001:00"); + assert!(with_place_view(Some(view), || scoped( + &open, + has_place_view + ))); + assert!(!has_place_view()); + let _ = std::fs::remove_dir_all(&home); +} diff --git a/control/crates/layerfs-store/tests/repair_postgresql.rs b/control/crates/layerfs-store/tests/repair_postgresql.rs index 5596ddae1d..714cd96e08 100644 --- a/control/crates/layerfs-store/tests/repair_postgresql.rs +++ b/control/crates/layerfs-store/tests/repair_postgresql.rs @@ -117,14 +117,6 @@ impl Drop for Database { } } -fn future_ms() -> i64 { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("the clock is after the epoch") - .as_millis(); - i64::try_from(now).expect("the clock fits an i64") + 60_000 -} - fn mount(branch: &[u8], stack: &[u8], op: u8) -> GcIntent { GcIntent::shared( [op; 16], @@ -206,6 +198,7 @@ fn operator_repair_round_trips_on_postgresql() { &open, "app", "main", "preview", None, false, "alice", 0, 100, ) .expect("preview"); + assert_eq!(preview.get("audit"), Some(&SdkValue::Null), "{preview:?}"); let rows = holders(&preview); assert_eq!(rows.len(), 2, "{rows:?}"); let row = rows @@ -300,12 +293,8 @@ fn operator_repair_round_trips_on_postgresql() { }) .collect(); assert_eq!(releases.len(), 2, "{audit:?}"); - let previews: Vec<_> = items - .iter() - .filter(|item| item.get_text("evidence") == Some("action=preview;operator=alice")) - .collect(); - assert_eq!(previews.len(), 2, "the durable preview rows: {audit:?}"); - for item in previews { + assert_eq!(items.len(), 2, "no preview wrote a row: {audit:?}"); + for item in releases { assert_eq!(item.get_text("project"), Some("app")); assert_eq!(item.get_text("branch"), Some("main")); assert_eq!(item.get_text("op").map(str::len), Some(32)); diff --git a/docs/architecture/api/sdk/store.md b/docs/architecture/api/sdk/store.md index 77b8687dc2..994cb656f4 100644 --- a/docs/architecture/api/sdk/store.md +++ b/docs/architecture/api/sdk/store.md @@ -607,7 +607,7 @@ $ layerfs store remove nope ### store.repair_mount_holders Explicit, operator-only repair of the mount admissions held at one Branch. -Nothing is automatic: preview and audit change no live intent, the doctor only +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. ```text @@ -619,7 +619,7 @@ The action is one of: | 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 and writes one retained `done` row with `action=preview;operator=NAME` in `evidence`, `op` null, the operator label and no owner or place columns; it changes no live intent | +| `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` and clears the owner columns, so the unique owner key cannot block a remount | | `settle_legacy` | marks only rows with missing owner or place evidence | @@ -628,9 +628,9 @@ The action is one of: Every holder row carries `safe` and `reason`: an uncertain (settled) row is safe to release and says so; 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: -"gc_intent" }`; list answers the holders alone; settle and `settle_legacy` are -in the home's `trace/calls.jsonl` call log only. `--operator` is the local name +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 From 25c261b205763a2e489de7675d6ce41cf0e6044c Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 16:27:11 +0800 Subject: [PATCH 04/16] fix(persistence): keep the base Store format; place tokens live in evidence PR #770 bumped the SQLite schema to version 3 (user_version 39-41/45-47) to add two gc_intent columns, refused every base Store as SchemaVersion2 and shipped an offline converter. The Store keeps the base format exactly now: - gc.sql (SQLite and PostgreSQL), the user_version scheme (36-38/42-44), connection.rs, store/config.rs, both schema.rs checks (the kept_node migration no longer accepts the current source "for the authority migration") and the PostgreSQL schema diagnostic are back at fe9b4d1a3c. SchemaVersion2 / SCHEMA_VERSION_2 and the POSTGRESQL_TABLES test export are gone. - A live mount row keeps machine_incarnation / sandbox_generation in the existing evidence column as `place:v1;inc=;gen=` (absent part omitted, NULL when both absent). One helper pair in history/bindings.rs (place_evidence / place_tokens) serves the shared SQLite/PostgreSQL intent queries and the mount-holder diagnostic. NULL, a prefixless value (a done row's audit text) or a malformed value decodes as no token: missing evidence is no proof, never death. - Done-row guards: the owner's release DELETE, the uncertain UPDATE and the insert's ON CONFLICT DO UPDATE skip `state = 'done'`. A registration whose op id is already a retained done row returns no row and is refused Conflict instead of reviving it. - tools/store_gc_convert.py and its tests are deleted with every reference; the merge-forms-root.sqlite fixture (user_version 42) and the test hunks that only tracked the version bump are restored. Deleted tests: - layerfs-persistence tests/gc_conversion.rs (the_converted_store_opens_and_ the_home_holds_the_old_authority, the_converted_store_serves_the_operator_ audit, an_unconverted_machine_refuses_until_the_operator_declares_it_gone) - layerfs-persistence tests/gc_schema.rs (whole file: version 3 columns, POSTGRESQL_TABLES, the version 2 refusal) - layerfs-persistence tests/gc_intent_authority.rs (a_new_store_ships_the_ intent_authority_columns, an_old_store_without_the_intent_authority_ columns_is_refused) - layerfs-persistence tests/sealed_open.rs::a_sealed_store_recorded_before_ the_intent_authority_columns_is_malformed - tools/test_store_gc_convert.py Added: gc_intent_done.rs::place_tokens_round_trip_through_evidence_and_ live_statements_keep_a_done_row. Production LOC: 214081 -> 214104 (delta +23) 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-api/tests/project_export.rs | 4 +- .../docs/issues/project-41/LayerFS-GC-spec.md | 11 +- core/docs/issues/project-41/gc-runbook.md | 19 +- .../issues/project-41/lean-gap-closure.md | 14 +- .../project-41/mount-authority-lease.md | 5 +- docs/architecture/api/sdk/store.md | 4 +- docs/architecture/engine/store/README.md | 1 - docs/architecture/engine/store/sqlite.md | 2 +- .../layerfs-persistence/sql/postgresql/gc.sql | 3 - .../layerfs-persistence/sql/sqlite/gc.sql | 3 - .../queries/history/gc_intent_all_branch.sql | 2 +- .../queries/history/gc_intent_all_project.sql | 2 +- .../queries/history/gc_intent_all_store.sql | 2 +- .../queries/history/gc_intent_done_insert.sql | 13 +- .../sqlite/queries/history/gc_intent_get.sql | 2 +- .../queries/history/gc_intent_insert.sql | 13 +- .../sqlite/queries/history/gc_intent_list.sql | 2 +- .../history/gc_intent_list_machine.sql | 2 +- .../queries/history/gc_intent_ops_branch.sql | 2 +- .../queries/history/gc_intent_ops_project.sql | 2 +- .../queries/history/gc_intent_ops_store.sql | 2 +- .../queries/history/gc_intent_release.sql | 4 +- .../queries/history/gc_intent_uncertain.sql | 3 +- .../src/backend/postgresql/schema.rs | 37 +- .../backend/postgresql/schema_diagnostic.rs | 2 - .../src/backend/records.rs | 15 +- .../src/backend/sqlite/schema.rs | 22 +- .../src/backend/sqlite/session/connection.rs | 16 +- .../src/diagnostic/mounts.rs | 9 +- .../src/history/admission.rs | 24 +- .../src/history/bindings.rs | 46 ++ .../layerfs-persistence/src/history/mod.rs | 1 + .../layerfs-persistence/src/internals.rs | 1 - .../layerfs-persistence/src/store/config.rs | 24 +- .../layerfs-persistence/tests/admission.rs | 15 +- .../tests/fixtures/sqlite_compact_golden.json | 2 +- .../tests/gc_conversion.rs | 354 ----------- .../tests/gc_intent_authority.rs | 142 ----- .../tests/gc_intent_done.rs | 131 +++- .../layerfs-persistence/tests/gc_schema.rs | 169 ------ .../tests/lineage_backfill.rs | 3 +- .../tests/old_format_columns.rs | 3 +- .../tests/old_format_open.rs | 3 +- .../tests/postgresql_gc_mark.rs | 3 +- .../layerfs-persistence/tests/sealed_open.rs | 99 +--- .../tests/sqlite_compact_done.rs | 6 +- .../tests/sqlite_group_rows.rs | 2 +- .../tests/sqlite_group_rows_indexed.rs | 6 +- .../tests/sqlite_inode_values.rs | 2 +- .../tests/sqlite_publication.rs | 4 +- .../tests/fixtures/merge-forms-root.sqlite | Bin 278528 -> 221184 bytes .../fixtures/merge-forms-root.sqlite-shm | Bin 0 -> 32768 bytes .../fixtures/merge-forms-root.sqlite-wal | 0 .../tests/merge_forms_fixture.rs | 6 +- tools/store_gc_convert.py | 558 ------------------ tools/test_store_gc_convert.py | 391 ------------ 56 files changed, 317 insertions(+), 1896 deletions(-) delete mode 100644 engine/crates/layerfs-persistence/tests/gc_conversion.rs delete mode 100644 engine/crates/layerfs-persistence/tests/gc_intent_authority.rs delete mode 100644 engine/crates/layerfs-persistence/tests/gc_schema.rs create mode 100644 engine/crates/layerfs-store-service/tests/fixtures/merge-forms-root.sqlite-shm create mode 100644 engine/crates/layerfs-store-service/tests/fixtures/merge-forms-root.sqlite-wal delete mode 100644 tools/store_gc_convert.py delete mode 100644 tools/test_store_gc_convert.py diff --git a/api/crates/layerfs-api/tests/project_export.rs b/api/crates/layerfs-api/tests/project_export.rs index f5094afe3d..bb87481e72 100644 --- a/api/crates/layerfs-api/tests/project_export.rs +++ b/api/crates/layerfs-api/tests/project_export.rs @@ -483,8 +483,8 @@ fn schema_version_1_store_is_refused_before_prepare_and_keeps_destination() { let store_file = paths::store_file(&home, "shop"); let current = read_user_version(&store_file); assert!( - (39..=47).contains(¤t), - "expected a schema version 3 Store, read user_version {current}" + (36..=44).contains(¤t), + "expected a schema version 2 Store, read user_version {current}" ); write_user_version(&store_file, 22); assert_eq!(read_user_version(&store_file), 22); diff --git a/core/docs/issues/project-41/LayerFS-GC-spec.md b/core/docs/issues/project-41/LayerFS-GC-spec.md index 8b69c07aaf..52f38cc6fa 100644 --- a/core/docs/issues/project-41/LayerFS-GC-spec.md +++ b/core/docs/issues/project-41/LayerFS-GC-spec.md @@ -458,15 +458,18 @@ Admission is one Store-DB table and two `BEGIN IMMEDIATE` transactions `gc_intent(op_id PRIMARY KEY, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, -generation, artifact, high_water, evidence, updated_ms, -machine_incarnation, sandbox_generation)`, +generation, artifact, high_water, evidence, updated_ms)`, `STRICT`, with `UNIQUE(scope_kind, scope_id, owner_boot)`; `kind` is `mount`, `init`, `merge`, `removal` or `compaction`, `state` is `live`, `uncertain` or `done`, `scope_kind` is `store`/`project`/`branch`, and the ids are typed per kind (17-byte project/Branch, 33-byte commit/layer, 32-byte catalog id). The migration step that adds it is the same additive step as -§4.1; the two place-authority columns were appended after `updated_ms` by a -later additive step (lease and fence are deferred, #775). +§4.1. The Store format adds no place-authority column: a live mount row +keeps its `machine_incarnation`/`sandbox_generation` tokens in `evidence` as +`place:v1;inc=;gen=` (an absent part omitted, NULL when both +are absent). A value without that prefix (a `done` row's audit text) or a +malformed one decodes as no token: missing evidence is no proof, never death +(lease and fence are deferred, #775). - A **mount** transaction checks that no operation op is running at every scope it names (Store, project, Branch), inserts its intent and commits. A diff --git a/core/docs/issues/project-41/gc-runbook.md b/core/docs/issues/project-41/gc-runbook.md index 4af899224d..75f3d863f3 100644 --- a/core/docs/issues/project-41/gc-runbook.md +++ b/core/docs/issues/project-41/gc-runbook.md @@ -122,17 +122,14 @@ installed → it records the outcome. A dead owner's op is adopted; only a live and frees no bytes; objects reachable only via the path are retained (§6.2, decisions 16/35). - **No path-level physical reclaim:** path-aware walk and per-entry page pruning are follow-ups; `keptWaste` has no page component (§6.2). - 1.0 Stores convert offline (§4.1); no online migration. -- **2.0 Stores convert per machine.** The lean 2.0 GC has no Store-side authority, - tombstone or audit tables: the proof is the home `MachineRecord.incarnation`, the - `SandboxRecord.generation`, the machine-level - `machine//sandbox-retired/*.json` tombstone and the retained - `gc_intent` `done` rows. `tools/store_gc_convert.py convert` copies each owner - home's incarnation and tombstones into the new closed Store, exports any old - audit rows to `/log/gc-audit.jsonl`, and drops the three old tables only - after every machine with rows is copied, named `--converted`, or declared - `--gone` (the missing-machine policy). The source file is never changed: it is - the backup. The tool converts SQLite Stores; a PostgreSQL Store's per-machine - copy and the final `DROP TABLE` remain an explicit operator step. +- **No Store format change for place authority.** The lean 2.0 GC has no + Store-side authority, tombstone or audit tables and no new `gc_intent` column: + the proof is the home `MachineRecord.incarnation`, the `SandboxRecord.generation`, + the machine-level `machine//sandbox-retired/*.json` tombstone, the + tokens a live mount row keeps in `gc_intent.evidence` (`place:v1;...`) and the + retained `gc_intent` `done` rows. A Store of the base format opens unchanged; + there is nothing to convert. The owner's release, an uncertain mark and a + retried registration never delete or revive a `done` row. - **Four SQLite deviations from the frozen text remain** (D1, D3, D4, D5), plus the settled D2 build decision; all are recorded in [`gc-42-decisions.md`](gc-42-decisions.md) and the frozen spec text is diff --git a/core/docs/issues/project-41/lean-gap-closure.md b/core/docs/issues/project-41/lean-gap-closure.md index 4d01b32666..084c6f3896 100644 --- a/core/docs/issues/project-41/lean-gap-closure.md +++ b/core/docs/issues/project-41/lean-gap-closure.md @@ -41,15 +41,11 @@ the exported pages; admission is unaffected. ## G3. 2.0 conversion -`tools/store_gc_convert.py` already implements the per-machine conversion -(copy the machine incarnation and Sandbox tombstones, export old audit rows -to JSONL, `--gone` for a missing machine, drop the three old tables only after -every machine converts, never touch the source file). Remaining work: a test -on a real old-format Store fixture and a documented operator runbook (the -`gc-runbook.md` already describes it). - -Acceptance: a 3-table Store fixture converts to the lean schema; `--gone` -covers a missing machine; the source is unchanged. +Withdrawn (pre-merge review): the Store keeps the base format exactly. A +live mount row stores its place tokens in the existing `gc_intent.evidence` +column (`place:v1;inc=;gen=`), so no schema version bump, +refusal or conversion tool exists, and `tools/store_gc_convert.py` was +removed. ## G4. Durable preview row diff --git a/core/docs/issues/project-41/mount-authority-lease.md b/core/docs/issues/project-41/mount-authority-lease.md index 1463b43f92..788957066c 100644 --- a/core/docs/issues/project-41/mount-authority-lease.md +++ b/core/docs/issues/project-41/mount-authority-lease.md @@ -87,7 +87,10 @@ Record the authority on the mount intent and make admission consult it: | `workspace_id` / `branch` | existing `gc_intent.workspace` / `branch` + `project` | The own-intent end key (7ab's `mount_intents::end`); never a path/folder. | | `owner_runtime` / `owner_boot` | existing `gc_intent` | The fallback evidence for private/place-null mounts; unchanged. | -Schema: additive columns on `gc_intent` (see `engine/crates/layerfs-persistence/sql/sqlite/gc.sql` +Schema (as built, superseding the additive columns proposed here): no new +column; a live row keeps both tokens in `gc_intent.evidence` as +`place:v1;inc=;gen=`, decoded as no token when NULL, prefixless +(a `done` row's audit text) or malformed. Proposed: additive columns on `gc_intent` (see `engine/crates/layerfs-persistence/sql/sqlite/gc.sql` and `sql/postgresql/gc.sql`; the `GcIntent` struct at `core/crates/layerfs-history/src/contract/records.rs:750`, builders `placed`/`owned` at 847/861). A `machine_incarnation` authority row (per machine) and a diff --git a/docs/architecture/api/sdk/store.md b/docs/architecture/api/sdk/store.md index 77b8687dc2..2ce1017cb3 100644 --- a/docs/architecture/api/sdk/store.md +++ b/docs/architecture/api/sdk/store.md @@ -619,9 +619,9 @@ The action is one of: | 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 and writes one retained `done` row with `action=preview;operator=NAME` in `evidence`, `op` null, the operator label and no owner or place columns; it changes no live intent | +| `preview` | lists the same typed view and writes one retained `done` row with `action=preview;operator=NAME` in `evidence`, `op` null, the operator label and no owner columns or place tokens; it changes no live intent | | `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` and clears the owner columns, so the unique owner key cannot block a remount | +| `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 | diff --git a/docs/architecture/engine/store/README.md b/docs/architecture/engine/store/README.md index 2308b952eb..b79bb3a01e 100644 --- a/docs/architecture/engine/store/README.md +++ b/docs/architecture/engine/store/README.md @@ -182,7 +182,6 @@ A PostgreSQL Store has no profile; its write setting is `synchronous_commit`. | `Capacity` | `Refused "Capacity"` | `Capacity("persistence")` | A bound or the disk margin was reached | | `Integrity` | `Malformed` | `Integrity("persistence")` | Stored or supplied data broke a rule | | `SchemaVersion1` | `Refused` (names the conversion) | `Integrity` | A schema version 1 SQLite Store | -| `SchemaVersion2` | `Refused` (names `tools/store_gc_convert.py convert`) | `Integrity` | A schema version 2 SQLite Store (36–38, or 42–44 with acquisition); the phase-3 authority tables convert offline | | `UnsupportedSchemaVersion` | `Refused` | `Unsupported` | Diagnostic open of an unknown layout | | `Unknown` | `Uncertain` | `UnknownOutcome` | Outcome unknown; session quarantined, its connection closed and the writer lane released ([SQLite](sqlite.md#quarantine), [PostgreSQL](postgresql.md#session)) | diff --git a/docs/architecture/engine/store/sqlite.md b/docs/architecture/engine/store/sqlite.md index 67b80dd4f1..a353c3ed2c 100644 --- a/docs/architecture/engine/store/sqlite.md +++ b/docs/architecture/engine/store/sqlite.md @@ -43,7 +43,7 @@ UPDATE and DELETE on `pack` and `pack_unit`. Open checks `application_id`, | Open | Steps | Source | | --- | --- | --- | | `create` | platform check; policy and catalog config valid; `create_new` (an existing file refuses); schema scripts, `application_id`, `user_version`, `store_policy` and `history_meta` rows | [`open.rs`](../../../../engine/crates/layerfs-persistence/src/store/open.rs) | -| `open_writable` | `user_version` 39–41 or 45–47 (16–18/22–24 get `SchemaVersion1`, 36–38/42–44 get `SchemaVersion2`, which names `tools/store_gc_convert.py convert`; others `Integrity`); additive `add_binding_hints`, `add_lineage` (with backfill), `add_merge_scratch`, `add_file_digests`, each only when the recorded schema is exactly the one before; then sweep merge records of expired owners | [`open.rs`](../../../../engine/crates/layerfs-persistence/src/store/open.rs), [`connection.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs) | +| `open_writable` | `user_version` 36–38 or 42–44 (16–18 and 22–24 get `SchemaVersion1`, others `Integrity`); additive `add_binding_hints`, `add_lineage` (with backfill), `add_merge_scratch`, `add_file_digests`, each only when the recorded schema is exactly the one before; then sweep merge records of expired owners | [`open.rs`](../../../../engine/crates/layerfs-persistence/src/store/open.rs), [`connection.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs) | | `open_read_only` | same checks, no migrations; every write refused before `BEGIN` | same | | `open_diagnostic` | read-only, never changes journal or checkpoint settings; see [Diagnostics](diagnostics.md) | [`open.rs`](../../../../engine/crates/layerfs-persistence/src/store/open.rs) | diff --git a/engine/crates/layerfs-persistence/sql/postgresql/gc.sql b/engine/crates/layerfs-persistence/sql/postgresql/gc.sql index 3df041b857..c1e97b483c 100644 --- a/engine/crates/layerfs-persistence/sql/postgresql/gc.sql +++ b/engine/crates/layerfs-persistence/sql/postgresql/gc.sql @@ -47,8 +47,6 @@ CREATE TABLE gc_intent ( high_water BIGINT, evidence TEXT, updated_ms BIGINT NOT NULL, - machine_incarnation TEXT, - sandbox_generation TEXT, UNIQUE (scope_kind, scope_id, owner_boot) ); CREATE TABLE gc_op ( @@ -98,4 +96,3 @@ CREATE TABLE kept_node ( OR (kind = 'stack' AND length(node_id) = 17 AND get_byte(node_id, 0) = 49) ) ); - diff --git a/engine/crates/layerfs-persistence/sql/sqlite/gc.sql b/engine/crates/layerfs-persistence/sql/sqlite/gc.sql index 80c89b8b1c..392c538e92 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/gc.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/gc.sql @@ -54,8 +54,6 @@ CREATE TABLE gc_intent ( high_water INTEGER, evidence TEXT, updated_ms INTEGER NOT NULL, - machine_incarnation TEXT, - sandbox_generation TEXT, UNIQUE (scope_kind, scope_id, owner_boot) ) STRICT; @@ -101,4 +99,3 @@ CREATE TABLE kept_node ( OR (kind = 'stack' AND length(node_id) = 17 AND substr(node_id, 1, 1) = X'31') ) ) STRICT, WITHOUT ROWID; - diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_branch.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_branch.sql index 3aed74891a..e3e3dfdb06 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_branch.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_branch.sql @@ -1,6 +1,6 @@ SELECT op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, - machine_incarnation, sandbox_generation + evidence FROM gc_intent WHERE state <> 'done' AND ( diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_project.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_project.sql index f52ed31cb2..34dbbd3d55 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_project.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_project.sql @@ -1,6 +1,6 @@ SELECT op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, - machine_incarnation, sandbox_generation + evidence FROM gc_intent WHERE state <> 'done' AND ( diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_store.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_store.sql index 06017a299d..3734c5cad3 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_store.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_all_store.sql @@ -1,6 +1,6 @@ SELECT op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, - machine_incarnation, sandbox_generation + evidence FROM gc_intent WHERE state <> 'done' AND op_id <> $1; 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 index 23dbed7b4b..a4c382100f 100644 --- 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 @@ -1,8 +1,9 @@ -- The durable operator preview row: a `done` row written without a live --- intent to release. The owner columns and every place column stay NULL, 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, machine_incarnation, sandbox_generation, evidence, updated_ms) -VALUES ($1, $2, $3, $4, NULL, NULL, NULL, $5, $6, NULL, NULL, 'done', FALSE, $7, NULL, NULL, $8, $9) +-- 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_get.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_get.sql index 2999fd2e4d..213d17e001 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_get.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_get.sql @@ -1,6 +1,6 @@ SELECT op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, - machine_incarnation, sandbox_generation + evidence FROM gc_intent WHERE state <> 'done' AND op_id = $1; diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_insert.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_insert.sql index fece6191fd..fd92e3ac16 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_insert.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_insert.sql @@ -1,9 +1,12 @@ -- A retry reuses the operation id. It must also replace the ownership, --- placement and authority evidence of its predecessor: a row that kept a +-- placement and place-token evidence of its predecessor: a row that kept a -- dead process's owner token would let a concurrent GC call settle the -- retried, live operation as dead instead of reporting it `Busy` (§5.1). -INSERT INTO gc_intent (op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, machine_incarnation, sandbox_generation, generation, artifact, high_water, evidence, updated_ms) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, ($13 <> 0), $14, $15, $16, NULL, NULL, NULL, NULL, $17) +-- `evidence` carries a live row's place tokens (`place:v1;...`). A retained +-- `done` row is never revived: the conflict branch skips it, so no row is +-- returned and the registration is refused. +INSERT INTO gc_intent (op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, generation, artifact, high_water, evidence, updated_ms) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, ($13 <> 0), $14, NULL, NULL, NULL, $15, $16) ON CONFLICT(op_id) DO UPDATE SET state = excluded.state, uncertain = excluded.uncertain, @@ -13,7 +16,7 @@ ON CONFLICT(op_id) DO UPDATE SET machine = excluded.machine, owner_runtime = excluded.owner_runtime, owner_boot = excluded.owner_boot, - machine_incarnation = excluded.machine_incarnation, - sandbox_generation = excluded.sandbox_generation, + evidence = excluded.evidence, updated_ms = excluded.updated_ms +WHERE gc_intent.state <> 'done' RETURNING op_id; diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_list.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_list.sql index 58f7acc674..46c2fa433f 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_list.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_list.sql @@ -1,6 +1,6 @@ SELECT op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, - machine_incarnation, sandbox_generation + evidence FROM gc_intent WHERE state <> 'done' AND scope_kind = $1 AND scope_id = $2 diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_list_machine.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_list_machine.sql index ebd8c3229d..8492a6b0d6 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_list_machine.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_list_machine.sql @@ -1,6 +1,6 @@ SELECT op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, - machine_incarnation, sandbox_generation + evidence FROM gc_intent WHERE state <> 'done' AND machine = $1; diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_branch.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_branch.sql index 277e010551..94ac35ac5a 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_branch.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_branch.sql @@ -1,6 +1,6 @@ SELECT op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, - machine_incarnation, sandbox_generation + evidence FROM gc_intent WHERE state <> 'done' AND kind IN ('init', 'merge', 'removal', 'compaction') diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_project.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_project.sql index 9556db36b2..3b1e90bee3 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_project.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_project.sql @@ -1,6 +1,6 @@ SELECT op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, - machine_incarnation, sandbox_generation + evidence FROM gc_intent WHERE state <> 'done' AND kind IN ('init', 'merge', 'removal', 'compaction') diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_store.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_store.sql index 725fbd4f08..3876eee1ea 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_store.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_ops_store.sql @@ -1,6 +1,6 @@ SELECT op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, phase, - machine_incarnation, sandbox_generation + evidence FROM gc_intent WHERE state <> 'done' AND op_id <> $1 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 4874b5ef1d..5bd14604a7 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 +1,3 @@ -DELETE FROM gc_intent WHERE op_id = $1 RETURNING op_id; +-- 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). +DELETE FROM gc_intent WHERE op_id = $1 AND state <> 'done' RETURNING op_id; diff --git a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_uncertain.sql b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_uncertain.sql index b47218d8b2..50bfa6c4e0 100644 --- a/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_uncertain.sql +++ b/engine/crates/layerfs-persistence/sql/sqlite/queries/history/gc_intent_uncertain.sql @@ -1 +1,2 @@ -UPDATE gc_intent SET state = 'uncertain', uncertain = TRUE, updated_ms = $1 WHERE op_id = $2 RETURNING op_id; +-- A retained `done` audit row is never turned back into a live intent. +UPDATE gc_intent SET state = 'uncertain', uncertain = TRUE, updated_ms = $1 WHERE op_id = $2 AND state <> 'done' RETURNING op_id; diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/schema.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/schema.rs index 762b4bf462..18243bdf72 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/schema.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/schema.rs @@ -47,7 +47,6 @@ const TRACE_SALT: &str = ",\n trace_salt bytea NOT NULL DEFAULT decode(repeat('0 /// The GC marker, position and admission tables; a Store written before them /// gains them at open ([`add_gc`]). const GC: &str = include_str!("../../../sql/postgresql/gc.sql"); - /// Init's acquisition tables, created after [`SCHEMA`] in a new schema. const ACQUISITION: &str = include_str!("../../../sql/postgresql/acquisition.sql"); /// The acquisition tables, in name order. @@ -65,7 +64,7 @@ pub(crate) const SCHEMA_VERSION: i64 = 3; /// [`SCHEMA_VERSION`] 3. const PRE_2_0_VERSION: i64 = 2; /// Every table of one Store schema, in name order. -pub const TABLES: [&str; 27] = [ +pub(crate) const TABLES: [&str; 27] = [ "absorbed", "binding_hint_block", "branch", @@ -230,21 +229,18 @@ fn kept_node_table() -> &'static str { &GC[start..end] } -/// The recorded sources of a Store written before [`kept_node_table`]: the -/// current source with that one statement removed, and the current source -/// itself (a step of the same open may have recorded it before this table is -/// added). -fn pre_kept_node_sources(acquisition: bool) -> Vec { - let without = source(acquisition).replacen(kept_node_table(), "", 1); - vec![without, source(acquisition)] +/// The recorded source of a Store written before [`kept_node_table`]: the +/// current source with that one statement removed. +fn pre_kept_node_source(acquisition: bool) -> String { + source(acquisition).replacen(kept_node_table(), "", 1) } /// One additive migration of an existing Store schema. `probe` is the /// `information_schema` relation and condition that finds what the migration /// adds; a schema that already has it is left alone, first in one statement /// with no transaction and no lane wait, then again under the lane, because -/// another process may have migrated first. `earlier` gives, for each -/// acquisition choice, the sources a Store recorded before the migration. +/// another process may have migrated first. `earlier` gives the source a Store +/// recorded before the migration, without and with the acquisition tables. /// A recorded source that is not a revision of one of those /// ([`is_earlier_source`]), or a recorded definition that is not the live one, /// is refused with `Integrity`, never migrated. Otherwise `apply` runs and the @@ -252,7 +248,7 @@ fn pre_kept_node_sources(acquisition: bool) -> Vec { fn migrate( session: &Session, probe: &str, - earlier: impl Fn(bool) -> Vec, + earlier: fn(bool) -> String, apply: impl FnOnce(&Transaction<'_>, bool) -> Result<(), PersistenceError>, ) -> Result<(), PersistenceError> { let present = session.run_as::<_, BackendError>(Mode::Statement, |tx| { @@ -279,11 +275,10 @@ fn migrate( return Err(BackendError::Integrity.into()); }; let recorded: String = row.get(0)?; - let Some(acquisition) = [false, true].into_iter().find(|&acquisition| { - earlier(acquisition) - .iter() - .any(|previous| is_earlier_source(&recorded, previous.clone())) - }) else { + let Some(acquisition) = [false, true] + .into_iter() + .find(|&acquisition| is_earlier_source(&recorded, earlier(acquisition))) + else { return Err(BackendError::Integrity.into()); }; if row.get::(1)? != definition(tx)? { @@ -305,7 +300,7 @@ pub(crate) fn add_kept_node(session: &Session) -> Result<(), PersistenceError> { migrate( session, "tables WHERE table_name='kept_node' AND table_type='BASE TABLE'", - pre_kept_node_sources, + pre_kept_node_source, |tx, _| Ok(tx.batch(kept_node_table())?), ) } @@ -316,7 +311,7 @@ pub(crate) fn add_gc(session: &Session) -> Result<(), PersistenceError> { migrate( session, "tables WHERE table_name='gc_intent' AND table_type='BASE TABLE'", - |acquisition| vec![pre_gc_source(acquisition)], + pre_gc_source, |tx, acquisition| { let tables = tx.query(TABLE_NAMES, vec![])?; let actual: Vec = tables.iter().map(|r| r.get(0)).collect::>()?; @@ -341,7 +336,7 @@ pub(crate) fn add_position_state(session: &Session) -> Result<(), PersistenceErr migrate( session, "columns WHERE table_name='history_meta' AND column_name='next_history_serial'", - |acquisition| vec![source(acquisition)], + source, |tx, _| { tx.batch("ALTER TABLE history_meta ADD COLUMN next_history_serial bigint NOT NULL DEFAULT 1;")?; Ok(tx.batch( @@ -374,7 +369,7 @@ pub(crate) fn add_position_columns(session: &Session) -> Result<(), PersistenceE migrate( session, "columns WHERE table_name='commit' AND column_name='history_serial'", - |acquisition| vec![source(acquisition)], + source, |tx, _| { tx.batch(POSITION_COLUMNS)?; Ok(backfill_position_serials(tx)?) diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/schema_diagnostic.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/schema_diagnostic.rs index 296a262e59..aa2857738a 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/schema_diagnostic.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/schema_diagnostic.rs @@ -65,8 +65,6 @@ gc_intent artifact text YES gc_intent high_water bigint YES gc_intent evidence text YES gc_intent updated_ms bigint NO -gc_intent machine_incarnation text YES -gc_intent sandbox_generation text YES gc_op id bigint NO gc_op generation bigint NO gc_op phase text NO diff --git a/engine/crates/layerfs-persistence/src/backend/records.rs b/engine/crates/layerfs-persistence/src/backend/records.rs index 74e76effa9..1fb7c9dcc0 100644 --- a/engine/crates/layerfs-persistence/src/backend/records.rs +++ b/engine/crates/layerfs-persistence/src/backend/records.rs @@ -130,10 +130,6 @@ pub enum BackendError { /// A SQLite Store of schema version 1 (before #91): refused at open with /// the offline conversion named, never misread. SchemaVersion1, - /// A SQLite Store of the released schema version 2 (36/37/38, or - /// 42/43/44 with acquisition tables): refused at open with the explicit - /// 2.0 conversion named, never silently migrated to version 3. - SchemaVersion2, /// A PostgreSQL Store of schema version 2, written before 2.0's ancestor /// lists and pack directories (#758): refused at open, never converted. PostgresSchema2, @@ -146,11 +142,6 @@ pub enum BackendError { pub(crate) const SCHEMA_VERSION_1: &str = "schema version 1 Store (one row per inode value and binding hint, before #91): \ convert a closed copy offline with tools/store_blocks.py migrate"; -/// The refusal a released schema version 2 SQLite Store gets at open. -pub(crate) const SCHEMA_VERSION_2: &str = - "schema version 2 Store (36/37/38, or 42/43/44 with acquisition tables): \ -this build writes schema version 3; back up and convert the closed Store once with \ -tools/store_gc_convert.py convert (the 2.0 conversion), then reopen"; /// The refusal a PostgreSQL Store of schema version 2 gets at open (#758 D5). pub(crate) const POSTGRES_SCHEMA_2: &str = "PostgreSQL Store schema version 2 (before 2.0's ancestor lists and pack directories, #758): \ @@ -164,14 +155,11 @@ impl From for layerfs_storage::port::PersistenceError { BackendError::SchemaVersion1 => Self::Refused { status: SCHEMA_VERSION_1.to_owned(), }, - BackendError::SchemaVersion2 => Self::Refused { - status: SCHEMA_VERSION_2.to_owned(), - }, BackendError::PostgresSchema2 => Self::Refused { status: POSTGRES_SCHEMA_2.to_owned(), }, BackendError::UnsupportedSchemaVersion(version) => Self::Refused { - status: format!("unsupported SQLite Store schema version {version}; supported versions are 39/40/41 and 45/46/47; no migration performed"), + status: format!("unsupported SQLite Store schema version {version}; supported versions are 36/37/38 and 42/43/44; no migration performed"), }, // §10: the definite out-of-space refusal, named explicitly so a // new variant cannot silently inherit a capacity verdict. @@ -198,7 +186,6 @@ impl From for layerfs_history::HistoryError { BackendError::Capacity => Self::Capacity("persistence"), BackendError::Integrity => Self::Integrity("persistence"), BackendError::SchemaVersion1 => Self::Integrity(SCHEMA_VERSION_1), - BackendError::SchemaVersion2 => Self::Integrity(SCHEMA_VERSION_2), BackendError::PostgresSchema2 => Self::Integrity(POSTGRES_SCHEMA_2), BackendError::UnsupportedSchemaVersion(_) => { Self::Unsupported("SQLite Store schema version") diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/schema.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/schema.rs index 44c735a0a1..ef412d1e0f 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/schema.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/schema.rs @@ -18,7 +18,6 @@ pub(crate) const DIGESTS: &str = include_str!("../../../sql/sqlite/file_digest.s /// GC markers, positions and admission records; a Store written before them /// gains them at open. pub(crate) const GC: &str = include_str!("../../../sql/sqlite/gc.sql"); - /// The position columns T1.2a/T1.4 append, as `("table", "column", ALTER)`; /// a Store written before them gains them at open. pub(crate) const POSITION_COLUMNS: [(&str, &str, &str); 4] = [ @@ -46,7 +45,7 @@ pub(crate) const POSITION_COLUMNS: [(&str, &str, &str); 4] = [ const UNIT_INDEX: &str = include_str!("../../../sql/sqlite/objects_units_index.sql"); const UNITS: &str = include_str!("../../../sql/sqlite/objects_units.sql"); const ACQUISITION: &str = include_str!("../../../sql/sqlite/acquisition/schema.sql"); -pub(crate) type Selection = (crate::SqlitePackLayout, crate::SqliteAcquisitionSchema); +type Selection = (crate::SqlitePackLayout, crate::SqliteAcquisitionSchema); pub(super) fn scripts((layout, acquisition): Selection) -> Vec { let objects = match layout { crate::SqlitePackLayout::Monolithic => OBJECTS.to_owned(), @@ -340,9 +339,13 @@ pub(crate) fn check( expected.push("pack_unit"); } if acquisition == crate::SqliteAcquisitionSchema::Tables { - expected.extend(["init_entry", "init_host_file", "init_operation"]); - // Init's AUTOINCREMENT operation identity creates `sqlite_sequence`. - expected.push("sqlite_sequence"); + // `sqlite_sequence` is the engine's never-reused operation identity counter. + expected.extend([ + "init_entry", + "init_host_file", + "init_operation", + "sqlite_sequence", + ]); } expected.sort_unstable(); if actual != expected { @@ -500,19 +503,16 @@ impl super::session::connection::Session { |tx| tx.bootstrap(GC), ) } - /// Adds the `kept_node` history-closure table (T7.1) to a Store written - /// before it, with or without the T1.4 next-serial column. A Store an - /// earlier step of this same open brought forward (the authority - /// migration) recorded the current source before this table exists, so - /// that source is accepted too. The table is empty until a mark writes it. + /// before it, with or without the T1.4 next-serial column. The table is + /// empty until a mark writes it. pub(crate) fn add_kept_node(&self) -> Result<(), BackendError> { self.migrate( &has_table("kept_node"), |current| { let without = current.replacen(kept_node_table(), "", 1); let earlier = without.replacen(next_history_serial_column(), "", 1); - (vec![earlier, without, current.clone()], current) + (vec![earlier, without], current) }, |tx| tx.bootstrap(kept_node_table()), ) diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs index ed6f455d0b..d9988e8560 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs @@ -261,16 +261,12 @@ impl Session { // Versions 1 to 6 kept inode values in pooled packs behind an // ordinal catalogue. Versions 16 to 18 and 22 to 24 (schema // version 1) kept one row per inode value and binding hint; - // versions 36 to 38 and 42 to 44 (schema version 2) keep them in - // blocks but carry the removed Store-side authority tables; - // versions 39 to 41 and 45 to 47 (schema version 3) are the lean - // phase-3 schema. A Store of version 1 or 2 is refused here, - // never misread or silently converted. + // schema version 2 (#91) keeps them in blocks. Such a Store is + // refused here, never misread or converted. let acquisition = match stored { - 39..=41 => crate::SqliteAcquisitionSchema::Absent, - 45..=47 => crate::SqliteAcquisitionSchema::Tables, + 36..=38 => crate::SqliteAcquisitionSchema::Absent, + 42..=44 => crate::SqliteAcquisitionSchema::Tables, 16..=18 | 22..=24 => return Err(BackendError::SchemaVersion1), - 36..=38 | 42..=44 => return Err(BackendError::SchemaVersion2), _ => { return Err(if diagnostic { BackendError::UnsupportedSchemaVersion(stored) @@ -280,8 +276,8 @@ impl Session { } }; let layout = match stored - acquisition.version_offset() { - 39 => crate::SqlitePackLayout::Monolithic, - 40 => crate::SqlitePackLayout::GroupRows, + 36 => crate::SqlitePackLayout::Monolithic, + 37 => crate::SqlitePackLayout::GroupRows, _ => crate::SqlitePackLayout::GroupRowsIndexed, }; (layout, acquisition) diff --git a/engine/crates/layerfs-persistence/src/diagnostic/mounts.rs b/engine/crates/layerfs-persistence/src/diagnostic/mounts.rs index 1f3cf10ac3..58cda1e148 100644 --- a/engine/crates/layerfs-persistence/src/diagnostic/mounts.rs +++ b/engine/crates/layerfs-persistence/src/diagnostic/mounts.rs @@ -109,7 +109,7 @@ pub(super) fn read( view: &dyn View, stack: Option, ) -> Result, BackendError> { - let mut sql = String::from("SELECT g.op_id,g.scope_id,g.workspace,g.sandbox,g.machine,p.name,b.name,g.owner_runtime,g.owner_boot,g.machine_incarnation,g.sandbox_generation,g.uncertain FROM gc_intent g LEFT JOIN branch b ON g.scope_kind='branch' AND b.branch_id=g.scope_id LEFT JOIN layer_stack p ON p.layer_stack_id=CASE WHEN g.scope_kind='project' THEN g.scope_id ELSE b.layer_stack_id END WHERE g.kind='mount' AND g.state<>'done'"); + let mut sql = String::from("SELECT g.op_id,g.scope_id,g.workspace,g.sandbox,g.machine,p.name,b.name,g.owner_runtime,g.owner_boot,g.evidence,g.uncertain FROM gc_intent g LEFT JOIN branch b ON g.scope_kind='branch' AND b.branch_id=g.scope_id LEFT JOIN layer_stack p ON p.layer_stack_id=CASE WHEN g.scope_kind='project' THEN g.scope_id ELSE b.layer_stack_id END WHERE g.kind='mount' AND g.state<>'done'"); let mut params = Vec::new(); if let Some(stack) = stack { sql.push_str(" AND (g.scope_kind='store' OR p.layer_stack_id=?1)"); @@ -119,6 +119,7 @@ pub(super) fn read( view.query(&sql, params)? .iter() .map(|r| { + let (machine_incarnation, sandbox_generation) = crate::history::place_tokens(r.get(9)?); Ok(MountHolder { operation: r.get(0)?, scope: r.get(1)?, @@ -129,9 +130,9 @@ pub(super) fn read( branch: r.get(6)?, owner_runtime: r.get(7)?, owner_boot: r.get(8)?, - machine_incarnation: r.get(9)?, - sandbox_generation: r.get(10)?, - uncertain: r.get::(11)? != 0, + machine_incarnation, + sandbox_generation, + uncertain: r.get::(10)? != 0, }) }) .collect() diff --git a/engine/crates/layerfs-persistence/src/history/admission.rs b/engine/crates/layerfs-persistence/src/history/admission.rs index 9e93d2260f..de669b144c 100644 --- a/engine/crates/layerfs-persistence/src/history/admission.rs +++ b/engine/crates/layerfs-persistence/src/history/admission.rs @@ -31,7 +31,7 @@ use super::rows::{cell, one, unsigned}; use super::transaction::Transaction; -use super::{branch, layerstack, params, paths, position}; +use super::{branch, layerstack, params, paths, place_evidence, place_tokens, position}; use crate::backend::records::Param; use crate::backend::Engine; use crate::history::provider::HistoryProvider; @@ -149,10 +149,9 @@ fn workspace_of(text: Option) -> HistoryResult> { Ok(Some(body)) } -/// Decodes the sixteen columns every intent query returns, in order: -/// op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, -/// branch, owner_runtime, owner_boot, state, uncertain, phase, -/// machine_incarnation, sandbox_generation. +/// Decodes the fifteen columns every intent query returns, in order: op_id, +/// kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, +/// owner_runtime, owner_boot, state, uncertain, phase, evidence (place tokens). fn intent_row(row: &crate::backend::records::Record) -> HistoryResult { let op_id: Vec = cell(row, 0)?; let op_id: [u8; 16] = op_id @@ -161,6 +160,7 @@ fn intent_row(row: &crate::backend::records::Record) -> HistoryResult .map_err(|_| HistoryError::Integrity("gc intent op_id"))?; let state: String = cell(row, 11)?; let uncertain_flag: i64 = cell(row, 12)?; + let (machine_incarnation, sandbox_generation) = place_tokens(cell(row, 14)?); Ok(GcIntent { op_id, kind: kind_of(&cell::(row, 1)?)?, @@ -175,8 +175,8 @@ fn intent_row(row: &crate::backend::records::Record) -> HistoryResult owner_boot: cell(row, 10)?, project_id: None, phase: cell(row, 13)?, - machine_incarnation: cell(row, 14)?, - sandbox_generation: cell(row, 15)?, + machine_incarnation, + sandbox_generation, uncertain: state == "uncertain" || uncertain_flag != 0, }) } @@ -555,7 +555,7 @@ pub(super) fn register_in( "live" }; let uncertain = i64::from(intent.uncertain); - tx.execute( + let written = tx.execute( INSERT, params![ intent.op_id.to_vec(), @@ -572,12 +572,13 @@ pub(super) fn register_in( state, uncertain, intent.phase.clone(), - intent.machine_incarnation.clone(), - intent.sandbox_generation.clone(), + place_evidence(intent), now_ms(), ], )?; - Ok(()) + (written > 0) + .then_some(()) + .ok_or(HistoryError::Conflict("gc intent op released as done")) } /// The advisory keys a PostgreSQL intent names, Store key first, each with the @@ -996,4 +997,3 @@ pub(crate) fn register(provider: &HistoryProvider, intent: &GcIntent) -> History } } } - diff --git a/engine/crates/layerfs-persistence/src/history/bindings.rs b/engine/crates/layerfs-persistence/src/history/bindings.rs index 0b361ec2bd..333a673e21 100644 --- a/engine/crates/layerfs-persistence/src/history/bindings.rs +++ b/engine/crates/layerfs-persistence/src/history/bindings.rs @@ -1,5 +1,6 @@ //! Owned scalar bindings for history statements. use crate::backend::records::Param; +use layerfs_history::records::GcIntent; pub(crate) trait Parameters { fn into_params(self) -> Vec; } @@ -55,3 +56,48 @@ impl From for Param { Self::I64(v) } } + +/// The prefix of a live `gc_intent` row's place tokens in its `evidence` +/// column. A retained `done` row's audit text never carries it. +const PLACE_EVIDENCE: &str = "place:v1"; + +/// Encodes a live intent's place tokens into `evidence`: +/// `place:v1;inc=;gen=`, an absent part omitted and +/// NULL when both are absent. A token that is empty or holds `;` cannot round +/// trip and is not recorded: missing evidence is no proof, never death. +pub(crate) fn place_evidence(intent: &GcIntent) -> Option { + let mut text = String::from(PLACE_EVIDENCE); + let tokens = [&intent.machine_incarnation, &intent.sandbox_generation]; + for (key, token) in ["inc", "gen"].into_iter().zip(tokens.map(Option::as_deref)) { + if let Some(token) = token.filter(|t| !t.is_empty() && !t.contains(';')) { + text.push_str(&format!(";{key}={token}")); + } + } + (text.len() > PLACE_EVIDENCE.len()).then_some(text) +} + +/// Decodes [`place_evidence`] into `(machine_incarnation, sandbox_generation)`. +/// NULL, a value without the `place:v1` prefix (a `done` row's audit text) +/// or a malformed value yields no tokens. +pub(crate) fn place_tokens(evidence: Option) -> (Option, Option) { + let text = evidence.unwrap_or_default(); + let Some(rest) = text + .strip_prefix(PLACE_EVIDENCE) + .and_then(|r| r.strip_prefix(';')) + else { + return (None, None); + }; + let (mut incarnation, mut generation) = (None, None); + for part in rest.split(';') { + let (slot, token) = match part.split_once('=') { + Some(("inc", token)) if incarnation.is_none() => (&mut incarnation, token), + Some(("gen", token)) if generation.is_none() => (&mut generation, token), + _ => return (None, None), + }; + if token.is_empty() { + return (None, None); + } + *slot = Some(token.to_owned()); + } + (incarnation, generation) +} diff --git a/engine/crates/layerfs-persistence/src/history/mod.rs b/engine/crates/layerfs-persistence/src/history/mod.rs index 05642ba601..3a5d89075f 100644 --- a/engine/crates/layerfs-persistence/src/history/mod.rs +++ b/engine/crates/layerfs-persistence/src/history/mod.rs @@ -35,6 +35,7 @@ pub(crate) use rows::{ }; use bindings::params; +pub(crate) use bindings::{place_evidence, place_tokens}; use layerfs_history::query; pub use objects::{Sequence, Spans}; pub(crate) mod facts; diff --git a/engine/crates/layerfs-persistence/src/internals.rs b/engine/crates/layerfs-persistence/src/internals.rs index c928af8da1..449a2c9bc0 100644 --- a/engine/crates/layerfs-persistence/src/internals.rs +++ b/engine/crates/layerfs-persistence/src/internals.rs @@ -10,7 +10,6 @@ pub use crate::backend::postgresql::compact::{ pub use crate::backend::postgresql::probe::{ reads as postgresql_reads, Outcome as PostgresReadOutcome, Read as PostgresRead, }; -pub use crate::backend::postgresql::schema::TABLES as POSTGRESQL_TABLES; pub use crate::backend::postgresql::session::rows::sqlstate; pub use crate::backend::records::BackendError; pub use crate::backend::sqlite::compact::{ diff --git a/engine/crates/layerfs-persistence/src/store/config.rs b/engine/crates/layerfs-persistence/src/store/config.rs index d09b0615c3..718b70a742 100644 --- a/engine/crates/layerfs-persistence/src/store/config.rs +++ b/engine/crates/layerfs-persistence/src/store/config.rs @@ -121,12 +121,12 @@ impl SqlitePersistenceProfile { /// Explicit physical layout for a newly created embedded Store. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub enum SqlitePackLayout { - /// Complete pack BLOBs (schema version 39, or 45 with acquisition tables). + /// Complete pack BLOBs (schema version 36, or 42 with acquisition tables). #[default] Monolithic, - /// Complete encoded groups in independent immutable rows (40 or 46). + /// Complete encoded groups in independent immutable rows (37 or 43). GroupRows, - /// Group rows with a covering index for bounded mapping validation (41 or 47). + /// Group rows with a covering index for bounded mapping validation (38 or 44). GroupRowsIndexed, } impl SqlitePackLayout { @@ -134,26 +134,24 @@ impl SqlitePackLayout { matches!(self, Self::GroupRows | Self::GroupRowsIndexed) } /// The stored schema version of this layout without acquisition - /// tables. Versions 39 to 41 (45 to 47 with them) are schema version 3: - /// the lean phase-3 schema, with the four `gc_intent` authority columns - /// and no Store-side authority or audit tables. Versions 16 to 18 and - /// 22 to 24 (schema version 1) and 36 to 38 and 42 to 44 (schema version - /// 2) are refused at open, never misread or converted. + /// tables. Versions 36 to 38 (42 to 44 with them) are schema version 2 + /// (#91): inode values and binding hints in append-only blocks. The + /// version 1 layouts, 16 to 18 and 22 to 24, are refused at open. pub(crate) const fn version(self) -> i64 { match self { - Self::Monolithic => 39, - Self::GroupRows => 40, - Self::GroupRowsIndexed => 41, + Self::Monolithic => 36, + Self::GroupRows => 37, + Self::GroupRowsIndexed => 38, } } } /// Explicit creation-only selection of the initial-acquisition working tables. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub enum SqliteAcquisitionSchema { - /// Schema versions 39 to 41: no acquisition tables; acquisition is unavailable. + /// Schema versions 36 to 38: no acquisition tables; acquisition is unavailable. #[default] Absent, - /// Schema versions 45 to 47: the same pack layouts with the acquisition tables. + /// Schema versions 42 to 44: the same pack layouts with the acquisition tables. Tables, } impl SqliteAcquisitionSchema { diff --git a/engine/crates/layerfs-persistence/tests/admission.rs b/engine/crates/layerfs-persistence/tests/admission.rs index 4f586c4b07..505d299e55 100644 --- a/engine/crates/layerfs-persistence/tests/admission.rs +++ b/engine/crates/layerfs-persistence/tests/admission.rs @@ -375,17 +375,20 @@ fn an_intent_round_trips_its_place_authority() { assert_eq!(listed[0].machine_incarnation, authority.machine_incarnation); assert_eq!(listed[0].sandbox_generation, authority.sandbox_generation); - // The registration writes the two place columns, not just the memory value. + // The registration writes the tokens into the row's `evidence` column, + // not just the memory value: the base Store format has no place columns. let connection = rusqlite::Connection::open(&path).unwrap(); - let row: (Option, Option) = connection + let evidence: Option = connection .query_row( - "SELECT machine_incarnation, sandbox_generation FROM gc_intent WHERE op_id = ?1", + "SELECT evidence FROM gc_intent WHERE op_id = ?1", [op(30).as_slice()], - |row| Ok((row.get(0)?, row.get(1)?)), + |row| row.get(0), ) .unwrap(); - assert_eq!(row.0.as_deref(), Some("worker:7")); - assert_eq!(row.1.as_deref(), Some("sandbox:3")); + assert_eq!( + evidence.as_deref(), + Some("place:v1;inc=worker:7;gen=sandbox:3") + ); history.gc_release(&op(30)).unwrap(); } diff --git a/engine/crates/layerfs-persistence/tests/fixtures/sqlite_compact_golden.json b/engine/crates/layerfs-persistence/tests/fixtures/sqlite_compact_golden.json index 3a492547ce..30582fab8a 100644 --- a/engine/crates/layerfs-persistence/tests/fixtures/sqlite_compact_golden.json +++ b/engine/crates/layerfs-persistence/tests/fixtures/sqlite_compact_golden.json @@ -378,7 +378,7 @@ "logicalDiscarded": 182465, "path": "rebuild", "peakTempBytes": 405504, - "physicalShrink": 225280, + "physicalShrink": 221184, "residue": { "artifacts": [], "bytes": 0, diff --git a/engine/crates/layerfs-persistence/tests/gc_conversion.rs b/engine/crates/layerfs-persistence/tests/gc_conversion.rs deleted file mode 100644 index fa64e6c37f..0000000000 --- a/engine/crates/layerfs-persistence/tests/gc_conversion.rs +++ /dev/null @@ -1,354 +0,0 @@ -//! The 2.0 conversion of a phase-3 schema version 2 Store -//! (`tools/store_gc_convert.py`): the old machine authority and Sandbox -//! tombstones move to the home, `gc_audit` is exported to JSONL, and the -//! converted Store opens as schema version 3 only after every known machine -//! is copied or declared gone. The tool is the offline operator step the -//! version 2 refusal names; the source file stays the backup. -#![cfg(any(target_os = "macos", target_os = "linux"))] -mod support; - -use layerfs_history::{ - GcIntent, GcIntentKind, GcScopeKind, HistoryCatalog, HistoryCatalogConfig, PlaceAuthority, -}; -use layerfs_persistence::{PersistenceConfig, SqliteHandles, SqlitePersistenceProfile}; -use layerfs_storage::StoragePolicy; -use support::{Temp, BINDING}; - -/// The lean `gc.sql`; the phase-3 source was this text plus [`AUTHORITY`]. -const GC: &str = include_str!("../sql/sqlite/gc.sql"); - -/// The three tables the phase-3 branch's `gc.sql` appended. -const AUTHORITY: &str = "CREATE TABLE gc_machine_authority (\n machine TEXT PRIMARY KEY,\n incarnation TEXT NOT NULL,\n updated_ms INTEGER NOT NULL CHECK (updated_ms >= 0)\n) STRICT;\n\nCREATE TABLE gc_sandbox_tombstone (\n sandbox TEXT NOT NULL,\n machine TEXT NOT NULL,\n generation TEXT NOT NULL,\n retired_ms INTEGER NOT NULL CHECK (retired_ms >= 0),\n PRIMARY KEY (sandbox, machine)\n) STRICT, WITHOUT ROWID;\n\nCREATE TABLE gc_audit (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n at_ms INTEGER NOT NULL CHECK (at_ms >= 0),\n action TEXT NOT NULL,\n op_id BLOB,\n detail TEXT\n) STRICT;\n"; - -fn config(path: &std::path::Path) -> PersistenceConfig { - PersistenceConfig::sqlite(path).with_sqlite_profile(SqlitePersistenceProfile::Normal) -} - -fn create(path: &std::path::Path) -> SqliteHandles { - SqliteHandles::create( - config(path), - StoragePolicy::frozen_default(), - &HistoryCatalogConfig { - binding_key: BINDING.to_vec(), - cursor_key: [71; 32], - incarnation: 7, - }, - ) - .expect("Store creation") -} - -fn writable( - path: &std::path::Path, -) -> Result { - SqliteHandles::open_writable(config(path), BINDING, [71; 32]) -} - -fn definition(sql: &rusqlite::Connection) -> String { - let mut statement = sql - .prepare("SELECT type,name,sql FROM sqlite_schema WHERE substr(name,1,7)!='sqlite_' ORDER BY type,name") - .unwrap(); - let rows = statement - .query_map([], |r| Ok([r.get::<_, String>(0)?, r.get(1)?, r.get(2)?])) - .unwrap(); - rows.map(|r| r.unwrap().map(|v| v + "\n").concat()) - .collect() -} - -/// Rewrites a fresh version 3 Store into the phase-3 version 2 format: the -/// three authority tables, the version 36 checks and values, and the source -/// and definition that build recorded. -fn downgrade(path: &std::path::Path, machines: &[(&str, &str)]) { - let sql = rusqlite::Connection::open(path).unwrap(); - let source: String = sql - .query_row( - "SELECT schema_source FROM history_meta WHERE id=1", - [], - |r| r.get(0), - ) - .unwrap(); - let old = source - .replace("schema_version=39", "schema_version=36") - .replace(GC, &format!("{GC}{AUTHORITY}")); - assert_ne!(old, source, "the lean source became the phase-3 source"); - sql.execute_batch(AUTHORITY).unwrap(); - for (machine, incarnation) in machines { - sql.execute( - "INSERT INTO gc_machine_authority(machine,incarnation,updated_ms) VALUES(?1,?2,5)", - rusqlite::params![machine, incarnation], - ) - .unwrap(); - } - sql.execute( - "INSERT INTO gc_sandbox_tombstone(sandbox,machine,generation,retired_ms) \ - VALUES('box','native','old-generation',7)", - rusqlite::params![], - ) - .unwrap(); - sql.execute( - "INSERT INTO gc_audit(at_ms,action,op_id,detail) VALUES(8,'settle',?1,'conversion')", - rusqlite::params![vec![0u8, 1, 2, 3]], - ) - .unwrap(); - sql.execute_batch( - "PRAGMA writable_schema=ON; \ - UPDATE sqlite_schema SET sql=replace(sql,'schema_version=39)','schema_version=36)') \ - WHERE type='table' AND name IN ('store_policy','history_meta'); \ - PRAGMA writable_schema=OFF;", - ) - .unwrap(); - sql.execute_batch("PRAGMA user_version=36").unwrap(); - drop(sql); - // Reopen: SQLite reads the patched checks before the version columns change. - let sql = rusqlite::Connection::open(path).unwrap(); - sql.execute( - "UPDATE store_policy SET schema_version=36", - rusqlite::params![], - ) - .unwrap(); - sql.execute( - "UPDATE history_meta SET schema_version=36,schema_source=?1,schema_definition=?2", - rusqlite::params![old, definition(&sql)], - ) - .unwrap(); - let _ = sql.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)"); - drop(sql); - // The tool refuses a non-empty -wal: a closed Store leaves none. - for suffix in ["-wal", "-shm"] { - let side = std::path::PathBuf::from(format!("{}{suffix}", path.display())); - if side.metadata().map(|meta| meta.len() == 0).unwrap_or(false) { - let _ = std::fs::remove_file(side); - } - } -} - -/// A layout 3 home with one machine record per name. -fn home(temp: &Temp, machines: &[&str]) -> std::path::PathBuf { - let path = temp.join("home"); - std::fs::create_dir_all(path.join("machine")).unwrap(); - std::fs::write( - path.join("layerfs.json"), - "{\"layout\":3,\"id\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}\n", - ) - .unwrap(); - for machine in machines { - let folder = path.join("machine").join(machine); - std::fs::create_dir_all(&folder).unwrap(); - std::fs::write( - folder.join("record.json"), - format!("{{\"v\":1,\"name\":\"{machine}\",\"platform\":\"native\",\"created\":1}}\n"), - ) - .unwrap(); - } - path -} - -/// The tool's path, or None when python3 is not on this machine (NOT_RUN). -fn tool() -> Option { - let tool = - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../tools/store_gc_convert.py"); - if !tool.is_file() - || std::process::Command::new("python3") - .arg("--version") - .output() - .is_err() - { - return None; - } - Some(tool) -} - -fn run(tool: &std::path::Path, args: &[&str]) -> std::process::Output { - std::process::Command::new("python3") - .arg(tool) - .args(args) - .output() - .expect("the conversion tool runs") -} - -#[test] -fn the_converted_store_opens_and_the_home_holds_the_old_authority() { - let Some(tool) = tool() else { - eprintln!("NOT_RUN: python3 or tools/store_gc_convert.py is absent"); - return; - }; - let temp = Temp::new("gc-conversion"); - let path = temp.join("db"); - drop(create(&path)); - downgrade(&path, &[("native", "old-incarnation")]); - let home = home(&temp, &["native"]); - let target = temp.join("converted"); - let output = run( - &tool, - &[ - "convert", - path.to_str().unwrap(), - target.to_str().unwrap(), - home.to_str().unwrap(), - ], - ); - assert!( - output.status.success(), - "the conversion succeeds: {}", - String::from_utf8_lossy(&output.stderr) - ); - let record = std::fs::read_to_string(home.join("machine/native/record.json")).unwrap(); - assert!( - record.contains("\"incarnation\":\"old-incarnation\""), - "the machine record took the old authority: {record}" - ); - let tombstone = - std::fs::read_to_string(home.join("machine/native/sandbox-retired/box.json")).unwrap(); - assert!( - tombstone.contains("\"generation\":\"old-generation\""), - "the home holds the old Sandbox tombstone: {tombstone}" - ); - let audit = std::fs::read_to_string(home.join("log/gc-audit.jsonl")).unwrap(); - assert!( - audit.contains("\"action\":\"settle\""), - "the audit is exported: {audit}" - ); - let handles = writable(&target).expect("the converted Store opens as schema version 3"); - drop(handles); - let sql = rusqlite::Connection::open(&target).unwrap(); - assert_eq!( - sql.query_row("PRAGMA user_version", [], |r| r.get::<_, i64>(0)) - .unwrap(), - 39 - ); - for table in ["gc_audit", "gc_machine_authority", "gc_sandbox_tombstone"] { - let count: i64 = sql - .query_row( - "SELECT count(*) FROM sqlite_schema WHERE type='table' AND name=?1", - rusqlite::params![table], - |r| r.get(0), - ) - .unwrap(); - assert_eq!(count, 0, "{table} is dropped in the target"); - } - let sequence: i64 = sql - .query_row( - "SELECT count(*) FROM sqlite_schema WHERE name='sqlite_sequence'", - [], - |r| r.get(0), - ) - .unwrap(); - assert_eq!(sequence, 0, "gc_audit's sequence table is gone"); -} - -/// The converted Store is usable by the phase-4 GC surface: a mount intent -/// registers on the lean schema, the operator release retains its `done` row, -/// and the bounded audit reads it back. No authority table is involved, so the -/// conversion's drop cannot take the audit writer with it. -#[test] -fn the_converted_store_serves_the_operator_audit() { - let Some(tool) = tool() else { - eprintln!("NOT_RUN: python3 or tools/store_gc_convert.py is absent"); - return; - }; - let temp = Temp::new("gc-conversion-audit"); - let path = temp.join("db"); - drop(create(&path)); - downgrade(&path, &[("native", "old-incarnation")]); - let home = home(&temp, &["native"]); - let target = temp.join("converted"); - let output = run( - &tool, - &[ - "convert", - path.to_str().unwrap(), - target.to_str().unwrap(), - home.to_str().unwrap(), - ], - ); - assert!( - output.status.success(), - "the conversion succeeds: {}", - String::from_utf8_lossy(&output.stderr) - ); - let handles = writable(&target).expect("the converted Store opens as schema version 3"); - let scope = [0x52u8; 32]; - let intent = GcIntent::shared([0x51; 16], GcIntentKind::Mount, GcScopeKind::Store, scope) - .placed(Some([0x53; 32]), Some("box"), Some("native")) - .owned(Some("pid:1@0"), Some("boot:1")) - .with_phase(Some("bind")) - .authorized(PlaceAuthority::default()); - handles - .history - .gc_register(&intent) - .expect("the lean schema admits a mount intent"); - handles - .history - .gc_mark_uncertain(&[0x51; 16]) - .expect("the operator settle marks the row uncertain"); - let evidence = "action=release;operator=alice;op=51515151515151515151515151515151"; - assert!( - handles - .history - .gc_release_done(&[0x51; 16], evidence) - .expect("the converted Store retains the released row"), - "the registered mount is released" - ); - assert!( - handles - .history - .gc_intents(GcScopeKind::Store, &scope) - .expect("the live read runs on the converted Store") - .is_empty(), - "the retained done row is not a live holder" - ); - let page = handles - .history - .gc_done_intents(0, 10) - .expect("the bounded audit reads the converted Store"); - assert_eq!(page.items.len(), 1, "{page:?}"); - assert_eq!(page.items[0].op_id, [0x51; 16]); - assert_eq!(page.items[0].evidence.as_deref(), Some(evidence)); - assert_eq!(page.items[0].phase.as_deref(), Some("bind")); -} - -#[test] -fn an_unconverted_machine_refuses_until_the_operator_declares_it_gone() { - let Some(tool) = tool() else { - eprintln!("NOT_RUN: python3 or tools/store_gc_convert.py is absent"); - return; - }; - let temp = Temp::new("gc-conversion-gone"); - let path = temp.join("db"); - drop(create(&path)); - downgrade(&path, &[("native", "a"), ("elsewhere", "b")]); - let home = home(&temp, &["native"]); - let target = temp.join("converted"); - let refused = run( - &tool, - &[ - "convert", - path.to_str().unwrap(), - target.to_str().unwrap(), - home.to_str().unwrap(), - ], - ); - assert!(!refused.status.success(), "an unconverted machine refuses"); - assert!( - String::from_utf8_lossy(&refused.stderr).contains("elsewhere"), - "the refusal names the machine: {}", - String::from_utf8_lossy(&refused.stderr) - ); - assert!(!target.exists(), "a refused conversion writes no target"); - let gone = run( - &tool, - &[ - "convert", - path.to_str().unwrap(), - target.to_str().unwrap(), - home.to_str().unwrap(), - "--gone", - "elsewhere", - ], - ); - assert!( - gone.status.success(), - "--gone is the missing-machine policy: {}", - String::from_utf8_lossy(&gone.stderr) - ); - drop(writable(&target).expect("the converted Store opens after the gone declaration")); -} diff --git a/engine/crates/layerfs-persistence/tests/gc_intent_authority.rs b/engine/crates/layerfs-persistence/tests/gc_intent_authority.rs deleted file mode 100644 index 393a05c0ad..0000000000 --- a/engine/crates/layerfs-persistence/tests/gc_intent_authority.rs +++ /dev/null @@ -1,142 +0,0 @@ -//! Phase 3: the two `gc_intent` place columns. A new Store ships them and -//! records them in its schema source. The 2.0 schema has no additive -//! migration: a Store written before them is refused `Malformed` at open and -//! needs the explicit 2.0 conversion. -#![cfg(any(target_os = "macos", target_os = "linux"))] -mod support; - -use layerfs_history::HistoryCatalogConfig; -use layerfs_persistence::{PersistenceConfig, SqliteHandles, SqlitePersistenceProfile}; -use layerfs_storage::StoragePolicy; -use support::{Temp, BINDING}; - -/// The two `gc_intent` place columns as `sql/sqlite/gc.sql` writes them -/// after `phase`. -const INTENT_COLUMNS: &str = " machine_incarnation TEXT,\n sandbox_generation TEXT,\n"; - -/// The two columns, in the order the schema declares them. -const INTENT_COLUMN_NAMES: [&str; 2] = ["machine_incarnation", "sandbox_generation"]; - -fn config(path: &std::path::Path) -> PersistenceConfig { - PersistenceConfig::sqlite(path).with_sqlite_profile(SqlitePersistenceProfile::Normal) -} - -fn create(path: &std::path::Path) -> SqliteHandles { - SqliteHandles::create( - config(path), - StoragePolicy::frozen_default(), - &HistoryCatalogConfig { - binding_key: BINDING.to_vec(), - cursor_key: [71; 32], - incarnation: 7, - }, - ) - .expect("Store creation") -} - -fn writable( - path: &std::path::Path, -) -> Result { - SqliteHandles::open_writable(config(path), BINDING, [71; 32]) -} - -fn definition(sql: &rusqlite::Connection) -> String { - let mut statement = sql - .prepare("SELECT type,name,sql FROM sqlite_schema WHERE substr(name,1,7)!='sqlite_' ORDER BY type,name") - .unwrap(); - let rows = statement - .query_map([], |r| Ok([r.get::<_, String>(0)?, r.get(1)?, r.get(2)?])) - .unwrap(); - rows.map(|r| r.unwrap().map(|v| v + "\n").concat()) - .collect() -} - -fn recorded(path: &std::path::Path) -> (String, String) { - let sql = rusqlite::Connection::open(path).unwrap(); - let row = sql - .query_row( - "SELECT schema_source,schema_definition FROM history_meta WHERE id=1", - [], - |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)), - ) - .unwrap(); - drop(sql); - row -} - -fn column_present(sql: &rusqlite::Connection, column: &str) -> i64 { - sql.query_row( - "SELECT count(*) FROM pragma_table_info('gc_intent') WHERE name=?1", - rusqlite::params![column], - |r| r.get(0), - ) - .unwrap() -} - -/// Rewrites a fresh Store into the format a p3-schema Store recorded: the four -/// columns are gone and the recorded source no longer holds them. Returns the -/// fresh source it replaced. -fn make_pre_intent_authority(path: &std::path::Path) -> String { - let fresh = recorded(path).0; - let sql = rusqlite::Connection::open(path).unwrap(); - for column in INTENT_COLUMN_NAMES.into_iter().rev() { - sql.execute_batch(&format!("ALTER TABLE gc_intent DROP COLUMN {column};")) - .unwrap(); - } - let old = fresh.replacen(INTENT_COLUMNS, "", 1); - assert_ne!( - old, fresh, - "a fresh Store holds the intent authority columns" - ); - sql.execute( - "UPDATE history_meta SET schema_source=?1,schema_definition=?2", - rusqlite::params![old, definition(&sql)], - ) - .unwrap(); - fresh -} - -#[test] -fn a_new_store_ships_the_intent_authority_columns() { - let t = Temp::new("gc-intent-authority-new"); - let path = t.join("db"); - drop(create(&path)); - let (source, recorded_definition) = recorded(&path); - assert_eq!( - source.matches(INTENT_COLUMNS).count(), - 1, - "the source holds the four columns once" - ); - let sql = rusqlite::Connection::open(&path).unwrap(); - for column in INTENT_COLUMN_NAMES { - assert_eq!(column_present(&sql, column), 1, "{column} is created"); - } - assert_eq!( - recorded_definition, - definition(&sql), - "the recorded definition is the live one" - ); - drop(sql); - support::sqlite::open_read_only(&path, BINDING, [71; 32]).expect("a new Store opens read-only"); -} - -/// The 2.0 schema has no additive migration: a Store recorded before the -/// four authority columns is refused at its first writable open instead of -/// being altered, and read-only authority refuses it too. -#[test] -fn an_old_store_without_the_intent_authority_columns_is_refused() { - let t = Temp::new("gc-intent-authority-old"); - let path = t.join("db"); - drop(create(&path)); - let _ = make_pre_intent_authority(&path); - // Read-only authority cannot add the columns, so it refuses. - assert!(support::sqlite::open_read_only(&path, BINDING, [71; 32]).is_err()); - // Nor does a writable open migrate: the direct-schema 2.0 Store refuses. - assert!( - matches!( - writable(&path), - Err(layerfs_storage::port::PersistenceError::Malformed) - ), - "a pre-column Store is not migrated" - ); -} diff --git a/engine/crates/layerfs-persistence/tests/gc_intent_done.rs b/engine/crates/layerfs-persistence/tests/gc_intent_done.rs index ff7457f23c..7655635323 100644 --- a/engine/crates/layerfs-persistence/tests/gc_intent_done.rs +++ b/engine/crates/layerfs-persistence/tests/gc_intent_done.rs @@ -63,11 +63,9 @@ fn done_row(path: &std::path::Path, branch: BranchId, body: u8, evidence: &str, "INSERT INTO gc_intent ( op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, - phase, machine_incarnation, sandbox_generation, - evidence, updated_ms + phase, evidence, updated_ms ) VALUES (?1, 'mount', 'branch', ?2, NULL, 'box', 'box', - 'proj', 'work', NULL, NULL, 'done', 0, 'release', NULL, NULL, - ?3, ?4)", + 'proj', 'work', NULL, NULL, 'done', 0, 'release', ?3, ?4)", params![op(body).as_slice(), branch.as_slice(), evidence, updated_ms], ) .unwrap(); @@ -331,10 +329,131 @@ fn a_branch_audit_reads_only_its_own_done_rows() { .unwrap(); } - let page = history.gc_done_intents_branch("proj", "work", 0, 10).unwrap(); + let page = history + .gc_done_intents_branch("proj", "work", 0, 10) + .unwrap(); assert_eq!(page.items.len(), 1, "only the named Branch's row"); assert_eq!(page.items[0].op_id, op(0x01)); - let other = history.gc_done_intents_branch("proj", "other", 0, 10).unwrap(); + let other = history + .gc_done_intents_branch("proj", "other", 0, 10) + .unwrap(); assert_eq!(other.items.len(), 1); assert_eq!(other.items[0].op_id, op(0x02)); } + +fn stored(path: &std::path::Path, body: u8) -> (String, Option) { + rusqlite::Connection::open(path) + .unwrap() + .query_row( + "SELECT state, evidence FROM gc_intent WHERE op_id = ?1", + params![op(body).as_slice()], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap() +} + +/// The place tokens live in the base format's `evidence` column: a live row +/// round-trips both, a value without the `place:v1` prefix (a `done` row's +/// audit text) or a malformed one decodes as no tokens, and the live-path +/// release, uncertain and insert-conflict statements neither delete nor +/// revive a retained `done` row. +#[test] +fn place_tokens_round_trip_through_evidence_and_live_statements_keep_a_done_row() { + let temp = Temp::new("gc-done-place-evidence"); + let path = temp.join("store.sqlite"); + let history = catalog(&temp); + let (_, branch) = project(&history); + let incarnation = "p1:worker:0000000000000010:aa"; + let generation = "p1:sandbox:0000000000000020:bb"; + let mounted = GcIntent::shared( + op(40), + GcIntentKind::Mount, + GcScopeKind::Branch, + branch.as_slice(), + ) + .in_project(stack(1).as_slice()) + .named(Some("proj"), Some("work")) + .placed(Some([40; 32]), Some("box"), Some("box")) + .owned(Some("pid:1@0"), Some("boot:40")) + .authorized(PlaceAuthority { + machine_incarnation: Some(incarnation.to_owned()), + sandbox_generation: Some(generation.to_owned()), + }); + history.gc_register(&mounted).unwrap(); + let encoded = format!("place:v1;inc={incarnation};gen={generation}"); + assert_eq!(stored(&path, 40), ("live".to_owned(), Some(encoded))); + let tokens = |history: &HistoryProvider| { + let listed = history + .gc_intents(GcScopeKind::Branch, branch.as_slice()) + .unwrap(); + assert_eq!(listed.len(), 1, "{listed:?}"); + ( + listed[0].machine_incarnation.clone(), + listed[0].sandbox_generation.clone(), + ) + }; + assert_eq!( + tokens(&history), + (Some(incarnation.to_owned()), Some(generation.to_owned())) + ); + + // Foreign or malformed evidence is no proof: no token at all. + let connection = rusqlite::Connection::open(&path).unwrap(); + for text in [ + "place:v2;inc=a", + "place:v1", + "place:v1;inc=", + "place:v1;inc=a;inc=b", + "place:v1;who=a", + ] { + connection + .execute( + "UPDATE gc_intent SET evidence = ?1 WHERE op_id = ?2", + params![text, op(40).as_slice()], + ) + .unwrap(); + assert_eq!(tokens(&history), (None, None), "{text}"); + } + connection + .execute( + "UPDATE gc_intent SET evidence = ?1 WHERE op_id = ?2", + params![format!("place:v1;gen={generation}"), op(40).as_slice()], + ) + .unwrap(); + assert_eq!(tokens(&history), (None, Some(generation.to_owned()))); + + // The operator retains the row as `done`; its evidence is the audit text. + let audit = "action=release;operator=alice;op=28282828282828282828282828282828"; + assert!(history.gc_release_done(&op(40), audit).unwrap()); + let done = ("done".to_owned(), Some(audit.to_owned())); + assert_eq!(stored(&path, 40), done); + + // The owner's own release, a late uncertain mark and a retried + // registration under the same op id all leave the done row as it was. + history.gc_release(&op(40)).unwrap(); + assert_eq!(stored(&path, 40), done, "release keeps the done row"); + history.gc_mark_uncertain(&op(40)).unwrap(); + assert_eq!(stored(&path, 40), done, "uncertain keeps the done row"); + assert!(matches!( + history.gc_register(&mounted), + Err(layerfs_history::HistoryError::Conflict(_)) + )); + assert_eq!( + stored(&path, 40), + done, + "a retry does not revive the done row" + ); + assert!(history + .gc_intents(GcScopeKind::Branch, branch.as_slice()) + .unwrap() + .is_empty()); + + // Read as a live row, the done row's audit text decodes as no tokens. + connection + .execute( + "UPDATE gc_intent SET state = 'live' WHERE op_id = ?1", + params![op(40).as_slice()], + ) + .unwrap(); + assert_eq!(tokens(&history), (None, None)); +} diff --git a/engine/crates/layerfs-persistence/tests/gc_schema.rs b/engine/crates/layerfs-persistence/tests/gc_schema.rs deleted file mode 100644 index a015ad0ade..0000000000 --- a/engine/crates/layerfs-persistence/tests/gc_schema.rs +++ /dev/null @@ -1,169 +0,0 @@ -//! The lean phase-3 schema (version 3): the four `gc_intent` authority -//! columns, and none of the removed Store-side machine-authority, Sandbox -//! tombstone or audit tables. A released schema version 2 Store is refused, -//! never silently migrated. -#![cfg(any(target_os = "macos", target_os = "linux"))] -mod support; - -use layerfs_history::HistoryCatalogConfig; -use layerfs_persistence::{PersistenceConfig, SqliteHandles, SqlitePersistenceProfile}; -use layerfs_storage::StoragePolicy; -use support::{Temp, BINDING}; - -const SQLITE_GC: &str = include_str!("../sql/sqlite/gc.sql"); -const POSTGRESQL_GC: &str = include_str!("../sql/postgresql/gc.sql"); - -/// The removed tables, in name order. -const REMOVED_TABLES: [&str; 3] = ["gc_audit", "gc_machine_authority", "gc_sandbox_tombstone"]; - -/// The two authority columns the lean schema keeps. -const AUTHORITY_COLUMNS: [&str; 2] = ["machine_incarnation", "sandbox_generation"]; - -fn config(path: &std::path::Path) -> PersistenceConfig { - PersistenceConfig::sqlite(path).with_sqlite_profile(SqlitePersistenceProfile::Normal) -} - -fn create(path: &std::path::Path) -> SqliteHandles { - SqliteHandles::create( - config(path), - StoragePolicy::frozen_default(), - &HistoryCatalogConfig { - binding_key: BINDING.to_vec(), - cursor_key: [71; 32], - incarnation: 7, - }, - ) - .expect("Store creation") -} - -fn writable( - path: &std::path::Path, -) -> Result { - SqliteHandles::open_writable(config(path), BINDING, [71; 32]) -} - -fn recorded(path: &std::path::Path) -> (String, String) { - let sql = rusqlite::Connection::open(path).unwrap(); - let row = sql - .query_row( - "SELECT schema_source,schema_definition FROM history_meta WHERE id=1", - [], - |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)), - ) - .unwrap(); - drop(sql); - row -} - -fn table_present(sql: &rusqlite::Connection, table: &str) -> i64 { - sql.query_row( - "SELECT count(*) FROM sqlite_schema WHERE type='table' AND name=?1", - rusqlite::params![table], - |r| r.get(0), - ) - .unwrap() -} - -#[test] -fn a_new_store_ships_the_authority_columns_and_no_authority_tables() { - let t = Temp::new("gc-schema-new"); - let path = t.join("db"); - drop(create(&path)); - let sql = rusqlite::Connection::open(&path).unwrap(); - for table in REMOVED_TABLES { - assert_eq!(table_present(&sql, table), 0, "{table} is gone"); - } - for column in AUTHORITY_COLUMNS { - let present: i64 = sql - .query_row( - "SELECT count(*) FROM pragma_table_info('gc_intent') WHERE name=?1", - rusqlite::params![column], - |r| r.get(0), - ) - .unwrap(); - assert_eq!(present, 1, "gc_intent keeps {column}"); - } - let version: i64 = sql - .query_row("PRAGMA user_version", [], |r| r.get(0)) - .unwrap(); - assert_eq!(version, 39, "the Monolithic layout is schema version 3"); - drop(sql); - let (source, definition) = recorded(&path); - for table in REMOVED_TABLES { - assert!( - !source.contains(&format!("CREATE TABLE {table} (")), - "the recorded source has no {table}" - ); - } - for column in AUTHORITY_COLUMNS { - assert!( - source.contains(&format!(" {column} ")), - "the source keeps {column}" - ); - } - let sql = rusqlite::Connection::open(&path).unwrap(); - let live: String = { - let mut statement = sql - .prepare( - "SELECT type,name,sql FROM sqlite_schema \ - WHERE substr(name,1,7)!='sqlite_' ORDER BY type,name", - ) - .unwrap(); - let rows = statement - .query_map([], |r| Ok([r.get::<_, String>(0)?, r.get(1)?, r.get(2)?])) - .unwrap(); - rows.map(|r| r.unwrap().map(|v| v + "\n").concat()) - .collect() - }; - assert_eq!(definition, live, "the recorded definition is the live one"); - drop(sql); - drop(writable(&path).expect("the new Store reopens writable")); -} - -#[test] -fn both_engine_scripts_drop_the_authority_tables_and_keep_the_columns() { - for (engine, gc) in [("SQLite", SQLITE_GC), ("PostgreSQL", POSTGRESQL_GC)] { - for table in REMOVED_TABLES { - assert!( - !gc.contains(&format!("CREATE TABLE {table} (")), - "{engine}: gc.sql creates no {table}" - ); - } - for column in AUTHORITY_COLUMNS { - assert!( - gc.contains(&format!(" {column} ")), - "{engine}: gc.sql keeps the {column} column" - ); - } - } -} - -#[test] -fn the_postgresql_table_set_has_no_authority_table() { - let tables = layerfs_persistence::internals::POSTGRESQL_TABLES; - assert_eq!(tables.len(), 27); - for table in REMOVED_TABLES { - assert!(!tables.contains(&table), "the table set omits {table}"); - } - assert!(tables.contains(&"gc_intent"), "gc_intent remains"); - assert!( - tables.windows(2).all(|pair| pair[0] < pair[1]), - "the table set is in name order" - ); -} - -#[test] -fn a_released_version_2_store_is_refused_with_its_conversion() { - let t = Temp::new("gc-schema-v2"); - let path = t.join("db"); - drop(create(&path)); - { - let sql = rusqlite::Connection::open(&path).unwrap(); - sql.pragma_update(None, "user_version", 36).unwrap(); - } - let refusal = writable(&path).err().expect("a version 2 Store is refused"); - let text = format!("{refusal:?}"); - assert!(text.contains("schema version 2"), "{text}"); - assert!(text.contains("convert"), "{text}"); - assert!(text.contains("store_gc_convert.py"), "{text}"); -} diff --git a/engine/crates/layerfs-persistence/tests/lineage_backfill.rs b/engine/crates/layerfs-persistence/tests/lineage_backfill.rs index cfc6aca796..15ed2e6300 100644 --- a/engine/crates/layerfs-persistence/tests/lineage_backfill.rs +++ b/engine/crates/layerfs-persistence/tests/lineage_backfill.rs @@ -74,8 +74,7 @@ fn make_old(path: &std::path::Path) { DROP TABLE layer_lineage; DROP TABLE commit_lineage; DROP TABLE absorbed; DROP TABLE reach; \ DROP TABLE merge_operation; DROP TABLE merge_record; DROP TABLE file_digest; \ DROP TABLE branch_retired; DROP TABLE layer_stack_retired; DROP TABLE path_removed; \ - DROP TABLE project_epoch; \ - DROP TABLE gc_intent; DROP TABLE gc_op; DROP TABLE gc_dead; DROP TABLE kept_node;", + DROP TABLE project_epoch; DROP TABLE gc_intent; DROP TABLE gc_op; DROP TABLE gc_dead; DROP TABLE kept_node;", ) .unwrap(); let source: String = sql diff --git a/engine/crates/layerfs-persistence/tests/old_format_columns.rs b/engine/crates/layerfs-persistence/tests/old_format_columns.rs index 1dfdb586fe..db5990ce93 100644 --- a/engine/crates/layerfs-persistence/tests/old_format_columns.rs +++ b/engine/crates/layerfs-persistence/tests/old_format_columns.rs @@ -40,8 +40,7 @@ fn make_old(path: &std::path::Path) { ALTER TABLE store_policy DROP COLUMN trace_salt; \ ALTER TABLE history_meta DROP COLUMN next_history_serial; \ DROP TABLE branch_retired; DROP TABLE layer_stack_retired; DROP TABLE path_removed; \ - DROP TABLE project_epoch; \ - DROP TABLE gc_intent; DROP TABLE gc_op; DROP TABLE gc_dead; DROP TABLE kept_node;", + DROP TABLE project_epoch; DROP TABLE gc_intent; DROP TABLE gc_op; DROP TABLE gc_dead; DROP TABLE kept_node;", ) .unwrap(); let source: String = sql diff --git a/engine/crates/layerfs-persistence/tests/old_format_open.rs b/engine/crates/layerfs-persistence/tests/old_format_open.rs index 3141a1cbe0..2edc44cbdb 100644 --- a/engine/crates/layerfs-persistence/tests/old_format_open.rs +++ b/engine/crates/layerfs-persistence/tests/old_format_open.rs @@ -55,8 +55,7 @@ fn make_old(path: &std::path::Path) { DROP TABLE absorbed; DROP TABLE reach; DROP TABLE merge_operation; \ DROP TABLE merge_record; DROP TABLE file_digest; \ DROP TABLE branch_retired; DROP TABLE layer_stack_retired; DROP TABLE path_removed; \ - DROP TABLE project_epoch; \ - DROP TABLE gc_intent; DROP TABLE gc_op; DROP TABLE gc_dead; DROP TABLE kept_node;", + DROP TABLE project_epoch; DROP TABLE gc_intent; DROP TABLE gc_op; DROP TABLE gc_dead; DROP TABLE kept_node;", ) .unwrap(); let source: String = sql diff --git a/engine/crates/layerfs-persistence/tests/postgresql_gc_mark.rs b/engine/crates/layerfs-persistence/tests/postgresql_gc_mark.rs index bfa481a393..89f142f8fa 100644 --- a/engine/crates/layerfs-persistence/tests/postgresql_gc_mark.rs +++ b/engine/crates/layerfs-persistence/tests/postgresql_gc_mark.rs @@ -26,8 +26,7 @@ use support::pg::{ const BINDING: &[u8] = b"postgresql-gc-mark"; const CURSOR: [u8; 32] = [76; 32]; -/// The GC tables the additive migration restores; the pre-GC Store has none -/// of them. The lean phase 3 schema keeps no authority or audit table. +/// The eight tables T1.3b appended; the pre-GC Store has none of them. const GC_TABLES: [&str; 8] = [ "branch_retired", "gc_dead", diff --git a/engine/crates/layerfs-persistence/tests/sealed_open.rs b/engine/crates/layerfs-persistence/tests/sealed_open.rs index d3fa2048cb..a02a162d3b 100644 --- a/engine/crates/layerfs-persistence/tests/sealed_open.rs +++ b/engine/crates/layerfs-persistence/tests/sealed_open.rs @@ -1,6 +1,4 @@ -//! A sealed Store opens: the fresh file. One recorded by the phase-3 branch -//! before the intent-authority columns existed is refused: the lean 2.0 -//! schema has no additive migration. +//! A sealed Store opens: the fresh file. use layerfs_history::HistoryCatalogConfig; use layerfs_persistence::{ PersistenceConfig, SqliteAcquisitionSchema, SqliteHandles, SqlitePersistenceProfile, @@ -10,32 +8,6 @@ use layerfs_storage::StoragePolicy; const BINDING: &[u8] = b"sealed-open"; const CURSOR: [u8; 32] = [61; 32]; -/// The definition `definition()` records: every non-internal `sqlite_schema` -/// row as `type\nname\nsql\n`, ordered as the engine reads it. -fn definition(connection: &rusqlite::Connection) -> String { - let mut statement = connection - .prepare( - "SELECT type,name,sql FROM sqlite_schema \ - WHERE substr(name,1,7)!='sqlite_' ORDER BY type,name", - ) - .unwrap(); - let rows: Vec<(String, String, String)> = statement - .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))) - .unwrap() - .map(|row| row.unwrap()) - .collect(); - let mut text = String::new(); - for (kind, name, sql) in rows { - text.push_str(&kind); - text.push('\n'); - text.push_str(&name); - text.push('\n'); - text.push_str(&sql); - text.push('\n'); - } - text -} - fn catalog() -> HistoryCatalogConfig { HistoryCatalogConfig { binding_key: BINDING.to_vec(), @@ -75,72 +47,3 @@ fn a_sealed_store_opens_read_only() { SqliteHandles::open_read_only(installed(&path), BINDING, CURSOR).unwrap(); std::fs::remove_dir_all(&directory).unwrap(); } - -/// The phase-3 branch sealed Stores with `gc.sql` ending in two extra -/// newlines and without the two `gc_intent` place columns. Opening one -/// cannot add them: the lean 2.0 schema is direct, so the recorded source is -/// refused `Malformed` and the explicit 2.0 conversion is required. -#[test] -fn a_sealed_store_recorded_before_the_intent_authority_columns_is_malformed() { - let directory = - std::env::temp_dir().join(format!("sealed-open-pre-columns-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&directory); - std::fs::create_dir_all(&directory).unwrap(); - let path = sealed_store(&directory); - - let columns = ["machine_incarnation", "sandbox_generation"]; - let (current_source, old_source) = { - let connection = rusqlite::Connection::open(&path).unwrap(); - let source: String = connection - .query_row( - "SELECT schema_source FROM history_meta WHERE id=1", - [], - |row| row.get(0), - ) - .unwrap(); - let mut old = source.replacen( - " machine_incarnation TEXT,\n sandbox_generation TEXT,\n", - "", - 1, - ); - old = old.replacen( - "CREATE TABLE init_operation (\n", - "\n\nCREATE TABLE init_operation (\n", - 1, - ); - assert_ne!(old, source); - for column in columns.iter().rev() { - connection - .execute(&format!("ALTER TABLE gc_intent DROP COLUMN {column}"), []) - .unwrap(); - } - let definition = definition(&connection); - connection - .execute( - "UPDATE history_meta SET schema_source=?1, schema_definition=?2 WHERE id=1", - rusqlite::params![old, definition], - ) - .unwrap(); - (source, old) - }; - assert!(!old_source.contains("machine_incarnation")); - assert!(old_source.len() < current_source.len()); - - // There is no additive migration: the old recorded source is refused at - // the first writable open, and the Store is not rewritten for it. - assert!( - matches!( - SqliteHandles::open_writable(installed(&path), BINDING, CURSOR), - Err(layerfs_storage::port::PersistenceError::Malformed) - ), - "a pre-column sealed Store is not migrated" - ); - assert!( - matches!( - SqliteHandles::open_read_only(installed(&path), BINDING, CURSOR), - Err(layerfs_storage::port::PersistenceError::Malformed) - ), - "read-only authority refuses it too" - ); - std::fs::remove_dir_all(&directory).unwrap(); -} diff --git a/engine/crates/layerfs-persistence/tests/sqlite_compact_done.rs b/engine/crates/layerfs-persistence/tests/sqlite_compact_done.rs index a34a4c9b2a..7d690d2008 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_compact_done.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_compact_done.rs @@ -140,11 +140,9 @@ fn insert_done_audit(path: &Path, branch: BranchId, op: u8, evidence: &str, upda "INSERT INTO gc_intent ( op_id, kind, scope_kind, scope_id, workspace, sandbox, machine, project, branch, owner_runtime, owner_boot, state, uncertain, - phase, machine_incarnation, sandbox_generation, evidence, - updated_ms + phase, evidence, updated_ms ) VALUES (?1, 'mount', 'branch', ?2, NULL, 'box', 'box', - 'proj', 'work', NULL, NULL, 'done', 0, 'release', NULL, NULL, - ?3, ?4)", + 'proj', 'work', NULL, NULL, 'done', 0, 'release', ?3, ?4)", rusqlite::params![[op; 16].as_slice(), branch.as_slice(), evidence, updated_ms], ) .unwrap(); diff --git a/engine/crates/layerfs-persistence/tests/sqlite_group_rows.rs b/engine/crates/layerfs-persistence/tests/sqlite_group_rows.rs index 71f61e5af8..4a20bfc3d6 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_group_rows.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_group_rows.rs @@ -89,7 +89,7 @@ fn explicit_creation_reopens_declared_units_and_keeps_sparse_canonical_order() { assert_eq!( db.query_row("PRAGMA user_version", [], |r| r.get::<_, i64>(0)) .unwrap(), - 40 + 37 ); assert_eq!( db.query_row("SELECT count(*) FROM pack_unit", [], |r| r.get::<_, i64>(0)) diff --git a/engine/crates/layerfs-persistence/tests/sqlite_group_rows_indexed.rs b/engine/crates/layerfs-persistence/tests/sqlite_group_rows_indexed.rs index 31b5bcaf6d..156460e76f 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_group_rows_indexed.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_group_rows_indexed.rs @@ -81,9 +81,9 @@ fn fixture(h: &SqliteHandles) -> Vec { #[test] fn declared_layouts_reopen_without_mutating_or_promoting_their_schema() { for (layout, version) in [ - (SqlitePackLayout::Monolithic, 39), - (SqlitePackLayout::GroupRows, 40), - (SqlitePackLayout::GroupRowsIndexed, 41), + (SqlitePackLayout::Monolithic, 36), + (SqlitePackLayout::GroupRows, 37), + (SqlitePackLayout::GroupRowsIndexed, 38), ] { let t = support::Temp::new("indexed-legacy-open"); let path = t.join("db"); diff --git a/engine/crates/layerfs-persistence/tests/sqlite_inode_values.rs b/engine/crates/layerfs-persistence/tests/sqlite_inode_values.rs index f7b9601df6..0183744aef 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_inode_values.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_inode_values.rs @@ -368,7 +368,7 @@ fn a_store_of_the_value_group_format_is_refused_at_open() { .unwrap() .query_row("PRAGMA user_version", [], |row| row.get(0)) .unwrap(); - assert_eq!(version, 39); + assert_eq!(version, 36); SqliteHandles::open_writable(config(&path), BINDING, [73; 32]).unwrap(); } diff --git a/engine/crates/layerfs-persistence/tests/sqlite_publication.rs b/engine/crates/layerfs-persistence/tests/sqlite_publication.rs index d32120a865..9815c6591d 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_publication.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_publication.rs @@ -96,9 +96,7 @@ fn wal_full_settings_are_explicit() { // #353 added layer_lineage, commit_lineage, absorbed and reach; #355 // added merge_operation and merge_record; #364 added file_digest; // the GC work added the markers, project_epoch, gc_intent, gc_op, gc_dead - // and kept_node; the lean phase 3 schema keeps no authority or audit - // table, and without the acquisition tables no AUTOINCREMENT identity - // creates sqlite_sequence. + // and kept_node. assert_eq!(names, 28); } #[test] diff --git a/engine/crates/layerfs-store-service/tests/fixtures/merge-forms-root.sqlite b/engine/crates/layerfs-store-service/tests/fixtures/merge-forms-root.sqlite index 49e1b382ddfbf61dd61edd6d5569915fd50b6f5b..3615ffda403c1ea98d94dc20498a0936be30158f 100644 GIT binary patch delta 2017 zcmcIldr(wW7{A~7?ql!5?pNZ2ZY`HJ^@AhA6vrsbGKp@xP_Y;@d9$91?1WUOjn2Ixeg2k zT=t>gT;3eC4vHwiX5FN~f65L>yKt}*zkjo^=WwQk!ZhwXB8jv@4q++^frUjVEl6zm^RUGi?p*e#qqW!P8fHThDt1kut^ z;A21iVnEE$H^csDyU=CMm69>vxiV}ncDl`m*qZ$6ni?rzuaXpCj0uz0(NEpx&6YqC z0=Q*TaAed!vi{H(-}6wnrvh9%+En?RWSkQ|zc=Dy0CV)FmZr6}t!<(9;M%6vmV-W! zeY@p=xY{Y^<7$A7f9sT`Zpl`IvlxnxO@rorQL1Ai>s_0o>1q{bf|L8JaVcO|aTI;I z26Mr|uf2yhz`j^JIXW;AqWPak@rs zBxN1Ccx^ZS$UvhzAH_7#Nt`l{cV^29iomk+|ESmms|-{ulbkO_4eQ5ko0Zil$~A2I z(Eh&{dk|8pBpohGQDOUQ`e|L)F35X~SK+c_xir^N=cpSrQ?aWdfxayl9h5k-b6W{u z&kQ%+y%K$pK-+)D{Of2g=&cNU7sOKaV$23NZ#jdhh+Xk9^lYVQ$~YSS0>{u??xNT4 z5ZQ~R@fq^IB(uthgt+U0NUqvL!G?Py5JRslz=J7H&ExgLBezGS!TOHY_WDrcKdXz( zJMkNEP~Ae|(%@SbVhhBHpt?L+S3A(#1kwR3Lc)j9J3e;#L<-i=0H59FUHIw zhkdUUFB(Iyw3TZYwSFyAeOXOX9#P`u7v%+b0^8U%wu^b7Px@J^HkLWx95j>AOwOj8 zT5u<1S&Nr0wV(-^w5}BkA)DrXjBYA8j|z>B;aoJ84BApBZk;tLsbtHhkt>Ml!YJVa zma&d>Y7UA(Wzb*{7eN|*7sL#hHeqn+Bh)Bx0@K(UKULO?c1WKP1VX~c`@do#tM$zi5{LmMLH-BH`o z`apX_C_Z_0K2uRp}4Y~xf)4q+;ICk2&|L}am&Cs_)862d%~ zLgOKkk*U}5EABx*yDgD6+=cVyq^@WW9dE+|q1k^~wB`+!DCV2&Bqq{1k<}aq|5T<` zi3DhRbLnC;?t&cJu^M+D96(XFg(KP9K1bSDiYkAr1it`&DvW2WCxnY9BwCwn=*q|h zEuwwBm`IzCis1iw37zEY!)oeWkLi5++jxS}xi`_vGakh4a%7_H5fg<9M#W5sK8E{M zYX}!pc#Tm1?gP;bRM3J7*FV8M8h_{v8j7V*LT$A;K#!k9o%W7lEPYsq^Z2^+*ax(< z6n%W!7%p+pzHxM0>ZQD56c59Vo_VJtzlD5VjQsxOgUFA?$XvHy^WTI9L9fpPwPe;!x7IF6vZejrSMG3xTgHl^g$lVEFU1eCTY?((*!W#B_RohaD^}=nP!?!ONVr(9nwh{Fhk1ZAawUVNq#a8p((j$ z{Kj7G`*;6;|NVFWZ~y(Jj$Um?N6MD`f@w_uQ$?z>=xZhU1mwT8dum~(3&=@Tu0KZ` zC+NS_|3}}a|5SgjC#Br4<}VYE>2~Zqt(Db~P!+DI-?HuOo8}Uh=PrylKdb{Mn$l zsHyl#w5X=VWLiw2#Z+2YX;DLq+Mbk@{kq54By@-Vi=LFZ7xc1;y+F$Y7M{>gr~*k0 zP$K{U1a+m5VGJtOT##zr{^dx1eDQtZJ&T;Z`=F&b^uTY|{_Dd9lj?W%jhZ;&H2ig4{K*9DX-uuGwEHK3XwgQ;~=s#if zpOEGIhdv_>m8mL>10HP;xOgr9S-?JL0PM4%oNyDq=VecWkJ6MNgVFsV$)c`No>4r8 zLLdX^xIc#^0Wngfpv~HF5tn| z#V8k4;5|EGJ?hjcB7S)>Q1OQrp?^aZo*|EfRAoTfvs;x3P}n8Iv)+bfK*6uv4ab3= z6Y6t7)43iBBX&)Ryqfg*PiqhGPrnG4fx-h!G81OBtCOy1ma3hqi1KB{4*A2fJ9Hbs zc_ysuVw$=`GnT5zqBGh9=pFjm|Ad>eltz;Y+^-Khm$h*IfNuro3OYEy&()Ohl2be1 zW^J&s4c3}E8=KI?n(@l5Fbl6xqe9$~hSIRzj>_>%R%DD^laDOiv$a5Z!5ENnGfIX1dgaCsrh#2nuV9kQt z3JkdWG)$)pqD~bBBrI2?zCDjNs*$*;muAf3La;?eWaj_lB!VM>BhAiPSLO@MQ{nuH<^gV*4G zkb+-%4d#MWthJysXoJy!_Z@&{FpU5E0q7+Na-SYQ&;du1etVvPsr;5YR0CkG4qrYF zYvcyvbSJt)N5+TmH7bpjmEisyVU!lj!X!dyBY=iACa;U}*R^cdQ%|gp8J8L$%e66jXpsBy3cXah{eo3BE3!bswLZ@^Zu z9j3|!N5dCif!ULW z(QJf7-K^yP^lZU{9#Y4I`}{bXSyF5A=@~YRpQ+zp$Qc7e>n*)5ai=8_COXC@HuR37cayo_z!k2c;tI*GFI}7=>Rr0t-NiNIGAH#=#Z~HXbFk z(UdkDh0@Hp^C)2(CHAR529>z?C|m+eIPVzD1C}^_DHw_WcnszPbDX5aA0LBLzzA$U zPUt3)PP9?r4g(quUB!6waRP%Q`x~~I5Zhi+q%hj@0Ylt}Tidp>#S`Ql&Q(F5@a`bq z;qeAJZ_qI|UL8?UcylZjahBpu;|c`O-7+EOd7{`xb8LX3fi5U^h4shM^ zD>eyh(BfH5mtd9G#RY;+kC)WlJ}(zvRIveHXh7NRtU2C|AQEdXFR6$f&lL2fvmvJe zNAO>QUEc_iO`gUk#~Pw*AO>?{S8lb(%@MWY29UGtD!&^q>4L-CqxK^%*AJ3(ON*>g zdpjgr^fxZF&ziT;Cfy(&<22j}#^I&! z!e>w@w-VR)!lwvSl8-!`bO?qBI(8j`6`)eY5`v!7(rA7~#vEl-`A7pkV2*+Zz^U$# zTLw-6eRpUU3MXsv#1pU_=yCH2cm`G`V?~%Cu#T??Lk$2)coMl^kwgl)Ieae5-F%Nm zY0Sz3JB>&5bqVt5S#6@K&ySjhkLPLvDrsVCtzAjc^ku(^j# z(aE=UKn1UO4_?g&)%@wj=nUZZeFi_i$;&@~{tA3!kO|R|uR=UojST#nO|TcxM9O45 zxeVpub0sLqpLhu7$gbB|FvN4j5IkW$tiT6Gp(5U7Aki-sFomCE!xg4uH7WkYvdWnSYq25`6bj*Aao zf>{*W=&k&wG8Xi-OcB%BLn$aXx#`8OQ8&mX#jY*iIR!6l~{7!=I9M;{7I;38li)e$061eGAIRpN>Ik zG=Q8Ws9eMMK~yfkQP|iu0lf~(B>|!);dU-*i03o0~4eJ4?o|HYy3 zdltl62#1(hxK7YezF{ce5E#lg^rsYValSz#T;w&x0eyba`Lwp^_q77;Cz^2293D`cQ!)dH=u3=vtiB~R1;M3obz#?fRVc|%>ZbZ{pSA}=Vr@&|LMDqS1 z<$W7U{hkveG%Dd$^UyFMA;m;Wlft5U&orRfz%0#{ByKHf%g-{8LT5fIA%!wvg3_P3 c44#kr4nJKH?0tSAa>Jk4Z-ky%gqF(x3rkYthyVZp diff --git a/engine/crates/layerfs-store-service/tests/fixtures/merge-forms-root.sqlite-shm b/engine/crates/layerfs-store-service/tests/fixtures/merge-forms-root.sqlite-shm new file mode 100644 index 0000000000000000000000000000000000000000..fe9ac2845eca6fe6da8a63cd096d9cf9e24ece10 GIT binary patch literal 32768 zcmeIuAr62r3/sandbox-retired/.json` tombstones and a JSONL audit -replace those tables, and the tables are gone. This tool converts a closed -schema version 2 Store once: - - store_gc_convert.py inspect - Reads the Store immutable, read only, and prints its version, its - machines and the rows per authority table, as JSON. - store_gc_convert.py copy - Read only on the Store. For every machine the home owns (a - `machine//record.json` exists) it copies - `gc_machine_authority.machine` into `MachineRecord.incarnation` and - `gc_sandbox_tombstone` into `machine//sandbox-retired/`. - It exports every `gc_audit` row to `/log/gc-audit.jsonl` and - records the converted machines in `/log/gc-conversion.json`. - A machine with rows and no home record is reported as missing; it is - never dropped implicitly. - store_gc_convert.py convert - [--converted ]... [--gone ]... - `copy` first, then converts into a NEW closed Store file: the three - tables are dropped, the two recorded `schema_version` checks and values - move to version 3, and the recorded schema source/definition are the - version 3 ones. The source is never modified, so it is the backup; the - target must not exist. `convert` refuses while any machine with rows is - neither owned by this home (and copied), named with `--converted` (its - owner home copied it), nor named with `--gone`. `--gone` is the - missing-machine policy: the operator declares the machine's home is - gone, its authority and tombstone rows are not copied, the audit is - exported, and only then are the tables dropped. A machine this home - owns cannot be declared gone; convert it. - -The conversion is per machine: a shared PostgreSQL Store holds rows for every -machine, and one home can copy only its own machines' rows. This tool converts -SQLite Stores; a PostgreSQL Store is converted in its own `psql` run after -every owner home has copied its rows (the offline copy/export half is the same -`copy` logic; no PostgreSQL connection is made here). The three tables are -dropped only in the converted target, so the old Store stays whole until every -known machine is accounted for. - -This is an offline tool: never point it at a live Store (a non-empty `-wal` is -refused), and keep the source file until the new Store is accepted. -""" - -import json -import os -import re -import shutil -import sqlite3 -import sys -from pathlib import Path - -APPLICATION_ID = 1279677264 -TABLES = ("gc_audit", "gc_machine_authority", "gc_sandbox_tombstone") -# A phase-3 schema version 2 user_version -> the lean schema version 3 one. -VERSIONS = {36: 39, 37: 40, 38: 41, 42: 45, 43: 46, 44: 47} -# The three tables as the phase-3 branch's `gc.sql` appended them; the current -# `gc.sql` is that text without them. A version 2 Store recorded them in its -# schema source, so its source is the current one plus this text. -AUTHORITY = """CREATE TABLE gc_machine_authority ( - machine TEXT PRIMARY KEY, - incarnation TEXT NOT NULL, - updated_ms INTEGER NOT NULL CHECK (updated_ms >= 0) -) STRICT; - -CREATE TABLE gc_sandbox_tombstone ( - sandbox TEXT NOT NULL, - machine TEXT NOT NULL, - generation TEXT NOT NULL, - retired_ms INTEGER NOT NULL CHECK (retired_ms >= 0), - PRIMARY KEY (sandbox, machine) -) STRICT, WITHOUT ROWID; - -CREATE TABLE gc_audit ( - seq INTEGER PRIMARY KEY AUTOINCREMENT, - at_ms INTEGER NOT NULL CHECK (at_ms >= 0), - action TEXT NOT NULL, - op_id BLOB, - detail TEXT -) STRICT; -""" - -SQL = Path(__file__).resolve().parent.parent / "engine/crates/layerfs-persistence/sql" -# The home name grammar (`layerfs_home::names`): a machine or Sandbox name is -# one folder under the home, so a row that is not one is never a path. -NAME = re.compile(r"[a-z0-9](?:[a-z0-9._-]{0,61}[a-z0-9])?\Z") -DEVICES = {"con", "nul", "aux", "prn"} | {f"com{n}" for n in range(1, 10)} | {f"lpt{n}" for n in range(1, 10)} - - -def refuse(message): - raise SystemExit(f"refused: {message}") - - -def _read_sql(*parts): - return (SQL.joinpath(*parts)).read_text() - - -def _layout(version): - """The pack layout script names of a stored schema version (2 or 3).""" - # 36/39 are Monolithic, 37/40 GroupRows, 38/41 GroupRowsIndexed; versions - # 42.. and 45.. are the same three layouts with the acquisition tables. - objects = { - 0: (("sqlite", "objects.sql"),), - 1: (("sqlite", "objects_units.sql"),), - 2: (("sqlite", "objects_units.sql"), ("sqlite", "objects_units_index.sql")), - } - if version not in VERSIONS and version not in VERSIONS.values(): - refuse(f"not a schema version 2 or 3 Store (user_version {version})") - return objects[version % 3] - - -def _scripts(version): - """The scripts `Session::initialize` runs, in order, for `version`.""" - names = _layout(version) - parts = [_read_sql(*name) for name in names] - for name in ("metadata.sql", "history.sql"): - parts.append(_read_sql("sqlite", name).replace("schema_version=1", f"schema_version={version}")) - parts.extend( - _read_sql("sqlite", name) for name in ("lineage.sql", "merge_scratch.sql", "file_digest.sql", "gc.sql") - ) - if version >= 42: - parts.append(_read_sql("sqlite", "acquisition", "schema.sql")) - return "".join(parts) - - -def _source(version): - """The schema source a Store of `version` records (the lean source for 3).""" - return _scripts(version) - - -def _old_source(version): - """The phase-3 source a Store of version 2 records: the current one plus the three tables.""" - source = _scripts(version) - gc = _read_sql("sqlite", "gc.sql") - if source.count(gc) != 1: - refuse("the engine's gc.sql is not the one this tool was written for") - return source.replace(gc, gc + AUTHORITY, 1) - - -def _definition(con): - rows = con.execute("SELECT type,name,sql FROM sqlite_schema WHERE substr(name,1,7)!='sqlite_' ORDER BY type,name") - return "".join(f"{t}\n{n}\n{s}\n" for t, n, s in rows) - - -def _name_set(con): - return {r[0] for r in con.execute("SELECT name FROM sqlite_schema WHERE type='table'")} - - -def _hex(value): - return value.hex() if isinstance(value, (bytes, bytearray)) else value - - -def _open_closed(path): - """Open `path` immutable and prove it is the closed Store this tool converts.""" - path = Path(path) - if not path.is_file(): - refuse(f"{path} is not a file") - wal = Path(str(path) + "-wal") - if wal.exists() and wal.stat().st_size: - refuse(f"{path} is not closed (its -wal is not empty); use a closed copy") - con = sqlite3.connect(f"file:{path}?immutable=1", uri=True) - app = con.execute("PRAGMA application_id").fetchone()[0] - if app != APPLICATION_ID: - refuse(f"{path} is not a LayerFS Store (application_id {app})") - version = con.execute("PRAGMA user_version").fetchone()[0] - if version not in VERSIONS: - refuse(f"{path} is not a phase-3 schema version 2 Store (user_version {version}); this build writes 3") - names = _name_set(con) - missing = [table for table in TABLES if table not in names] - if missing: - refuse(f"{path} has no {', '.join(missing)}; only a phase-3 Store (the three authority tables) is converted") - rows = con.execute("SELECT schema_source,schema_definition FROM history_meta WHERE id=1").fetchall() - if len(rows) != 1: - refuse(f"{path} has no one history_meta row") - recorded, definition = rows[0] - if definition != _definition(con): - refuse(f"{path}: the live schema differs from the recorded definition") - expected = _old_source(version) - if recorded != expected: - refuse(f"{path}: the recorded schema is not the phase-3 source this tool converts") - catalog = con.execute("SELECT catalog_id FROM history_meta WHERE id=1").fetchone()[0] - return con, version, bytes(catalog).hex() - - -def _checked(what, name): - """A machine or Sandbox name as the home holds it, or a refusal.""" - if not isinstance(name, str) or not NAME.fullmatch(name) or name in DEVICES: - refuse(f"{what} name {name!r} is not a checked home name; the three tables are not trusted paths") - - -def _authority(con): - machines = { - machine: [incarnation, updated_ms] - for machine, incarnation, updated_ms in con.execute( - "SELECT machine,incarnation,updated_ms FROM gc_machine_authority ORDER BY machine" - ) - } - tombstones = {} - for sandbox, machine, generation, retired_ms in con.execute( - "SELECT sandbox,machine,generation,retired_ms FROM gc_sandbox_tombstone ORDER BY machine,sandbox" - ): - _checked("machine", machine) - _checked("Sandbox", sandbox) - tombstones.setdefault(machine, []).append([sandbox, generation, retired_ms]) - for machine in machines: - _checked("machine", machine) - audit = [ - {"seq": seq, "at_ms": at_ms, "action": action, "op_id": op_id, "detail": detail} - for seq, at_ms, action, op_id, detail in con.execute( - "SELECT seq,at_ms,action,op_id,detail FROM gc_audit ORDER BY seq" - ) - ] - known = sorted(set(machines) | set(tombstones)) - return machines, tombstones, audit, known - - -def _lock_down(path): - os.chmod(path, 0o600) - - -def _write_json(path, value): - path = Path(path) - path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) - temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp") - temporary.write_text(json.dumps(value, separators=(",", ":")) + "\n") - _lock_down(temporary) - os.replace(temporary, path) - - -def _read_json(path): - path = Path(path) - if not path.is_file(): - return None - try: - return json.loads(path.read_text()) - except ValueError as error: - refuse(f"{path}: {error}") - - -def _layout_is_current(home): - home = Path(home) - value = _read_json(home / "layerfs.json") - if not isinstance(value, dict) or value.get("layout") != 3: - refuse(f"{home} is not a current (layout 3) home; open it once with this build, then convert") - - -def _entity(value): - """A record's value with the layout 3 `"v": 1` first, as `write_entity` writes it.""" - fields = [("v", 1)] + [(name, item) for name, item in value.items() if name != "v"] - return dict(fields) - - -def _ordered(token): - """A `p1:` ordered token, or None: an old random/time value has no order.""" - if not isinstance(token, str) or not token.startswith("p1:"): - return None - parts = token.split(":") - if len(parts) != 4 or len(parts[2]) != 16 or not parts[2].isdigit(): - return None - return token - - -def _newer(recorded, stored): - """The value a home keeps: the newer of two ordered ones, else an ordered home value, else the Store's.""" - recorded_ordered, stored_ordered = _ordered(recorded), _ordered(stored) - if recorded_ordered is not None and stored_ordered is not None: - return max(recorded_ordered, stored_ordered) - if recorded_ordered is not None: - return recorded - return stored - - -def _home_machine(home, machine): - return (Path(home) / "machine" / machine / "record.json").is_file() - - -def _set_incarnation(home, machine, incarnation): - path = Path(home) / "machine" / machine / "record.json" - value = _read_json(path) - if not isinstance(value, dict): - refuse(f"{path}: not a machine record") - recorded = value.get("incarnation") - if recorded != incarnation: - value["incarnation"] = incarnation if recorded is None else _newer(recorded, incarnation) - _write_json(path, _entity(value)) - return value["incarnation"] - - -def _write_tombstone(home, machine, sandbox, generation, retired_ms): - path = Path(home) / "machine" / machine / "sandbox-retired" / f"{sandbox}.json" - value = _read_json(path) or { - "name": sandbox, - "machine": machine, - "generation": generation, - "retired_ms": retired_ms, - } - if not isinstance(value, dict): - refuse(f"{path}: not a tombstone") - recorded = value.get("generation") - if recorded != generation: - value["generation"] = generation if recorded is None else _newer(recorded, generation) - value["retired_ms"] = max(int(value.get("retired_ms") or 0), retired_ms) - _write_json(path, _entity(value)) - return value["generation"] - - -def _write_audit(home, audit): - path = Path(home) / "log" / "gc-audit.jsonl" - path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) - lines = [] - for row in audit: - line = {"seq": row["seq"], "at_ms": row["at_ms"], "action": row["action"]} - if row["op_id"] is not None: - line["op_id"] = {"hex": bytes(row["op_id"]).hex()} - if row["detail"] is not None: - line["detail"] = row["detail"] - lines.append(json.dumps(line, separators=(",", ":"))) - temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp") - temporary.write_text("".join(f"{line}\n" for line in lines)) - _lock_down(temporary) - os.replace(temporary, path) - - -def _ledger_path(home): - return Path(home) / "log" / "gc-conversion.json" - - -def _ledger(home, catalog): - ledger = _read_json(_ledger_path(home)) or {"v": 1, "stores": {}} - if not isinstance(ledger, dict) or not isinstance(ledger.get("stores"), dict): - refuse("the conversion ledger is not a ledger") - store = ledger["stores"].setdefault(catalog, {"machines": {}}) - if not isinstance(store.get("machines"), dict): - refuse("the conversion ledger's machines are not a map") - return ledger, store - - -def inspect(path): - """The read-only summary of a phase-3 schema version 2 Store.""" - con, version, catalog = _open_closed(path) - machines, tombstones, audit, known = _authority(con) - con.close() - return { - "user_version": version, - "catalog": catalog, - "machines": known, - "authority": machines, - "tombstones": {machine: rows for machine, rows in sorted(tombstones.items())}, - "audit_rows": len(audit), - } - - -def copy(path, home): - """Copy this home's machines out of the Store; read only on the Store.""" - home = Path(home) - _layout_is_current(home) - con, version, catalog = _open_closed(path) - machines, tombstones, audit, known = _authority(con) - con.close() - owned = [machine for machine in known if _home_machine(home, machine)] - copied = {} - for machine in owned: - recorded = None - if machine in machines: - recorded = _set_incarnation(home, machine, machines[machine][0]) - retired = [] - for sandbox, generation, retired_ms in tombstones.get(machine, []): - written = _write_tombstone(home, machine, sandbox, generation, retired_ms) - retired.append({"sandbox": sandbox, "generation": written}) - copied[machine] = { - "at_ms": _now_ms(), - "incarnation": recorded, - "tombstones": retired, - } - _write_audit(home, audit) - ledger, store = _ledger(home, catalog) - for machine, entry in copied.items(): - store["machines"][machine] = { - "at_ms": entry["at_ms"], - "incarnation": entry["incarnation"], - "tombstones": len(entry["tombstones"]), - "audit_rows": len(audit), - } - _write_json(_ledger_path(home), ledger) - return { - "source": str(Path(path)), - "user_version": version, - "catalog": catalog, - "known": known, - "owned": owned, - "missing": [machine for machine in known if machine not in owned], - "copied": copied, - "audit_rows": len(audit), - "audit_export": str(home / "log" / "gc-audit.jsonl"), - "ledger": str(_ledger_path(home)), - } - - -def _convert_file(source, target, version): - """Copy `source` to `target` and lay schema version 3 over it.""" - new = VERSIONS[version] - shutil.copyfile(source, target) - try: - con = sqlite3.connect(target, isolation_level=None) - con.execute("BEGIN IMMEDIATE") - for table in TABLES: - con.execute(f"DROP TABLE {table}") - con.execute("PRAGMA writable_schema=ON") - if version < 42: - # gc_audit's AUTOINCREMENT created sqlite_sequence; the lean - # non-acquisition table set has none, and SQLite cannot DROP it. - con.execute("DELETE FROM sqlite_schema WHERE type='table' AND name='sqlite_sequence'") - for table in ("store_policy", "history_meta"): - con.execute( - "UPDATE sqlite_schema SET sql=replace(sql,?,?) WHERE type='table' AND name=?", - (f"schema_version={version})", f"schema_version={new})", table), - ) - con.execute("PRAGMA writable_schema=OFF") - con.execute("COMMIT") - con.close() - # Reopen so SQLite reads the patched schema text before the version columns change. - con = sqlite3.connect(target, isolation_level=None) - con.execute("BEGIN IMMEDIATE") - con.execute(f"PRAGMA user_version={new}") - con.execute("UPDATE store_policy SET schema_version=?", (new,)) - con.execute( - "UPDATE history_meta SET schema_version=?,schema_source=?,schema_definition=?", - (new, _source(new), _definition(con)), - ) - con.execute("COMMIT") - # VACUUM first: deleting the phase-3 `sqlite_sequence` schema row - # leaves its page unused until the rebuild reclaims it. - con.execute("VACUUM") - if con.execute("PRAGMA integrity_check").fetchone()[0] != "ok": - raise SystemExit("refused: the converted Store fails integrity_check; the target was removed") - con.close() - for suffix in ("-wal", "-shm"): - leftover = Path(str(target) + suffix) - if leftover.exists(): - if leftover.stat().st_size: - raise SystemExit(f"refused: the converted Store left a non-empty {suffix}; the target was removed") - leftover.unlink() - except BaseException: - Path(target).unlink(missing_ok=True) - raise - return new - - -def convert(path, target, home, converted=(), gone=()): - """Copy this home's machines, then convert; drop only with every machine accounted for.""" - target = Path(target) - if target.exists(): - refuse(f"{target} exists; a conversion writes a new Store, never over one") - home = Path(home) - report = copy(path, home) - known, owned = set(report["known"]), set(report["owned"]) - converted, gone = set(converted), set(gone) - owned_gone = sorted(owned & gone) - if owned_gone: - refuse(f"this home owns {', '.join(owned_gone)}; convert it, do not declare it gone") - uncovered = sorted(known - owned - converted - gone) - if uncovered: - refuse( - "no home copied and no operator declaration covers " - + ", ".join(uncovered) - + "; run `copy` in each owner home, then name the rest with --converted or --gone" - ) - temporary = target.with_name(f".{target.name}.{os.getpid()}.tmp") - new = _convert_file(path, temporary, report["user_version"]) - os.replace(temporary, target) - ledger, store = _ledger(home, report["catalog"]) - entry = { - "at_ms": _now_ms(), - "from": report["user_version"], - "to": new, - "target": str(target), - "converted": sorted(converted), - "gone": sorted(gone), - } - store["convert"] = entry - _write_json(_ledger_path(home), ledger) - report["converted"] = sorted(converted) - report["gone"] = sorted(gone) - report["target"] = str(target) - report["from"] = report["user_version"] - report["to"] = new - report["dropped"] = list(TABLES) - return report - - -def _now_ms(): - import time - - return int(time.time() * 1000) - - -def _usage(): - for paragraph in __doc__.strip().split("\n\n"): - if "store_gc_convert.py inspect" in paragraph: - return paragraph - return __doc__ - - -def main(argv): - arguments = list(argv[1:]) - if not arguments or arguments[0] in ("-h", "--help"): - print(_usage()) - return 0 - command, rest = arguments[0], arguments[1:] - if command == "inspect": - if len(rest) != 1: - print(_usage(), file=sys.stderr) - return 2 - print(json.dumps(inspect(rest[0]), separators=(",", ":"))) - return 0 - if command == "copy": - if len(rest) != 2: - print(_usage(), file=sys.stderr) - return 2 - print(json.dumps(copy(rest[0], rest[1]), separators=(",", ":"))) - return 0 - if command == "convert": - converted, gone, positional, option = [], [], [], None - for word in rest: - if option is not None: - (converted if option == "--converted" else gone).append(word) - option = None - elif word in ("--converted", "--gone"): - option = word - else: - positional.append(word) - if option is not None or len(positional) != 3: - print(_usage(), file=sys.stderr) - return 2 - print( - json.dumps( - convert(positional[0], positional[1], positional[2], converted, gone), - separators=(",", ":"), - ) - ) - return 0 - print(f"refused: no command {command}", file=sys.stderr) - return 2 - - -if __name__ == "__main__": - try: - sys.exit(main(sys.argv)) - except SystemExit as error: - if not isinstance(error.code, int): - print(error.code, file=sys.stderr) - sys.exit(1) - raise diff --git a/tools/test_store_gc_convert.py b/tools/test_store_gc_convert.py deleted file mode 100644 index 3c75ec62d6..0000000000 --- a/tools/test_store_gc_convert.py +++ /dev/null @@ -1,391 +0,0 @@ -"""Tests for store_gc_convert.py: a phase-3 schema version 2 Store becomes the -lean schema version 3 one, per machine, with the three tables dropped only -after every known machine is accounted for.""" - -import hashlib -import json -import os -import sqlite3 -import tempfile -import unittest -from pathlib import Path - -import store_gc_convert as sg - - -def store(path, version=36, machines=None, tombstones=None, audit=None): - """A closed phase-3 schema version 2 Store as the released build wrote it.""" - source = sg._old_source(version) - con = sqlite3.connect(path, isolation_level=None) - con.executescript(source) - con.execute(f"PRAGMA application_id={sg.APPLICATION_ID}") - con.execute(f"PRAGMA user_version={version}") - con.execute( - "INSERT INTO store_policy(id,schema_version,format_profile,small_file_threshold_bytes," - "whole_file_delta_max_depth,chunk_delta_max_depth,metadata_delta_max_depth) " - "VALUES(1,?,1,262144,3,3,3)", - (version,), - ) - con.execute( - "INSERT INTO history_meta(id,catalog_id,catalog_incarnation,binding_key," - "identity_format,schema_version,schema_source,schema_definition) " - "VALUES(1,?,1,?,3,?,?,?)", - (bytes(32), b"binding", version, source, sg._definition(con)), - ) - for machine, (incarnation, updated_ms) in (machines or {}).items(): - con.execute( - "INSERT INTO gc_machine_authority(machine,incarnation,updated_ms) VALUES(?,?,?)", - (machine, incarnation, updated_ms), - ) - for sandbox, machine, generation, retired_ms in tombstones or (): - con.execute( - "INSERT INTO gc_sandbox_tombstone(sandbox,machine,generation,retired_ms) VALUES(?,?,?,?)", - (sandbox, machine, generation, retired_ms), - ) - for at_ms, action, op_id, detail in audit or (): - con.execute( - "INSERT INTO gc_audit(at_ms,action,op_id,detail) VALUES(?,?,?,?)", - (at_ms, action, op_id, detail), - ) - con.close() - return path - - -def home(root, machines=("native",), layout=3): - """A layout 3 home with one record per machine.""" - path = Path(root) / "home" - path.mkdir(parents=True) - (path / "layerfs.json").write_text(json.dumps({"layout": layout, "id": "a" * 32}) + "\n") - for machine in machines: - folder = path / "machine" / machine - folder.mkdir(parents=True) - (folder / "record.json").write_text( - json.dumps({"v": 1, "name": machine, "platform": machine, "created": 1}, separators=(",", ":")) + "\n" - ) - return path - - -def digest(path): - return hashlib.sha256(Path(path).read_bytes()).hexdigest() - - -def fresh_tables(version): - """The table set `Session::initialize` creates for a version 3 layout.""" - con = sqlite3.connect(":memory:") - con.executescript(sg._source(version)) - names = {row[0] for row in con.execute("SELECT name FROM sqlite_schema WHERE type='table'")} - con.close() - return names - - -class Conversion(unittest.TestCase): - def setUp(self): - self._tmp = tempfile.TemporaryDirectory() - self.addCleanup(self._tmp.cleanup) - self.root = Path(self._tmp.name) - self.v2 = self.root / "old.sqlite" - self.target = self.root / "new.sqlite" - - def test_inspect_reads_the_phase_three_store(self): - store( - self.v2, - machines={"native": ("old-incarnation", 5)}, - tombstones=[("box", "native", "old-generation", 6)], - audit=[(7, "settle", bytes(16), "detail")], - ) - found = sg.inspect(self.v2) - self.assertEqual(found["user_version"], 36) - self.assertEqual(found["catalog"], "00" * 32) - self.assertEqual(found["machines"], ["native"]) - self.assertEqual(found["authority"], {"native": ["old-incarnation", 5]}) - self.assertEqual(found["tombstones"], {"native": [["box", "old-generation", 6]]}) - self.assertEqual(found["audit_rows"], 1) - - def test_copy_writes_home_records_and_leaves_the_store_alone(self): - before = digest( - store( - self.v2, - machines={"native": ("p1:native:0000000000000005:aa", 5), "docker": ("worker", 6)}, - tombstones=[("box", "native", "p1:sandbox:0000000000000007:bb", 7)], - audit=[(8, "reconcile", bytes(range(16)), "start")], - ) - ) - where = home(self.root, machines=("native",)) - report = sg.copy(self.v2, where) - self.assertEqual(digest(self.v2), before, "the source is read only") - self.assertEqual(report["known"], ["docker", "native"]) - self.assertEqual(report["owned"], ["native"]) - self.assertEqual(report["missing"], ["docker"]) - self.assertEqual(report["audit_rows"], 1) - record = json.loads((where / "machine/native/record.json").read_text()) - self.assertEqual( - record, - { - "v": 1, - "name": "native", - "platform": "native", - "created": 1, - "incarnation": "p1:native:0000000000000005:aa", - }, - ) - tombstone = json.loads((where / "machine/native/sandbox-retired/box.json").read_text()) - self.assertEqual( - tombstone, - { - "v": 1, - "name": "box", - "machine": "native", - "generation": "p1:sandbox:0000000000000007:bb", - "retired_ms": 7, - }, - ) - lines = [json.loads(line) for line in (where / "log/gc-audit.jsonl").read_text().splitlines()] - self.assertEqual( - lines, - [ - { - "seq": 1, - "at_ms": 8, - "action": "reconcile", - "op_id": {"hex": bytes(range(16)).hex()}, - "detail": "start", - } - ], - ) - ledger = json.loads((where / "log/gc-conversion.json").read_text()) - self.assertEqual(sorted(ledger["stores"]), ["00" * 32]) - self.assertEqual(sorted(ledger["stores"]["00" * 32]["machines"]), ["native"]) - - def test_convert_writes_a_version_three_store(self): - before = digest( - store( - self.v2, - machines={"native": ("p1:native:0000000000000005:aa", 5)}, - tombstones=[("box", "native", "p1:sandbox:0000000000000007:bb", 7)], - audit=[(9, "release", bytes(16), None)], - ) - ) - where = home(self.root) - report = sg.convert(self.v2, self.target, where) - self.assertEqual(report["from"], 36) - self.assertEqual(report["to"], 39) - self.assertEqual(digest(self.v2), before, "the source is the backup and never changes") - self.assertTrue(self.target.is_file()) - con = sqlite3.connect(self.target) - self.assertEqual(con.execute("PRAGMA application_id").fetchone()[0], sg.APPLICATION_ID) - self.assertEqual(con.execute("PRAGMA user_version").fetchone()[0], 39) - names = {row[0] for row in con.execute("SELECT name FROM sqlite_schema WHERE type='table'")} - for table in sg.TABLES: - self.assertNotIn(table, names, table) - self.assertNotIn("sqlite_sequence", names, "the phase-3 audit's sequence table is gone") - self.assertEqual(names, fresh_tables(39), "the converted table set is a fresh version 3 one") - for table in ("store_policy", "history_meta"): - self.assertEqual(con.execute(f"SELECT schema_version FROM {table}").fetchone()[0], 39) - text = con.execute("SELECT sql FROM sqlite_schema WHERE name=?", (table,)).fetchone()[0] - self.assertIn("schema_version=39)", text) - self.assertNotIn("schema_version=36)", text) - source, definition = con.execute("SELECT schema_source,schema_definition FROM history_meta").fetchone() - self.assertEqual(source, sg._source(39)) - self.assertEqual(definition, sg._definition(con)) - self.assertEqual(con.execute("PRAGMA integrity_check").fetchone()[0], "ok") - con.close() - ledger = json.loads((where / "log/gc-conversion.json").read_text()) - self.assertEqual(ledger["stores"]["00" * 32]["convert"]["to"], 39) - - def test_convert_refuses_while_a_machine_is_unaccounted_for(self): - store(self.v2, machines={"native": ("a", 5), "elsewhere": ("b", 6)}) - where = home(self.root) - with self.assertRaises(SystemExit) as caught: - sg.convert(self.v2, self.target, where) - self.assertIn("elsewhere", str(caught.exception.code)) - self.assertFalse(self.target.exists(), "a refused conversion writes no target") - - def test_gone_is_the_missing_machine_policy_after_the_audit_export(self): - store( - self.v2, - machines={"native": ("a", 5), "elsewhere": ("b", 6)}, - tombstones=[("lost", "elsewhere", "gone-generation", 7)], - audit=[(9, "settle", bytes(16), "gone")], - ) - where = home(self.root) - report = sg.convert(self.v2, self.target, where, gone=["elsewhere"]) - self.assertEqual(report["gone"], ["elsewhere"]) - self.assertEqual(report["to"], 39) - self.assertTrue((where / "log/gc-audit.jsonl").is_file(), "the audit is exported before the drop") - self.assertEqual(json.loads((where / "log/gc-audit.jsonl").read_text().splitlines()[0])["action"], "settle") - con = sqlite3.connect(self.target) - self.assertEqual(con.execute("PRAGMA user_version").fetchone()[0], 39) - con.close() - - def test_a_three_table_fixture_converts_end_to_end(self): - """The real old-format fixture: a version 2 Store with the three tables. - - One conversion test covers all four acceptance points together: the - conversion, the `--gone` missing-machine policy, the source file - unchanged, and the JSONL audit export. The fixture is the recorded - phase-3 source (the only shape an old Store wrote); no old binary is - needed, and `inspect` refuses anything that is not exactly that shape. - """ - before_digest = digest( - store( - self.v2, - machines={ - "native": ("p1:native:0000000000000005:aa", 5), - "elsewhere": ("p1:worker:0000000000000006:bb", 6), - }, - tombstones=[ - ("box", "native", "p1:sandbox:0000000000000007:cc", 7), - ("lost", "elsewhere", "p1:sandbox:0000000000000008:dd", 8), - ], - audit=[(9, "release", bytes(range(16)), "operator=alice")], - ) - ) - where = home(self.root, machines=("native",)) - before = sg.inspect(self.v2) - self.assertEqual(before["user_version"], 36) - self.assertEqual(before["machines"], ["elsewhere", "native"]) - self.assertEqual(before["audit_rows"], 1) - - report = sg.convert(self.v2, self.target, where, gone=["elsewhere"]) - self.assertEqual(report["gone"], ["elsewhere"]) - self.assertEqual(report["dropped"], list(sg.TABLES)) - self.assertEqual(report["from"], 36) - self.assertEqual(report["to"], 39) - - self.assertEqual(digest(self.v2), before_digest, "the source is the backup") - con = sqlite3.connect(self.target) - self.assertEqual(con.execute("PRAGMA user_version").fetchone()[0], 39) - names = {row[0] for row in con.execute("SELECT name FROM sqlite_schema WHERE type='table'")} - for table in sg.TABLES: - self.assertNotIn(table, names, table) - self.assertEqual(con.execute("PRAGMA integrity_check").fetchone()[0], "ok") - con.close() - - # The gone machine's authority and tombstone were not copied, and the - # home the tool owns got its own machine and tombstone. - self.assertFalse((where / "machine/elsewhere").exists(), "a gone machine is not copied") - self.assertFalse((where / "machine/native/sandbox-retired/lost.json").exists()) - copied = json.loads((where / "machine/native/record.json").read_text()) - self.assertEqual(copied["incarnation"], "p1:native:0000000000000005:aa") - self.assertTrue((where / "machine/native/sandbox-retired/box.json").is_file()) - - # The old audit rows were exported before the tables were dropped. - lines = [json.loads(line) for line in (where / "log/gc-audit.jsonl").read_text().splitlines()] - self.assertEqual(len(lines), 1) - self.assertEqual(lines[0]["action"], "release") - self.assertEqual(lines[0]["op_id"], {"hex": bytes(range(16)).hex()}) - ledger = json.loads((where / "log/gc-conversion.json").read_text()) - self.assertEqual(ledger["stores"]["00" * 32]["convert"]["gone"], ["elsewhere"]) - - def test_a_machine_the_home_owns_cannot_be_declared_gone(self): - store(self.v2, machines={"native": ("a", 5)}) - where = home(self.root) - with self.assertRaises(SystemExit) as caught: - sg.convert(self.v2, self.target, where, gone=["native"]) - self.assertIn("convert it, do not declare it gone", str(caught.exception.code)) - self.assertFalse(self.target.exists()) - - def test_the_command_line_converts(self): - store(self.v2, machines={"native": ("a", 5), "elsewhere": ("b", 6)}) - where = home(self.root) - self.assertEqual( - sg.main( - ["store_gc_convert.py", "convert", str(self.v2), str(self.target), str(where), "--gone", "elsewhere"] - ), - 0, - ) - self.assertTrue(self.target.is_file()) - self.assertEqual(sg.main(["store_gc_convert.py", "convert"]), 2, "a wrong command line is 2") - - def test_a_converted_elsewhere_machine_is_covered(self): - store(self.v2, machines={"native": ("a", 5), "elsewhere": ("b", 6)}) - where = home(self.root) - report = sg.convert(self.v2, self.target, where, converted=["elsewhere"]) - self.assertEqual(report["converted"], ["elsewhere"]) - self.assertTrue(self.target.is_file()) - - def test_every_schema_version_2_layout_moves_by_three(self): - for old, new in ((36, 39), (37, 40), (38, 41), (42, 45), (43, 46), (44, 47)): - source = self.root / f"v{old}.sqlite" - target = self.root / f"v{new}.sqlite" - store(source, version=old, machines={"native": ("a", 5)}) - sg.convert(source, target, home(self.root / f"home-{old}")) - con = sqlite3.connect(target) - self.assertEqual(con.execute("PRAGMA user_version").fetchone()[0], new) - self.assertEqual(con.execute("SELECT schema_source FROM history_meta").fetchone()[0], sg._source(new)) - names = {row[0] for row in con.execute("SELECT name FROM sqlite_schema WHERE type=?", ("table",))} - self.assertEqual(names, fresh_tables(new), f"version {old} gives a fresh version {new} table set") - self.assertEqual(con.execute("PRAGMA integrity_check").fetchone()[0], "ok") - con.close() - - def test_the_acquisition_layout_moves_by_three(self): - store(self.v2, version=42, machines={"native": ("a", 5)}) - sg.convert(self.v2, self.target, home(self.root)) - con = sqlite3.connect(self.target) - self.assertEqual(con.execute("PRAGMA user_version").fetchone()[0], 45) - names = {row[0] for row in con.execute("SELECT name FROM sqlite_schema WHERE type='table'")} - self.assertIn("init_operation", names, "the acquisition tables stay") - self.assertIn("sqlite_sequence", names, "the acquisition layout keeps its sequence table") - self.assertEqual(names, fresh_tables(45), "the converted table set is a fresh version 3 one") - source = con.execute("SELECT schema_source FROM history_meta").fetchone()[0] - self.assertEqual(source, sg._source(45)) - con.close() - - def test_a_home_owned_ordered_value_wins_over_the_old_unordered_one(self): - store(self.v2, machines={"native": ("old-random", 5)}) - where = home(self.root) - record = where / "machine/native/record.json" - record.write_text( - json.dumps( - {"v": 1, "name": "native", "incarnation": "p1:native:0000000000000009:cc"}, separators=(",", ":") - ) - + "\n" - ) - sg.copy(self.v2, where) - self.assertEqual(json.loads(record.read_text())["incarnation"], "p1:native:0000000000000009:cc") - - def test_copy_is_idempotent(self): - store(self.v2, machines={"native": ("a", 5)}, audit=[(9, "settle", None, None)]) - where = home(self.root) - sg.copy(self.v2, where) - first = json.loads((where / "log/gc-conversion.json").read_text())["stores"]["00" * 32]["machines"] - sg.copy(self.v2, where) - again = json.loads((where / "log/gc-conversion.json").read_text())["stores"]["00" * 32]["machines"] - for entries in (first, again): - for entry in entries.values(): - entry.pop("at_ms") - self.assertEqual(again, first) - self.assertEqual(len((where / "log/gc-audit.jsonl").read_text().splitlines()), 1) - - def test_refusals(self): - current = store(self.root / "current.sqlite", version=39, machines={}) - with self.assertRaises(SystemExit) as caught: - sg.inspect(current) - self.assertIn("not a phase-3 schema version 2 Store", str(caught.exception.code)) - - store(self.v2, machines={}) - with self.assertRaises(SystemExit) as caught: - sg.copy(self.v2, home(self.root / "layout-2", layout=2)) - self.assertIn("not a current (layout 3) home", str(caught.exception.code)) - - bad = self.root / "bad-name.sqlite" - store(bad, machines={"../escape": ("a", 5)}) - with self.assertRaises(SystemExit) as caught: - sg.inspect(bad) - self.assertIn("not a checked home name", str(caught.exception.code)) - - closed = store(self.root / "closed.sqlite", machines={}) - Path(str(closed) + "-wal").write_text("not empty") - with self.assertRaises(SystemExit) as caught: - sg.inspect(closed) - self.assertIn("not closed", str(caught.exception.code)) - - Path(str(closed) + "-wal").unlink() - self.target.write_text("occupied") - with self.assertRaises(SystemExit) as caught: - sg.convert(self.v2, self.target, home(self.root / "layout-3")) - self.assertIn("exists", str(caught.exception.code)) - - -if __name__ == "__main__": - unittest.main() From 2c120f08cabf7cba66f9cb994550edff03f77d9a Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 16:27:02 +0800 Subject: [PATCH 05/16] test(store): read main's list row by its `branch` key `project_delete_store::main_resolves_to_the_branch_add_project_recorded` (added in this PR) read `items[0].name`, but the main line's list row names itself under `branch` (listing.rs `main_item`), so the test failed at the PR head. Read the key the row has; the id assertion is unchanged. Production LOC: 214,022 -> 214,022 (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-store/tests/project_delete_store.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/control/crates/layerfs-store/tests/project_delete_store.rs b/control/crates/layerfs-store/tests/project_delete_store.rs index b55e31f0d2..d9b8dddf00 100644 --- a/control/crates/layerfs-store/tests/project_delete_store.rs +++ b/control/crates/layerfs-store/tests/project_delete_store.rs @@ -206,7 +206,7 @@ fn main_resolves_to_the_branch_add_project_recorded() { panic!("no items: {listed:?}"); }; assert_eq!(items.len(), 1, "{listed:?}"); - assert_eq!(items[0].get_text("name"), Some("main")); + assert_eq!(items[0].get_text("branch"), Some("main")); let wanted = recorded.to_string(); assert_eq!(items[0].get_text("id"), Some(wanted.as_str()), "{listed:?}"); let _ = std::fs::remove_dir_all(&home); From 32fd231d0c4b65a703f33b02616f0cd21c7f3709 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 16:35:32 +0800 Subject: [PATCH 06/16] fix(gc): admission never judges a live holder dead where the base would not Place tokens now name the home that minted them, `p1:.::`, and `compare_place` orders two tokens only when their labels match: on a Store two homes share, another home's `box` incarnation, Sandbox generation or tombstone is Unordered (Uncertain at worst), never Dead. A token with no home id is not ordered (equal only). Machine incarnations (create, start) and Sandbox generations are minted with the home id and a floor: at least one millisecond past the previous incarnation, or past the name's previous record and tombstone, so a wall clock stepped back never mints an older value. An equal Sandbox record with a newer tombstone is Uncertain, not Dead; only the tombstone of that very generation retires a live record. The process-global MACHINE_INCARNATION fallback is removed: a mount intent records only the incarnation its control caller read from the home. The worker's own minted value (no host supplied one) carries no home id. The owner (namespace/boot) check always applies first, as in the base; place evidence only adds proofs of death. Mount registration no longer runs `settle_place` (an unindexed gc_intent scan inside the write transaction); settling stays in removal/compaction admission and the worker-start reconcile. owner_boot is per Workspace, so UNIQUE(scope_kind, scope_id, owner_boot) still admits every fresh mount, as in the base. Mount rows record the project name (from a named bind, or the stack read once for a bind by Branch id), so gc_intent_done_branch finds released rows. Tests changed: settle-at-mount tests now prove the registration settles no other row and the removal (given the place view) or reconcile settles it (persistence admission.rs, gc_place_writers.rs, store-service admission.rs); place_incarnation.rs proves no process-wide incarnation is filled in; test tokens carry a home label (incl. control store_repair_live.rs and mount_place_authority.rs). Added: different-home tokens/places never Dead (history authority.rs, gc_place_view.rs, gc_place_writers.rs), minting floor (layerfs-home ordered_token.rs, sandbox record_codec.rs), equal record with newer tombstone is Uncertain, owner-dead with a current place is still settled (Linux only), mount rows record the project. Removed dead `future_ms` helpers and an orphaned doc block in touched test files. No tests deleted. Production LOC: 214,081 -> 214,096 (delta +15) core 42,466 -> 42,474 (+8) layerfs-history +8 engine 98,274 -> 98,249 (-25) layerfs-persistence -24, layerfs-store-service -1 control 62,950 -> 62,982 (+32) layerfs-home +15, layerfs-sandbox +17, layerfs-machine +1, layerfs-control -1 api 10,391 -> 10,391 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent ec99bf29c2 and the staged tree scope: tools/production_loc.py (repo-pinned counter), first-parent tree vs committed tree Co-Authored-By: Claude Opus 5.5 --- .../layerfs-control/src/worker_server.rs | 13 +- .../tests/mount_place_authority.rs | 14 +- .../tests/store_repair_live.rs | 44 +++---- control/crates/layerfs-home/src/helpers.rs | 40 +++++- .../layerfs-home/tests/ordered_token.rs | 29 ++++ control/crates/layerfs-machine/src/create.rs | 2 +- .../crates/layerfs-machine/src/endpoint.rs | 17 ++- control/crates/layerfs-sandbox/src/create.rs | 2 +- .../layerfs-sandbox/src/record/sandbox.rs | 47 +++++-- .../layerfs-sandbox/tests/record_codec.rs | 48 ++++++- .../layerfs-history/src/contract/authority.rs | 81 +++++++----- .../crates/layerfs-history/tests/authority.rs | 94 ++++++++++++- docs/architecture/api/sdk/machine.md | 2 +- .../control/machines/workers-and-reach.md | 23 ++-- .../src/history/admission.rs | 53 ++------ .../src/history/admission/place.rs | 37 +++--- .../layerfs-persistence/tests/admission.rs | 124 +++++++++++------- .../tests/gc_place_view.rs | 40 +++++- .../tests/gc_place_writers.rs | 59 +++++++-- .../src/history/admission.rs | 53 +++----- .../layerfs-store-service/src/store/bind.rs | 23 +++- .../layerfs-store-service/tests/admission.rs | 81 ++++++++---- .../tests/place_incarnation.rs | 28 ++-- 23 files changed, 635 insertions(+), 319 deletions(-) create mode 100644 control/crates/layerfs-home/tests/ordered_token.rs diff --git a/control/crates/layerfs-control/src/worker_server.rs b/control/crates/layerfs-control/src/worker_server.rs index 316a9be68f..a7defbd141 100644 --- a/control/crates/layerfs-control/src/worker_server.rs +++ b/control/crates/layerfs-control/src/worker_server.rs @@ -100,11 +100,12 @@ struct Server { faults: Arc, } -/// One fresh, ordered incarnation for a worker starting now: a newer start -/// compares greater than every younger one across restarts and pid reuse, so -/// admission can tell an old placement from the current one. +/// One fresh incarnation for a worker no host supplied one to (an older +/// host, or a test). The worker knows no home, so the value carries no home +/// id and orders against nothing: it is only reported, and a host whose +/// record names another value skips its reconcile. fn incarnation() -> String { - layerfs_home::helpers::ordered_token("worker") + layerfs_home::helpers::ordered_token("", "worker", &[]) } /// Serves `listener` until it fails or the process is ended (`machine.stop`; @@ -128,10 +129,6 @@ pub fn serve_with_incarnation( supplied: Option, ) -> std::io::Result { let server = Server::new(secret, root, supplied); - // Recorded before any request is served: every mount intent this worker - // places carries this incarnation, and the host's start reconcile writes - // the same value into each Store and settles what the previous one left. - layerfs_store_service::history::admission::set_machine_incarnation(server.incarnation.clone()); server.run(&listener) } diff --git a/control/crates/layerfs-control/tests/mount_place_authority.rs b/control/crates/layerfs-control/tests/mount_place_authority.rs index ad45a7fced..137e356a05 100644 --- a/control/crates/layerfs-control/tests/mount_place_authority.rs +++ b/control/crates/layerfs-control/tests/mount_place_authority.rs @@ -12,9 +12,7 @@ mod support; use layerfs_bridge::control::SdkValue; use layerfs_history::records::GcScopeKind; -use layerfs_history::{ - BranchId, ForkRequest, ForkSource, HistoryName, LayerStackId, WorkspaceId, -}; +use layerfs_history::{BranchId, ForkRequest, ForkSource, HistoryName, LayerStackId, WorkspaceId}; use layerfs_machine::record::MachineRecord; use layerfs_sandbox::internal::Control; use layerfs_sandbox::record::{mount_place, retire_in, SandboxRecord}; @@ -30,13 +28,13 @@ fn a_daemon_mount_records_the_home_place_and_its_tombstone_settles_it() { let home = f.host.directory.join("home"); std::fs::create_dir_all(&home).unwrap(); let machine = "docker"; - let incarnation = "p1:worker:10:aa"; + let incarnation = "p1:aa11.worker:10:aa"; MachineRecord::built_in(machine, "home-id") .with_incarnation(incarnation) .write(&home) .unwrap(); let sandbox = "place-sbx"; - let generation = "p1:sandbox:10:bb"; + let generation = "p1:aa11.sandbox:10:bb"; let directory = layerfs_home::home::paths::sandbox_dir(&home, sandbox); std::fs::create_dir_all(&directory).unwrap(); SandboxRecord::from_record( @@ -77,7 +75,11 @@ fn a_daemon_mount_records_the_home_place_and_its_tombstone_settles_it() { let service = f.service.clone(); let (channel, worker) = support::pair(move |connection| { for _ in 0..2 { - drop(service.serve_one(connection, |_, _, _| unreachable!()).unwrap()); + drop( + service + .serve_one(connection, |_, _, _| unreachable!()) + .unwrap(), + ); } }); let mut client = Control::new(channel); diff --git a/control/crates/layerfs-control/tests/store_repair_live.rs b/control/crates/layerfs-control/tests/store_repair_live.rs index d7dd7db60c..a84f4f2055 100644 --- a/control/crates/layerfs-control/tests/store_repair_live.rs +++ b/control/crates/layerfs-control/tests/store_repair_live.rs @@ -12,7 +12,6 @@ mod worker_store; use layerfs_bridge::control::{SdkCall, SdkRefusal, SdkValue}; -use layerfs_history::error::HistoryError; use layerfs_history::records::{GcIntent, GcIntentKind, GcScopeKind}; use layerfs_history::PlaceAuthority; use layerfs_home::events::Events; @@ -54,16 +53,6 @@ fn source(tag: &str) -> PathBuf { directory } -fn future_ms() -> i64 { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("the clock is after the epoch") - .as_millis(); - // An hour: seeding the 331 retired Branches must never let a lease the - // test calls live expire underneath it. - i64::try_from(now).expect("the clock fits an i64") + 3_600_000 -} - fn text(value: &str) -> SdkValue { SdkValue::text(value) } @@ -183,7 +172,6 @@ fn seed(home: &Path) { .named(Some("app"), Some(&name)), }; history.gc_register(&intent).unwrap(); - } // The 331 already retired behind the six: fork, a wholly dead pack, @@ -402,8 +390,8 @@ fn seed_reconcile(home: &Path) { // admission consults its caller's home, so the mounts must exist before // the new incarnation does for the worker start to be the first caller // that can settle the older placement. - let current = "p1:worker:0000000000000020:aa"; - let retired = "p1:sandbox:0000000000000010:aa"; + let current = "p1:aa11.worker:0000000000000020:aa"; + let retired = "p1:aa11.sandbox:0000000000000010:aa"; let record = StoreRecord::read(home, "shop").unwrap().unwrap(); let open = OpenArgs::of_record(home, "shop", &record).unwrap(); with_service(&open, |service| { @@ -445,8 +433,8 @@ fn seed_reconcile(home: &Path) { .gc_register(&mount( 0x82, "live", - "p1:worker:0000000000000030:aa", - "p1:sandbox:0000000000000020:aa", + "p1:aa11.worker:0000000000000030:aa", + "p1:aa11.sandbox:0000000000000020:aa", "boot:82", )) .unwrap(); @@ -457,8 +445,8 @@ fn seed_reconcile(home: &Path) { .gc_register(&mount( 0x81, "live", - "p1:worker:0000000000000010:aa", - "p1:sandbox:0000000000000020:aa", + "p1:aa11.worker:0000000000000010:aa", + "p1:aa11.sandbox:0000000000000020:aa", "boot:81", )) .unwrap(); @@ -494,13 +482,13 @@ fn a_worker_start_reconciles_the_incarnations_its_home_records() { &placed.home, "shop", "box", - "p1:worker:0000000000000020:aa", + "p1:aa11.worker:0000000000000020:aa", ) .expect("the start reconciles the worker's Store"); assert_eq!(outcome.get_text("machine"), Some("box"), "{outcome:?}"); assert_eq!( outcome.get_text("incarnation"), - Some("p1:worker:0000000000000020:aa"), + Some("p1:aa11.worker:0000000000000020:aa"), "{outcome:?}" ); let mut settled = Vec::new(); @@ -720,7 +708,11 @@ fn the_live_six_of_three_hundred_thirty_one_is_repaired_removed_and_reclaimed() let Some(SdkValue::List(rows)) = audit.get("items") else { panic!("audit items: {audit:?}"); }; - assert_eq!(rows.len(), 1, "main's audit is the preview it wrote: {audit:?}"); + assert_eq!( + rows.len(), + 1, + "main's audit is the preview it wrote: {audit:?}" + ); assert_eq!( rows[0].get_text("evidence"), Some("action=preview;operator=alice") @@ -742,8 +734,14 @@ fn the_live_six_of_three_hundred_thirty_one_is_repaired_removed_and_reclaimed() .iter() .filter(|row| row.get_text("evidence") == Some("action=preview;operator=alice")) .count(); - assert_eq!(releases, 1, "the compaction kept {name}'s release: {audit:?}"); - assert_eq!(previews, 2, "the compaction kept {name}'s previews: {audit:?}"); + assert_eq!( + releases, 1, + "the compaction kept {name}'s release: {audit:?}" + ); + assert_eq!( + previews, 2, + "the compaction kept {name}'s previews: {audit:?}" + ); } placed.remove(); diff --git a/control/crates/layerfs-home/src/helpers.rs b/control/crates/layerfs-home/src/helpers.rs index 2b69489dd5..ca06d75d6e 100644 --- a/control/crates/layerfs-home/src/helpers.rs +++ b/control/crates/layerfs-home/src/helpers.rs @@ -29,20 +29,46 @@ pub fn required<'a>(value: Option<&'a str>, name: &str) -> Result<&'a str, SdkRe value.ok_or_else(|| refused("InvalidInput", format!("missing text argument `{name}`"))) } -/// One ordered place value, `p1: