Skip to content

fix(sqlite): prevent WAL split-brain cleanup corruption - #132844

Merged
roboclaw-bot merged 2 commits into
mainfrom
openclaw/vito-vacinc-issue-132363
Aug 29, 2026
Merged

roboclaw-bot merged 2 commits into
mainfrom
openclaw/vito-vacinc-issue-132363

Conversation

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Closes #132363

What Problem This Solves

Fixes an issue where a Linux Gateway that detected a replaced SQLite WAL/SHM family would close its stale connection, allowing SQLite's last-close cleanup to checkpoint stale pages into the main database or remove the replacement sidecars.

Why This Change Was Made

A verified descriptor/path identity mismatch is now a terminal process boundary. OpenClaw writes a synchronous fatal diagnostic containing the sidecar identity details, then self-terminates with SIGKILL so Node exit hooks and SQLite destructors cannot run. The managed service supervisor can restart a clean process against the directory-visible database family.

The obsolete callback-driven cache eviction path is removed. No schema, protocol, configuration, retry, or timeout surface changes.

User Impact

Operators get a brief, explicit Gateway restart instead of risking persistent shared-state corruption and offline database reconstruction. A repeated external sidecar replacement remains visible as a restart loop requiring investigation rather than silently damaging data.

Evidence

  • Regression-first proof on unmodified main: all four WAL/SHM unlink-or-replacement containment cases failed because the process did not hard-stop; the process-level replacement-family test observed the stale connection closing.
  • node scripts/run-vitest.mjs src/infra/sqlite-wal.test.ts — 53 passed.
  • node scripts/run-vitest.mjs src/state/openclaw-state-db.test.ts — 177 passed.
  • node scripts/check-changed.mjs -- src/infra/sqlite-wal.ts src/infra/sqlite-wal.test.ts src/state/openclaw-state-db-open.ts src/state/openclaw-state-db.ts src/state/openclaw-state-db.test.ts — passed.
  • Linux process-level proof: writer A retains the detached family, writer B commits through the replacement family, containment kills A without its fallback close marker, B is crash-stopped, and a fresh reopen reports PRAGMA integrity_check = ok with exactly the authoritative rows.
  • Codex autoreview at xhigh reasoning: no findings; patch correct (0.97 confidence).
  • Production LOC: +40/-41 (net -1). Tests: +176/-80.

AI-assisted; implementation and lifecycle behavior reviewed and understood.

Worked on by


View the OpenClaw team session

roboclaw-bot and others added 2 commits August 29, 2026 20:29
Worked on by:
- @VACInc

Co-authored-by: VACInc <[email protected]>
OpenClaw-Publication: 3e783eee-3a6a-40ed-95ec-29a64b9b5f73
@clawsweeper

clawsweeper Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Aug 29, 2026
@roboclaw-bot
roboclaw-bot marked this pull request as ready for review August 29, 2026 20:30
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 29, 2026
@clawsweeper

clawsweeper Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 29, 2026, 4:39 PM ET / 20:39 UTC.

ClawSweeper review

What this changes

The PR replaces stale SQLite-handle cleanup after a Linux WAL/SHM identity mismatch with a fatal process stop, preserving the replacement database family for a clean restart.

Warning

SQLite table change

This PR modifies persisted SQLite tables in src/infra/sqlite-wal.ts. Prefer a design that avoids changing persisted SQLite tables. If the change is necessary, verify migration and upgrade compatibility against an existing database before merge.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

This PR remains necessary: current main still closes the stale SQLite handle after a verified WAL-sidecar mismatch. The introduced fail-stop path removes that cleanup route and is technically coherent, but its process-wide restart behavior needs maintainer acceptance before merge.

Priority: P0
Reviewed head: 3f712b330c0d8a9369b78fc50c8800f688bb302a
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is focused and its regression design exercises the production SQLite process boundary; the remaining blocker is the intentional restart policy, not a demonstrated implementation defect.
Proof confidence 🌊 off-meta tidepool Not applicable: This is a member/bot-authored PR, so the ordinary external-contributor proof gate does not apply; its body describes a Linux process-level after-fix scenario, but this read-only review did not execute it.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This is a member/bot-authored PR, so the ordinary external-contributor proof gate does not apply; its body describes a Linux process-level after-fix scenario, but this read-only review did not execute it.
Evidence reviewed 6 items Current-main unsafe path: The PR base verifies a mismatch, invokes the state callback, and then closes the still-live DatabaseSync handle; the PR head is not an ancestor of the fetched main SHA.
Introduced containment: The introduced timer clears itself and invokes the fatal helper immediately after a verified mismatch, without calling the removed callback or db.close().
State-owner boundary: The shared-state opener reaches the generic WAL owner with its database path, while the callback that previously evicted and closed the handle is removed.
Findings None None.
Security None None.

How this fits together

SQLite WAL maintenance periodically compares an open database connection’s sidecar descriptors with the directory-visible files. It protects the Gateway shared-state database and other timed, path-backed SQLite owners before checkpointing or orderly cleanup can run.

flowchart LR
  A[Open SQLite connection] --> B[WAL maintenance timer]
  B --> C[Descriptor and sidecar identity check]
  C -->|Match| D[Checkpoint maintenance]
  C -->|Mismatch| E[Fatal diagnostic]
  E --> F[Immediate process stop]
  F --> G[Supervisor restart]
  G --> H[Directory-visible database family]
Loading

Decision needed

Question Recommendation
Should a verified SQLite WAL-sidecar identity mismatch deliberately terminate the full process for all timed Linux database owners? Accept fail-stop containment: Approve immediate process termination on a verified mismatch so no stale SQLite cleanup can run.

Why: The patch removes a data-corruption path, but it intentionally changes the operator-visible outcome to a fatal restart for a generic persistence helper.

Before merge

  • Resolve merge risk (P1) - A verified mismatch in the generic helper will now stop the entire process for every Linux path-backed timed caller, including shared-state and agent databases; maintainers should explicitly accept that availability tradeoff and confirm supervision/restart handling.
  • Complete next step (P2) - A maintainer must choose the intended process-wide availability behavior; no narrow mechanical repair remains to queue.
Agent review details

Security

None.

PR surface

Source -1, Tests +96. Total +95 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 40 41 -1
Tests 2 176 80 +96
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 216 121 +95

Review metrics

Metric Value Why it matters
Production versus regression coverage production +40/-41 (net -1); tests +176/-80 The repair replaces the stale-close path without net production growth and adds both identity-case and process-boundary coverage.

Stored data model

Persistent data-model change detected: serialized state: src/infra/sqlite-wal.ts, unknown-data-model-change: src/infra/sqlite-wal.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #132363
Summary: This PR explicitly targets the open WAL split-brain corruption report and replaces its identified stale-handle close path.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Accept fail-stop containment (recommended)
    Approve the intentional restart behavior after confirming managed Gateway recovery is the desired response to a verified mismatch.
  2. Pause for narrower containment
    Keep the PR unmerged while maintainers choose a different lifecycle boundary that still prevents every stale-handle SQLite call.

Technical review

Best possible solution:

Adopt one fail-stop invariant for verified sidecar mismatches, with maintainer-confirmed process-wide restart semantics instead of any stale-handle cleanup path.

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

Yes: the Linux child-process regression creates the stale and replacement WAL families in the relevant order and distinguishes the old orderly-close behavior from fatal containment. It was inspected but not executed in this read-only review.

Is this the best way to solve the issue?

Yes, contingent on maintainer acceptance of the process-wide restart policy: terminating before SQLite cleanup is the narrowest source-backed way to preserve the verified mismatch invariant.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f9b3bcccdba3.

Labels

Label changes:

  • add P0: The central defect can persistently corrupt the shared SQLite database and leave the Gateway unable to recover normally.
  • add merge-risk: 🚨 availability: A verified mismatch now intentionally terminates the process rather than allowing the affected database owner to continue.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is a member/bot-authored PR, so the ordinary external-contributor proof gate does not apply; its body describes a Linux process-level after-fix scenario, but this read-only review did not execute it.

Label justifications:

  • P0: The central defect can persistently corrupt the shared SQLite database and leave the Gateway unable to recover normally.
  • merge-risk: 🚨 availability: A verified mismatch now intentionally terminates the process rather than allowing the affected database owner to continue.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is a member/bot-authored PR, so the ordinary external-contributor proof gate does not apply; its body describes a Linux process-level after-fix scenario, but this read-only review did not execute it.

Evidence

What I checked:

  • Current-main unsafe path: The PR base verifies a mismatch, invokes the state callback, and then closes the still-live DatabaseSync handle; the PR head is not an ancestor of the fetched main SHA. (src/infra/sqlite-wal.ts:642, f9b3bcccdba3)
  • Introduced containment: The introduced timer clears itself and invokes the fatal helper immediately after a verified mismatch, without calling the removed callback or db.close(). (src/infra/sqlite-wal.ts:663, 3f712b330c0d)
  • State-owner boundary: The shared-state opener reaches the generic WAL owner with its database path, while the callback that previously evicted and closed the handle is removed. (src/state/openclaw-state-db-open.ts:75, 3f712b330c0d)
  • Process-boundary regression: The new Linux regression creates a replacement WAL family, requires the stale process to die without its close marker, then verifies integrity and the authoritative rows after reopen. (src/infra/sqlite-wal.test.ts:624, 3f712b330c0d)
  • Node SQLite contract: Direct local Node type inspection identifies DatabaseSync as a synchronous SQLite connection and documents close() as a sqlite3_close_v2() wrapper; upstream SQLite source was unavailable because DNS resolution failed.
  • Feature provenance: Commit metadata identifies the original split-brain tripwire change as the merged fix(sqlite): isolate read-only snapshot preparation to stop WAL lock drops #127855 feature; its source tree was unavailable in this promisor checkout, so this is routing context rather than line-introduction proof. (5248c2fac7c4)

Likely related people:

  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record maintainer acceptance of the process-wide fail-stop and managed-restart behavior.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

ClawSweeper follow-up:

  • Lifecycle decision resolved: @VACInc explicitly approved the recommended process-wide fail-stop behavior and asked me to publish this PR. A verified WAL/SHM identity mismatch is intentionally terminal because no SQLite API, cache eviction, or orderly shutdown may touch that stale handle afterward.
  • Managed recovery confirmed: OpenClaw's generated systemd unit uses Restart=always and RestartSec=5 in src/daemon/systemd-unit.ts; the managed launchd path uses KeepAlive=true. Unmanaged foreground launches still require an operator restart, with the synchronous fatal JSON diagnostic explaining why the process stopped.
  • Generic-owner scope is intentional: every timed Linux path-backed caller reaching this verified mismatch has an unsafe SQLite handle; retaining a narrower state-only callback would leave sibling owners able to run stale cleanup.
  • No SQLite table or schema change: this PR changes WAL process lifecycle only. It contains no DDL, schema version, migration, table, index, or persisted-shape modification, so the stored-data warning is a path-classification false positive.
  • Proof executed: src/infra/sqlite-wal.test.ts passed 53/53, src/state/openclaw-state-db.test.ts passed 177/177, the complete changed gate passed, exact-head CI is green, and Sol xhigh autoreview reported no findings (0.97 confidence).

This applies the sole Rank-up move. No merge or automerge is requested.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

Additional P0 clean-host sanity proof (no code changes):

  • Exact head: 3f712b330c0d8a9369b78fc50c8800f688bb302a
  • Environment: direct AWS Crabbox, clean Ubuntu host, Node v24.18.1, lease cbx_32eba1e5de31 (released after proof)
  • Run: run_acb8fb5b31f3
  • Command: node scripts/run-vitest.mjs src/infra/sqlite-wal.test.ts -t 'hard-stops|preserves the replacement WAL family'
  • Result: 5 passed, 48 intentionally filtered; exit 0

This exercised real Linux processes and real SQLite files: stale writer A retained the detached WAL family, replacement writer B committed through the directory-visible family, A received the production self-SIGKILL without running its stale-close fallback, B was crash-stopped, and a fresh connection reopened with PRAGMA integrity_check = ok and exactly the authoritative base + current rows. The four detector cases also covered unlinked/replaced -wal and -shm identities without calling DatabaseSync.close().

The clean host reported a running systemd user manager. I did not install or mutate a service for this proof; supervisor behavior remains owned by OpenClaw's generated Restart=always, RestartSec=5 unit and existing daemon CI. This is clean-machine live OS/SQLite containment proof, not a claim that the operator's production Gateway was touched.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

Land-ready verification for exact head 3f712b330c0d8a9369b78fc50c8800f688bb302a:

Observed behavior: stale writer A self-terminated without SQLite cleanup, replacement writer B remained authoritative, and a fresh reopen returned integrity_check = ok with no stale row. The operator Gateway was not touched; managed restart behavior remains the existing systemd/launchd contract. Both PR commits display VACInc as a co-author. No known proof gaps or actionable findings remain.

@roboclaw-bot
roboclaw-bot merged commit 89eb6c1 into main Aug 29, 2026
307 checks passed
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

Merged via squash.

@roboclaw-bot
roboclaw-bot deleted the openclaw/vito-vacinc-issue-132363 branch August 29, 2026 21:34
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 30, 2026
)

* fix(sqlite): fail-stop on WAL split brain

Co-authored-by: Vito Cappello <[email protected]>

* fix(sqlite): prevent WAL split-brain cleanup corruption

Worked on by:
- @VACInc

Co-authored-by: VACInc <[email protected]>
OpenClaw-Publication: 3e783eee-3a6a-40ed-95ec-29a64b9b5f73

---------

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: Vito Cappello <[email protected]>
Co-authored-by: VACInc <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

[Bug]: WAL split-brain tripwire can corrupt the main DB by closing a stale connection

1 participant