Skip to content

improve(sqlite): harden state lifecycle and snapshots - #104859

Merged
vincentkoc merged 21 commits into
mainfrom
fix/sqlite-state-hardening
Jul 12, 2026
Merged

vincentkoc merged 21 commits into
mainfrom
fix/sqlite-state-hardening

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Closes #104856

Related: #101290

Related: #83712

What Problem This Solves

Resolves SQLite lifecycle gaps where concurrent schema/session activity, busy WAL checkpoints, bloated freelists, or malformed backup contents could cause stale transcript rewrites, hidden checkpoint failures, unverifiable snapshots, deleted-page data in archives, unbounded state database growth, or first-open lock failures.

Why This Change Was Made

This gives OpenClaw-owned SQLite state one explicit lifecycle: bounded incremental-vacuum defaults and hot indexes, serialized schema mutation and first-open initialization, transaction-time transcript revalidation, fail-closed compact backup snapshots, strict archive verification, and an offline openclaw doctor --state-sqlite compact command with integrity proof.

The branch reconciles current main's agent schema v5 transcript-watermark migration with the new index migration as schema v6. Released v5 databases and older v4 databases converge on the canonical v6 schema with their persisted transcript state intact.

Plugin-owned databases remain opaque to core schema interpretation and fail closed when owner capabilities are required for a privacy-safe snapshot. Workspace SQLite files remain ordinary workspace backup content; the compact-snapshot guarantee applies to SQLite databases under the state asset.

AI-assisted: implementation and review used Codex. I reviewed the code, migration boundaries, tests, failure modes, and docs; final scoped autoreview reported no accepted/actionable findings.

User Impact

Operators can explicitly compact shared state, inspect reclaimed bytes and integrity results, and trust state backup verification to reject malformed, mis-scoped, sidecar-contaminated, role-mismatched, truncated, or case-aliased SQLite snapshots. Concurrent processes no longer silently erase newly appended transcript events during destructive rewrites, busy WAL checkpoints are surfaced, and concurrent first opens receive bounded lock retry before schema inspection and WAL activation.

Latest-message reads now seek (session_id, event_type, seq DESC) directly and avoid a temporary ORDER BY B-tree.

Evidence

  • Final scoped Codex autoreview after the current-main rebase and terminal-freshness fixture alignment: clean, no accepted/actionable findings.
  • Blacksmith Testbox tbx_01kxa5h62fwx4shyccd0gpgv65: 857 focused tests passed across terminal-session admission, transcript rewrite races, lifecycle freshness, state DB, agent DB, query plans, WAL, transactions, and real session-accessor readers; the generated docs map check also passed.
  • Blacksmith Testbox tbx_01kxa5h62fwx4shyccd0gpgv65: exact final pnpm check:changed passed in 9m37s.
  • Native ARM64 Crabbox cbx_6d80d4150203, run run_bb49a88c28c9: the same 229 focused tests passed.
  • Fresh/open migration proof covers current-main agent schema v5 -> v6, v4 -> v6 transcript watermark creation, concurrent additive upgrades, and forced concurrent fresh-database initialization.
  • Earlier Blacksmith Testbox focused matrix: 226 tests passed across state DB, agent DB, query plans, WAL, backup creation/verification, doctor compaction, CLI registration, and cross-process transcript races.
  • Rebase conflict proof: state DB 37/37 and backup verifier 26/26 passed in https://github.com/openclaw/openclaw/actions/runs/29175503593.
  • Final case-folded state-root security regression: backup verifier 27/27 passed in https://github.com/openclaw/openclaw/actions/runs/29175656951.
  • Native Crabbox AMD64 and ARM64 SQLite suites: 238/238 passed on each architecture.
  • Docker/sandbox probes passed on Node 22 Debian, Node 24 Debian, Node 24 Alpine, tmpfs ENOSPC on Debian and Alpine, and ARMv7 under QEMU.
  • High-I/O probes completed 655k shared-state writes, 50k agent writes, and a 291,288,152-byte WAL truncate cycle on AMD64 and ARM64.
  • Live compaction reduced a 4,734,976-byte shared DB with 1,152 freelist pages to 20,480 bytes with zero freelist pages and zero WAL bytes; quick_check and integrity_check returned ok.
  • Native Windows/WSL2 proof was blocked by Azure broker admin_required. Native macOS proof was blocked by unavailable Apple/EC2 Mac capacity. Windows sandbox required a Windows host; other sandbox providers lacked the required runtime/warm pool. These are explicit platform gaps, not claimed passes.

Residual Runtime Risk

SQLite documents a rare WAL-reset corruption bug affecting WAL databases through 3.51.2 under concurrent writers/checkpointers, fixed in 3.51.3 and selected backports: https://sqlite.org/wal.html#walreset_bug

OpenClaw currently supports older Node releases that can embed affected SQLite versions. This PR hardens OpenClaw's lifecycle and concurrency behavior but does not claim to patch an upstream embedded-runtime defect. A separate compatibility follow-up should decide and propagate the minimum safe Node/SQLite runtime across engines, installers, CI, docs, and release tooling.

@vincentkoc vincentkoc self-assigned this Jul 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation cli CLI command changes commands Command implementations size: XL maintainer Maintainer-authored PR labels Jul 12, 2026
@vincentkoc
vincentkoc force-pushed the fix/sqlite-state-hardening branch from 495f344 to 0eddf6f Compare July 12, 2026 01:49
@clawsweeper

clawsweeper Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed July 11, 2026, 11:30 PM ET / July 12, 2026, 03:30 UTC.

Summary
The PR hardens SQLite initialization, schema upgrades, WAL maintenance, transcript mutations, backup snapshots and verification, query indexes, and offline doctor compaction.

PR surface: Source +968, Tests +2013, Docs +46, Generated +3, Other +1. Total +3031 across 36 files.

Reproducibility: yes. The source gives a concrete sequence: the runtime reads rows, another process commits an append, and the later unconditional replacement deletes that append.

Review metrics: 2 noteworthy metrics.

  • Public maintenance surface: 1 CLI option added. The offline shared-state compaction mode creates a new operator-facing recovery and compatibility contract.
  • Stored schema surface: 1 agent schema version bump. Fresh databases and released v4/v5 databases must converge on v6 without losing transcript state or indexes.

Stored data model
Persistent data-model change detected: database schema: src/commands/doctor-state-sqlite-compact.test.ts, database schema: src/infra/backup-create.test.ts, database schema: src/state/openclaw-agent-db.ts, database schema: src/state/openclaw-agent-schema.generated.ts, database schema: src/state/openclaw-agent-schema.sql, database schema: src/state/openclaw-state-db.ts, and 35 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #104856
Summary: This PR is the implementation candidate for the maintainer-authored SQLite lifecycle issue; the two external production reports overlap only in narrower failure modes.

Members:

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

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🦞 diamond lobster
Patch quality: 🦐 gold shrimp
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Route and test the actual embedded runtime rewrite through the snapshot-aware lock.
  • Refresh focused migration, transcript, backup, WAL, and compaction proof against the repaired final head.

Risk before merge

  • [P1] The production embedded rewrite can silently delete an event appended by another process between its read and unconditional replacement.
  • [P1] The schema v6 migration, stricter backup acceptance, fail-closed checkpoint behavior, and new doctor mode remain compatibility and availability-sensitive and need refreshed final-head proof after the correctness repair.

Maintainer options:

  1. Guard the production rewrite before merge (recommended)
    Route the embedded runtime flow through the snapshot-aware lock, add a production-entry cross-process regression, and refresh focused lifecycle proof against the repaired final head.
  2. Pause if rewrite ownership remains split
    Keep the PR open if the production read-modify-replace path cannot use the canonical snapshot-aware mutation boundary.

Next step before merge

  • [P2] The protected member-authored PR needs its previously reported production caller defect repaired and then re-reviewed on the final head.

Security
Cleared: No concrete security or supply-chain regression was found in archive extraction, path normalization, SQLite role validation, extension loading, file permissions, dependencies, or command registration.

Review findings

  • [P1] Route runtime rewrites through the snapshot-aware lock — src/config/sessions/session-accessor.sqlite.ts:1999-2008
Review details

Best possible solution:

Move rewriteSqliteRuntimeTranscript onto withTranscriptWriteLock so its read, transform, transaction-time snapshot revalidation, and replacement share one owner boundary, then add a cross-process regression through the actual runtime rewrite entry.

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

Yes. The source gives a concrete sequence: the runtime reads rows, another process commits an append, and the later unconditional replacement deletes that append.

Is this the best way to solve the issue?

No. The snapshot-aware helper is the correct mechanism, but the actual embedded runtime rewrite still bypasses it; migrating that caller is the narrowest maintainable repair.

Full review comments:

  • [P1] Route runtime rewrites through the snapshot-aware lock — src/config/sessions/session-accessor.sqlite.ts:1999-2008
    The new guard only protects callers using the lock context's readEvents and replaceEvents, while rewriteSqliteRuntimeTranscript still performs a separate public load and unconditional replacement. A cross-process append committed between those calls can be deleted; move the production flow into withTranscriptWriteLock and exercise that entry in the race regression.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

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

Label changes

Label justifications:

  • P1: The surviving production race can silently lose a concurrently committed transcript event.
  • merge-risk: 🚨 compatibility: The branch changes persistent schema, backup verification acceptance, and an operator-facing doctor command across upgrades.
  • merge-risk: 🚨 session-state: The embedded runtime still bypasses snapshot revalidation during destructive transcript replacement.
  • merge-risk: 🚨 availability: Initialization, checkpoint, backup, and compaction paths intentionally fail closed and can prevent startup or maintenance under contention.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The author is a repository member, so the external-contributor proof gate does not apply; the PR nevertheless includes substantial live compaction, high-I/O, Testbox, Crabbox, Docker, and architecture evidence.
Evidence reviewed

PR surface:

Source +968, Tests +2013, Docs +46, Generated +3, Other +1. Total +3031 across 36 files.

View PR surface stats
Area Files Added Removed Net
Source 15 1142 174 +968
Tests 14 2100 87 +2013
Docs 4 76 30 +46
Config 0 0 0 0
Generated 2 6 3 +3
Other 1 3 2 +1
Total 36 3327 296 +3031

What I checked:

Likely related people:

  • vincentkoc: Introduced the SQLite lifecycle hardening stack, the snapshot-aware transcript helper, and the current embedded runtime rewrite behavior. (role: feature owner and recent area contributor; confidence: high; commits: d826581d2696, 5145db7f969e, 3948604c8a95; files: src/agents/embedded-agent-runner/transcript-rewrite.ts, src/config/sessions/session-accessor.sqlite.ts, src/config/sessions/session-accessor.reply-init-concurrency.test.ts)
  • steipete: Recently changed the shared state database surface on current main and is a useful secondary routing candidate for the broad state-lifecycle and upgrade boundary. (role: recent adjacent contributor; confidence: medium; commits: 7a456e362d0b; files: src/state/openclaw-state-db.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (3 earlier review cycles)
  • reviewed 2026-07-12T02:21:08.748Z sha 70a961a3371416d5cf5ec015a25b57b0ebcfb533 :: needs changes before merge. :: [P1] Reject unsupported state SQLite modes before compaction
  • reviewed 2026-07-12T03:07:07.198Z sha 4fdb60923dd12e3587d111612bab0b8cb4a0a3d7 :: found issues before merge. :: [P1] Route runtime rewrites through the snapshot-aware lock
  • reviewed 2026-07-12T03:22:59.305Z sha 740d338a7daa9d5ce3abef0010a1b170ffeb14ba :: needs changes before merge. :: [P1] Route runtime rewrites through the snapshot-aware lock

@vincentkoc
vincentkoc marked this pull request as ready for review July 12, 2026 01:53
@vincentkoc
vincentkoc force-pushed the fix/sqlite-state-hardening branch 2 times, most recently from 850d872 to 70a961a Compare July 12, 2026 02:11
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Jul 12, 2026
@vincentkoc
vincentkoc force-pushed the fix/sqlite-state-hardening branch from 4fdb609 to 740d338 Compare July 12, 2026 03:14
@vincentkoc

Copy link
Copy Markdown
Member Author

Land-ready verification is complete for the SQLite lifecycle hardening.

Exact final head: c69753bab5f754cb9574448966904e0a68e58fb4

Validation:

  • Blacksmith Testbox tbx_01kxa5h62fwx4shyccd0gpgv65
    • Focused terminal-session, transcript-concurrency, lifecycle, state/agent DB, query-plan, WAL, transaction, and session-accessor suites.
    • 857 tests passed; generated docs map check passed.
    • pnpm check:changed
    • Passed in 9m37s.
  • Native ARM64 Crabbox cbx_6d80d4150203, run run_bb49a88c28c9
    • The same 229 focused tests passed.
  • Final scoped Codex autoreview after the current-main rebase
    • No accepted/actionable findings.
  • Migration and plan proof
    • Current-main agent schema v5 and older v4 databases converge on v6.
    • Concurrent schema upgrades and forced concurrent first opens pass.
    • Latest-message reads use (session_id, event_type, seq DESC) and do not use a temporary ORDER BY B-tree.
  • Prior matrix
    • Native AMD64/ARM64, Node 22/24 Debian, Node 24 Alpine, ARMv7/QEMU, tmpfs ENOSPC, high-I/O WAL cycles, malformed files/archives, backup verification, and live compaction passed.

Known proof gaps:

  • Native Windows/WSL2 was blocked by Azure admin_required.
  • Native macOS was blocked by unavailable Apple/EC2 Mac capacity.
  • Older accepted Node builds can embed SQLite versions affected by the upstream WAL-reset bug. That runtime-floor compatibility change is intentionally tracked separately from this PR.

@vincentkoc
vincentkoc merged commit 350bac4 into main Jul 12, 2026
116 of 118 checks passed
@vincentkoc
vincentkoc deleted the fix/sqlite-state-hardening branch July 12, 2026 03:35
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 12, 2026
* fix(sqlite): enable bounded vacuum and hot indexes

* fix(sqlite): serialize shared schema upgrades

* fix(sessions): reject stale transcript rewrites

* fix(sqlite): surface busy checkpoints and refresh registry

* fix(backup): verify sqlite snapshots

* feat(doctor): compact shared sqlite state

* test(sqlite): align hardening helpers

* fix(backup): respect plugin sqlite ownership

* fix(backup): snapshot plugin sqlite opaquely

* fix(doctor): reject mixed sqlite actions

* fix(backup): reject unsafe sqlite snapshots

* fix(sessions): track unconditional transcript replacements

* fix(backup): reject page-aligned sqlite truncation

* fix(backup): reject state-root case aliases

* docs: refresh sqlite maintenance map

* fix(sqlite): register doctor compaction boundary

* fix(sqlite): serialize fresh database initialization

* fix(sqlite): prove main v5 agent upgrade

* perf(sqlite): seek latest transcript messages

* test(sessions): align terminal freshness fixtures with SQLite

* docs: refresh generated map
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Harden SQLite state snapshots, compaction, and concurrent mutations

1 participant