Skip to content

perf(state): skip full agent scans on clean same-version restarts - #153463

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-agent-db-integrity-gate-20260919
Sep 20, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-agent-db-integrity-gate-20260919

Conversation

@steipete

@steipete steipete commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Large agent databases repeat full integrity scans during clean same-version restarts, delaying writable admission and Gateway readiness.

User Impact

A clean same-version agent reopen reuses its integrity verification and schedules quick_check plus foreign-key validation in the existing forked verifier after the Gateway is listening. Updates, pending migrations, missing or unclean verification, and replaced files retain full checks. Doctor’s full checks remain unchanged.

Why This Change Was Made

This implements the maintainer-approved policy to gate full boot-time agent checks on updates and unclean or replaced state. The existing quarantine store owns an additive agent_integrity_verifications table with path TEXT PRIMARY KEY, dev TEXT, ino TEXT, app_version TEXT, verified_at INTEGER, and clean_close INTEGER CHECK (clean_close IN (0,1)). Agent/shared-state schema versions remain unchanged; older builds ignore the table. The record is reconstructible, contains no content hashes, and ordinary writes do not change its eligibility.

The existing lease owner consumes clean proof before admission and publishes clean close only after the last handle checkpoints and closes. Failed native cleanup, forced Worker exit, stale claims, and path aliases invalidate proof conservatively. A live lease may still lend identity-bound, revocable runtime proof to another handle, but only while matching durable metadata remains present. Missing, replaced, or version-mismatched metadata cannot be bypassed by remembered runtime validation.

Cached opens notify the existing host verifier, including late Worker opens. Quick-check success is logged and leaves full-check receipts unchanged; only the full-check lease owner publishes verification metadata. Gateways sharing a state directory in one process share serialized verification work and a daily deadline while retaining independent async contexts and shutdown ownership. Stopping one hands unfinished checks to surviving Gateways. Full scans also retain queued paths absent from the registered inventory. Clean consolidated WAL files use an immutable readiness read under the existing exclusive source-handle owner; uncertain or contended reads retain full snapshot verification.

The accepted tradeoff is that same-inode damage after a clean close may be detected after readiness. Background terminal failures retain live confirmation and quarantine; the next open fails through the existing terminal path. A failed durable dirty-marker write refuses admission, preserving the existing clean proof until the metadata-write problem is repaired. Shared-state boot checks, migrations and index repairs, explicit copied-file preflight, Doctor, and the existing full background scan (initially after five minutes, then daily) retain full checks. Independent Gateways must not share mutable agent databases across state roots.

Backup now includes the quarantine store in its existing verified SQLite snapshot path. The released quarantine schema remains version 2, with its existing rows preserved when the additive receipt table is first created.

Evidence

Six alternating-order warmed samples against the real agent schema with 4,428 synthetic sessions, 100,000 transcript rows, and 899,518,464 bytes, on Node 26.8.2 / SQLite 3.53.4:

Operation Mean
Full gate 1,094 ms
Receipt lookup + durable dirty write + cached gate 17.8 ms
quick_check 543 ms
foreign_key_check 160 ms

The optimized gate saves 98.4%; all six samples report integrityGateOutcome: "cached". This isolates the gate and excludes shared lease acquisition, whole-open cost, Gateway readiness, and shutdown. Host contention makes absolute times variable.

The original 162 focused tests were supplemented during landing by passing suites covering 158 session/config cases, 15 auth-admission cases, 188 memory-plugin cases, 156 backup cases (two platform skips), 144 final integrity/admission/verifier cases, and eight real multi-Gateway lifecycle cases. Some suites overlap. The released v2026.9.5 quarantine-schema fixture proves additive receipt creation preserves existing rows and schema version; policy cases cover retained and borrowed runtime proof, version changes, missing receipts, file replacement, and failed dirty writes followed by recovery. Backup proof covers verified snapshot and restore of the receipt store.

Initial CI failures were reproduced or compared against pure main before attribution. Repairs preserve warm Worker proof, independent Gateway lifetimes, verified backup ownership, and all FIFO, authority, corruption, and cleanup assertions. Full-scan fixtures now explicitly invalidate receipts or replace their files. A separate cold-start timing failure reproduced on pure main and was left unchanged; the repaired startup suite passed its other 15 cases. Line-cap checks, formatting, docs checks, scoped lint, core and plugin-test typechecks passed. Independent review of the corrections is clean through P2, in addition to the completed review of the original change.

A Linux-only quick-check identity failure exposed a ctime-based replacement/restoration assumption and a fixture intercepting the coordinator open. The redundant quick-success timestamp writer and its identity certification were removed. A regression assertion fails on the old writer and passes after removal; 90 focused verifier, process, lease, policy, and shutdown cases pass, including the real cached-Worker relay. Scoped lint, core typechecking, docs checks, and fresh independent review through P2 pass. Pure main passes its 27 process cases but does not contain the new quick-check identity path.

Hosted CI run 35498498098 passed for head 0c0e3fbfc9a483879a9eb524e3da4c62734c3b39; the completed check set has 170 passing and 38 skipped checks. The dependency-review workflow briefly published its incomplete status before replacing it with success three seconds later; no dependency change required review.

Limits: no production Gateway was modified or restarted, no live end-to-end restart timing or published-updater × candidate campaign was run, and no standalone local full build is claimed. Focused runs built their compiled Worker bundles; hosted CI owns the complete build/test gate. Updates retain version-mismatch full checks and the existing migration/Doctor owners.

@clawsweeper

clawsweeper Bot commented Sep 20, 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 scripts Repository scripts commands Command implementations size: XL maintainer Maintainer-authored PR labels Sep 20, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 20, 2026
@clawsweeper

clawsweeper Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 20, 2026, 4:46 AM ET / 08:46 UTC (Revision 5).

ClawSweeper review

What this changes

The PR reuses persisted agent-database verification after clean same-version restarts, schedules background checks, and includes verification metadata in SQLite backups.

Warning

SQLite table change

This PR modifies persisted SQLite tables in src/state/openclaw-agent-db-schema-helpers.ts, 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 - 5 items remain

This remains useful work that current main does not implement. No concrete introduced correctness defect was found; the protected, maintainer-authored PR remains open with an unresolved upgrade-validation requirement.

Priority: P2
Reviewed head: 0c0e3fbfc9a483879a9eb524e3da4c62734c3b39
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is coherent and has meaningful lifecycle coverage, with no concrete blocking code finding; upgrade validation still needs resolution.
Proof confidence 🌊 off-meta tidepool Not applicable: The ordinary external-contributor proof gate does not apply to this maintainer-authored PR. The reported real-schema benchmark exercises the changed integrity gate, and the inspected real-worker harness covers cached-open verification; the published-updater requirement remains a separate unresolved policy gate.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary external-contributor proof gate does not apply to this maintainer-authored PR. The reported real-schema benchmark exercises the changed integrity gate, and the inspected real-worker harness covers cached-open verification; the published-updater requirement remains a separate unresolved policy gate.
Evidence reviewed 9 items Pinned introduction and merge result: The reviewed checkout is the pinned original head. The verified test merge has the recorded base followed by that exact head; its lease-admission delta retains the introduced durable verification dependency.
Still necessary on current main: Current-main documentation explicitly describes process-local verification and a fresh full check after Gateway restart. Current-main writable admission still passes remembered runtime validation rather than a durable clean-close record.
Admission and cleanup invariants: Admission durably clears cleanliness before inserting its lease. Reuse checks canonical path, device, inode, application version, and migration status; last-close publication follows checkpoint and native close. Existing maintenance and deletion authority checks remain before admission.
Findings None None.
Security None None.

How this fits together

Agent databases hold sessions, transcripts, memory indexes, and other agent state. Their admission and lifecycle owners validate storage before use, while the Gateway verifier checks databases in the background and quarantines confirmed corruption.

flowchart TD
  A[Agent database open] --> B[Lease owner consumes clean record]
  B --> C{Matching version and file?}
  C -->|No| D[Full integrity checks]
  C -->|Yes| E[Schema and ownership checks]
  D --> F[Agent database available]
  E --> F
  F --> G[Gateway background verification]
  F --> H[Last graceful close records cleanliness]
Loading

Decision needed

Question Recommendation
Should this storage change await published-updater transition evidence, or receive an explicit exception based on its released-schema and lifecycle coverage? Complete transition validation: Demonstrate the published updater activating the candidate with existing state and preserving recoverability when verification metadata cannot be written.

Why: The applicable repository policy requires that transition, and the captured PR body explicitly says it was not run; the reviewer cannot waive it.

Before merge

  • Resolve merge risk (P1) - An existing installation with an unwritable or damaged quarantine store can now lose agent admission even when its agent database is healthy; the published-updater transition and operator recovery for this dependency remain unverified.
  • Resolve merge risk (P1) - Same-inode damage after a clean close may be detected after readiness; this tradeoff is explicitly documented and accepted in the PR description.
  • Complete next step (P2) - Resolve the published-updater × candidate validation requirement with transition evidence or an explicit maintainer exception covering the new quarantine-store admission dependency.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +761, Tests +986, Docs +22, Other +4. Total +1773 across 60 files.

View PR surface stats
Area Files Added Removed Net
Source 23 891 130 +761
Tests 33 1072 86 +986
Docs 2 48 26 +22
Config 0 0 0 0
Generated 0 0 0 0
Other 2 4 0 +4
Total 60 2015 242 +1773

Review metrics

Metric Value Why it matters
Persistent storage contract 1 additive table; 0 schema-version bumps The verification cache survives restarts and makes metadata writes part of agent admission.
Production versus test growth production +761; tests/support +986; tooling +4 net lines Production growth supports durable verification, lifecycle invalidation, background checking, and backup integration.

Stored data model

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

Merge-risk options

Maintainer options:

  1. Validate the upgrade boundary (recommended)
    Cover the published-updater transition and recovery from quarantine-store write failure before relying on the new admission dependency.
  2. Accept the bounded validation gap
    A maintainer can explicitly waive the transition campaign while accepting the documented admission and delayed-detection tradeoffs.

Technical review

Best possible solution:

Keep verification reuse under the existing lease owner, with a validated updater transition and actionable recovery for verification-metadata write failures.

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

Not applicable as a correctness bug: current source confirms repeated full checks across process restarts, and the PR supplies an isolated benchmark; this read-only review executed no runtime tests.

Is this the best way to solve the issue?

Yes, the implementation fits the existing lease, verifier, and backup owners without creating competing policy owners; upgrade acceptance remains conditional on transition evidence or an explicit exception.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded restart-performance improvement without evidence of an urgent user-facing outage.
  • merge-risk: 🚨 compatibility: The new durable dirty-marker requirement can refuse previously usable installations when their quarantine store cannot be written.
  • 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: The ordinary external-contributor proof gate does not apply to this maintainer-authored PR. The reported real-schema benchmark exercises the changed integrity gate, and the inspected real-worker harness covers cached-open verification; the published-updater requirement remains a separate unresolved policy gate.

Evidence

What I checked:

  • Pinned introduction and merge result: The reviewed checkout is the pinned original head. The verified test merge has the recorded base followed by that exact head; its lease-admission delta retains the introduced durable verification dependency. (src/state/openclaw-agent-db-lease.ts:246, 7ff32998f356)
  • Still necessary on current main: Current-main documentation explicitly describes process-local verification and a fresh full check after Gateway restart. Current-main writable admission still passes remembered runtime validation rather than a durable clean-close record. Public docs: docs/reference/database-schemas/integrity-and-recovery.md. (docs/reference/database-schemas/integrity-and-recovery.md:20, f802444ee92c)
  • Admission and cleanup invariants: Admission durably clears cleanliness before inserting its lease. Reuse checks canonical path, device, inode, application version, and migration status; last-close publication follows checkpoint and native close. Existing maintenance and deletion authority checks remain before admission. (src/state/openclaw-agent-db-lease.ts:234, 0c0e3fbfc9a4)
  • Intentional new admission failure: The consuming reader propagates quarantine-store write failures instead of continuing with stale clean proof. The policy test explicitly verifies refusal after an injected dirty-marker failure and successful admission after removing that failure. (src/state/openclaw-quarantine-store.ts:91, 0c0e3fbfc9a4)
  • Released schema compatibility: The v2026.9.5 source uses quarantine schema version 2 and has no integrity-verification table. This agrees with the PR's additive-schema fixture, which asserts preservation of existing quarantine rows and version 2. (src/state/openclaw-quarantine-store.ts:18, ec9c1a13db89)
  • Relevant lifecycle coverage: Inspected tests cover clean, missing, dirty, version-mismatched, and replaced records; killed processes; aliases; failed checkpoint/native close; startup source exclusion; and background quarantine. The real-worker harness observes cached-open verification through the production native-generation and verifier owners. These tests were inspected, not executed during this review. (src/state/openclaw-agent-db.integrity-policy.test.ts:33, 0c0e3fbfc9a4)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • VACInc: 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.

  • Provide the published-updater × candidate transition evidence, or record an explicit maintainer exception.

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-20T05:56:12.213Z sha 7eb886aeec0581bbf5c2d7b2cba7852a8b513cd0 :: blocked before merge. :: none
  • reviewed 2026-09-20T07:12:54.571Z sha 96e619474acd90ddae8f2f09414c7486dd4cf7a0 :: blocked before merge. :: none
  • reviewed 2026-09-20T07:33:09.734Z sha 6e48837 :: blocked before merge. :: none
  • reviewed 2026-09-20T08:11:59.516Z sha 0c0e3fb :: blocked before merge. :: none

@steipete
steipete force-pushed the steipete/perf-micro-agent-db-integrity-gate-20260919 branch from 7eb886a to 96e6194 Compare September 20, 2026 07:05
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime extensions: memory-core Extension: memory-core agents Agent runtime and tooling labels Sep 20, 2026
@steipete
steipete force-pushed the steipete/perf-micro-agent-db-integrity-gate-20260919 branch from 96e6194 to 6e48837 Compare September 20, 2026 07:26
Keep verification records in the quarantine store and let the existing
lease owner consume clean proof and certify the last checkpointed close.
Share gate eligibility with readiness, queue quick verification after
listening, and invalidate proof across crashes, aliases, and maintenance.

The warmed 899.5 MB fixture gate falls from 1094 ms to 17.8 ms (98.4%).
Full checks remain for updates, migrations, unclean or replaced files,
Doctor, shared state, snapshot fallback, and daily verification.
@steipete
steipete force-pushed the steipete/perf-micro-agent-db-integrity-gate-20260919 branch from 6e48837 to 0c0e3fb Compare September 20, 2026 08:03
@steipete
steipete merged commit 6584af0 into main Sep 20, 2026
223 of 224 checks passed
@steipete
steipete deleted the steipete/perf-micro-agent-db-integrity-gate-20260919 branch September 20, 2026 08:50
@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 21, 2026
…enclaw#153463)

Keep verification records in the quarantine store and let the existing
lease owner consume clean proof and certify the last checkpointed close.
Share gate eligibility with readiness, queue quick verification after
listening, and invalidate proof across crashes, aliases, and maintenance.

The warmed 899.5 MB fixture gate falls from 1094 ms to 17.8 ms (98.4%).
Full checks remain for updates, migrations, unclean or replaced files,
Doctor, shared state, snapshot fallback, and daily verification.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation extensions: memory-core Extension: memory-core gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL 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