Skip to content

fix: interrupted triage leaves full-size SQLite snapshot copies in the cache - #193174

Merged
fuller-stack-dev merged 8 commits into
openclaw:mainfrom
fuller-stack-dev:fix/sqlite-snapshot-cancelled-retirement
Nov 5, 2026
Merged

fuller-stack-dev merged 8 commits into
openclaw:mainfrom
fuller-stack-dev:fix/sqlite-snapshot-cancelled-retirement

Conversation

@fuller-stack-dev

@fuller-stack-dev fuller-stack-dev commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Fixes: interrupting openclaw triage (Ctrl-C or SIGTERM) while Doctor's database inspection is copying a database leaves the full-size read-only copy under ~/Library/Caches/openclaw/sqlite-<hash>/openclaw-sqlite-readonly-v2-*/openclaw-sqlite-readonly-v2-*/database.sqlite after the process exits.

On one Mac host, two triage runs left four nested copies of the agent and state databases (13, 15, 6.2 and 15 GB), and free disk fell from 87 GiB to 38 GiB. Every leftover owner.sqlite was empty with a 512-byte -journal, and no process held the files afterwards. Those two runs were not interrupted: one was refused late for an oversized --update-result file, the other was a non-TTY --run refusal, and both exited 1. This PR fixes the leak mechanism I can reproduce, which is cancellation of the inspection task while it holds a copy. I have not reproduced that host's exact trigger; see Evidence.

User Impact

An interrupted triage or Doctor inspection now removes its private snapshot copy before it exits. A copy that a live reader still holds is kept until that reader releases it, as before.

Why This Change Was Made

Doctor's database-engine inspection runs as a served worker task. When triage is interrupted, the task is cancelled, and its cleanup does start. But each SQLite statement on the private staging token, and the retirement of the copy's admission facts, goes through the worker's admission-facts exchange. That exchange checks the task's cancellation first. So cleanup failed with SQLite admission facts exchange cancelled by its caller, and the worker thread was torn down with the copy still on disk.

This adds withSqliteDatabaseAdmissionSettlement to the admission-wait scope. The scope now lives in a leaf module, sqlite-database-admission-wait.ts, so the staging token and the admission store can import it without a madge cycle through the worker relay; the relay re-exports the helpers its existing importers use. The settlement scope stops outer cancellation from failing the exchange but keeps outer deadlines. Two cleanup primitives use it: the staging token's reclaim and read opens, release and retirement, and retireSqliteDatabaseAdmissionForPath. Creating a new staging owner is not settled, so a cancelled task still cannot allocate another copy. Every retirement path goes through those two. Live readers still fence retirement with their own disk tokens, and cancelled admission waits outside these two primitives behave as before. Each half alone still leaks; both are required.

Ruled out:

  • Reclamation skips the nested layout. Once the holders were dead, beginSqliteSnapshotRetirement with the gateway sweep's cutoff removed both nested and flat leftovers, including the stale -journal.
  • The owner record never commits. An empty owner.sqlite with a 512-byte -journal is what a creator token holding BEGIN IMMEDIATE leaves when its process ends without releasing. It's a live lock, not a failed commit.
  • A normal run leaks. Uninterrupted triage runs, with and without a live Gateway owning the database, left nothing.
  • A non-zero CLI exit leaks. On base, with a 12.6 GB live-owned state DB, triage --json --update-result <9 KB file> (refused with File exceeds 8192 bytes after 237 s) removed every copy before it exited 1. Head behaves the same, as does the non-TTY triage --run refusal (exit 1 after writing the bundle).
  • The Gateway's side of triage's RPCs leaks. An instrumented Gateway created no snapshot copies while serving triage's health and diagnostics.capabilities calls.

Not fixed here: when the host dies, the spawn broker's SQLite native resource deliberately keeps creator custody of its own session-allocated snapshot (covered by the existing "refuses cleanup after losing its host fence port" test). The orphaned broker then keeps one flat copy alive. That fail-closed behaviour needs a maintainer decision, so it belongs in a separate PR.

Evidence

Head 67fb70d48f3f, which contains origin/main 480d50305383. The end-to-end red reproduction ran on ffbbb514ba3b. The unit red/green below ran against merge base 341f69b93d2d; after merging main to 9f07ae4789dc, the focused tests were rerun. The last main merge (480d50305383) touches only Doctor's Codex route warnings, outside these paths, so the tests were not rerun for it.

Reproduction, in a disposable HOME and state dir with a 3.1 GB state database owned by a disposable Gateway, then SIGINT to the openclaw triage --non-interactive --json process group as soon as the nested copy appears:

Build Runs Nested copy left after exit
base 9 9 (3 GB each, empty owner.sqlite with a 512-byte -journal)
this branch 3 0

Instrumenting base showed the worker calling removeTempDirectoryAsync 10 ms after cancellation, then failing at BEGIN on the staging token (getSqliteDatabaseSchemaRevision → admission exchange → worker task cancelled). With only the token change, it failed next at retireSqliteDatabaseAdmissionForPath.

Regression test in src/infra/worker-task-server.test.ts: "retires a cancelled task's snapshot copy unless a live reader still holds it". It drives the real task server, cancellation word, admission relay, staging tokens and real SQLite copies. Each copy sits in a nested staging directory, as Doctor's inspection leaves it: the child that wrote it releases its creator token first, so removing the parent after cancellation must take reclaim on the child. The test also checks that the host admission exchange was used and awaits the task's result.

  • base: fails (the idle nested copy survives)
  • staging token acquisition left unsettled (release and retirement settled): fails the same way
  • token-only change and admission-retirement-only change (first revision): fail
  • previous head 41e89ee105b4, which also settled create: fails the new control below
  • this branch: passes

Negative controls in the same test:

  • While a live read token holds one copy, removal returns false and the nested copy stays. After the reader releases, the same removal succeeds.
  • After cancellation, allocating a new staging directory still fails with the cancellation, and leaves nothing behind.

Commands:

  • vitest run src/infra/worker-task-server.test.ts test/scripts/eager-import-closure.test.ts on the head: 29 passed.
  • vitest run on the 209 test files that import the staging token, admission store or relay, snapshot staging, read-only location cleanup, retirement, reclamation or the worker task server: 4 failures in 3 files, and each fails identically with this PR's source reverted to the merge base: src/state/openclaw-state-db-readonly.test.ts ("reads only active disposable scopes…", a /private/var vs /var temp-path alias on macOS), src/config/sessions/session-transcript-reconcile.lease.test.ts (claim-before and claim-after cases) and src/cli/update-cli/update-command-failure-recovery.test.ts ("settles a headless package rollback…").
  • pnpm check:changed: lint, format, import-cycle and boundary guards pass. The local tsgo typecheck can't run on this machine because the checkout uses the shared pnpm store, which its graph boundary refuses. CI's typecheck is the gate for that.
  • Autoreview (Codex, branch mode against origin/main, P0–P2): scoped-clean on 389bc572e467 (the head before that last main merge).
  • scripts/check-madge-import-cycles.ts: 0 cycles (the first push had 1, fixed by the leaf module). Runtime import cycles: 0.
  • The new leaf is listed in scripts/pr-lib/wrapper-components.txt, the PR wrapper's import-closure inventory; CI's wrapper bootstrap and PR worktree provisioning tests failed without it. test/scripts/eager-import-closure.test.ts passes locally (36/36). The cases from test/scripts/pr-worktree-provision.test.ts that failed in CI now pass locally; one other case there times out locally (178 s against a 120 s limit while materializing full clones) and did not fail in CI.
  • Related: fix: leftover SQLite snapshot copies from Doctor and triage are never reclaimed #193229 makes any copy that still escapes cleanup reclaimable. Doctor's snapshots were staged in a per-run namespace the Gateway never sweeps.
  • Test-lines ratchet: this PR's net growth is +58, recorded exactly in config/test-lines-allocations/sqlite-snapshot-cancelled-retirement.txt. With current main the check passes (slack 30).

Test file audit (src/infra/worker-task-server.test.ts, read in full): the fixture's synthetic node:worker_threads mock now reports a worker threadId, so fact retirement takes the cross-thread path a real served worker takes. The other six tests pass unchanged. The new nativeSections fixture parameter and the temp-dir tracker are used only by the new test, which owns and removes its temp root and awaits its task. Nothing was pruned: every existing case covers distinct behaviour.

When `openclaw triage` (or Doctor's in-process collection) is interrupted,
the database-engine inspection worker task is cancelled while it holds a
private read-only snapshot. Its cleanup runs, but every SQLite statement on
the staging token, and the retirement of the copy's admission facts, goes
through the worker's admission exchange. That exchange checks the task's
cancellation first, so cleanup failed with "SQLite admission facts exchange
cancelled by its caller" and the multi-gigabyte copy stayed under
~/Library/Caches/openclaw/sqlite-<hash>/ after the process exited.

Add a settlement scope to the admission relay that keeps the caller's
deadline but not its cancellation, and use it in the two cleanup
primitives: the staging token's lock operations and admission-fact
retirement for a removed path. Live readers still fence retirement through
their own disk tokens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 5, 2026
@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR lets cancelled inspection workers release SQLite staging locks and retire snapshot admission facts while preserving deadlines and live-reader protection.

Example: Interrupt triage with SIGINT while inspecting a disposable 3.1 GB database.

  • Before: The reported base reproduction left a roughly 3 GB nested snapshot after all nine runs.
  • After: The reported branch reproduction left no nested snapshot after three runs.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-supported repair with reported production-path red/green results and successful reviewed-head CI; no actionable findings remain.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied triage reproduction exercises served-worker cleanup after SIGINT with disposable state and a live disposable Gateway, reporting nine leaking base runs and three clean branch runs; the regression additionally proves live-reader retention and cancelled-allocation rejection.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Interrupting a database inspection can leave a full-size private snapshot consuming disk space after the command exits.
Reason: The maintainer-authored direction addresses reproduced resource leakage with a narrow repair and preserves active-reader custody.

Merge readiness

✅ Ready for maintainer review

This PR fixes a concrete cancellation cleanup failure still present on main. No actionable code finding remains; the verified squash workflow resolves the earlier attribution concern.

Priority: P1
Reviewed head: 67fb70d48f3f6a887b5ac5eb35bd87ef11f15295

Before merge

None.

Findings

None.

Agent review details

How this fits together

Doctor and triage run database inspections in served workers; snapshot cleanup uses staging locks and host admission exchanges before removing private database copies.

flowchart TD
  A[Triage or Doctor] --> B[Inspection worker]
  B --> C[Private SQLite snapshot]
  B --> D[Cancellation and cleanup]
  D --> E[Admission settlement scope]
  E --> F[Staging locks and admission retirement]
  F --> G[Remove unheld snapshot]
Loading

Technical review

Best possible solution:

Land the focused cancellation settlement repair through the native squash workflow, keeping deadline-expiry and hangup repairs separately scoped.

Do we have a high-confidence way to reproduce the issue?

Source confirms cancellation rejects cleanup admission exchanges, and the author supplies repeated real-command red/green reproduction; this read-only review ran no target code, and the original non-interrupted host incidents remain unexplained.

Is this the best way to solve the issue?

The patch repairs the existing cleanup primitives, retains their lock checks, and extracts the existing wait scope into a leaf to avoid an import cycle; each added component serves the cancellation fix.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 474592cc2b42.

Provenance checked

  • Admission wait cancellation and deadline handling changes intended behavior with a stated reason (910b54b: Bound stalled inspections and honor caller cancellation without revoking already admitted writes.)
  • Staging-token custody and retirement keeps the original intent (0e4f556: Reclaim abandoned scratch while preserving live transaction custody; subsequent identity and exclusive-lock safeguards remain unchanged.)
  • Admission descriptor retirement keeps the original intent (19eddcf: Retire closed admission metadata under host ownership without releasing live siblings' custody.)
  • Snapshot lifecycle simplification keeps the original intent (19fe879: Remove synthetic cancellation machinery while retaining one ordinary cleanup owner; this repair handles a reproduced command interruption without restoring the removed coordination graph.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 0e4f556 adds src/infra/sqlite-staging-token.ts:18 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0e4f556d0527; files: src/infra/sqlite-staging-token.ts)
  • Vincent Koc: Raw commit b25f3d8 adds src/infra/sqlite-staging-token.ts:32 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b25f3d82963c; files: src/infra/sqlite-staging-token.ts)

PR surface

Source +55, Tests +58, Other +3. Total +116 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 131 76 +55
Tests 1 60 2 +58
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 3 0 +3
Total 7 194 78 +116

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Interrupted inspections can retain multi-gigabyte snapshot copies and consume substantial disk space during real diagnostic workflows.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-05T04:50:04.400Z sha 7cde4f6 :: needs changes before merge. :: [P2] [P2] Remove the new admission-to-transport dependency cycle | [P3] [P3] Allocate the justified regression-test growth | [P3] [P3] Remove the public agent attribution
  • reviewed 2026-11-05T18:18:37.752Z sha 67fb70d :: needs changes before merge. :: [P3] Remove the remaining agent-attribution trailers

Reviewed November 5, 2026, 2:15 PM ET / 19:15 UTC (Revision 3).

fuller-stack-dev and others added 2 commits November 4, 2026 23:12
Move the admission-wait scope (its store, deadline reader, cancellation
check and the new settlement scope) into a leaf module. The staging token
and admission-fact retirement import it there instead of through the
worker relay, which closed a madge type-import cycle. The relay re-exports
the helpers its existing importers use. Record the regression test's exact
net test-line growth.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fuller-stack-dev and others added 2 commits November 4, 2026 23:50
The PR wrapper extracts its import closure from
scripts/pr-lib/wrapper-components.txt. The new
src/infra/sqlite-database-admission-wait.ts is in that closure, so
wrapper bootstrap and PR worktree provisioning failed to resolve it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cancelled cleanup only needs reclaim, release and retirement, so leave
create-mode token acquisition outside the settlement scope. The regression
test now stages the copy in a nested child directory whose creator exits
first, so retiring the parent must reclaim the child after cancellation.
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 5, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 5, 2026
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

On the remaining P3 about agent-attribution trailers:

The branch commits are not what gets published. This PR lands through scripts/pr merge-run as a single squash commit. scripts/pr-lib/merge-body.mjs builds that commit's message, and it drops [email protected] co-author trailers, logged as "Dropped squash co-author credit". So the one commit that reaches main carries no agent attribution.

#193134, #193622, #193626, #193132, #193229 and #193648 all landed today the same way: their branches had these trailers, and their squash commits on main have none.

Removing the trailers from the branch would need a force-push to an open PR, and that wouldn't change what lands. No commits added since the review carry the trailer, and the PR body has no generated footer.

@fuller-stack-dev

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 5, 2026
@fuller-stack-dev
fuller-stack-dev merged commit 8785b57 into openclaw:main Nov 5, 2026
171 of 172 checks passed
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Merged via squash.

@fuller-stack-dev
fuller-stack-dev deleted the fix/sqlite-snapshot-cancelled-retirement branch November 5, 2026 19:32
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 6, 2026
…e cache (openclaw#193174)

* fix: retire cancelled workers' SQLite snapshot copies

When `openclaw triage` (or Doctor's in-process collection) is interrupted,
the database-engine inspection worker task is cancelled while it holds a
private read-only snapshot. Its cleanup runs, but every SQLite statement on
the staging token, and the retirement of the copy's admission facts, goes
through the worker's admission exchange. That exchange checks the task's
cancellation first, so cleanup failed with "SQLite admission facts exchange
cancelled by its caller" and the multi-gigabyte copy stayed under
~/Library/Caches/openclaw/sqlite-<hash>/ after the process exited.

Add a settlement scope to the admission relay that keeps the caller's
deadline but not its cancellation, and use it in the two cleanup
primitives: the staging token's lock operations and admission-fact
retirement for a removed path. Live readers still fence retirement through
their own disk tokens.

* fix: keep the admission-wait scope out of the worker relay import cycle

Move the admission-wait scope (its store, deadline reader, cancellation
check and the new settlement scope) into a leaf module. The staging token
and admission-fact retirement import it there instead of through the
worker relay, which closed a madge type-import cycle. The relay re-exports
the helpers its existing importers use. Record the regression test's exact
net test-line growth.

* fix: list the admission-wait leaf in the PR wrapper inventory

The PR wrapper extracts its import closure from
scripts/pr-lib/wrapper-components.txt. The new
src/infra/sqlite-database-admission-wait.ts is in that closure, so
wrapper bootstrap and PR worktree provisioning failed to resolve it.

* fix(sqlite): keep cancelled tasks from minting snapshot staging owners

Cancelled cleanup only needs reclaim, release and retirement, so leave
create-mode token acquisition outside the settlement scope. The regression
test now stages the copy in a nested child directory whose creator exits
first, so retiring the parent must reclaim the child after cancellation.
wangmiao0668000666 pushed a commit to wangmiao0668000666/openclaw that referenced this pull request Nov 6, 2026
…e cache (openclaw#193174)

* fix: retire cancelled workers' SQLite snapshot copies

When `openclaw triage` (or Doctor's in-process collection) is interrupted,
the database-engine inspection worker task is cancelled while it holds a
private read-only snapshot. Its cleanup runs, but every SQLite statement on
the staging token, and the retirement of the copy's admission facts, goes
through the worker's admission exchange. That exchange checks the task's
cancellation first, so cleanup failed with "SQLite admission facts exchange
cancelled by its caller" and the multi-gigabyte copy stayed under
~/Library/Caches/openclaw/sqlite-<hash>/ after the process exited.

Add a settlement scope to the admission relay that keeps the caller's
deadline but not its cancellation, and use it in the two cleanup
primitives: the staging token's lock operations and admission-fact
retirement for a removed path. Live readers still fence retirement through
their own disk tokens.

* fix: keep the admission-wait scope out of the worker relay import cycle

Move the admission-wait scope (its store, deadline reader, cancellation
check and the new settlement scope) into a leaf module. The staging token
and admission-fact retirement import it there instead of through the
worker relay, which closed a madge type-import cycle. The relay re-exports
the helpers its existing importers use. Record the regression test's exact
net test-line growth.

* fix: list the admission-wait leaf in the PR wrapper inventory

The PR wrapper extracts its import closure from
scripts/pr-lib/wrapper-components.txt. The new
src/infra/sqlite-database-admission-wait.ts is in that closure, so
wrapper bootstrap and PR worktree provisioning failed to resolve it.

* fix(sqlite): keep cancelled tasks from minting snapshot staging owners

Cancelled cleanup only needs reclaim, release and retirement, so leave
create-mode token acquisition outside the settlement scope. The regression
test now stages the copy in a nested child directory whose creator exits
first, so retiring the parent must reclaim the child after cancellation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant