Repository navigation
fix(cli): keep backup records and device approvals consistent with the Gateway - #168466
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. What this changesRoutes CLI backup records through the Gateway owner and requires exclusive offline ownership for device-approval fallback. Example: Run
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 4 items remain Keep open: this maintainer-authored PR addresses a current ownership defect, but backup recording still lacks requester revalidation at worker commit. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherCLI administrative commands select the live Gateway or exclusive offline owner; those owners authorize worker-backed writes to shared SQLite state. flowchart TD
A[CLI command] --> B[Local state owner]
B --> C[Live Gateway RPC]
B --> D[Exclusive offline custody]
C --> E[SQLite worker]
D --> E
E --> F[Backup ledger or device approvals]
Technical reviewBest possible solution: Keep the existing ownership routing and bind the backup worker's transaction and commit admission to the captured requester guard. Do we have a high-confidence way to reproduce the issue? Current main directly dispatches CLI ledger writes and permits local approval fallback without the shared ownership adapter; supplied regressions report failures on the original implementation, but this review ran no target code. Is this the best way to solve the issue? Reusing the existing local-state owner is appropriate, and device approval already carries its guard through worker admission, but backup recording needs the same effect-boundary protection. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 7517981b5e67. Provenance checked
TestingProof path: in-process harness. SecurityNeeds attention: Backup requester authority is not fenced at the durable worker effect. EvidenceSecurity concerns:
What I checked:
Likely related people:
PR surfaceSource +132, Tests +319, Docs +7, Other -2. Total +456 across 24 files. Added test files: 1. View PR surface stats
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (4 earlier review cycles)
Reviewed October 10, 2026, 12:41 PM ET / 16:41 UTC (Revision 5). |
Keep the missing-ledger early return explicit for consistent-return lint and update the corrupt-database assertion to the owner-aware refusal warning. Validation: backup-sqlite.test.ts passes 8 tests (166.36s command wall); targeted worker lint passes. Codex fix-diff review: no P0/P1 findings.
The schema validator builds a transient reference database. Keep the administrative owner assertions focused on persisted state while continuing to observe file-backed statements. Validation: administrative owner process tests 25/25 on Testbox; focused formatting and lint; independent P0/P1 review.
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
…e Gateway (openclaw#168466) * fix(cli): keep device approval and backup writes with the state owner * fix(gateway): validate backup recording on the current protocol train * refactor(cli): isolate device fallback validation * fix(backup): preserve database bytes on refused outcomes * fix(backup): align refusal return and warning expectations Keep the missing-ledger early return explicit for consistent-return lint and update the corrupt-database assertion to the owner-aware refusal warning. Validation: backup-sqlite.test.ts passes 8 tests (166.36s command wall); targeted worker lint passes. Codex fix-diff review: no P0/P1 findings. * test(cli): exclude in-memory schema SQL from owner observation The schema validator builds a transient reference database. Keep the administrative owner assertions focused on persisted state while continuing to observe file-backed statements. Validation: administrative owner process tests 25/25 on Testbox; focused formatting and lint; independent P0/P1 review.
Final landing proof (2026-10-10)
6273a54dbca8corrects the administrative SQL observer: canonical schema validation in a fresh in-memory database is not persisted-state access. The observer still checks file-backed statements and custody. The formerly failing Linux pairing case now passes with all 25 administrative-owner process tests (26.93 s Vitest; 41.05 s test-command wall). Focused formatting/lint and independent Codex P0/P1 review passed.The published-driver 2026.9.9 × candidate 6273a54 update cell passed on Blacksmith Testbox. The package's embedded commit matched the candidate, the update reached
finished, and readiness returned HTTP 200 (483.443 s remote command).CI run 38066676485, attempt 1, completed all 119 jobs with exactly two failed roots and their aggregate, and no cancellations. The untouched cron case “refuses keyless delivery inherited from another conversation's shared main bucket” expected
error, receivedok; it fails identically on main run 38059964113, job 114236115312. The untouched chat case “chat.send returns in_flight when duplicate attachment send wins parsing race” expected one dispatch but observed zero at line 2396; it fails identically on main run 38068164099, job 114260176569. Both owners are byte-identical between the tested main baseline and the PR merge. The coordinator explicitly authorized native admin admission for independently proven inherited failures; no rerun was requested to obtain green.CI correction (2026-10-10)
67755c833cedefixes two PR-caused CI failures: the missing-ledger path now explicitly returnsundefinedfor consistent-return lint, and the existing corrupt-database test expects the complete ownership-aware warning. Runtime behavior is unchanged by this correction.Focused validation:
pnpm test src/commands/backup-sqlite.test.ts --maxWorkers=1passed 8/8 (166.36 s command wall; the original CI shard failed this case in 59.10 s across 49 files). Targeted worker-runtime lint andgit diff --checkpassed. Independent Codex review of the two-line fix found no P0/P1 issues.Refusal correction (2026-10-10)
The lander found three real byte-preservation failures at
9009852efc36: rejected zero-byte, schema-empty, and wrongly owned global databases changed before the backup outcome writer ran. Runtime configuration loading inside local ownership admission was opening SQLite. A stronger settlement assertion also exposed the outcome writer bootstrapping the rejected zero-byte source afterward.f73bcfc27f683makes runtime configuration lazy within the existing local ownership scope. Backup outcome recording does not consume it. The state worker inspects an unopened ledger through the existing artifact-preserving read-only owner check before its writable open; an admitted writer is reused. Missing files remain absent, rejected files retain their bytes, and accepted outcomes still use the existing guarded transaction and settlement. There are no schema or retention changes.The corrected two-argument outcome assertion is retained, and the test spy now forwards the authority options. The nine managed-source cases assert exact bytes both before the outcome attempt and after settlement. New regressions cover missing/empty files when local admission refuses and a live Gateway refusing a routed outcome without local replay.
f73bcfc27f683git diff --checkFocused commands:
pnpm test src/infra/backup-create.test.ts -t 'rejects a managed' --maxWorkers=1andpnpm test src/cli/local-state-owner.test.ts src/commands/backup-outcome.test.ts src/state/backup-run-records.test.ts src/cli/devices-cli.test.ts --maxWorkers=1. The three new test bodies took 7.14 s combined locally; CI execution time has not been measured separately, and the existing CI job layout is unchanged. Proof ran locally through the campaign proof slot using the lane's established local fallback (disk above 15 GiB; load below 48).This follow-up adds a read-only ownership inspection to cold backup ledger admission; already-open writers bypass it. Ordinary chat-turn paths are unchanged. No additional SQL harness run or savings claim is made for this corrective pass. The earlier campaign evidence below remains labeled with its measured heads. The accepted correctness finding is fixed under the three-round review convergence rule.
Corrective diff: production +31/-10 lines, tests +73/-6, docs +2/-0. The requested scope is focused tests plus build, push, and stop; this PR remains ready and unmerged.
What Problem This Solves
CLI backup outcomes and local device-approval fallback could write the same SQLite state as a running Gateway from another process, bypassing its single-owner lifecycle and in-process publications.
User Impact
Backup commands now send outcome records to the local Gateway when it owns the state directory, and otherwise acquire exclusive offline ownership. Recording remains best-effort and never creates an absent state database. A failed or uncertain Gateway call produces the existing warning without replaying locally.
Device approval still uses the existing Gateway RPC. Its direct bootstrap fallback now refuses while a Gateway owns the state, with guidance to stop the Gateway and rerun the exact approval. Offline approval preserves request identity, same-device replacement checks, admin scope semantics, and current approval authority through commit. Explicit remote URLs never fall back to local state.
Why This Change Was Made
Both commands reuse
runWithLocalStateOwner. The new admin-onlybackup.recordOutcomemethod validates a closed payload, binds the expected physical owner and live requester, and calls the existing worker-backed ledger writer with that authority. Ledger insertion/pruning, retained rows, durability, schema versions, and backup/archive execution ownership are unchanged.Client bootstrap is deliberately unchanged: client token reads select current rows directly, and device identity bootstrap only inserts an absent key while preserving the first valid winner. The process identity cache retains successful values, never missing rows; no runtime bootstrap path can replace a cached identity. Identity repair remains Doctor-owned under its exclusive migration lock. This is an immutable-bootstrap exemption, not a claim that device identity has no cache.
Evidence
The command boundary regressions use real SQLite writers and physical owner locks with mocked discovery/transport; they are not full WebSocket end-to-end tests. The original implementation failed the foreign-live-owner device approval regression and the missing Gateway-call backup regression. Final device suites pass 60/60 after the mechanical helper extraction; backup outcome tests pass 4/4, and the unchanged owner/ledger/bootstrap siblings passed in the original focused run.
The nine-file focused command is
pnpm test src/cli/devices-cli.test.ts src/cli/devices-cli.gateway.test.ts src/infra/device-auth-store.client.test.ts src/infra/device-identity-worker.test.ts src/commands/backup-outcome.test.ts src/commands/backup.create-verify.test.ts src/commands/backup-git.test.ts src/state/backup-run-records.test.ts src/gateway/server-methods/backup.test.ts --maxWorkers=1. Its first run passed 103/104; the closed-payload case exposed TypeBoxOmitdropping additional-property rejection. Rebuilding that payload throughclosedObjectfixed it. A later device run hit compiled-worker preparation inside a test; moving preparation to file setup fixed the timeout/spillover. The final backup/device unit command passed 54/54 in 335.79 s wall time; the final extracted-device command passed 60/60 in 314.38 s, including worker preparation. CI seconds are not yet available.The final 29 remaining canonical checks ran on an isolated
9009852efc36checkout: 27 passed, with only the two inherited failures below. They included formatting, config/plugin boundaries, production and test typechecks, typed lint, scripts, schema parity, database/media/sidecar guards, and import cycles. Summed command wall time was 915.97 seconds. The earlier six changed-check guards, including the database-worker/T1 ratchet, passed; the exact two-row mock-baseline shrink now passes its final check. Madge also passed. The aggregate changed-check/Knip result is not claimed green. Full Knip reports only two inherited exports on the exact base:isTelegramReadOnlyControlLaneTextandresolveContextTokens. The same base failure was independently recorded; upstream commitafb4f0ff366balready removes them. This branch does not touch those files or integrate unrelated main changes. The final deprecated-API guard also reportsinternal-config-apiin untouchedsrc/gateway/server-methods/agents.ts. Its blob matches the baseline exactly (ffa3cffaad743); main commit959197ba0923fremoves the reported direct config mutation and states the guard fix. This inherited failure is recorded without an unrelated integration.Full
pnpm buildpassed on final head9009852efc36in 346.88 seconds on macOS / Node 26.11.1. The final checks and build used the authorized static-proof fallback through the campaign proof slot after capacity waits and the earlier Testbox job expiration. The source checkout remained clean.Plugin SDK API diff completed for
427f926e7c2d→b2825e4bebc5: no entrypoints added or removed, four changed reachable declarations from the additive backup RPC, with 152 transitively affected exports. Acknowledgement:8032bf73. The later commit only extracts existing internal device-fallback helpers and prunes two stale mock-ratchet entries.Three Codex P2 review rounds completed. The first two were scoped-clean. The third reported a P2 follow-up: append
backup.recordOutcomeat the end of the method table to preserve advertised method indices. It remains recorded under the campaign's three-round convergence rule; this is not a clean-review claim. No accepted P0/P1 finding remains. Post-review changes are the mechanical device helper extraction required by the file-size gate and the exact two-row mock-baseline shrink, with device regressions rerun.Scope: production +254/−143 lines; tests +260/−13; docs/config +6/−3. The added code supplies the narrow ownership adapter and RPC, plus regression coverage. Existing fallback helpers moved to keep the runtime module within its established size ratchet.
SQL and worker-request report
Six runs alternated baseline
427f926e7c2dand candidate13959252b2d6on the same host. Cells are medians [minimum–maximum]. Warmed counts are per-turn means over ten turns; other rows are phase totals. All-thread includes MAIN, workers, and helper processes. No phase-median duration ratio exceeds 1.5.The initial raw general SQL gate does not pass: warmed SQL rises by 15.8/turn (+1.43%), and first-turn SQL rises by 490 (+24.65%). The designated additional whole-workload pair completed with lower statement and request totals, but its detailed attribution files were lost during subsequent proof setup. A separate Testbox observation and the remaining evidence limitations are reported below. No removed statements or requests, and no performance saving, are claimed. The fixed workload never invokes the changed CLI operations or
backup.recordOutcome; the worker command and its SQL remain unchanged.The exact warmed median-run difference is
database.prepareWrite+11.4 SQL/+0.3 requests per turn,session.entry.read+2.7 SQL,session-entry-read+1.1 SQL,session-maintenance-read+1.1 SQL/+0.1 requests, and other unchanged owners net −0.5 SQL. Remaining request movements areplugins.catalogSnapshot.write+0.1 andsession.maintenance.read−0.1. No new logical request type appears.The first-turn difference is existing
database.prepareWrite+196 SQL, domain binding +49, MAIN/unassigned +42, domain execution +35, tombstones +27, plugin-state compare/delete +26, session entry +25, memory source replacement +21, and other unchanged owners net +69. Lost async origins prevent claiming every extra execution is background work; the conservative origin verdict remains indeterminate. Boot+connect+first medians rise 5692→6135; control+cron falls 1427→1367; compaction+shutdown rises 619→669. These are recorded rather than described as passing exceptions.All 78 top-level turns, six children, cron runs, compactions, RPC receipts, and graceful shutdowns passed; every warmed request completed. Native/request count conservation and MAIN/worker calibration passed. Three failed
BEGIN IMMEDIATEexecutions are excluded from successful totals and preserved as diagnostics: one baseline deferred-plugin lease release and two candidate shutdown idle-agent lease releases, all in unchanged owners. The workload passed despite those warnings.Measurement source is pinned to
13959252b2d6; the later implementation delta corrects release-train metadata/test setup and mechanically extracts existing internal fallback helpers, with no SQL-path change. The shared workload is unchanged; the private invocation disables evidence archives and reuses the established request observer. No raw traces or fixture databases are retained.Designated additional pair: retained evidence and limitation
A separate Hetzner pair ran baseline
427f926e7c2dthen candidateb2825e4bebc5, with all 13 turns passing on each side. Retained command output records whole-workload statements 22,583 → 22,437, requests 3,396 → 3,391, and wall time 52.239 → 52.149 seconds (ratio 0.9983). These are single-run observations, not a new multi-run median.The subsequent final-check checkout failed while writing files under
/tmp. Automatic lease cleanup preceded detailed JSON export, so the full phase and per-operation tables from this pair are unavailable. The totals above remain valid retained output; they are not presented as complete attribution evidence. The separate Testbox pair used persistent storage and independent run/copy/inspection checkpoints. It supplies another observation and retained operation vectors; it does not replace this observation or reconstruct the missing Hetzner vectors.Independent Testbox observation and count attribution
This supplements the original M,C,M,C,M,C macOS series; it does not replace or pool those observations. The original warmed medians remain 1,105.7 → 1,121.5 SQL/turn and 204.4 → 204.8 requests/turn, with first-turn SQL 1,988 → 2,478.
The designated additional Hetzner M,C pair at
427f926e7c2d/b2825e4bebc5recorded 22,583 → 22,437 all-thread statements (−146) and 3,396 → 3,391 requests (−5) from startup through shutdown; wall time was 52.239 → 52.149 s. Its whole-total criterion passed. First-turn SQL was 1,904 → 1,808 and warmed SQL/turn 1,079.4 → 1,069.3. A subsequent checkout exhausted the original/tmpstorage and automatic cleanup ran before granular files were exported. That pair’s per-operation breakdown and complete phase table remain an explicit evidence gap. The terminal lease is deleted; its native failure archive contains only logs/config/timing metadata, no SQL or request datasets. Testbox data below does not reconstruct that missing breakdown.The separate Testbox recovery M,C pair uses the same exact source pins, one sample per side, after restoring the byte-unchanged observer’s expected census-helper path. Each source had its own clean worktree in an independent Git repository outside native sync. No SQL saving is claimed: removed statements/requests attributable to this PR are 0 / 0.
Each cell is median [min–max] for this one-pair recovery sample. Warmed counts are per turn across ten turns; other counts are per phase. All-thread includes MAIN, worker threads, and helper processes. MAIN is the Gateway’s process/thread 0.
Whole workload: all-thread SQL 21,645 → 21,652 (+7; +0.0323%); requests 3,315 → 3,317 (+2; +0.0603%); wall time 41.840 → 41.774 s (ratio 0.9984). No phase has duration skew above 1.5. First-turn SQL rises by 3 (+0.1655%); warmed SQL/turn falls by 0.5 with requests unchanged. These exact increases are retained, not rounded to a pass or replaced by the earlier pair.
Other previously implicated owners are unchanged in this recovery pair:
database.domain.bind400 SQL / 74 requests on each side;database.domain.execute733 SQL / 98 requests on each side;database.prepareWrite268 SQL / 7 requests on each side;pluginState.compareDelete169 SQL / 26 requests on each side;plugins.catalogSnapshot.write8 SQL / 1 requests on each side;session-entry63 SQL / 7 requests on each side;session-tombstones81 SQL / 9 requests on each side.Phase reconciliation, in boot/connect/first/warmed-ten-turns/second-session/control/cron/compaction/shutdown order: SQL −1 +6 +3 −5 +4 +0 +1 −1 +0 = +7; requests 0 +1 −1 +0 +2 +0 +0 +0 +0 = +2. The complete per-phase operation/caller vector is retained in
phase-operation-caller-attribution.json; it conserves both totals exactly.lifecycle-artifact-plansession-pending-archivesmentions.snapshotrestartSentinel.snapshotworkers.placementProjectionsession-exact-entriescatalogsession-row-factsThe first-turn identity is +3 +3 +1 +1 +1 −1 −5 = +3 SQL.
session-row-factshas an identical complete normalized SQL vector; its +6/−6 change is only movement between unknown and named caller buckets. ApluginCatalog.readsend is absent from the first-turn request window while its SQL remains 14 on both sides; its whole-workload request total is unchanged. Full SQL text/count vectors are retained in the request-statements CSVs.Named varying callers are
session-transcript-worker-runtime.ts:257,openclaw-state-read-worker.ts:407, the auth/catalog readonly-process adapter, and the existing session/state worker clients. Every named varying caller file is byte-identical between the two pins. Unknown caller labels are preserved rather than invented; no retained native SQL stack names any of the 9 changed operational source files. The harness does not invoke the device CLI fallback orbackup.recordOutcome.Validation: all 26 top-level turns, both native children, cron runs, compactions, RPC receipts, and graceful shutdowns passed. MAIN and worker calibration each observed 8 calls / 2 prepares / 7 successful statements / 0 errors. Reduction recorded exact equality by phase, thread and normalized SQL, zero missing contexts and zero duplicate sends. The two known boot-only unknown-target links per run remain disclosed. Failed native executions in these samples: two
BEGIN IMMEDIATEattempts, one per side during connect-time plugin lifecycle lease release (database is locked); successful statement totals exclude them. Both stacks are unchanged, and all product receipts passed.Limits: raw per-event streams were removed after verified reduction under disk-hygiene policy. Phase boundaries, aggregate transport/request counts, normalized SQL, and unique native stacks remain; arbitrary new reconstruction of worker/timestamp/async-origin chains is therefore unavailable. This is complete count attribution for the retained Testbox sample, not proof that every unknown origin was scheduled background work, and not a reconstruction of the lost Hetzner per-operation data. All original observations remain in the evidence record; there was no rerun to obtain lower numbers.
The designated additional whole-workload totals check passed. The independent Testbox count vectors and source comparison identify no reproducible PR-caused statement or request increase. This supports publication under RAW TURN INCREASE together with TARGETS ARE AIMS; it is not a standalone noise-floor pass, a reconstruction of lost event origins, or a claim of SQL savings.
Published-driver × candidate update cell: passed at final head 6273a54, as recorded above. This change has no SQLite schema migration.