Skip to content

fix: CLI runs stall for minutes scanning an agent database the Gateway already opened - #182984

Merged
steipete merged 1 commit into
mainfrom
steipete/gateway-sql-performance-a1b557
Oct 24, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/gateway-sql-performance-a1b557

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: CLI processes such as openclaw agent exec (used by the Auto Review tool for every pass) spend up to several minutes in a full SQLite integrity_check when they open an agent database that the running Gateway already holds.

User Impact

Auto Review passes and other CLI commands that open a large, Gateway-held agent database start in seconds instead of waiting minutes, and the Gateway no longer stalls on its own rescans after one of those processes is killed mid-open.

Why This Change Was Made

When the Gateway holds a lease on an agent database, any second process opening the same file was refused reuse of integrity proof (integrityGateReason=lease-class) and ran a full scan. A live process that already finished admitting that exact file has verified it, and a second process rescanning a file the Gateway is actively writing adds no protection.

Now a claimant reuses that admission when another lease on the exact same path has completed admission and its PID start time still matches. Schema and canonical-index validation still run. Migrations, alias paths, unfinished admissions, and stale or revoked leases keep the full check. Doctor and updater quick-check handles hold the maintenance lease, which refuses all lease claims, so they cannot lend admission.

Named edge case: the borrowing process never verified the file itself, so if it is the last process to close it does not publish a clean-close seal, and the next opener runs one full check. That is still strictly fewer scans than before, where every borrower scanned at open. Documented in docs/reference/database-schemas/integrity-and-recovery.md.

Evidence

Production (OpenClaw Team Gateway, 2026.10.7, read-only log analysis, 2026-10-24): the main agent database is 43 GB. Auto Review's agent exec passes produced 97 lease-class full scans totaling 7,465 s that day (about 2.1 hours), 50–321 s per open. Two of those processes were killed mid-scan; their unfinished leases then forced Gateway-side stale-lease-full rescans (4 scans, 280 s total, one 89 s scan that stalled all of that agent's sessions for about 55 s).

Local reproduction through the real entry point: isolated dev Gateway on this branch's base, main agent database grown to 1.98 GB with synthetic rows, a synthetic API-key profile so agent exec reads the agent database the same way production does.

Build Separate agent exec open of the Gateway-held agent DB
main (52068cf86d6) integrityGateReason=lease-class, mode=full, 967 ms integrity scan
this PR Opens the same file (confirmed with lsof), no integrity gate event, no slow-open warning

Scan time scales with file size, which matches the minutes observed at 43 GB.

Tests:

  • New reuses a live peer process admission instead of rescanning the file (real child process holds the database): fails on main with integrityGateOutcome: "healthy" (a full scan ran), passes with the fix. It also asserts that a borrower closing last publishes no seal.
  • New lease unit cases: an admitted live peer lends admission; a peer with unfinished admission or on an alias path does not.
  • openclaw-agent-db.integrity-lease, openclaw-agent-db-lease, openclaw-agent-db.integrity-cache, openclaw-agent-db.open-timing, server-close.agent-databases, and sqlite-integrity suites pass. The existing clean-close test now has its last closer verify the file itself, since a borrower intentionally cannot certify it.
  • tsgo:core and the core oxlint shard pass; independent Codex review (P0–P2) was scoped-clean.

Not covered: the effect on the production Gateway itself, which needs this change deployed and the same log query repeated.

A second process that opens an agent database the Gateway already holds
no longer runs a full integrity_check. When another lease on the exact
path has completed admission and its PID start time still matches, the
claimant reuses that admission and keeps schema and index validation.
Migrations, alias paths, unfinished admissions, and stale or revoked
leases still take the full check. The borrower records no verification,
so closing last leaves the next opener to verify instead of sealing.

On Team, autoreview's agent exec runs hit this on the 43 GB roboclaw
store: 97 lease-class scans totaling 7,465 s on 2026-10-24 (max 321 s
per open), and kills mid-scan forced Gateway-side full rescans.
@clawsweeper

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

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 🔄 Running since 2026-10-24T22:40:19.605032Z b537fd5 PR opened
ℹ️ 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 24, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. 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: 🦪 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

Reuse a live peer process’s completed agent-database admission instead of repeating an integrity scan.

Example: A separate agent exec process opens a 1.98 GB database already held by an isolated Gateway.

  • Before: The reported baseline performs a 967 ms full integrity scan with reason lease-class.
  • After: The reported candidate opens the database without an integrity gate or slow-open warning.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful, focused performance repair with reported production-entry-point evidence, but the new reuse predicate weakens physical-file integrity admission.
Proof confidence 🐚 platinum hermit (4/6) The maintainer-authored PR is outside the ordinary contributor proof gate; its complete body reports isolated Gateway and real agent exec results on a synthetic 1.98 GB database, supported by a red-on-base child-process regression.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: CLI commands repeatedly wait for large database scans even while a live Gateway already holds an admitted database.
Reason: The supplied measurements establish substantial user-visible cost, and the maintainer-authored direction removes redundant work without introducing configuration or another owner.

Merge readiness

⛔ Needs changes before merge - 1 item remains

This PR addresses a measured CLI stall, but borrowed admission is not bound to the physical file the peer verified.

Priority: P1
Reviewed head: b537fd572052cc44e69390df3bdaeef5ac637b6c

Before merge

  • Bind borrowed admission to the peer’s physical database (P2) - On systems allowing rename over an open file, keep the admitted child process alive, replace its database pathname with a current-schema copy containing physical index corruption, then open that path in a fresh process. The child still satisfies all four conditions here, although it holds the old inode. The fresh process has no local revoked validation, so openclaw-agent-db.ts passes liveOwnerAdmitted into the integrity gate and skips checking the replacement. Schema and index-definition validation do not detect corrupted index contents. This breaks the existing same-path replacement invariant exercised in openclaw-agent-db.integrity-cache.test.ts. Establish that the peer’s admission covers the claimant’s physical file through the existing identity/provenance owner, and retain full verification when that match cannot be established.

Findings

  • [P2] Bind borrowed admission to the peer’s physical database — src/state/openclaw-agent-db-lease.ts:234-238

Tests

  • Missing end-to-end proof: The supplied child-process coverage does not replace the pathname while its original admitted peer remains alive and require rejection of a physically damaged replacement.
Agent review details

How this fits together

The agent database opener claims a shared-state lease, validates SQLite storage, and exposes an admitted connection; lease and validation owners govern reuse and clean-close certification.

flowchart TD
  A[Gateway or CLI] --> B[Agent database opener]
  B --> C[Shared-state lease owner]
  C --> D[Peer admission decision]
  D --> E[Schema and integrity gate]
  E --> F[Admitted database connection]
  F --> G[Close and seal owner]
Loading

Technical review

Best possible solution:

Reuse peer admission only when existing identity or provenance owners establish that it covers the claimant’s physical file, retaining full verification otherwise.

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

Current-main source forces fresh foreign-process opens through integrity verification, matching the supplied real-entry-point comparison; no target code was executed during this review.

Is this the best way to solve the issue?

Removing redundant scans through the existing lease owner is appropriately scoped, but path equality cannot substitute for the physical-file binding already required by admission.

Full review comments:

  • [P2] Bind borrowed admission to the peer’s physical database — src/state/openclaw-agent-db-lease.ts:234-238
    On systems allowing rename over an open file, keep the admitted child process alive, replace its database pathname with a current-schema copy containing physical index corruption, then open that path in a fresh process. The child still satisfies all four conditions here, although it holds the old inode. The fresh process has no local revoked validation, so openclaw-agent-db.ts passes liveOwnerAdmitted into the integrity gate and skips checking the replacement. Schema and index-definition validation do not detect corrupted index contents. This breaks the existing same-path replacement invariant exercised in openclaw-agent-db.integrity-cache.test.ts. Establish that the peer’s admission covers the claimant’s physical file through the existing identity/provenance owner, and retain full verification when that match cannot be established.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Foreign-owner integrity reuse changes intended behavior with a stated reason (429d97b: Same-process workers consume physical-file-bound, revocable proof; foreign or unknown ownership remains conservative.)
  • Lease claim and completion bookkeeping keeps the original intent (d6bed86: Derive peer ownership from rows already read in the claim transaction and record completion without redundant queries.)
  • Clean-close certification keeps the original intent (f787a89: Only completed verification tied to the physical database can certify a clean-close seal.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/state/openclaw-agent-db.integrity-lease.test.ts --maxWorkers=1
  • pnpm test src/state/openclaw-agent-db-lease.test.ts --maxWorkers=1
  • pnpm test src/state/openclaw-agent-db.integrity-cache.test.ts --maxWorkers=1
  • pnpm test src/state/openclaw-agent-db.open-timing.test.ts --maxWorkers=1
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 429d97b adds src/state/openclaw-agent-db-lease.ts:148 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 429d97b8fa03; files: src/state/openclaw-agent-db-lease.ts)
  • Dallin Romney: Raw commit ec38f53 adds src/state/openclaw-agent-db-lease.ts:76 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: ec38f535d3d5; files: src/state/openclaw-agent-db-lease.ts)

PR surface

Source +14, Tests +65, Docs +8. Total +87 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 15 1 +14
Tests 2 67 2 +65
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 90 3 +87

Labels

Label changes:

  • add P1: Reported repeated scans delay real CLI workflows for minutes and can induce subsequent Gateway admission stalls.
  • add merge-risk: 🚨 session-state: The new bypass can admit a replacement agent database without checking physical corruption that existing admission rejects.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P1: Reported repeated scans delay real CLI workflows for minutes and can induce subsequent Gateway admission stalls.
  • merge-risk: 🚨 session-state: The new bypass can admit a replacement agent database without checking physical corruption that existing admission rejects.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • 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.

Reviewed October 24, 2026, 6:55 PM ET / 22:55 UTC.

@steipete
steipete merged commit 0a59270 into main Oct 24, 2026
264 of 271 checks passed
@steipete
steipete deleted the steipete/gateway-sql-performance-a1b557 branch October 24, 2026 23:51
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

@steipete

Copy link
Copy Markdown
Contributor Author

The P2 finding (borrowed admission not bound to the peer's physical file) is valid and is fixed forward in #183052: borrowing now also requires matching lease provenance (boot, PID namespace, build, file inode), re-checked after the native open, with a replaced-file regression that fails on current main.

steipete added a commit that referenced this pull request Oct 25, 2026
…e while the Gateway holds it (#183052)

* fix(state): bind borrowed agent database admission to the peer's file

A process reusing a live peer's admission (#182984) matched the peer by
path, completed admission and PID start time only. If a different file
was renamed over the path while the peer stayed alive, a fresh process
could borrow the peer's admission and skip integrity_check for a file
nobody verified.

Borrowing now also requires the peer's lease provenance (boot, PID
namespace, build, file inode) to equal the claimant's, and the opener
re-reads provenance after the native open so a file swapped between
claim and open still gets the full check. Provenance exists only on
Linux, so other platforms fall back to the full check.

* test(state): let a separate process create the borrowed database

* test(state): prove borrowing without the creator's clean-close seal
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…82984)

A second process that opens an agent database the Gateway already holds
no longer runs a full integrity_check. When another lease on the exact
path has completed admission and its PID start time still matches, the
claimant reuses that admission and keeps schema and index validation.
Migrations, alias paths, unfinished admissions, and stale or revoked
leases still take the full check. The borrower records no verification,
so closing last leaves the next opener to verify instead of sealing.

On Team, autoreview's agent exec runs hit this on the 43 GB roboclaw
store: 97 lease-class scans totaling 7,465 s on 2026-10-24 (max 321 s
per open), and kills mid-scan forced Gateway-side full rescans.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…e while the Gateway holds it (openclaw#183052)

* fix(state): bind borrowed agent database admission to the peer's file

A process reusing a live peer's admission (openclaw#182984) matched the peer by
path, completed admission and PID start time only. If a different file
was renamed over the path while the peer stayed alive, a fresh process
could borrow the peer's admission and skip integrity_check for a file
nobody verified.

Borrowing now also requires the peer's lease provenance (boot, PID
namespace, build, file inode) to equal the claimant's, and the opener
re-reads provenance after the native open so a file swapped between
claim and open still gets the full check. Provenance exists only on
Linux, so other platforms fall back to the full check.

* test(state): let a separate process create the borrowed database

* test(state): prove borrowing without the creator's clean-close seal
steipete added a commit that referenced this pull request Oct 25, 2026
…3379)

* 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 #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.
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 merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S 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