Skip to content

perf(sqlite): reuse database validation after clean shutdown - #169649

Merged
steipete merged 25 commits into
mainfrom
steipete/perf-micro-db-seal-file-20260919
Oct 13, 2026
Merged

steipete merged 25 commits into
mainfrom
steipete/perf-micro-db-seal-file-20260919

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Clean Gateway restarts repeat database snapshot, readiness, schema, and integrity inspection after the previous owner cleanly closed unchanged files.

User Impact

A matching clean-close seal reuses completed validation at startup. Missing, torn, stale, or nonmatching seals retain full validation. Doctor and explicit verification keep their checks. No configuration option, database schema migration, or operator action is required.

Why This Change Was Made

Database admission owns a small checksummed <database>.seal file. A successful TRUNCATE checkpoint and native close publish only completed validation facts; the first subsequent write unlinks the seal. Reuse requires matching device, inode, stable birthtime, size, nanosecond mtime, empty journals, schema/version and loaded-commit identity, and a full verification no more than seven days old. Clean close and worker adoption never advance that timestamp.

The same lifecycle covers cached shared-state release, disposable startup-checkpoint connections, native close and lease cleanup. Retaining the admission generation through final-reference retirement prevents an idle close from creating a successor generation that permanently caches a miss. Worker handoffs carry current revocation and physical-file identity. Source and compiled workers use the loaded commit in the fingerprint, so equivalent builds can share proof; build ID remains the conservative fallback without commit provenance.

Restored requester wakes join their known agent's startup preparation before reading or reserving delivery, then recheck source and abort authority. Canonical invalidation republishes current receipts only when the owner already holds physical integrity proof; a canonical-only handoff cannot acquire integrity admission. These cutovers replace the former quarantine-backed runtime receipts and deferred unverified-admission path.

Doctor, migration, repair, backup, restore, and deployment/update owners retain their checks. Replaced or restored files cannot reuse predecessor seals. Both database reference pages document the ownership and maintenance behavior.

A plain seal write is sufficient: torn writes fail parsing/checksum; a database write surviving a lost unlink changes metadata or leaves WAL. If both unlink and writes are lost, the database remains at the sealed state. Silent corruption preserving all checked metadata is the accepted limit, caught by normal access or periodic full verification.

Evidence

Current head is 524c1f8299da6321242512e1a46f281f6b80c4c5, rebased onto 6dbbb5925efd24e61d7b44637afc12f79eb0ace2 to resolve a concrete conflict after main independently landed the same reader-order fixture repair. All 25 lane commits remain; production patches are preserved and the final conflict resolution changes one explanatory comment. Fresh reclamation proof passes 17/17 (245.32 s wall), with scoped format and diff checks passing. Independent production and fixture reviews are clean through P2; the mechanical rebase retains their reviewed patches.

Exact-head CI run 38379496638, attempt 1, completed: 133 successful jobs, 20 skipped, eight failed test jobs plus the aggregate. Actual tested merge c80bfd525794f8a2db98a5d66d4c982f88a517fa has ordered parents main 04c459451a8b10074ddcae554a09e23e1c570a45 and the PR head. Retained checkout logs, Git objects and independently derived merge tree agree. Every failed log was fetched once. All failed jobs are independently attributed to inherited defects or deadlines; failed CI is not claimed green.

Failure group Classification and proof
Auth recovery Inherited: Linux candidate/base controls reproduce the same credential-write owner contention; relevant failing write path remains unchanged.
Session-end shutdown Inherited: Linux controls reproduce [null, "SIGKILL"] rather than [0, null] at the same exit assertion.
Hook concurrency Inherited: unchanged baseline reproduces nine accepted responses where the fixture expects eight.
CLI recovery Inherited: candidate/base reproduce legacy executable/missing-marker and undefined compile-cache marker assertions.
Incomplete stream Inherited: scheduled-main run 38378024699, job 115231440064, reproduces all four missing assistant.stopReason assertions at line 218. Test and projection blobs match actual CI main and tested merge.
Refusal history Inherited: exact current candidate and actual CI main parent both produce three missing initial-refusal history assertions at line 237, with the retryable case passing. Files take 166.114 / 166.416 s wall. Main changed terminal failure-notice projection; these tests still expect host copy in assistant history.
Provider review Inherited: actual CI main parent reproduces the same extra failure-notice user item at line 524 (25.034 s case / 182.247 s wall). The acknowledged steer is preserved; later device-revocation assertions are not reached. Main's custom terminal report is replayed as a synthetic user message. Exact canonical Linux build outputs were reused for this focused local comparison; no local runtime build ran.
LINE Doctor Inherited cold-start deadline: both current candidate/main-parent files fail the first case after 30 seconds with UI build completion in captured output; the other five cases pass. Files take 117.351 / 109.629 s. Controls use missing generated UI assets, a fresh compile cache and eight CPUs, matching the observed CI runner. Warm controls pass 6/6 on both revisions; this state dependence is retained, not claimed fixed. Final output does not identify the precise blocked Doctor suboperation.
Restart handoff Inherited persisted-state defect: original and warm files on both revisions stop earlier at the same SIGKILL exit assertion. A read-only observation before that unchanged assertion independently finds six interrupted/aborted rows, five valid recovery markers and one missing mainRestartRecovery on both revisions—the same missing field as CI line 373. No assertion or production code was changed; original files were restored. This does not establish a clean exit or successor recovery in the sandbox.

The hook and handoff cases share one failed job. The aggregate fails only the group containing these eight root jobs; security and every other selected group pass. The native inherited-failure packet binds all jobs, source inputs and hashed evidence to the exact head and tested merge. Upstream-fixed membership and older failures that no longer recur are not carried as exceptions.

The three requested files ran individually on both exact revisions in the authorized isolated Linux sandbox. Node 24.19.0 and pnpm 12.9.0 were used, with CPUs 64–127 and 64 GiB memory limit, low CPU/I/O priority and synthetic state only. Frozen installs pass in 3.342 / 3.361 s; canonical private-QA runtime preparation passes in approximately 75 s each. Runtime artifact hashes and clean tracked checkouts are preserved. No Testbox/Crabbox lease or CI rerun was used.

Focused tests and review

Proof Result
Clean-close seal, agent worker store, and native execution integrity files 59 passed, 1 platform skip in the initial four-file run; that run took 162.537 s and separately exposed the stale lease assertions below
pnpm test src/state/openclaw-agent-db.integrity-lease.test.ts --maxWorkers=1 after correcting the assertions 23 passed, 71.922 s
Full rebased production review No actionable production finding; identified the stale test assertions, now corrected. Scoped review of the staged correction is clean through P2; all findings are resolved

The initial four-file run had four failures, all from the three remaining calls to the removed test helper. Those failures were fixed, not classified as inherited. The other three files completed successfully and were not rerun without a changed input.

Final CI fixture repairs: idle-reopen reproduced its obsolete one-catalog-scan assertion locally (10 pass / 1 fail, 112.943 s), while unchanged base passed all 11. The corrected file asserts a valid seal after idle close and zero validation SQL on reopening: 11 passed, 124.765 s. The reclamation fixture now checks joined native retirement and its clean seal before admitting its extra retained reader; the deleted-row assertion is preserved. It passes all 17 cases in 299.41 s. The original reclamation file also passed locally, so the precise CI timing cause remains unverified; this is a bounded fixture-order correction, not a claimed deterministic product fix. Focused format/lint and independent review of both corrections pass through P2.

The final raw-database fixture repair awaits owner retirement and revokes the exact database admission before each external schema mutation. All existing assertions remain: 25 passed in 226.51 s (Vitest 182.94 s), with format, focused lint, and independent review clean through P2. Both original candidate and unchanged base passed locally, so the precise CI timing was not reproduced; the change repairs the fixture's invalid lifecycle instead of weakening its assertion.

Final-head restart measurement

One matched no-seal/clean-hit pair on the isolated Linux rig used exact pushed head 524c1f8299da6321242512e1a46f281f6b80c4c5, six synthetic databases totaling 1,086,480,384 bytes (1.01 GiB), and the same ten-second post-ready observation and joined clean shutdown. Canonical schema/version contracts were unchanged from the already-warmed v22 fixture, so no additional migration warm-up was needed. Frozen install passed in 3 s, canonical CLI preparation in 95 s, and the measured pair in 46 s.

Metric No seals Seal hit
Ready wall 12,940.6 ms 11,379.4 ms
Child total CPU 52.137 s 40.989 s
State snapshot 2,140.4 ms 1,149.4 ms
Database readiness 654.5 ms 46.1 ms
Schema preflight 552.8 ms 6.1 ms
Session admission 607.3 ms 656.8 ms
Schema inspections / agent integrity gates 5 / 5 0 / 0

This pair saved 1,561.2 ms / 12.06% to ready and 11.148 s / 21.38% of child CPU. It misses the estimated 6.5-second boot reduction. This is one controlled pair, not a statistical estimate or pure attribution of all CPU savings. Earlier pairs varied in wall savings (the e2c pair was only 0.22% faster to ready while using 18.98% less CPU), so this is not a stable wall-time guarantee. Phase durations overlap and must not be summed.

Both children ran pnpm openclaw gateway run --bind loopback --port 19578 --tailscale off with task-owned synthetic state and TMPDIR, and exited 0. All six seals were valid after close; full-verification timestamps stayed unchanged on the hit. No post-ready verifier was observed. Runtime artifact SHA256, size and nanosecond mtime were preserved, the instrumented driver was restored, and the rig has no owned runtime processes. Earlier lifecycle proof covers kill-9 restart, torn seal, external modification, schema-identity change and stale interval. Production services and data were untouched.

Linux failure attribution and historical CI

Fresh exact-revision Linux controls compare e2c5937 with unchanged base c146b99c. The two test files are byte-identical between them:

File Candidate Unchanged base Observed failure
src/gateway/gateway-auth-recovery.test.ts 1 pass / 1 fail, 109.140 s 1 pass / 1 fail, 110.880 s Same GatewayStateOwnerContentionError at credential replacement, line 286: the fixture writes credentials outside the running Gateway owner
test/gateway-session-end-shutdown.e2e.test.ts 1 fail, 31.853 s 1 fail, 31.736 s Same line-131 exit assertion: [null, "SIGKILL"] instead of [0, null] after SIGTERM during the synthetic session-end hook

These controls establish inherited failures on the cited revisions, not passing tests. They used Node 24.19.0, pnpm 12.9.0, CPUs 64–127 and a 64 GiB limit in an explicitly authorized isolated Linux sandbox. Frozen install passed in 5.490/5.511 s; canonical private-QA runtime preparation passed in 126.455/124.614 s. A disposable network-isolated container prepared the runtimes; tests ran directly on the host with OPENCLAW_E2E_USE_PREBUILT_DIST=1, CI portable compile-cache settings and an 8 GiB Node heap. Exact head/tree, clean tracked checkout, and runtime artifact hashes were preserved; final scope was inactive and runtimes idle. No Testbox/Crabbox lease was used.

Production-size exception: the requested non-test/non-doc filter is +239 lines (1,113 added / 874 deleted); runtime source excluding test support is +132. The seal codec, worker physical-identity custody, and repair/restore invalidation preserve the required integrity contracts. The old receipt store and deferred-unverified path are removed; one admission lifecycle owns reuse and invalidation.

@clawsweeper

clawsweeper Bot commented Oct 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 gateway Gateway runtime scripts Repository scripts commands Command implementations agents Agent runtime and tooling size: XL labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR persists file-bound validation seals so clean Gateway restarts can reuse completed SQLite checks.

Example: Restart six unchanged synthetic databases totaling about 1.01 GiB.

  • Before: The reported no-seal run repeats validation and consumes 51.349 seconds of child CPU.
  • After: Matching seals reuse validation and reduce child CPU to 40.229 seconds in the reported matched pair.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful owner-directed work with credible Gateway performance evidence and no actionable code findings; compatibility and current-head validation remain incomplete.
Proof confidence 🐚 platinum hermit (4/6) The maintainer-authored ordinary-proof exemption applies; the full PR body supplies a final-head Linux Gateway no-seal/clean-hit comparison over six synthetic databases with matching seal guards, but does not establish latest-stable upgrade preservation.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Clean Gateway restarts spend CPU and startup time inspecting unchanged databases that previously closed successfully.
Reason: The feature owner supplies direction, measured resource savings, and explicit acceptance of the seal's failure-model limits.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this owner-directed performance PR open: it provides distinct restart optimization absent from main, and no concrete introduced code defect was found.

Priority: P2
Reviewed head: 5ce08f1025c4c9661e1336f5f002df8be4e3ba88

Before merge

Findings

None.

Tests

  • Missing end-to-end proof: Provide a v2026.10.2-to-candidate upgrade preserving settings, sessions, and quarantine decisions, followed by clean restart and first-write seal invalidation, with private data redacted.
Agent review details

How this fits together

Physical database admission supplies shared validation facts to Gateway startup and workers; native-close owners persist eligible facts, and writers invalidate seals before mutation.

flowchart TD
  A[Gateway startup] --> B[Physical database admission]
  C[Database and seal] --> B
  B --> D[Shared validation facts]
  B --> E[Full validation on miss]
  E --> D
  D --> F[Database workers]
  F --> G[Checkpoint and native close]
  G --> C
Loading

Technical review

Best possible solution:

Keep restart reuse in the existing physical admission owner while preserving independent maintenance, quarantine, and live write-authority checks.

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

Current-main source retains repeated restart validation, and the supplied shipped-Gateway comparison exercises the avoided work; this read-only review performed no independent runtime reproduction.

Is this the best way to solve the issue?

Extending physical admission and removing superseded receipt and deferral paths is coherent, with the changed failure model explicitly recorded by the feature owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Reported Gateway resource benefit 21.66% lower child CPU; 9.04% lower readiness wall time One matched synthetic pair supports reduced validation cost, without establishing a statistical performance estimate.
Persisted validation contract Version-1 seal; eight eligible fact keys; seven-day verification age Reconstructible validation crosses restart without adding a user setting or changing database schema versions.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Useful restart performance work with measured resource savings and no established urgent deployed regression introduced by this PR.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 (8 earlier review cycles)
  • reviewed 2026-10-12T05:57:33.451Z sha 70cb7fd29798b3c2baffbeecb7e1df2b38dcf99a :: blocked before merge. :: [P2] Import the exported seal schema constant in the restart test
  • reviewed 2026-10-12T06:28:49.879Z sha 96dd98d :: blocked before merge. :: [P2] Carry integrity revocation through reclamation admission | [P2] Remove the unused schemaAdmission import
  • reviewed 2026-10-12T08:55:49.617Z sha 4e6528c8255da6c5ac7d8216870e75545ace1fcf :: blocked before merge. :: none
  • reviewed 2026-10-12T09:27:24.366Z sha dff0701 :: blocked before merge. :: [P2] Use the SDK export for QA Lab record coercion
  • reviewed 2026-10-12T10:01:26.666Z sha 398b25e :: blocked before merge. :: none
  • reviewed 2026-10-12T10:45:33.907Z sha f785e84 :: blocked before merge. :: none
  • reviewed 2026-10-13T00:01:24.459Z sha 109261798c6ea9f05e670e9ebaaff86f8965922d :: blocked before merge. :: [P2] Remove the deleted parameter from the remaining native-generation caller | [P2] Break the seal module's import cycle through schema admission | [P2] Establish verification after constructing the Doctor repair fixture | [P2] Update remaining restart fixtures to distinguish seal hits from cold admission
  • reviewed 2026-10-13T03:14:22.472Z sha 144aa441d39451edc269303be20a95565650ad99 :: blocked before merge. :: none

Reviewed October 12, 2026, 11:46 PM ET / October 13, 2026, 03:46 UTC (Revision 9).

@steipete
steipete force-pushed the steipete/perf-micro-db-seal-file-20260919 branch from 70cb7fd to 96dd98d Compare October 12, 2026 06:13
@steipete
steipete marked this pull request as ready for review October 12, 2026 06:20
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed 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. labels Oct 12, 2026
@steipete
steipete force-pushed the steipete/perf-micro-db-seal-file-20260919 branch 2 times, most recently from 1fca91c to b869cdc Compare October 12, 2026 09:15
@clawsweeper clawsweeper Bot added 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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@steipete
steipete force-pushed the steipete/perf-micro-db-seal-file-20260919 branch from dff0701 to 398b25e Compare October 12, 2026 09:42
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 12, 2026
@steipete
steipete force-pushed the steipete/perf-micro-db-seal-file-20260919 branch from 398b25e to f785e84 Compare October 12, 2026 10:12
@steipete
steipete force-pushed the steipete/perf-micro-db-seal-file-20260919 branch from c8933dc to 524c1f8 Compare October 13, 2026 09:52
@steipete
steipete merged commit f787a89 into main Oct 13, 2026
234 of 244 checks passed
@steipete
steipete deleted the steipete/perf-micro-db-seal-file-20260919 branch October 13, 2026 11:09
@steipete

Copy link
Copy Markdown
Contributor Author

Landed as f787a896894d52b7351b841416b194711315ac28 with the reviewed head pinned to 524c1f8299da6321242512e1a46f281f6b80c4c5 and the authorized inherited-failure exception. Native preparation and live admin/review/security/evidence verification passed. Two native attempts stopped before dispatch; the guarded synchronous squash fallback succeeded.

CI run 38379496638 attempt 1 completed with 133 successful jobs, 20 skipped, eight inherited test-job failures and their aggregate. The PR body records baseline evidence for auth recovery, shutdown, hook concurrency, CLI recovery, incomplete streams, refusal history, provider review, LINE Doctor, and restart handoff. The three final files were compared individually against actual CI main parent 04c459451a8b10074ddcae554a09e23e1c570a45; the handoff persisted-field observation and cold/warm Doctor limitations remain explicit. Failed CI is not claimed green.

The final controlled synthetic benchmark measured readiness at 12.9406 → 11.3794 seconds and child CPU at 52.137376 → 40.989323 seconds, with startup inspections/integrity checks 5 → 0. This is one controlled pair; the 6.5-second target was missed.

steipete added a commit that referenced this pull request Oct 13, 2026
The raw-corruption fixture kept the successful admission and clean-close
seal introduced by f787a89 (#169649). Revoke those facts before changing
the schema marker, matching the neighboring corruption fixtures.

Keep both schema rejection and database-byte preservation assertions.
Production admission behavior is unchanged.

Diagnosed in scheduled main run 38423359339, compact-small19.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…w#169649)

* perf(sqlite): reuse clean-close validation from adjacent seals

Publish checksummed file seals after TRUNCATE and native close. Restore physical admission facts once, revoke before writes, and retain explicit host refusals across worker handoff. Remove quarantine-backed runtime receipts and deferred admission while preserving the released quarantine schema.

* refactor(sqlite): separate seal persistence and native close lifecycle

* fix(sqlite): seal cached state after final lease release

* fix(sqlite): bind reused integrity proof to the opened file

* test(sqlite): use the exported restart seal identity

* fix(state): preserve sealed reads and revoked worker admission

* docs(sqlite): align seal recovery with native update ownership

* fix(qa): use the SDK record coercion boundary

* test(sqlite): isolate Bun cache from ownership snapshots

* test(sessions): exercise cold worker revocation and retirement

* fix(sqlite): preserve seals across final metadata retirement

* fix(sqlite): align seal reuse with worker startup and native close

Share commit-bound seal fingerprints across source and compiled workers.
Preserve healthy delegated close publication, await requester startup before
restored delivery claims, and update the affected ownership fixtures.

* fix(sqlite): preserve clean-close proof through owner handoffs

* refactor(sqlite): share admission lookup and seal disposal state

* fix(sqlite): check file generation before reusing startup seals

* fix(sqlite): retain current validation facts during readonly adoption

* fix(sqlite): preserve canonical revocation in clean-close seals

* test(qa): keep native settlement fixture unchanged

* test(state): make cold seal admission fixtures explicit

* refactor(sqlite): tidy execution authority rebase

* test(sqlite): invalidate raw fixtures and await owner cleanup

* test(sqlite): join cleanup before removing fixture state

* test(sqlite): assert seals in native close checkpoint cases

* test(sqlite): align idle and drain assertions with clean seals

* test(sqlite): retire owners before raw fixture mutation
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
The raw-corruption fixture kept the successful admission and clean-close
seal introduced by 2cb03c2 (openclaw#169649). Revoke those facts before changing
the schema marker, matching the neighboring corruption fixtures.

Keep both schema rejection and database-byte preservation assertions.
Production admission behavior is unchanged.

Diagnosed in scheduled main run 38423359339, compact-small19.
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: qa-lab gateway Gateway runtime P2 Normal backlog priority with limited blast radius. 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.

1 participant