Skip to content

fix: avoid repeated agent database integrity scans - #146512

Merged
steipete merged 4 commits into
mainfrom
codex/agent-db-integrity-once
Sep 13, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/agent-db-integrity-once

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Related: #145909, #118885.

What Problem This Solves

Large agent databases repeatedly stall session operations because every physical writable reopen performs a full SQLite integrity scan, including reopens after cache eviction and short-lived cleanup workers.

User Impact

Ordinary reopens now reuse the first successful integrity and foreign-key verification for the Gateway lifetime. A fresh Gateway process checks again. No configuration, database schema, persistent marker, retention, or durability setting changes.

This is the maintainer-requested policy: damage introduced into the same file after verification is detected by SQLite operations, the daily verifier, or explicit maintenance instead of a full scan on every reopen. Doctor, backup verification, migration checks, and repair validation remain intact.

Why This Change Was Made

Extend the existing validation owner with physical file identity and shared revocation. Reclamation and cold-storage workers borrow verified health under their existing live writer admission and return newly established proof only after cleanup. File replacement, disposal, registry invalidation, quarantine, and failed admission discard remembered health; current ownership, schema, and write authority are still checked independently.

CI also exposed an inherited Control UI build failure on unmodified main: dependency layout could split a tiny shared module into its own boot bundle. A two-line correction gives the existing measured boot groups a 16 KiB minimum so small tails stay with their consumers through automatic chunking. Maximum chunk sizes, generated manifests, route boundaries, and compressed-size budgets are unchanged.

Thanks to @najef1979-code for the detailed large-database report.

Evidence

  • 442 focused storage and admission tests passed, with four existing skips, covering all open modes, eviction, first-open corruption and foreign keys, replacement, migrations, cancellation, reclamation, and cold storage.

  • New regressions fail on pre-fix main: repeated synchronous/admitted/async opens rescan; a second fresh reclamation worker performs a second native integrity check. The fixed worker regression observes one scan across two workers, then another after owner invalidation, with persisted survivors verified.

  • Real isolated Gateway before/after comparison on macOS with Node 24.21.0: 70 agents, including one healthy 316 MB database. Two 70-agent session RPC sweeps reduced full canonical integrity scans from 140 to zero after startup and elapsed time from 38.86 seconds to 9.21 seconds. Hundreds of physical opens still occurred. These are single-run synthetic workload timings, not a production latency guarantee.

  • Two real chat-inject/session-delete flows succeeded and preserved their archived transcripts. Fresh cleanup workers added one full scan each before the fix and zero afterward.

  • A fresh Gateway process against the same completed-migration state checked all 70 databases again, then performed zero checks during subsequent sweeps. Pending one-time migrations retain their own independent full verification.

  • The final production follow-up was rebuilt and live-tested: another 70-agent sweep and two transcript deletions added zero integrity checks; session/archive contents, all 300 payload hashes, and final full integrity/foreign-key checks passed.

  • Supported runtime builds, the full changed-code check, and targeted lint passed. Independent reviews found no actionable P0–P2 issues. Cold-admission fixtures explicitly clear remembered verification where they need to exercise scan cancellation and FIFO ordering.

  • The inherited UI failure was reproduced on unmodified main and with this PR, producing byte-identical artifacts. With the grouping correction, the normal production build passes at 354,912 startup gzip bytes against the unchanged 355,116-byte limit. Five chunking tests, the existing production startup-recovery E2E, and served-production /new and /chat checks pass; both routes report zero page errors and chat send/final rendering succeeds.

  • Required CI passed on rebased head 55e1d13a7cb5302dbcbdf7e3b4446317c7c12374: https://github.com/openclaw/openclaw/actions/runs/34725497360. The clean rebase preserves all four patches and incorporates upstream fix: restore core test shard headroom #146538 to restore type-shard headroom without changing limits.

@clawsweeper

clawsweeper Bot commented Sep 12, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M maintainer Maintainer-authored PR labels Sep 12, 2026
@steipete
steipete marked this pull request as ready for review September 12, 2026 21:54
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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 Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 12, 2026, 7:59 PM ET / 23:59 UTC (Revision 5).

ClawSweeper review

What this changes

Reuse successful agent-database integrity checks across connection reopens and cleanup workers, update regression coverage and documentation, and consolidate undersized Control UI startup bundles.

Warning

SQLite table change

This PR modifies persisted SQLite tables in src/state/openclaw-agent-db-schema.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.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this remains useful work absent from current main, with convincing recorded runtime evidence and no blocking correctness finding. The previous blanket migration-proof blocker is unsupported by the actual diff; the integrity-policy tradeoff already has explicit maintainer acceptance.

Priority: P1
Reviewed head: 55e1d13a7cb5302dbcbdf7e3b4446317c7c12374

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A maintainable owner-level optimization with strong recorded runtime evidence, useful regressions, and no actionable blocking finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded real Gateway sweeps exercise the changed admission and cleanup owners, showing eliminated repeat scans, fresh-process revalidation, preserved archives and payload hashes, and clean final integrity checks. Served-production browser results cover the separate startup-chunk adjustment; this review did not rerun those experiments.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded real Gateway sweeps exercise the changed admission and cleanup owners, showing eliminated repeat scans, fresh-process revalidation, preserved archives and payload hashes, and clean final integrity checks. Served-production browser results cover the separate startup-chunk adjustment; this review did not rerun those experiments.
Evidence reviewed 9 items Current main still performs repeated scans: At fetched main, physical opens still call agentDatabaseIntegrityBeforeMutationSteps without integrity reuse; the existing cache only remembers the agent owner. The latest supplied release, v2026.9.4, also contains that older cache implementation. This branch’s central optimization is still necessary.
Verification cache has an explicit lifecycle: The cache uses a process-local Map and shared revocation cells, matches agent and physical file identity, and invalidates borrowed verification through the existing lifecycle. It introduces no persistent verification marker.
Migration concern checked against introduced hunks: The project-column predicate moves unchanged into its migration owner. No DDL, stored representation, schema version, migration transformation, or user setting changes. Pending migrations still perform full verification, maintenance callers retain the default non-reuse path, and index repairs verify before releasing their savepoint. These facts resolve the previous review’s generic migration/upgrade-proof warning.
Findings None None.
Security None None.

How this fits together

OpenClaw’s agent databases hold sessions, transcripts, and other agent state. Database admission prepares connections for session operations and cleanup workers while checking ownership, schema compatibility, and database health.

flowchart TD
  A[Session operations and cleanup] --> B[Database admission]
  B --> C[Current ownership and schema checks]
  C --> D{Reusable integrity verification?}
  D -->|No or migration pending| E[Full integrity verification]
  D -->|Yes| F[Admitted database operations]
  E --> F
  F --> G[Session results and preserved archives]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +137, Tests +233, Docs +18. Total +388 across 34 files.

View PR surface stats
Area Files Added Removed Net
Source 13 187 50 +137
Tests 19 255 22 +233
Docs 2 29 11 +18
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 34 471 83 +388

Review metrics

Metric Value Why it matters
Persistence compatibility 0 stored-format changes; 0 new settings The migration-file edit relocates an unchanged predicate, while verification reuse remains in memory.
Production versus regression coverage Net production +137 lines; tests and test support +233 lines Production growth implements identity-bound verification sharing and revocation, with regression coverage for reopens, workers, and lifecycle invalidation.

Stored data model

Persistent data-model change detected: unknown-data-model-change: src/state/openclaw-agent-db-schema.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: partial_overlap
Canonical: #118885
Summary: This PR addresses recurring agent-database scans within the broader canonical report; shared-state startup checks remain a distinct portion of that report.

Members:

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

Technical review

Best possible solution:

Keep verification reuse in the existing database owner, with independent migration, maintenance, schema, and current-authority checks under the accepted detection policy.

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

Yes: current-main physical writable reopens unconditionally reach full integrity verification, and the discussion supplies measured affected workloads. This review established the mechanism from source without executing it.

Is this the best way to solve the issue?

Yes: extending the existing validation owner avoids repeated full-file work without a competing cache or persistent format. The accepted same-file corruption detection window is explicit, and pending migrations retain full checks.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: Repeated full scans cause measured multi-second stalls in existing session workflows on large agent databases.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded real Gateway sweeps exercise the changed admission and cleanup owners, showing eliminated repeat scans, fresh-process revalidation, preserved archives and payload hashes, and clean final integrity checks. Served-production browser results cover the separate startup-chunk adjustment; this review did not rerun those experiments.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded real Gateway sweeps exercise the changed admission and cleanup owners, showing eliminated repeat scans, fresh-process revalidation, preserved archives and payload hashes, and clean final integrity checks. Served-production browser results cover the separate startup-chunk adjustment; this review did not rerun those experiments.

Evidence

What I checked:

  • Current main still performs repeated scans: At fetched main, physical opens still call agentDatabaseIntegrityBeforeMutationSteps without integrity reuse; the existing cache only remembers the agent owner. The latest supplied release, v2026.9.4, also contains that older cache implementation. This branch’s central optimization is still necessary. (src/state/openclaw-agent-db.ts:335, a0792d71e5b4)
  • Verification cache has an explicit lifecycle: The cache uses a process-local Map and shared revocation cells, matches agent and physical file identity, and invalidates borrowed verification through the existing lifecycle. It introduces no persistent verification marker. (src/state/openclaw-agent-db-validation-cache.ts:17, 55e1d13a7cb5)
  • Migration concern checked against introduced hunks: The project-column predicate moves unchanged into its migration owner. No DDL, stored representation, schema version, migration transformation, or user setting changes. Pending migrations still perform full verification, maintenance callers retain the default non-reuse path, and index repairs verify before releasing their savepoint. These facts resolve the previous review’s generic migration/upgrade-proof warning. (src/state/openclaw-agent-db-schema.ts:479, 55e1d13a7cb5)
  • Worker health reuse remains separate from write authority: Reclamation and cold-storage callers retain their current-owner assertions and final commit authorization. Verification accompanies allowed admission, and returned verification is adopted only after successful worker exit, admission settlement, and a current parent claim. The changed value records database health rather than granting a principal permission to write. (src/config/sessions/session-accessor.sqlite-archive.ts:404, 55e1d13a7cb5)
  • Integrity-policy decision is already recorded: The September 12 maintainer decision explicitly accepts the longer detection window for corruption introduced into the same file after verification, while retaining fresh-process checks, invalidation, migrations, repair validation, and independent maintenance: fix: avoid repeated agent database integrity scans #146512 (comment).
  • Recorded real Gateway and browser behavior: The supplied PR-body snapshot, sourceRevision 7f70576ba092a294d63028997ccbded3b55d7a1624f761f7fda959d0eade0fdd, records macOS/Node 24.21.0 runs with 70 agents and a 316 MB database: post-startup sweeps reduced full scans from 140 to zero and elapsed time from 38.86 to 9.21 seconds. Fresh-process verification checked all 70 databases again; final-candidate deletion/archive flows, 300 payload hashes, and final integrity/foreign-key checks passed. Served-production /new and /chat checks also reported successful chat completion and zero page errors after the chunking correction. These are reported isolated measurements, not independently rerun production benchmarks. (55e1d13a7cb5)

Likely related people:

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

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.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-12T22:01:44.215Z sha e76cf68 :: blocked before merge. :: none
  • reviewed 2026-09-12T22:19:30.763Z sha d7ef529 :: blocked before merge. :: none
  • reviewed 2026-09-12T23:17:50.471Z sha 4f71fa6 :: blocked before merge. :: none
  • reviewed 2026-09-12T23:34:38.526Z sha 55e1d13 :: blocked before merge. :: none

@steipete

Copy link
Copy Markdown
Contributor Author

Maintainer decision: accept the documented longer detection window for same-file corruption after successful verification. Checking once per Gateway lifetime, including reuse across eviction and cleanup workers, is the explicitly requested behavior. First-use verification, fresh-process verification, replacement/disposal/quarantine invalidation, migrations, repair validation, and independent maintenance checks remain in place.

The follow-up fixes lint issues and preserves deliberate cold-admission test coverage. The PR body now includes completed live restart and final-candidate evidence; 380 focused tests pass. No correctness finding remains from the review.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Sep 12, 2026
Reuse the first successful verification across physical reopens and admitted cleanup workers during the Gateway lifetime. Bind remembered health to the agent and physical database identity, share revocation with workers, and keep fresh ownership, schema, migration, repair, and quarantine checks.

Related: #145909, #118885. Maintainer-requested verification policy; no persistent marker or durability change.
Explicitly invalidate verification only where fixtures exercise cold integrity admission, and retain ordinary close and revocation paths. Move the unchanged session-project schema probe to its migration owner, extract native scan instrumentation, and remove callback shadowing.
Settle the canonical validity projection for healthy raw fixture rows and invalidate verification only for tests that exercise first-scan admission. Preserve existing history protection, warm-parent, and refusal assertions.
Keep undersized measured boot tails with their consumers through automatic chunking. This removes inherited dependency-layout-sensitive startup overhead while preserving the generated boot manifest, route boundaries, maximum chunk sizes, and all compressed-size budgets.
@steipete
steipete force-pushed the codex/agent-db-integrity-once branch from 4f71fa6 to 55e1d13 Compare September 12, 2026 23:28
@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime channel: feishu Channel integration: feishu size: L and removed size: M labels Sep 12, 2026
@steipete
steipete merged commit 694f9ae into main Sep 13, 2026
203 checks passed
@steipete
steipete deleted the codex/agent-db-integrity-once branch September 13, 2026 00:01
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
* fix: avoid repeated agent database integrity scans

Reuse the first successful verification across physical reopens and admitted cleanup workers during the Gateway lifetime. Bind remembered health to the agent and physical database identity, share revocation with workers, and keep fresh ownership, schema, migration, repair, and quarantine checks.

Related: openclaw#145909, openclaw#118885. Maintainer-requested verification policy; no persistent marker or durability change.

* test: preserve cold admission coverage with remembered integrity

Explicitly invalidate verification only where fixtures exercise cold integrity admission, and retain ordinary close and revocation paths. Move the unchanged session-project schema probe to its migration owner, extract native scan instrumentation, and remove callback shadowing.

* test: complete fixtures before reusing database verification

Settle the canonical validity projection for healthy raw fixture rows and invalidate verification only for tests that exercise first-scan admission. Preserve existing history protection, warm-parent, and refusal assertions.

* build: coalesce tiny Control UI boot chunks

Keep undersized measured boot tails with their consumers through automatic chunking. This removes inherited dependency-layout-sensitive startup overhead while preserving the generated boot manifest, route boundaries, maximum chunk sizes, and all compressed-size budgets.
@VACInc

VACInc commented Sep 13, 2026

Copy link
Copy Markdown
Member

Related follow-up #146597 has merged. This PR's ordinary runtime-open verification reuse and #146597's Doctor import-finalization optimization address complementary paths. The latter avoids redundant cleanup and a second full integrity/foreign-key check when an imported database is already in incremental auto-vacuum mode, has zero free pages, and has no WAL. Initial validation remains intact. This is a follow-up, not a replacement for this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui channel: feishu Channel integration: feishu docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR 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. size: L 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.

2 participants