Skip to content

perf(sqlite): retain admission facts across handle closure - #172676

Merged
steipete merged 8 commits into
mainfrom
dbasync/admitretire
Oct 15, 2026
Merged

steipete merged 8 commits into
mainfrom
dbasync/admitretire

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Closing the final SQLite handle discarded the physical store’s admitted facts. Reopening the same store then repeated quarantine, schema, and other admission reads during connection and first-turn work.

User Impact

OpenClaw reuses admitted facts across handle closure while preserving quarantine refusal and in-process write invalidation. There is no schema migration or operator action. The SDK pool options gain an optional databaseAccess: "read-only" declaration, carrying the existing host ownership contract to plugin task pools.

Why This Change Was Made

The existing admission owner now retains facts for the physical store’s process lifetime, until a write receipt or explicit invalidation/retirement. Remove final-close retirement, its native-open rebind loop, and the seal’s artificial retention reference. No second cache or synchronous fallback is introduced.

Fresh quarantine inspection still selects the decision row. It reuses the physical database’s schema-version fact; DDL continues to invalidate that fact.

Accepted edges for removed checks:

  • Final-close/worker-close retirement: an idle store retains its admission payloads until explicit retirement or process exit; closing a handle does not imply a store changed.
  • Native-open retirement retry and identity recapture: a pathname renamed after native binding leaves that handle on its original physical file; subsequent opens identify the replacement. The native-open identity bracket remains.
  • Fresh quarantine schema bypass: external schema changes while the Gateway owns the store are unsupported; in-process DDL invalidates the schema fact, and fresh decision SELECTs remain.

Explicit retirement, quarantine record/clear receipts, and clean-close seal publication checks remain because they protect real stored data or custody. An exiting write-capable worker with open handles invalidates the existing write, schema, and fact revisions: committed DDL can otherwise outlive its interrupted receipt publication. A normally closed worker retains the store facts. The final heartbeat carrier member now uses the existing close request/reply instead of forcibly terminating its worker with an open database; native handles settle before worker exit.

Evidence

The reviewed production correction is 7b4cc5ad00d; 655b5e12c53 additionally removes obsolete initial-read count assertions while preserving policy-change and stale-authority refusal coverage. Main was integrated at a0c443b004b (main f41b2b656be) to resolve an admission-registry conflict: preserve main’s batched changed-record publication and this PR’s removal of automatic final-handle retirement. Integrated-head CI passes all 16 owner/sibling test files, types, lint, source contracts, architecture and ratchet checks. All three Knip export scans completed; none of their findings is in a changed file, and every finding has exact main evidence below. Measurements retain the original base and dependency set, so integration drift is not presented as a lane saving.

Two Codex review rounds are complete. Interrupted-writer DDL is covered by existing worker-exit invalidation. No P0/P1 remains; the retained-reference-cell P2 is disclosed below.

Integrated-head CI tested merge 49176a07 against main e8eef4f656d0. All 16 owner/sibling regression files passed, including reply authority, production transcript-reader retirement, admission retention, and worker admission exchange. Local conflict-proof execution was cancelled after CI established the same three focused files passed; no local pass is claimed. Production/test types, core/common/extensions lint, source contracts/export collisions, format, Madge (zero cycles), T1/dialect ratchets, and security-fast passed. Integrated-head PostgreSQL conformance passed. CI completed with 55 successful jobs; the sidebar job and its aggregate gate are the only failures. The only failed behavior is the unrelated sidebar nesting expectation: both personal pin cases expect zero child rows and receive four at line 137. Scheduled main, head 47b0a1cc734c, reproduces the identical cases and assertion. The corresponding PR UI job and its aggregate gate use the authorized inherited-failure landing exception.

CI exposed obsolete admission-lifecycle expectations and a heartbeat fixture that suppressed the close acknowledgement. These were repaired and passed fresh CI. The latest repair removes only expectations that authority preparation must reread a fact already published by the fixture's write; changed-policy invalidation, stale authority refusal, borrowed-reader release, and no-main-thread-SQL assertions remain.

T1 in the touched area: 0 before → 0 after (repository live calls 223 → 223; deprecated-only calls 12 → 12). Dialect counts do not rise. The direct SDK API comparison shows one compatible optional constructor option, databaseAccess?: "read-only", through openclaw/plugin-sdk/process-runtime; existing options, methods, generics, return types, and export names are unchanged. The canonical API renderer fails on the untouched baseline: Unable to resolve Plugin SDK declaration dependencies: src/infra/worker-cpu.ts -> ../../worker-heap-flag.mjs. No generated API-diff pass is claimed. The SDK surface check passed on earlier integrated head 24200b9; the runtime-API guardrail passed all seven tests on 7b4cc5ad00d. The SDK-facing pool option and exports are unchanged since those checks; later production changes only integrate main’s admission exchange batching. Knip 6.40.0 completed all three scans on a0c443b004b: 8 production, 11 full-tree, and 10 scripts entries, all outside changed files. The same symbols and rules are recorded in scheduled main and newer scheduled main. The remaining unused type, src/auto-reply/reply/queue/types.ts: FollowupQueueDisposition, was reproduced directly on integrated main parent f41b2b656be with the same pinned production configuration; its eight findings exactly match the candidate production scan. These are explicit inherited-static exceptions, not a green Knip claim. The initial attempt exceeded 600 seconds, and a later retry was cancelled for the main conflict; the completed scans used unchanged rules/configuration with a longer execution allowance.

Published-driver × candidate update passed on corrected implementation 5f402974fd5, on its sole attempt. Published 2026.10.3 → candidate 2026.10.3 verified readiness, running version, durable/incognito sessions, and clean service shutdown. Package integrity, npm 12 installation, and package acceptance also passed.

Three alternating base/candidate pairs completed on base d25a316fc7c3 and head 080397cc893. Every accepted run passed all 13 turns, RPCs, child session, cron, committed compaction, readiness, shutdown, and SQL calibration checks. Warmed figures are ten-turn means per run, then median [min–max] across three runs. “Causal” counts follow the originating turn across threads; raw counts include background work within each phase window. Host load was high; no latency claim is made.

The first baseline attempt completed its turns and shutdown but failed cron setup because the fixture lacked a stored inference account; it is excluded. The lane copy saves its synthetic key through models.authSetApiKey before cron creation and selects the returned profile. This prerequisite is counted identically on both sides. Ordinary turns, SQL observers, and the shared harness are unchanged.

Retirement correction (7b4cc5ad00d): both memory CPU pools declare read-only canonical access through the public pool options. The final alternating pair passed all workload behaviors but still repeated the 104-statement memory-schema block during cron. A second production reader, the session-export pool, also lacked the declaration. Its real-worker control advanced the schema/fact revisions from 14/0 to 15/1 on exit and forced schema initialization; the one-line pool declaration preserves 14/0 and reuses the admitted schema. All six operations dispatched through that pool use read-only native database access. A focused regression covers the production pool. The corrected candidate replay ada11347ddd against saved baseline 7-M passed every workload/calibration check and removes that entire 104-statement block: cron memory-schema SQL is exactly 5 → 5 (FTS 2, provenance 2, recall 1). This replay keeps the original base/dependency set; the integrated production correction is 7b4cc5ad00d. The three-pair figures below remain pre-correction evidence, not three final-head pairs.

An additional candidate attempt stopped before its first turn with sessions.create: UNAVAILABLE (schema-missing) and is excluded. A focused reproduction using the production opener, schema initializer, and session-target discovery reproduced the pre-DDL refusal on both pinned revisions; both recovered after schema creation and final writer close without resetting admission facts. The failed trace overlaps initial schema creation with discovery and later shows successful readers. This establishes matching boundary behavior, not a natural baseline Gateway scheduling reproduction. The replacement uses the unchanged candidate and workload in a fresh isolated fixture.

Metric Base Candidate
Connect SQL / requests 42 [34–57] / 10 [8–22] 339 [329–370] / 20 [8–22]
First-turn SQL / requests 1380 [1378–1401] / 167 [167–167] 1052 [1038–1066] / 164 [162–165]
Connect + first-turn SQL / requests 1437 [1412–1443] / 177 [175–189] 1405 [1381–1408] / 184 [172–185]
Warmed causal SQL / requests / MAIN 116.7 [115.4–118.7] / 31.9 [31.3–32.3] / 0 [0–0] 114.6 [114.6–118.6] / 31.2 [31.2–32.1] / 0 [0–0]
Warmed raw SQL / requests / MAIN 146.7 [142.3–150.8] / 44.3 [42.8–45.1] / 1.3 [0–1.3] 145.1 [143–150.2] / 43.1 [43–44.6] / 1.3 [0.4–1.3]
Whole-workload SQL / requests 5181 [5179–5220] / 1157 [1148–1170] 5210 [5184–5266] / 1145 [1139–1170]

Whole-workload owner attribution (statements, median [min–max]):

Operation Base Candidate
Quarantine decision SELECTs 40 [35–40] 9 [8–13]
Quarantine schema-version reads 37 [36–40] 4 [4–4]
Schema catalog facts 127 [126–127] 151 [150–151]
Schema introspection 94 [92–95] 119 [118–121]
Other schema-version reads 31 [30–31] 35 [34–35]

The extra catalog/introspection work includes a repeat memory-schema initialization on the same canonical database and writer thread. The first two candidate runs each add 104 statements across memory schema, migration metadata, FTS, recall, and provenance operations. A production index-worker control confirms that closing the default pool invalidates memory admission and rebuilds schema; the existing internal read-only declaration preserves the fact and avoids rebuilding. Ordinary read-only retirement must not take the interrupted-writer invalidation path.

Shared read-family attribution, warmed causal statements per turn (median [min–max]): exact-entry facts 0.2 [0–0.4] → 0 [0–0.2]; actor hydration 0.1 [0.1–0.2] → 0 [0–0.2]; entry-cache snapshots 0 [0–0] → 0 [0–0]; row facts 0 [0–0] → 0 [0–0]; watermark reads 0.4 [0.1–0.7] → 0 [0–0.3]. No shared-family warmed median increases. Request counts in the workload table include zero-SQL requests; requests linked to individual SQL families are non-additive.

Final corrected replay (saved baseline d25a316fc7c3 versus ada11347ddd; one candidate replay following the final alternating pair):

Metric Base Corrected candidate
Connect SQL / requests 46 / 17 352 / 21
First-turn SQL / requests 1389 / 169 1059 / 171
Connect + first-turn SQL / requests 1435 / 186 1411 / 192
Warmed causal SQL / requests / MAIN 111.5 / 30.2 / 0 114.5 / 31.2 / 0
Warmed raw SQL / requests / MAIN 128.4 / 37.7 / 1.3 143.8 / 42.5 / 1.3
Whole-workload SQL / requests 4938 / 1049 5122 / 1143
Cron memory-schema SQL 5 5
Quarantine decision SELECTs 35 10
Quarantine schema-version reads 36 5
Schema catalog / introspection / other version reads 130 / 100 / 34 127 / 94 / 31

All five shared read families are 0 → 0 warmed causal statements and linked requests per turn. The sole warmed causal delta is ten additional session-entry-patch requests over ten turns, each executing BEGIN, one session_nodes upsert, and COMMIT; no warmed admission or shared-read increase is hidden in the totals. Provider traces attribute those ten commits to the existing activity-recap producer: one recap completes after each candidate warmed turn, while the final baseline omits them. Every original baseline and candidate run contains the same 90 warmed session_nodes upserts and 70 session_windows upserts as this corrected candidate; only the final baseline has 80/70. The recap producer, source reader, replica, and activity-summary reducer are byte-identical between the measured revisions. Terminal lifecycle events request immediate recaps, with in-flight coalescing; the exact reason the final baseline suppressed its initial recap was not captured. This existing producer explains the +3 SQL/+1 request per-turn replay difference; it is not a new admission request. The corrected warmed windows lasted 16.513 versus 68.103 seconds on the busy host; this is not a latency comparison. These controls satisfy attribution-over-raw without claiming a final-replay net saving.

Whole-workload request-producer attribution (SQL / requests):

Producer Base Corrected candidate
Session-entry patches 357 / 130 397 / 142
Row-transcript backfill 42 / 8 102 / 18
Session maintenance 204 / 96 258 / 124
Other producers, including admission savings 4335 / 815 4365 / 859

These rows partition all SQL and requests by the harness request origin (unlinked SQL is in Other). Whole-workload WAL checkpoints also rise by 27 statements. The quarantine descendant increase is six existing SQLite-capability probes in newly started cron worker isolates; quarantine initialization DDL remains identical. The removed schema rebuild is absent, and all admission catalog/introspection/version-read totals fall. No overall warmed or whole-workload saving is claimed from this single replay.

Production diff: +35/−105 (70 fewer lines); tests: +277/−273 (4 more lines); docs: +37/−17 (20 more lines). Superseded retirement code and tests are removed. Related: #172370, #172373.

Follow-up

P2 from automated review: prune admission reference cells left by exited read-only task workers without applying writer-crash invalidation. The task-host read-only path skips exit tracking, so retaining store records also retains those cells. Deferred under the two-round review limit; no P0/P1 finding remains.

The usage-cost read pool has a similar missing read-only declaration; it was not the cause of the observed repeat (its worker remained alive through cron). Record it as a focused follow-up; the write-capable refresh lane must retain its existing exit invalidation.

@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper reviews are opt-in for maintainers. If a review is required, finish the work and validation first, then comment @clawsweeper review. Please avoid repeated requests while a review is queued or running; agents should not request reviews automatically.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-15T08:58:45.584613Z a0c443b New commits
ℹ️ 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: L labels Oct 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7b4d417bf8

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +207 to +209
// A worker can commit DDL before its outer native call publishes admission receipts.
advanceSqliteDatabaseGeneration(record, "schemaRevision");
advanceSqliteDatabaseGeneration(record, "factRevision");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clean up references from read-only worker exits

When a databaseAccess: "read-only" task worker borrows an admission and later rotates or exits, src/infra/worker-task-host.ts skips trackSqliteDatabaseAdmissionWorker, so this exit cleanup never runs for it. Because this commit also preserves admission records after final close and install() retains every nonnegative owner cell, each departed read-only worker leaves its reference buffer in every database it touched; those buffers are then copied into later admission snapshots, causing unbounded metadata and message growth as the state and transcript read pools churn. Add a read-only exit cleanup path that removes its references without applying the writer-crash invalidations.

AGENTS.md reference: AGENTS.md:L50-L52

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 655b5e12c5

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +208 to +209
advanceSqliteDatabaseGeneration(record, "schemaRevision");
advanceSqliteDatabaseGeneration(record, "factRevision");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark usage readers read-only before invalidating exits

When costReadLane is rotated or closed while withHistoryDatabase retains a canonical reader, createUsageCostPool("read") lacks databaseAccess: "read-only", so the host tracks that worker as write-capable and these new increments discard both schema and integrity facts despite the lane performing only read-only operations. If another handle remains open, the parent preserved those facts before this change; subsequent opens will now repeat the once-per-process validation work. Propagate the read-only declaration to the read lane while leaving the refresh lane write-capable.

AGENTS.md reference: AGENTS.md:L68-L70

Useful? React with 👍 / 👎.

@steipete steipete changed the title improve: avoid repeated SQLite admission after handle closure perf(sqlite): retain admission facts across handle closure Oct 15, 2026
@steipete
steipete merged commit 31a4a60 into main Oct 15, 2026
135 of 138 checks passed
@steipete
steipete deleted the dbasync/admitretire branch October 15, 2026 09:40
steipete added a commit that referenced this pull request Oct 15, 2026
Revert 31a4a60 (#172676), which left
main red by retaining admission facts across final handle closure.
Retained pathname mappings and cached admission facts bypass physical
replacement detection, and Doctor can open preserved sources and mutate
SQLite SHM artifacts.

The three affected files have five failing tests:
- doctor --lint --json preserves schema 20 SQLite artifacts and reports pending repairs
- doctor --json preserves schema 19 SQLite artifacts and reports pending repairs
- doctor --lint --all --json preserves schema 19 SQLite artifacts and reports pending repairs
- SQLite session branches recomputes summaries after physical database replacement with identical watermarks
- refuses replacement shared-state bytes while its agent row preparation is pending

Restore final-close retirement and the preceding admission lifecycle.
The optimization can return once physical-file facts are separated from
pathname/cache validity and replacement, publication, and Doctor
preservation contracts remain intact.
@steipete

Copy link
Copy Markdown
Contributor Author

Reverted on main in 9f8c71e to fix red main.

From 31a4a60 onward these five tests failed on main (they pass on its parent and again after the revert):

  • src/commands/doctor-lint.sqlite-preservation.test.ts: three "preserves schema 19/20 SQLite artifacts and reports pending repairs" cases
  • src/config/sessions/session-accessor.sqlite-branches.test.ts: "recomputes summaries after physical database replacement with identical watermarks"
  • src/gateway/session-row-projection.worker-read.test.ts: "refuses replacement shared-state bytes while its agent row preparation is pending"

Root cause: final-close retirement was removed while the pathname mappings and cached admission facts were kept. Branch summaries therefore skip physical replacement detection, row projection skips validating its captured shared-state admission when cached facts avoid the shared read, and Doctor trusts the retained clean-close state, opening sources it was asked to preserve and changing their -shm bytes and timestamps.

The admission-query savings can come back once physical-file facts are kept separate from pathname/cache validity: retire or revalidate cached facts when the file identity changes (including across worker exchange and later metadata lookups, which can reattach a removed mapping), revalidate clean-close seals at use, and keep Doctor's preservation path from opening preserved sources.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…172676)

Keep physical-store admission facts in the existing owner until a write receipt or explicit invalidation, instead of retiring them when the last handle closes. Reuse admitted quarantine schema facts while retaining fresh quarantine decisions.

Declare read-only access for memory CPU and transcript reader pools so reader retirement preserves schema admission. Let the final heartbeat carrier close its database through the existing close protocol; interrupted write-capable workers still invalidate facts.

The corrected workload removes the repeated 104-statement memory-schema initializer. Quarantine decision reads fall from 35 to 10 and schema-version reads from 36 to 5; warmed MAIN remains zero. Full measurement tables, attribution limits, accepted edges, inherited CI evidence, and follow-ups are recorded in the PR.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
Revert f18968d (openclaw#172676), which left
main red by retaining admission facts across final handle closure.
Retained pathname mappings and cached admission facts bypass physical
replacement detection, and Doctor can open preserved sources and mutate
SQLite SHM artifacts.

The three affected files have five failing tests:
- doctor --lint --json preserves schema 20 SQLite artifacts and reports pending repairs
- doctor --json preserves schema 19 SQLite artifacts and reports pending repairs
- doctor --lint --all --json preserves schema 19 SQLite artifacts and reports pending repairs
- SQLite session branches recomputes summaries after physical database replacement with identical watermarks
- refuses replacement shared-state bytes while its agent row preparation is pending

Restore final-close retirement and the preceding admission lifecycle.
The optimization can return once physical-file facts are separated from
pathname/cache validity and replacement, publication, and Doctor
preservation contracts remain intact.
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 extensions: memory-core Extension: memory-core plugin: file-transfer size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant