Skip to content

perf(state): trust a live Gateway owner of the shared-state file - #183379

Merged
steipete merged 2 commits into
mainfrom
steipete/state-db-peer-integrity
Oct 25, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/state-db-peer-integrity

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: every separate OpenClaw process that opens the shared-state database while the Gateway is running re-verifies the whole file. On Team (read-only, 2026-10-24/25) the 8.4 GB state/openclaw.sqlite paid this in 143 distinct processes in about 21 hours (slow SQLite transaction hold, operation: "state.admission.fast-path"): 6.4–7.3 s each, 957 s total, all SQL time. #182984 fixed the same problem for agent databases.

User Impact

User impact: on Linux, CLI commands and other processes that open the shared state database while the Gateway runs no longer pay a whole-file integrity scan; on large installs that is several seconds per process. macOS and Windows behave as before.

Why This Change Was Made

The first revision tried to borrow the Gateway's completed integrity receipt. A Linux end-to-end run showed it never fired: at listening, the Gateway holds no completed proof for the live state file, because its startup inspection verifies a private snapshot copy. The maintainer chose to trust a live owner instead.

  • Publication. At markListening(), after startup admission, the Gateway publishes stateDatabaseProvenance in its existing owner-lease payload update. The value comes from the existing readAgentDatabaseLeaseProvenance helper, which binds host, boot id, PID namespace, build, and dev:inode, and is null off Linux.
  • Borrowing. In the fast path's existing read transaction, a different process skips only the integrity scan when the owner lease is live per the existing PID/start-time reader and the provenance equals its own view of the file.
  • Still checked. Schema shape, version and legacy-repair checks still run.
  • Borrowers never seal. The borrower records no verification and never writes a clean-close seal, so a later opener still verifies.
  • Corruption detection. Corruption still surfaces through normal SQLite access, Doctor, explicit verification, and the next startup without a reusable seal.
  • Footprint. No new table, schema, config or environment variable. The payload decoder is already lenient, and no strict reader of this payload exists (repo-wide search including apps/ and native code).

Production TypeScript: net −4 lines versus the first revision (the receipt condition and its imports are removed).

Evidence

Linux end-to-end on the Team perf sandbox (isolated Gateway on a loopback port, synthetic 2.16 GB state DB, separate pnpm openclaw agents list --json, 3 runs per cell, statement observer with stacks):

Revision Gateway Median wall Whole-DB integrity_check in the CLI process
base 5ba28c2 running 4.269 s one, 3/3
base stopped 4.320 s one, 3/3
head 98001fd running 4.070 s zero, 3/3
head stopped 4.270 s one, 3/3
  • Scans came only from openclaw-state-db-fast-path.ts → sqlite-integrity.ts:332. The existing-schema and existing-write paths did not scan.
  • All three live-head provenance values matched.
  • On this fixture the scan costs about 0.2 s because the bulk is a few large rows. On Team-shaped data (7M indexed rows) the logged cost is 6.4–7.3 s per process.

Tests:

  • src/state/openclaw-state-db.integrity-lease.test.ts (8) runs through the real openOpenClawStateDatabase path. A live matching peer gives 0 scans. Each of these still scans once: no lease, dead peer, changed start time, different inode, same process, missing provenance. The borrower leaves no receipt and no seal.
  • src/infra/gateway-owner-lease.test.ts (41) now publishes from the real startup order (preflight → lease → listening). It is red with the old receipt condition and green here.
  • openclaw-state-db-fast-path.test.ts (6) and openclaw-state-db-checkonce.test.ts (11) pass.
  • pnpm tsgo:core, changed-file oxlint, oxfmt --check, git diff --check: pass.
  • Codex autoreview (P1): scoped-clean on both revisions.

CI note: src/cli/gateway-diagnostics-opens.process.test.ts (an extra :memory: open from #183120's probeSqlite) and test/canonical-descendant.integration.test.ts fail identically on unchanged origin/main 3db36fc.

Not changed

Migrations, repair, Doctor, explicit verification, quarantine and seal policy. Other cold whole-scan entry points (existing-schema readers, one-shot writers, startup checkpoint/bootstrap) are separate borrowing points and keep their behavior.

Release note context: on Linux, CLI and other processes that open the shared state database while the Gateway runs no longer re-verify the whole file.

Every separate process that admitted the shared-state database while the
Gateway held it ran a whole-database integrity scan in the fast path. On
Team's 8.4 GB state database that was 143 processes in about 21 hours at
6.4-7.3 s each (957 s), the shared-state sibling of #182984.

The Gateway now publishes Linux file provenance in its owner lease when it
marks itself listening while holding a completed verification receipt. A
different process skips only the integrity scan when the owner is live
with a matching PID start time and the provenance matches its own view of
the file. Schema, version and legacy-repair checks still run, and the
borrower records no verification, so it can never write a clean-close
seal.
@clawsweeper

clawsweeper Bot commented Oct 25, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T20:34:41.107433Z 98001fd Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 25, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR lets Linux processes reuse a live Gateway’s completed shared-state integrity verification while retaining schema and ownership checks.

Example: A separate CLI process opens an 8.4 GB shared-state database held by a Linux Gateway.

  • Before: Each cold fast-path admission repeats a full integrity scan, reported as taking 6.4–7.3 seconds.
  • After: A matching live Gateway receipt skips that scan while schema checks still run.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The patch is focused and source review found no definite defect, but the supplied harness evidence does not replace proof through the changed shipped path.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Separate CLI processes repeatedly wait for a full scan of a large shared-state database already verified by the running Gateway.
Reason: The reported recurring cost has a matching source path, and the maintainer-authored direction removes duplicate work without introducing another owner or configuration surface.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a concrete shared-state performance cost that remains on main, and no definite introduced code defect was found. The failing CI checks remain unattributed.

Priority: P2
Reviewed head: 1507f8f82050b782bc16e5920b32f558da31f6fd

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The promised isolated Linux Gateway plus separate CLI run must show real receipt publication and scan avoidance; the reported red-on-base test result does not establish that shipped flow.
Agent review details

How this fits together

Shared-state admission sits between native SQLite opening and usable database handles; it validates schema and integrity before callers perform state operations.

flowchart TD
  A[Gateway verifies SQLite] --> B[Owner lease publishes provenance]
  C[Separate process opens SQLite] --> D[Validate schema and version]
  B --> E[Match live owner and file]
  D --> E
  E --> F[Reuse integrity admission]
  E --> G[Otherwise run full scan]
Loading

Technical review

Best possible solution:

Reuse the existing Gateway lease and physical-verification owner while preserving full checks for unmatched peers and preventing borrowers from sealing unverified state.

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

Current-main source shows the redundant integrity call for a cold process without shared admission, and the report identifies the matching operation in production; this read-only review did not execute a reproduction.

Is this the best way to solve the issue?

The patch is a focused implementation using existing owners: publish completed verification through the current lease, borrow only for a matching live peer, and leave schema validation and fallback verification intact.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared-state fast-path integrity verification changes intended behavior with a stated reason (06d231d: Preserve completed integrity verification across startup index repair and later worker admission without repeating scans.)
  • Gateway listening payload publication keeps the original intent (bb8e463: Publish listening state through an owner-qualified update while retaining existing transaction and custody ownership.)
  • Lock-free current-schema admission keeps the original intent (89e2d43: Inspect healthy current state in a deferred read snapshot rather than entering the SQLite writer queue.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit bb7d32e adds src/state/openclaw-state-db-fast-path.ts:95 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: bb7d32e55d48; files: src/state/openclaw-state-db-fast-path.ts)
  • Jason O'Neal: Raw commit 89e2d43 adds src/state/openclaw-state-db-fast-path.ts:25 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 89e2d430953a; files: src/state/openclaw-state-db-fast-path.ts)

PR surface

Source +22, Tests +114, Docs +8. Total +144 across 8 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 4 29 7 +22
Tests 3 115 1 +114
Docs 1 17 9 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 161 17 +144

Review metrics

Metric Value Why it matters
Production versus test changes Production TypeScript +29/−7; tests +114/−1 The small production addition reuses existing owners, and the tests cover distinct admission and clean-close boundaries.

Labels

Label changes:

  • add P2: Repeated cold-process scans impose a concrete delay on large shared-state databases, with limited impact on already-admitted handles.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Repeated cold-process scans impose a concrete delay on large shared-state databases, with limited impact on already-admitted handles.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Attach the promised redacted Linux Gateway and separate CLI result.

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.

Reviewed October 25, 2026, 3:25 AM ET / 07:25 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Converting to draft: a real-product Linux end-to-end run shows this does not remove the scan yet.

Run on the Team perf sandbox: a synthetic 2.16 GB shared-state DB, an isolated Gateway, and a separate pnpm openclaw agents list --json process, 3 runs per cell.

Revision Gateway Median wall Whole-DB integrity_check in the CLI
base 5ba28c2 running 4.27 s 3/3
base stopped 4.27 s 3/3
head 1507f8f running 4.37 s 3/3
head stopped 4.32 s 3/3

Every scan comes from openclaw-state-db-fast-path.ts → sqlite-integrity.ts:332. The live Gateway's owner lease carried stateIntegrityProvenance: null every time.

Root cause, from a follow-up probe of a real programmatic Gateway startup: at markListening() the Gateway itself holds no completed integrity proof for the live state file. There is no sqlite.full-verification receipt, no state.integrity fact, and the shared proof cell is -1. Its startup inspection verifies a private snapshot copy (openclaw-database-preflight.ts:345-360), not the live file. So there is nothing correct to publish, and the unit tests passed only because they hand-insert a lease row with provenance.

Making this work needs a design decision first. Either the Gateway records a live-file proof it can share, or a live Gateway owning the exact file becomes enough for a CLI process to skip its own scan. Until then this stays a draft.

CI note: src/cli/gateway-diagnostics-opens.process.test.ts (an extra :memory: open from the new probeSqlite in #183120) and test/canonical-descendant.integration.test.ts both fail identically on unchanged origin/main 3db36fc, so they are not caused by this PR.

The Linux end-to-end run showed the receipt condition never fired: at
listening the Gateway holds no completed integrity proof for the live
state file, because startup verifies a private snapshot. Publish the
owner's exact-file provenance at listening instead, after startup
admission, and let a different process with matching provenance and a
live owner PID/start time skip only its whole-file integrity scan.
Borrowers still record no verification and never seal.
@steipete steipete changed the title perf(state): reuse a live Gateway's shared-state integrity admission perf(state): trust a live Gateway owner of the shared-state file Oct 25, 2026
@steipete
steipete marked this pull request as ready for review October 25, 2026 20:32
@steipete
steipete enabled auto-merge (squash) October 25, 2026 20:51
@steipete
steipete merged commit 26fc0d7 into main Oct 25, 2026
260 of 261 checks passed
@steipete
steipete deleted the steipete/state-db-peer-integrity branch October 25, 2026 20:56
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
…nclaw#183379)

* perf(state): reuse a live Gateway's shared-state integrity admission

Every separate process that admitted the shared-state database while the
Gateway held it ran a whole-database integrity scan in the fast path. On
Team's 8.4 GB state database that was 143 processes in about 21 hours at
6.4-7.3 s each (957 s), the shared-state sibling of openclaw#182984.

The Gateway now publishes Linux file provenance in its owner lease when it
marks itself listening while holding a completed verification receipt. A
different process skips only the integrity scan when the owner is live
with a matching PID start time and the provenance matches its own view of
the file. Schema, version and legacy-repair checks still run, and the
borrower records no verification, so it can never write a clean-close
seal.

* perf(state): trust a live Gateway owner of the exact shared-state file

The Linux end-to-end run showed the receipt condition never fired: at
listening the Gateway holds no completed integrity proof for the live
state file, because startup verifies a private snapshot. Publish the
owner's exact-file provenance at listening instead, after startup
admission, and let a different process with matching provenance and a
live owner PID/start time skip only its whole-file integrity scan.
Borrowers still record no verification and never seal.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S 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