Skip to content

perf(state): reuse admitted schema facts on database reads - #156643

Merged
steipete merged 6 commits into
mainfrom
steipete/perf-micro-agent-db-admitted-schema-facts-20260919
Sep 23, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/perf-micro-agent-db-admitted-schema-facts-20260919

Conversation

@steipete

@steipete steipete commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session-entry and session-list reads repeatedly query schema versions and table existence on already-admitted SQLite handles, multiplying synchronous work during streaming and frequent reads.

User Impact

Warm reads reuse admitted schema facts, with at most one cache-freshness probe per event-loop turn per handle. Local DDL remains visible immediately; foreign commits are detected on the next turn. Authorization requests latest metadata and preserves per-request batching. Shared-state worker admission joins the previous probe’s expiry before executing another operation, preserving current receipt/schema reads without a second probe in the same turn. Stored schemas, configuration, durability, and update/migration behavior remain unchanged.

Why This Change Was Made

The native SQLite owner tracks revisions from open; agent/shared-state admission enables retained version and table facts. DDL execution, transaction settlement, rollback, deferred version publication, and close/replacement revoke those facts. Committed schema revisions publish to sibling handles by physical file identity. Explicit and implicit snapshots retain facts only for their lifetime. Dynamic authorizers retain uncached behavior; exact-read and migration/snapshot consistency probes remain fresh.

The merged #156610 guard is now a normal assertion, with separate-process migration refusal coverage. Windows identity lookup uses native realpath, and statement wrappers preserve both retained native observers and statement-owned methods.

Evidence

The guard performs 100 session-entry reads, 100 session-list reads, and 100 cached state acquisitions in one synchronous turn after warm admission, asserting the read results.

Handle user_version, before → after catalog, before → after data_version, before → after
Agent 300 → 0 100 → 0 100 → 0
Shared state 0 → 0 0 → 0 100 → 0

600 counted queries eliminated. Warm-up consumed the turn's freshness probe; the allowance is ≤1 per handle per turn. The composed catalog budget also improves from six to two SQLite reads per list. These are query-count measurements; production CPU/RSS impact remains unmeasured. No Gateway was modified or restarted.

All heavy validation used blacksmith-testbox, profile openclaw-check. No local suites, typechecks, or builds ran. All task-owned leases are stopped.

Lease / run Commands and results
tbx_01m37eyty4jsz01swtkrpmk1jw (run) Focused guard on unchanged production code at 5b29899f06ab733ee25334f1d3590d5aebb0aba8: reproduced the intended budget failure and baseline counts.
tbx_01m37fxwq97bg4a8k5pg817zs2 (run) pnpm test <focused owner file> --maxWorkers=1: established the zero-query result and passing runtime-fence/cache coverage.
tbx_01m37h32e3zx5v1gfw3c9f4s56 (run) 15 schema/guard tests passed; changed-check execution was interrupted by the session rate limit. Subsequent complete type validation passed below.
tbx_01m37kea3dwh7z58vc6h7vzg76 (run) node scripts/run-vitest.mjs <focused files> --maxWorkers=1: 399 passed, six existing skips. Production types and node scripts/run-tsgo-core-test-shards.mjs --stripe 1/1 --concurrency 4: all 25 test-type shards passed. Final schema/committed-reader/guard/observer replay passed; targeted lint and affected type graphs passed. The ownership budget retained 12 SELECTs and zero catalog reads.
tbx_01m37pqcsvhftsvew18dzb1cnw (run) Reproduced seven coordinator/transcript failures before repair. Final 13-file node scripts/run-vitest.mjs ... --maxWorkers=1: 216 passed in 202.03 s. Production, extension, UI E2E, and four selected core test-type graphs passed; repository formatting and core/UI lint passed. All 44 candidate-file checksums matched, and the scoped line-cap ratchet passed for 43 source files. One sync timed out before testing; the single retry succeeded.
tbx_01m37rrd7xw1p8fsbky4kykdap (run) node scripts/run-vitest.mjs src/state/database-runtime-schema-checks.test.ts src/infra/sqlite-schema-facts.test.ts src/infra/sqlite-worker-identity.test.ts --maxWorkers=1: 17 passed in 34.35 s, including zero warmed queries. After adopting upstream UI validation fixes, all 42 remaining PR files were byte-for-byte unchanged from the validated candidate.
tbx_01m37sg5vjrwxhzvm62snn2dnt (run) The new worker-admission regression failed before repair (a peer’s future schema was accepted) and passed afterward. Seven owner/receipt files: 45 passed in 30.93 s, with zero-query counts preserved. On CI’s Node 24.19.0, the receipt file passed 20 standalone runs, and its exact 15-file/eight-worker CI shard passed three runs (553 database-worker tests per replay, plus the isolated lifecycle config). Scripts, production, state-test, and UI E2E types passed; lint, formatting, checksum verification, and the six-file line-cap delta passed. pnpm test src/state/openclaw-state.worker.settlement.test.ts --maxWorkers=1: 4 passed, 8.97 s wall; the new regression took 57 ms in the owner replay.

The final type selection used node scripts/run-tsgo-core-test-shards.mjs --changed-paths-json <affected tests> --concurrency 4, selecting gateway-root, state-logging, gateway-methods, and agents-sessions. Other graphs used node scripts/run-tsgo.mjs -p <canonical config> --incremental. The Testbox's Git baseline initially included four untouched upstream files in the ratchet; a temporary index containing only the checksum-verified PR diff passed scripts/check-line-cap-ratchet.mts --staged --base 80c3c7424677dbc86dd79c188a8c4f62940a1451.

Measured focused costs (pnpm test <file> --maxWorkers=1, including runner/compiler preparation):

Test file Result Wall
sqlite-schema-facts.test.ts 14 passed 2.06 s
database-runtime-schema-checks.test.ts 2 passed 25.85 s
openclaw-state-db.runtime-fence.test.ts 2 passed 5.80 s
session-accessor.sqlite-data-version.test.ts 35 passed 13.73 s
openclaw-agent-db-readonly-scope.test.ts 14 passed 7.41 s
openclaw-agent-db.committed-read.test.ts 23 passed 25.17 s

CI exposed sibling DDL publication, native observer, Windows path, and multi-target authorization gaps; each has a repair and focused passing proof. Existing same-turn foreign-write fixtures advance a mocked turn while retaining their data/refusal assertions. Lifecycle cleanup restores synthetic future versions, and budget observers no longer install real authorizers. Upstream formatting/type fixes, including 3d66eb56567 and ee558121d1b, were adopted and their UI files are no longer in this PR. The original receipt failure passed unchanged in isolation; the deterministic backend regression established the stale-admission defect, and the required standalone/shard repetitions passed after repair. No assertion was weakened to obtain those passes.

Fresh independent Codex autoreview is scoped-clean through P2. The final PR diff passes git diff --check. Squash auto-merge is enabled via GraphQL. Final-head CI 35909995880 passed on 2db15a62830574ced7e12f6c82028ee2939945fc, including native Windows jobs and the formerly failing receipt/type gates. The final check rollup has 170 passing checks, zero failures or pending checks (41 skipped). GitHub completed the requested GraphQL-enabled squash auto-merge at 2026-09-23 19:48:51Z as bc6fedbe4633d3ccc0e4bb84ef323fa62794c6fd.

Keep schema facts with admitted handles and bound cache data-version probes to one per event-loop turn. Native open owns DDL, rollback, authorizer, and handle-lifecycle invalidation; consistency brackets retain fresh probes.
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L labels Sep 23, 2026
@steipete
steipete enabled auto-merge (squash) September 23, 2026 16:50
@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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 23, 2026
@clawsweeper

clawsweeper Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 23, 2026, 1:58 PM ET / 17:58 UTC.

ClawSweeper review

What this changes

The branch makes agent and shared-state SQLite readers reuse schema facts recorded at database admission, invalidates those facts after schema changes, and bounds cache-freshness probes to one per event-loop turn.

Warning

SQLite table change

This PR modifies persisted SQLite tables in src/infra/sqlite-schema-facts.ts, src/state/openclaw-state-db-schema-version.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 - 3 items remain

Keep this PR open. Current main still carries the expected-failure query-budget guard, and this branch supplies the production change that makes it pass. The warm-read measurement is credible; upgrade compatibility needs one required check.

Priority: P2
Reviewed head: 430d03b400d8515beb437bc3e8d679030bc279b9

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has focused native-SQLite boundary evidence and broad tests, with upgrade compatibility still unproven.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR reports a Testbox run of production session and shared-state read entry points over real SQLite, with returned data asserted and 600 fewer counted queries after the change. This covers the read-path optimization; a published-driver upgrade cell remains a separate gate. No stored-data contract change was identified.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR reports a Testbox run of production session and shared-state read entry points over real SQLite, with returned data asserted and 600 fewer counted queries after the change. This covers the read-path optimization; a published-driver upgrade cell remains a separate gate. No stored-data contract change was identified.
Evidence reviewed 8 items Current-main gap: The fetched main revision still marks the admitted-read query-budget assertion as an expected failure; the production optimization has not landed there.
Merged preparatory work: The related merged PR added the database-check policy and expected-failure guard, leaving the production cutover for this branch. See #156610.
Production owner: The introduced SQLite owner records schema versions and table names at admission, then refreshes them after local invalidation or a bounded foreign-commit probe.
Findings None None.
Security None None.

How this fits together

OpenClaw stores sessions and shared state in SQLite. Database admission supplies schema facts to session and state readers, which use those facts to decide whether a handle remains safe to read.

flowchart LR
  A[SQLite database open] --> B[Schema admission]
  B --> C[Retained schema facts]
  D[Local schema change] --> E[Invalidate facts]
  F[Foreign commit probe] --> E
  E --> B
  C --> G[Session and state reads]
Loading

Before merge

  • Resolve merge risk (P1) - A published-updater × candidate upgrade run on copied existing state is not evidenced, although the branch changes shared-state schema publication and admission reads.
  • Complete next step (P2) - Provide the repository-required published-updater × candidate upgrade proof on copied existing state before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +385, Tests +310, Docs +8. Total +703 across 30 files.

View PR surface stats
Area Files Added Removed Net
Source 20 474 89 +385
Tests 9 435 125 +310
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 30 917 214 +703

Review metrics

Metric Value Why it matters
Production and test growth production +474/−89 lines; tests +435/−125 lines The production growth supports lifecycle invalidation and is paired with boundary and regression coverage.
Warm-read query budget 600 counted queries eliminated across 300 reads The reported Testbox measurement directly targets the repeated SQLite work motivating this PR.

Stored data model

Persistent data-model change detected: database schema: src/config/sessions/session-accessor.sqlite-entry-revision.ts, database schema: src/infra/sqlite-pinned-read-snapshot.ts, database schema: src/infra/sqlite-schema-facts.ts, database schema: src/infra/sqlite-transaction.ts, database schema: src/state/openclaw-agent-canonical-validation-schema.ts, database schema: src/state/openclaw-state-db-cache.ts, and 2 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Prove the shipped upgrade path (recommended)
    Run the published v2026.9.5 updater against an isolated copy of existing state and show the candidate opening and reading that state successfully.

Technical review

Best possible solution:

Keep schema facts with their admitted SQLite handle and verify that the shipped updater can hand existing state to the candidate without changing stored schema or recovery behavior.

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

Yes. The merged expected-failure guard exercises the real session and state read entry points, and current main still contains it; I did not run current-main code in this read-only review.

Is this the best way to solve the issue?

Yes. Retaining facts at SQLite admission and invalidating them at the native owner follows the repository's documented boundary, subject to the required shipped-updater check.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 16908037a034.

Labels

Label changes:

  • add P2: The change improves a frequent database-read path without evidence of an urgent user-facing outage.
  • add merge-risk: 🚨 compatibility: Changed schema-publication and admission reads need the repository's shipped-updater compatibility proof before merge.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR reports a Testbox run of production session and shared-state read entry points over real SQLite, with returned data asserted and 600 fewer counted queries after the change. This covers the read-path optimization; a published-driver upgrade cell remains a separate gate. No stored-data contract change was identified.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR reports a Testbox run of production session and shared-state read entry points over real SQLite, with returned data asserted and 600 fewer counted queries after the change. This covers the read-path optimization; a published-driver upgrade cell remains a separate gate. No stored-data contract change was identified.

Label justifications:

  • P2: The change improves a frequent database-read path without evidence of an urgent user-facing outage.
  • merge-risk: 🚨 compatibility: Changed schema-publication and admission reads need the repository's shipped-updater compatibility proof before merge.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR reports a Testbox run of production session and shared-state read entry points over real SQLite, with returned data asserted and 600 fewer counted queries after the change. This covers the read-path optimization; a published-driver upgrade cell remains a separate gate. No stored-data contract change was identified.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports a Testbox run of production session and shared-state read entry points over real SQLite, with returned data asserted and 600 fewer counted queries after the change. This covers the read-path optimization; a published-driver upgrade cell remains a separate gate. No stored-data contract change was identified.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit f7dc8ad adds src/state/database-runtime-schema-checks.test.ts:58 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f7dc8adeeec2; files: src/state/database-runtime-schema-checks.test.ts)
  • Vincent Koc: 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.

  • Show a published v2026.9.5 updater × candidate run on copied existing state, including a successful post-update database read.

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.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime labels Sep 23, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the app: web-ui App: web-ui label Sep 23, 2026
@steipete
steipete merged commit bc6fedb into main Sep 23, 2026
218 checks passed
@steipete
steipete deleted the steipete/perf-micro-agent-db-admitted-schema-facts-20260919 branch September 23, 2026 19:48
steipete added a commit that referenced this pull request Sep 23, 2026
#156643 made src/infra/sqlite-coordinator.ts and
src/infra/sqlite-readonly-location.worker.ts import
sqlite-pinned-read-snapshot.ts and sqlite-schema-facts.ts, but the
scripts/pr wrapper inventory did not list them. The anchored wrapper
closure then cannot resolve those modules, which fails
pr-wrapper-source-closure, the extracted-anchor pr-wrappers case, and
the pr-main-refresh suite on every PR.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 24, 2026
…156643)

* perf(state): reuse admitted schema facts on database reads

Keep schema facts with admitted handles and bound cache data-version probes to one per event-loop turn. Native open owns DDL, rollback, authorizer, and handle-lifecycle invalidation; consistency brackets retain fresh probes.

* perf(state): preserve schema facts across native handle lifecycles

* perf(state): admit worker reads after the cached probe turn
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 24, 2026
openclaw#156643 made src/infra/sqlite-coordinator.ts and
src/infra/sqlite-readonly-location.worker.ts import
sqlite-pinned-read-snapshot.ts and sqlite-schema-facts.ts, but the
scripts/pr wrapper inventory did not list them. The anchored wrapper
closure then cannot resolve those modules, which fails
pr-wrapper-source-closure, the extracted-anchor pr-wrappers case, and
the pr-main-refresh suite on every PR.
@roboclaw-bot roboclaw-bot mentioned this pull request Sep 24, 2026
2 of 8 tasks
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 gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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