Repository navigation
perf(sqlite): retain admission facts across handle closure - #172676
Conversation
|
ClawSweeper reviews are opt-in for maintainers. If a review is required, finish the work and validation first, then comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| // A worker can commit DDL before its outer native call publishes admission receipts. | ||
| advanceSqliteDatabaseGeneration(record, "schemaRevision"); | ||
| advanceSqliteDatabaseGeneration(record, "factRevision"); |
There was a problem hiding this comment.
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 👍 / 👎.
Integrate upstream static-check repairs without changing the measured admission implementation.
There was a problem hiding this comment.
💡 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".
| advanceSqliteDatabaseGeneration(record, "schemaRevision"); | ||
| advanceSqliteDatabaseGeneration(record, "factRevision"); |
There was a problem hiding this comment.
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 👍 / 👎.
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.
|
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):
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 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. |
…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.
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.
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:
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;655b5e12c53additionally removes obsolete initial-read count assertions while preserving policy-change and stale-authority refusal coverage. Main was integrated ata0c443b004b(mainf41b2b656be) 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
49176a07against maine8eef4f656d0. 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: bothpersonal pincases expect zero child rows and receive four at line 137. Scheduled main, head47b0a1cc734c, 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", throughopenclaw/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 head24200b9; the runtime-API guardrail passed all seven tests on7b4cc5ad00d. 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 ona0c443b004b: 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 parentf41b2b656bewith 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
d25a316fc7c3and head080397cc893. 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.authSetApiKeybefore 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 replayada11347dddagainst saved baseline7-Mpassed 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 is7b4cc5ad00d. 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.Whole-workload owner attribution (statements, median [min–max]):
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
d25a316fc7c3versusada11347ddd; one candidate replay following the final alternating pair):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-patchrequests over ten turns, each executingBEGIN, onesession_nodesupsert, andCOMMIT; 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 warmedsession_nodesupserts and 70session_windowsupserts 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):
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.