Repository navigation
fix(gateway): finish shutdown writes before SQLite worker teardown - #169983
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 changes before merge. What this changesThis PR retains SQLite workers through shutdown accounting and restart handoff, removes duplicate host checkpoints, and reuses worker-owned deletion and plugin metadata facts. Example: A running Gateway receives SIGTERM.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 1 item remains Keep this PR: it repairs a current-main shutdown ownership defect, the earlier wrapper finding is resolved, and no new actionable code defect was found. Priority: P2 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherThe Gateway run loop coordinates shutdown signals, server cleanup, completion records, restart handoffs, and final SQLite retirement. flowchart TD
Signal[Shutdown signal] --> Loop[Gateway run loop]
Loop --> Cleanup[Server cleanup]
Cleanup --> Worker[Retained shared state worker]
Worker --> Records[Completion and handoff records]
Records --> Retirement[Worker and database retirement]
Technical reviewBest possible solution: Keep the existing shared-state owner alive until terminal persistence settles, then join worker retirement before closing native handles. Do we have a high-confidence way to reproduce the issue? Current-main source establishes synchronous boot completion after shared-state teardown; no target code or tests were executed during this read-only review. Is this the best way to solve the issue? Retaining the existing owner fixes the ordering inversion and removes redundant prewarming machinery while preserving interrupted-boot recovery and worker-owned deletion enforcement. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against da4864af49e8. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -285, Tests -128, Docs +5, Other 0. Total -408 across 77 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 (3 earlier review cycles)
Reviewed October 12, 2026, 2:59 PM ET / 18:59 UTC (Revision 4). |
|
The earlier wrapper dependency finding is fixed and its closure tests pass. The actual published-driver update now passes on production head The live native-SQL replay covers the cold metadata boundary directly: plugin-index MAIN is 1→0, all four owned cold MAIN categories are 32→0, and the post-exit database contains the completed shutdown record. The suggested mock-test simplification is recorded as a follow-up; it does not substitute for this boundary proof. The body distinguishes exact inherited failures from unclassified unrelated test failures and records the final gates and remaining nine session-owner calls. |
…#170292) ## What Problem This Solves The integrity lease fixture modeled a failed checkpoint by making `walMaintenance.close()` return `false`. After delegated close changed in `ebb360e17901cdc1b730cf3ab1fe7b3c8253b3a4` (#169983), that return can also mean a healthy delegated close; the last native close may correctly certify an empty WAL. The test expected no verification record but received `clean_close = 1`. ## User Impact This is a fixture correction. Production integrity policy and both existing no-certification assertions remain unchanged. No production SQLite calls, SQL requests, schema, security checks, SDK, or update behavior change; no SQL or T1 saving is claimed. A published-driver update cell is not required. ## Why This Change Was Made Inject a one-shot database preparation error, exercise the actual checkpoint operation, and assert the recorded health error before closing. Restore the spy before testing closure. This distinguishes failed checkpoint behavior from successful delegated close without weakening the native-close assertion. The reviewed source is `780c860b54367c72d2744e5344f4c6e5f25f0d88`: one test file, +10/−1 lines. The original scheduled-main assertion is retained in [run 38298274614, job 114974958634](https://github.com/openclaw/openclaw/actions/runs/38298274614/job/114974958634). Attribution uses the parent-relative source change and observed assertion; no new bisect or inverse test is claimed. ## Evidence At publication head `4743da172d268448dbee28ab414d77d514093510`, [run 38313966750, target job 115026423600](https://github.com/openclaw/openclaw/actions/runs/38313966750/job/115026423600) passed all **18/18** named cases in `src/state/openclaw-agent-db.integrity-lease.test.ts`. The changed failed-checkpoint/native-close case passed in **114 ms**. The single-file CI invocation took **11.26 s in Vitest and 13.48 s including the repository test wrapper**; these are CI timings, not a new local execution. That exact-head PR workflow completed successfully: **18 jobs passed, 29 were skipped, and none failed**. Selected source-contract, architecture/guard, additional-boundary, baseline-ratchet, test-type (`core-3`), lint, changed-test and `openclaw/ci-gate` checks passed. Build artifacts and the update cell were not selected; this fixture changes no production build or update implementation. This is the scoped PR workflow, not a scheduled full-main result. Knip was not selected on this PR. Its unchanged import/export graph supports scoped reuse of [V28 dependency job 115019807997](https://github.com/openclaw/openclaw/actions/runs/38311910220/job/115019807997): that scan failed only on three Team-scale exports subsequently removed by base commit `36e78f215f1f058af15919da8a60c06797a759e8`, which is included here. This is a source-qualified disposition, not a claim that the historical Knip scan or a new final-head scan passed. The unchanged graph also reuses [V28 topology job 115019805821](https://github.com/openclaw/openclaw/actions/runs/38311910220/job/115019805821), which reported zero runtime and Madge cycles. One isolated Codex review was scoped-clean. Focused formatting, lint, whitespace checks, normal commit hooks, and source-extraction checks passed; no extra review was run for the unchanged reviewed delta.
…penclaw#169983) Keep the shared-state owner alive through awaited lifecycle completion and restart handoff, then retire workers and native handles in order. Remove redundant host WAL maintenance, speculative restart preparation, cron deletion rereads, and cold plugin-index fallback reads. Preserve unfinished boot recovery and pinned-WAL durability. Live proof removes 32 owned cold MAIN statements, with zero warmed MAIN. Controlled warmed SQL stays at median 268 while requests fall from 64 to 63; final integrated runtime measures 255.5 SQL and 61.5 requests. Nine session reads remain with the active session-owner migrations. Static T1 is unchanged. Changed-owner regressions and published-driver update acceptance pass. The PR records exact inherited static findings and unresolved unrelated CI failures under the authorized relaxed landing policy.
…openclaw#170292) ## What Problem This Solves The integrity lease fixture modeled a failed checkpoint by making `walMaintenance.close()` return `false`. After delegated close changed in `f4202000f1fc48963c026e8913cc1d6741e48d55` (openclaw#169983), that return can also mean a healthy delegated close; the last native close may correctly certify an empty WAL. The test expected no verification record but received `clean_close = 1`. ## User Impact This is a fixture correction. Production integrity policy and both existing no-certification assertions remain unchanged. No production SQLite calls, SQL requests, schema, security checks, SDK, or update behavior change; no SQL or T1 saving is claimed. A published-driver update cell is not required. ## Why This Change Was Made Inject a one-shot database preparation error, exercise the actual checkpoint operation, and assert the recorded health error before closing. Restore the spy before testing closure. This distinguishes failed checkpoint behavior from successful delegated close without weakening the native-close assertion. The reviewed source is `780c860b54367c72d2744e5344f4c6e5f25f0d88`: one test file, +10/−1 lines. The original scheduled-main assertion is retained in [run 38298274614, job 114974958634](https://github.com/openclaw/openclaw/actions/runs/38298274614/job/114974958634). Attribution uses the parent-relative source change and observed assertion; no new bisect or inverse test is claimed. ## Evidence At publication head `4743da172d268448dbee28ab414d77d514093510`, [run 38313966750, target job 115026423600](https://github.com/openclaw/openclaw/actions/runs/38313966750/job/115026423600) passed all **18/18** named cases in `src/state/openclaw-agent-db.integrity-lease.test.ts`. The changed failed-checkpoint/native-close case passed in **114 ms**. The single-file CI invocation took **11.26 s in Vitest and 13.48 s including the repository test wrapper**; these are CI timings, not a new local execution. That exact-head PR workflow completed successfully: **18 jobs passed, 29 were skipped, and none failed**. Selected source-contract, architecture/guard, additional-boundary, baseline-ratchet, test-type (`core-3`), lint, changed-test and `openclaw/ci-gate` checks passed. Build artifacts and the update cell were not selected; this fixture changes no production build or update implementation. This is the scoped PR workflow, not a scheduled full-main result. Knip was not selected on this PR. Its unchanged import/export graph supports scoped reuse of [V28 dependency job 115019807997](https://github.com/openclaw/openclaw/actions/runs/38311910220/job/115019807997): that scan failed only on three Team-scale exports subsequently removed by base commit `2531250f65253f9d6466ee7f2d50c80184b41e42`, which is included here. This is a source-qualified disposition, not a claim that the historical Knip scan or a new final-head scan passed. The unchanged graph also reuses [V28 topology job 115019805821](https://github.com/openclaw/openclaw/actions/runs/38311910220/job/115019805821), which reported zero runtime and Madge cycles. One isolated Codex review was scoped-clean. Focused formatting, lint, whitespace checks, normal commit hooks, and source-extraction checks passed; no extra review was run for the unchanged reviewed delta.
What Problem This Solves
Gateway shutdown recorded its final boot outcome after global cleanup had stopped the SQLite worker, reopening shared state on the main thread. Host WAL retirement repeated worker maintenance, while cron availability and cold prepared-model metadata could synchronously read shared state.
Keep the shared-state database, worker owner, and broker alive through the run loop's awaited completion record and restart handoff, then retire them. Completion uses the existing
gatewayBoot.completeworker operation. Remove the separate plugin-state close call that prematurely closed the same shared-state owner, then delete its unused internal alias and move test cleanup to the canonical owner. Remove speculative restart worker preparation, reserved slots, and close-epoch handshakes; the retained owner now serves handoff through ordinary admission.Delegated host handles leave checkpoint SQL to worker retirement and native close. The existing lease owner publishes a clean seal only when the canonical WAL is empty after native close; a pinned WAL retains runtime validation without claiming a clean restart seal. Cron consumes deletion facts published by the journal owner and drops its duplicate planning read. Retention obtains journal facts through the existing worker. Cold model preparation awaits the prepared plugin metadata owner. A projected manifest now consumes that owner’s canonical install ledger instead of discarding it because the manifest object has a different identity.
No schema, stored format, retention, permission, or recovery contract changes. An interrupted shutdown still leaves the unfinished boot row for crash-loop recovery. Boot admission, migrations, and locks remain synchronous exceptions.
Measurements
One live baseline/candidate shared-harness pair under the campaign CPU gate, using baseline
32c839147a8067ac5f97decba92dca98ec469086and runtime candidate39bd0def25921e0581f582859956b3a43ec56ce0. The candidate also integrates main's locale refresh and one-line unused-type-export repair; neither changes runtime SQL. A later generated mock-baseline prune does not change runtime behavior. The harness copy preserves the shared workload; its legacy display-onlyevidence.headis hardcoded, so the Git/environment pins above identify the revisions.Lifecycle completion MAIN 22→0, shutdown WAL MAIN 7→0, deletion status MAIN 2→0: 31 removed. Completion uses four worker statements and one
gatewayBoot.completerequest; removing acloseResourcerequest offsets that request. No retained-body JSON projection moved out of SQL.The final integrated replay used production head
caeef8d0d4dafc8f7889c72f0bca28151f18e7ef; final head0573af7e72926e12269f3122fe51bd23b5d46a58changes only a test assertion. It passed all 13 turns, child/cron/compaction flows and 38 RPCs, then exited cleanly. An independent read-only process verified the persistedclean_stoprecord after shutdown. Build: 698.2 seconds; live workload: 159.6 seconds. Host load was about 97, so these are statement/request counts, not a latency claim. The task harness retained the controlled pair's v1 workload/counting; diagnostic changes only extended native stacks and recorded actual worker exits. The shared harness was untouched.The final column includes intervening main changes and is not an isolated saving attributable to this PR. Lifecycle completion is 22 main-thread statements → four worker statements. Deletion-fence kernel SQL is 15→13 overall; the remaining two MAIN reads are lock admission. Plugin metadata is two statements/one MAIN → one statement/zero MAIN. The controlled pair adds one completion request and removes one redundant resource-close request.
Shared read families per warm turn in the controlled pair: exact-entry 5.0→5.2, actor hydration 4.0→4.1, entry-cache snapshots 0.2→0.2, row-facts primary 1.0→1.1, watermark 2.0→2.1. Row-facts ownership comes from recorded worker request context because the original native stack truncates its outer caller. Watermark totals cover row-facts reads (1.0→1.1) plus entry-patch commits (1.0→1.0). All added reads cluster in one turn overlapping the Git worker’s idle-retirement deadline. The original trace does not record the actual worker exit; the diagnostic replay records it. The final replay directly observed the Git worker exit 30,019.457 ms after
checkout.baseline, followed by an exact-entry reload 617.135 ms later and actor hydration 652.065 ms later, with no intervening native write. The unchangedgit-workeridle timer, worker admission tracking, andreleaseWorkerinvalidation advance database revisions even for this Git worker. These source files are identical between the original baseline and final runtime. Final warm shared-family means are exact-entry 5.1, actor hydration 4.1, snapshot loads 0, row-facts 1.0, watermark 2.0. The original single-turn event remains inferred from timing, not retrospectively observed. This existing broad invalidation has a separate follow-up.The controlled pair’s static inventory has T1 482→482 across 182 files, with compatibility count 2. Final merged-context CI at head
0573af7e7292reports T1 481→481 and compatibility 2→2 against base94f8368625e1; main’s intervening reduction is separate from this PR. These lifecycle sites were inventoried as T2: T2 moves 412→409 and worker sites 1227→1230. This PR does not claim a T1 reduction.The controlled candidate had nine cold runtime-session MAIN statements: six admission row/participant reads whose prepared-fact replacement is implemented in #169757, plus one command-routing read and two command-admission reads implemented in #169622. The final native-stack audit still finds exactly these nine reads, all during the second-session flow: six through
loadGatewaySessionLookupStore→agent-admission-controller.assertAllowed, one throughresolveSessionKeyForRequestInternal→prepareAgentCommandExecution, and two throughagent-command.assertAllowed. No MAIN statements are unclassified. Those exact owners stay with their active caller/API migrations. They are not synchronous exceptions. The 135 Workshop source-authority reads in this baseline have an async replacement in already-merged #169966. The final replay confirms those 135 reads are now zero; that saving belongs to the integrated owner change. Startup business reads remain a separate lane. This PR does not claim the overall non-exempt cold MAIN target is zero.Relative to integrated main
2ae25faa8683: tooling: 2 files, +1/−1; docs: 1 file, +14/−9; tests and test support: 32 files, +510/−638; production: 42 files, +226/−511. Total: 77 files, +751/−1159 (net −408).Removed work and accepted edge cases
Evidence
Changed-file formatting and
git diff --checkpass. Basic oxlint reports only the existing max-lines advisory inplugin-state-store.ts, which this PR shrinks; no limit or suppression changed. Two Codex autoreview rounds completed: the first clean through P2, the second clean through P1. Main integrations retain the typed cron deletion deferral at the write boundary while removing the duplicate planning read, and preserve complete deletion of speculative runtime preparation after main simplified that code. Package and lockfile inputs are unchanged by the final conflict repair. No plugin SDK or extension runtime API surface changed.Fourteen focused regressions passed across the agent integrity-cache, worker-store, execution-integrity, and process-exit tests, including unchanged clean-close durability assertions and pinned/unpinned WAL cases with no host SQL (477.25 seconds including 182.21 seconds of worker compilation). The config reference-values regression passed. Wrapper closure tests passed: 20 tests across two files, 282.10 seconds Vitest / 303.20 seconds wrapper time. A separate type-aware wrapper lint timed out building SDK declarations and is not counted as a pass.
Final head
0573af7e72926e12269f3122fe51bd23b5d46a58is tested in PR CI run 38292371064, with merge context582d3f79over main94f8368625e1. Production types, lint, source contracts/export collisions, Madge/architecture, guards and database ratchets pass. General test types and core stripes 1/2/4/5 pass. Core stripe 3's six compiler graphs also all pass, including the changed state-logging graph (206.4 seconds, exit 0); its aggregate job then hit the 15-minute timeout in the trailing root scripts graph. The unfinished root scripts partition passed separately against exact CI merge582d3f7939a1e83e27e3635a32de40d3d7d08842under the CPU gate:node scripts/run-tsgo-core-test-shards.mjs --root-stripe 2/4, 96.3 seconds compiler / 98.03 seconds command wall time, exit 0 with no diagnostics. The aggregate CI job remains cancelled; successful leaf results and this focused completion cover every selected graph. Dependency manifests match the tested checkout. The test-only successor does not select another Knip scan: the production-head dependency job has exactly the same 26 UI rule/path/symbol findings as main's job (2 unused files, 20 exports, 4 exported types); no finding remains in this PR's changed files. Dialect mechanical 1→1, design 0→0, maintenance 18→16. No SDK surface change; PostgreSQL conformance was not selected.All 24 retained changed test files have passing coverage from the production head plus its test-only successor. The successor corrects a stale assertion that expected an aggregate for a sole cleanup error, preserving lease retention, blocked reopen, retry, successful write and integrity assertions. All 24 cases in that file pass; the exact failure/retry regression takes 868 ms in final worker-store job. Clean completion and interrupted accounting cases pass in 705 ms and 123 ms in shutdown regression job.
CI is not globally green. Two exact untouched cases reproduce on integrated main
2ae25faa8683: suspension caller ownership and startup legacy-session repair both fail withRuntime config is not preparedafter main's strict config-reader migration. The exact inherited UI Knip findings and baseline-reproduced test cases are assigned to the campaign's main-repair owner. Additional untouched CLI config-preparation failures and queued-collector AbortError remain unresolved follow-ups, not proven inherited cases. Earlier broad runs also recorded a UI fixture failure and a test-worker watchdog termination. They are not claimed passing or independently attributed; no changed-owner product regression is established. Landing uses the explicitly authorized relaxed workflow after the static gates and changed-owner proof.The projected-manifest owner/replacement regression passed (1 test, 135 ms test time, 56.24 s command wall time). The integrated cron deletion-deferral regression passed (1 selected test, 345.65 s command wall time including worker compilation).
Regressions cover completion persisted after clean shutdown, unfinished boot recovery, the same worker broker surviving through the completion write, server-close → handoff → shared-state cleanup ordering, deletion facts after an in-process write, and async metadata preparation. The run loop joins asynchronous lifecycle completion before retiring shared state.
The published-driver × candidate update passed on production head
caeef8d0d4dafc8f7889c72f0bca28151f18e7ef: published 2026.10.2 → candidate completed, readiness returned 200, running version matched, durable/incognito post-update probes passed, and service stop passed. The actual update step ran from 18:28:17Z to 18:36:36Z. Update job, proof artifact. The subsequent commit changes only the cleanup-error test assertion.