Repository navigation
perf(sqlite): prepare NOCOW stores and add offline btrfs repair - #160877
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. Reviewed September 28, 2026, 11:13 PM ET / September 29, 2026, 03:13 UTC (Revision 4). ClawSweeper reviewWhat this changesOn Linux btrfs, the branch requests NOCOW for new shared and agent SQLite stores and adds an offline Doctor rewrite for existing stores, with tests and storage documentation. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 13 items remain Keep open: this is a useful storage change absent from current main, but the durability choice lacks the required maintainer acceptance and the replacement path has unresolved safety gaps. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw keeps shared and per-agent state in SQLite, and its store-opening paths prepare directories before creating database files. Doctor can replace existing stores under maintenance ownership, while managed updates invoke Doctor repair. flowchart LR
A[New or existing SQLite store] --> B{Store exists?}
B -->|New| C[btrfs directory preparation]
B -->|Existing| D[Doctor inspection]
E[Managed update repair] --> D
D --> F[Offline directory rewrite]
C --> G[SQLite open]
F --> G
G --> H[Shared and agent state]
Decision needed
Why: This changes the storage durability and upgrade contract, which repository policy reserves for an accepted maintainer design. Before merge
Findings
Agent review detailsSecurityNeeds attention: The offline replacement can discard security-relevant extended attributes; the diff adds no package dependency or unrelated supply-chain change. PR surfaceSource +555, Tests +612, Docs +27, Other +10. Total +1204 across 22 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep existing btrfs durability defaults until an operator chooses NOCOW, preserve and verify all security-relevant metadata during replacement, and prove the upgrade and recovery path on real btrfs. Do we have a high-confidence way to reproduce the issue? Yes for the introduced updater path: current main passes repair: true, and the branch then calls the NOCOW rewrite for detected stores. Real btrfs replacement was not exercised in the supplied proof. Is this the best way to solve the issue? No. The offline maintenance owner is an appropriate boundary, but an explicit durability choice, complete metadata preservation, and real btrfs upgrade proof are needed before this implementation is safe to merge. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 842697352d23. LabelsLabel changes:
Label justifications:
EvidenceSecurity concerns:
What I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles)
|
The database write receipt has carried `fromGenerations` since #160671; the NOCOW attribution case added in #160877 still asserted the two-field shape, so src/commands/doctor-maintenance.settlement.test.ts was red on main and on every PR merge ref. Assert the admitted baseline like the sibling cases do.
…claw#160877) * perf(sqlite): prepare NOCOW stores and add offline btrfs repair * fix(sqlite): complete NOCOW integrity and tooling integration * test(gateway): leave terminal fixture cleanup with its suite owner
The database write receipt has carried `fromGenerations` since openclaw#160671; the NOCOW attribution case added in openclaw#160877 still asserted the two-field shape, so src/commands/doctor-maintenance.settlement.test.ts was red on main and on every PR merge ref. Assert the admitted baseline like the sibling cases do.
… restore Rebasing onto main surfaced two receipts that relied on interval-wide attribution: the NOCOW physical replacement (#160877) and Doctor's own schema upgrade during legacy-root relocation. Under the conservative policy neither is attributable, so both receipts are ineligible for automatic restoration.
…database writes (#160167) * fix(update): reject unattributed database writes during Doctor Keep the captured fingerprint baseline through Doctor settlement. Maintenance ownership does not exclude independent SQLite writers, so any observed change, including a new database, must refuse automatic restoration through the existing receipt contract. Preserve current databases and the existing actionable recovery guidance without adding schema or transaction receipt infrastructure. Forward-port the conservative safety correction from c3c20e0 onto the current capture owner. Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vyctorbrzezowski <[email protected]> Co-authored-by: steipete <[email protected]> Co-authored-by: jalehman <[email protected]> * test(update): expect Doctor-time writes to disable automatic database restore Rebasing onto main surfaced two receipts that relied on interval-wide attribution: the NOCOW physical replacement (#160877) and Doctor's own schema upgrade during legacy-root relocation. Under the conservative policy neither is attributable, so both receipts are ineligible for automatic restoration. --------- Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vyctorbrzezowski <[email protected]> Co-authored-by: steipete <[email protected]> Co-authored-by: jalehman <[email protected]>
…database writes (openclaw#160167) * fix(update): reject unattributed database writes during Doctor Keep the captured fingerprint baseline through Doctor settlement. Maintenance ownership does not exclude independent SQLite writers, so any observed change, including a new database, must refuse automatic restoration through the existing receipt contract. Preserve current databases and the existing actionable recovery guidance without adding schema or transaction receipt infrastructure. Forward-port the conservative safety correction from c3c20e0 onto the current capture owner. Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vyctorbrzezowski <[email protected]> Co-authored-by: steipete <[email protected]> Co-authored-by: jalehman <[email protected]> * test(update): expect Doctor-time writes to disable automatic database restore Rebasing onto main surfaced two receipts that relied on interval-wide attribution: the NOCOW physical replacement (openclaw#160877) and Doctor's own schema upgrade during legacy-root relocation. Under the conservative policy neither is attributable, so both receipts are ineligible for automatic restoration. --------- Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vyctorbrzezowski <[email protected]> Co-authored-by: steipete <[email protected]> Co-authored-by: jalehman <[email protected]>
Keep one path for channel configuration forwarding, Google thinking preparation, status projections and rendering, and voice digest settlement. Remove speculative catalog, transport, and lifecycle coordination while preserving security-effect authority and ordinary durable settlement. Best-effort tradeoffs accepted: - Replacing the process-default AI host mid-session leaves old runtime-local caches for global cleanup or bounded expiry. #158901 tested replacement synthetically; explicit runtime owners and stream authority remain. - A throwing synchronous custom-API registrar fails setup instead of requeuing a partial drain. #111669 supports initialization ordering, not recovery from an arbitrary throwing registrar; restart after repairing it. - Reentrant toJSON cleanup can replace a continuation claim during serialization. #128848's synthetic callback is unlike provider JSON; the next turn can replay full history. Credential isolation and cache limits remain. - A concurrent channel rebind may miss its activity touch. #154672's forced incarnation swaps no longer trigger a retry protocol; routing still rereads. - An admitted CLI registry load may finish during shutdown. The work scope joins and disposes it; new command admission remains closed (#142388/#142838). - Unsupported writers during offline NOCOW copying are no longer detected by a second inventory/fuser/fingerprint scan. #160877/#161501 used synthetic interleavings; initial exclusivity, integrity, atomic exchange, and retained originals still protect normal maintenance and recovery. - Remote keyword listings changing between pages may repeat or skip entries, rather than reject the cursor (#163459). Request binding and limits remain. - A missing subscription acknowledgment can leave stale observation until a fresh subscription or reconnect, without compensating requests. #126760 and #159564 forced ACK loss; server authorization and acknowledged leases remain. - A retained thinking callback may reject during plugin reload until the catalog refreshes or the caller retries. #162470 used forced retirement; the plugin instance continues to reject revoked execution. Use the existing compiled CLI fixture for native-resource lifetime proof so cold source transformation occurs before its unchanged runtime deadline. No schema, dependency, protocol shape, or permission change.
* refactor(ui): consolidate page state and refresh bookkeeping * refactor: simplify transient plugin and client bookkeeping Keep one path for channel configuration forwarding, Google thinking preparation, status projections and rendering, and voice digest settlement. Remove speculative catalog, transport, and lifecycle coordination while preserving security-effect authority and ordinary durable settlement. Best-effort tradeoffs accepted: - Replacing the process-default AI host mid-session leaves old runtime-local caches for global cleanup or bounded expiry. #158901 tested replacement synthetically; explicit runtime owners and stream authority remain. - A throwing synchronous custom-API registrar fails setup instead of requeuing a partial drain. #111669 supports initialization ordering, not recovery from an arbitrary throwing registrar; restart after repairing it. - Reentrant toJSON cleanup can replace a continuation claim during serialization. #128848's synthetic callback is unlike provider JSON; the next turn can replay full history. Credential isolation and cache limits remain. - A concurrent channel rebind may miss its activity touch. #154672's forced incarnation swaps no longer trigger a retry protocol; routing still rereads. - An admitted CLI registry load may finish during shutdown. The work scope joins and disposes it; new command admission remains closed (#142388/#142838). - Unsupported writers during offline NOCOW copying are no longer detected by a second inventory/fuser/fingerprint scan. #160877/#161501 used synthetic interleavings; initial exclusivity, integrity, atomic exchange, and retained originals still protect normal maintenance and recovery. - Remote keyword listings changing between pages may repeat or skip entries, rather than reject the cursor (#163459). Request binding and limits remain. - A missing subscription acknowledgment can leave stale observation until a fresh subscription or reconnect, without compensating requests. #126760 and #159564 forced ACK loss; server authorization and acknowledged leases remain. - A retained thinking callback may reject during plugin reload until the catalog refreshes or the caller retries. #162470 used forced retirement; the plugin instance continues to reject revoked execution. Use the existing compiled CLI fixture for native-resource lifetime proof so cold source transformation occurs before its unchanged runtime deadline. No schema, dependency, protocol shape, or permission change. * fix: preserve runtime cleanup error cause Keep the existing aggregate errors and message while attaching the caught error as the standard cause. No signature or import graph changes. * refactor(ui): finish subscription compensation cutover * test: retire obsolete subscription recovery expectations * fix(ui): guard legacy group import at the write boundary
…169375) * refactor(ui): consolidate page state and refresh bookkeeping * refactor: simplify transient plugin and client bookkeeping Keep one path for channel configuration forwarding, Google thinking preparation, status projections and rendering, and voice digest settlement. Remove speculative catalog, transport, and lifecycle coordination while preserving security-effect authority and ordinary durable settlement. Best-effort tradeoffs accepted: - Replacing the process-default AI host mid-session leaves old runtime-local caches for global cleanup or bounded expiry. openclaw#158901 tested replacement synthetically; explicit runtime owners and stream authority remain. - A throwing synchronous custom-API registrar fails setup instead of requeuing a partial drain. openclaw#111669 supports initialization ordering, not recovery from an arbitrary throwing registrar; restart after repairing it. - Reentrant toJSON cleanup can replace a continuation claim during serialization. openclaw#128848's synthetic callback is unlike provider JSON; the next turn can replay full history. Credential isolation and cache limits remain. - A concurrent channel rebind may miss its activity touch. openclaw#154672's forced incarnation swaps no longer trigger a retry protocol; routing still rereads. - An admitted CLI registry load may finish during shutdown. The work scope joins and disposes it; new command admission remains closed (openclaw#142388/openclaw#142838). - Unsupported writers during offline NOCOW copying are no longer detected by a second inventory/fuser/fingerprint scan. openclaw#160877/openclaw#161501 used synthetic interleavings; initial exclusivity, integrity, atomic exchange, and retained originals still protect normal maintenance and recovery. - Remote keyword listings changing between pages may repeat or skip entries, rather than reject the cursor (openclaw#163459). Request binding and limits remain. - A missing subscription acknowledgment can leave stale observation until a fresh subscription or reconnect, without compensating requests. openclaw#126760 and openclaw#159564 forced ACK loss; server authorization and acknowledged leases remain. - A retained thinking callback may reject during plugin reload until the catalog refreshes or the caller retries. openclaw#162470 used forced retirement; the plugin instance continues to reject revoked execution. Use the existing compiled CLI fixture for native-resource lifetime proof so cold source transformation occurs before its unchanged runtime deadline. No schema, dependency, protocol shape, or permission change. * fix: preserve runtime cleanup error cause Keep the existing aggregate errors and message while attaching the caught error as the standard cause. No signature or import graph changes. * refactor(ui): finish subscription compensation cutover * test: retire obsolete subscription recovery expectations * fix(ui): guard legacy group import at the write boundary
What Problem This Solves
Large SQLite stores on btrfs accumulate copy-on-write fragmentation, making page rewrites, checkpoints, and fsync expensive. The reported example was a 32.5 GB store with about 3.29 million extents and commit steps lasting 1.5–41 seconds.
User Impact
New agent and shared-state stores on Linux btrfs request
chattr +Con their directory before SQLite creates the database, WAL, or SHM files. NOCOW trades btrfs data checksums and compression for in-place writes; SQLite integrity checks remain enabled. Missing tools or denied attributes are nonfatal.Existing stores are repaired only in Doctor repair mode (
--fix/--repair, including managed updater invocations that request repair). Doctor requires exclusive maintenance ownership, closed store handles, sufficient space, and verified copies; it preserves ownership, modes, access/default ACLs, sibling files, WAL contents, and the original directory. Unsupported tools and pre-publication failures leave the previous store in place with a warning. An uncertain exchange keeps activation stopped for inspection. Rewritten files have a new physical identity, so canonical validation runs again on next boot.Why This Change Was Made
One filesystem-policy owner serves both open paths. Its extraction from
sqlite-wal.tspreserves existing network-filesystem journaling decisions and keeps the file within its enforced line cap. The offline repair reuses Doctor maintenance custody, WAL-aware snapshot verification, update write receipts, and owned filesystem cleanup. Publication uses capability-checked GNUmv --exchange --no-copy; it never applieschattrto data files.There are no SQL migrations, schema bumps, configuration options, or package dependencies. The offline path exceeds the micro-lane LOC guideline because the requested rewrite requires backup, permission preservation, source freshness checks, atomic-publication reconciliation, and recovery handling; the runtime addition is small.
Evidence
chattrcallsAll heavy proof used provider
blacksmith-testbox, profileopenclaw-check.Source proof passed: 162 focused and sibling test cases across the retained runs, the core typecheck and all 27 canonical test graphs, targeted lint, formatting, storage/schema guards, unused-export checks, and runtime import-cycle checks (0 cycles).
The baseline real-open regression failed on
tbx_01m3n4hbg5e7trv1hfzx9gvh7c(0 preparations). The final repair suite and native unprivileged-reader proof passed ontbx_01m3n9zh7yvektznmv626e46hw. Missing maintenance methods in CLI test fixtures were fixed; the remaining seven type graphs and new-store tests passed ontbx_01m3nbp0g16gq31thf4q27p6hp, followed by the remaining gates selected bynode scripts/check-changed.mjs --dry-run --base HEAD. Valid passing results for unchanged inputs were reused.The complete candidate build and tarball integrity check passed. The published
[email protected]→ candidatebaseupgrade-survivor cell passed ontbx_01m3nd63g6v43n28ka2x9dgxzn, pinned to commit4a64a2f06943a10544aaedbb8f6ab12aae66e9f5. Command:bash scripts/e2e/upgrade-survivor-docker.sh, with published baseline enabled, baseline[email protected], candidatecurrent, scenariobase, manual restart, and live models disabled. The run completed in 12m 29s; Gateway startup was 24s and health, readiness, and status probes were 1s each. It preserved state/config and completed Doctor while tolerating the intentionally unavailable plugin fixture. This is ordinary-filesystem upgrade proof, not a real btrfs rewrite. Testbox provisioning run. The initial dirty-tree attempt was correctly refused by the artifact identity guard and was replaced with this committed-candidate run.Native Linux probes verified
fuserclosed/open-handle behavior, ACL and default-ACL preservation/removal, special modes, and the permission transition using an unprivileged reader. The old ordering exposed the copy; the corrected ordering kept it private and retained the source denial.Independent review is clean through P2 after resolving ACL preservation and transient-access findings. Full btrfs inheritance, a real atomic directory exchange, and a latency comparison remain gaps: the lease lacks the btrfs kernel module and its GNU
mvlacks exchange support. The repair reports unsupported tooling instead of using a non-atomic fallback.Measured focused-test cost
Each command was
pnpm test <file> --maxWorkers=1on Testbox.src/infra/sqlite-wal.nocow.test.tssrc/state/sqlite-nocow.test.tssrc/commands/doctor-sqlite-nocow.test.tssrc/commands/doctor-maintenance.settlement.test.tssrc/flows/doctor-health.migration-refusal.test.tsCold compilation dominates the store-open and repair runs; the real open-boundary test itself took about 0.13 s and the final repair cases about 0.21 s total. The real owner test is needed to catch preparation occurring after native creation; a helper-only test would miss that regression. Final CI completed in 19m 32s (1172 s) across the selected jobs; this is total run wall time, not additive test cost.
CI follow-up
Initial CI on
4a64a2fidentified three integration omissions: the extracted filesystem module was absent from the PR wrapper source inventory,lsattrneeded registration as an OS utility, and Doctor duplicated a raw integrity pragma. The follow-up completes the wrapper inventory and reusesassertSqliteIntegrityfor quick-check and referential consistency.The same CI merge used main
5ff5fb2783and inherited two failures subsequently fixed upstream: plugin runtime API inventory (5b76930a9b6f) and shared-auth fixture ownership (70d7e7abf6e4). Those source owners are unchanged by this PR.Follow-up validation used
blacksmith-testboxleasetbx_01m3nfwpmbj690fk44kvtggdyv(provisioning run). After one frozen dependency installation, these passed:node --import ./scripts/tsx.mjs scripts/check-kysely-guardrails.mtspnpm deadcode:full(production dependency and full export scans)node scripts/run-vitest.mjs src/commands/doctor-sqlite-nocow.test.ts test/scripts/eager-import-closure.test.ts test/scripts/pr-worktree-provision.test.ts src/plugins/contracts/plugin-sdk-runtime-api-guardrails.test.ts(99.76 s runner wall; all selected files pass; one pre-existing platform-specific provisioning case skipped)node scripts/run-oxlint.mjs --tsconfig tsconfig.json src/commands/doctor-sqlite-nocow.ts config/knip.config.tsalso passed with 0 warnings and 0 errors (11.8 s lint; 136.13 s including SDK type preparation). The follow-up lease is stopped.Fresh independent review of the follow-up is clean through P2. The physical-btrfs gaps above remain unchanged.
Gateway fixture follow-up
CI on
ce124b0795c3passed all checks exceptchecks-node-changed-compact-large-13and its aggregate gate. The archive-terminal fixture's incognito-reset case encountered shared-state offline-maintenance admission after its archive case. This fixture duplicated the harness's read-context disposal and synchronously closed process-global shared SQLite, bypassing the existing suite's awaited, per-home lifecycle. The follow-up removes that redundant cleanup; all terminal ownership assertions remain intact. This is a test-fixture change, with no production lifecycle change.The failure was not reproduced on
blacksmith-testboxleasetbx_01m3nh3bvhk6kfzpseaadnzrpc(provisioning run): the unmodified two-case file and the original 18-file selection passed. This is not claimed as a deterministic regression fix. After removing the competing cleanup, the same 18-file selection passes all 167 cases in 128.99 s runner wall, usingnode --import ./scripts/tsx.mjs scripts/ci-run-node-test-shard.mtswith the CI group and worker settings. The affected file also passespnpm test src/gateway/server.sessions.archive-terminal.test.ts --maxWorkers=1in 13.76 s wall. The lease is stopped.Fresh independent review of the fixture cleanup is clean through P2; it confirms retained cleanup ownership and the stated reproduction gap. Follow-up commit:
e5a6a969fa2f.Final verification
Both parts merged as
fb5f1954a293f18e12f4632db84a87bcfc78b74a. CI run 36515580255 on exact heade5a6a969fa2f3b3f2bd6d30bfc8f6d7ef92aac63completed successfully in 19m 32s, with no failed jobs, including the Docker seed test andopenclaw/ci-gate. The lead watcher performed the squash merge. All task-owned Testbox leases are stopped. No production Gateway was modified or restarted; physical btrfs latency and native directory-exchange proof remain the disclosed gaps.