Repository navigation
improve: reduce repeated SQLite work during chat turns - #168093
Conversation
…odules Merge current main while preserving shared physical admission, cancellation, reader validation birthtime, and live deletion authority. Split worker usage, pool construction, failure settlement, and schema owner types to keep the existing line caps.
Checkpoint the single-owner cutover, cache invalidation regressions, and request-owned read transactions. Keep explicit migration verification. Paired measurement and final validation are still in progress.
Route retained existing-state writer coverage through the host-owned worker project, preserve first-admission incompatibility refusal, and match the final deletion-authority contract. Keep the gateway test under its inherited line count by moving existing pure fixture helpers. Regenerate assertion allowances without adding production assertions.
Include the thirteen transitive admission modules required by the native wrapper import-closure proof. Carry the existing birthtime through the worker validation fixture to preserve its physical-file identity.
Merge current main and preserve its optional settlement-only receipt delivery through the extracted owner. Keep the worker refusal error with the leaf contract to stay within the existing admission line cap. End the marker-free read-only fixture transaction normally; dedicated rollback and explicit revocation coverage remains unchanged.
Preserve snapshot-local reuse without freshness queries, publish dedicated archive writes, and remove Workboard polling. Retain native authority and settlement boundaries. Checkpoint reviewed corrections and focused regression repairs; final integrated proof remains in progress.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
|
Codex review: needs real behavior proof before merge. What this changesThis PR reuses transaction-owned session facts and complete transcript hydration to reduce repeated SQLite work during chat turns. Example: The supplied synthetic workload completes an ordinary warmed chat turn.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 3 items remain This PR provides a useful, distinct SQLite optimization; no definite introduced bug was found in the reviewed diff. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherChat preparation and completion pass session entries and messages through the existing database workers, which commit transcripts and publish facts used by custody checks, session projections, and model context. flowchart TD
A[Chat turn] --> B[Turn preparation]
B --> C[Existing worker transaction]
C --> D[SQLite session and transcript state]
C --> E[Committed publication facts]
D --> F[Bounded hydration and model context]
E --> A
F --> A
Technical reviewBest possible solution: Retain the existing worker owners and revision-scoped reuse while demonstrating final-effect rejection of stale authority. Do we have a high-confidence way to reproduce the issue? The supplied alternating workload measures repeated SQLite work through chat execution; this read-only review did not run target code. Is this the best way to solve the issue? Reusing certified facts within existing transaction and physical-reader lifetimes is a coherent optimization that preserves fresh-read fallbacks when reuse cannot be certified. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 4644b0272c68. Merge-risk optionsMaintainer options:
Provenance checked
TestingProof path: shipped entry point. SecurityNeeds attention: No reachable authorization bypass was established, but the changed authority-fact reuse needs final-effect validation. EvidenceSecurity concerns:
What I checked:
PR surfaceSource +310, Tests +329, Docs +17. Total +656 across 24 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (4 earlier review cycles)
Reviewed October 10, 2026, 12:11 PM ET / 16:11 UTC (Revision 5). |
|
Merged via squash.
|
* perf(sqlite): checkpoint shared admission across workers (WIP) * test(sqlite): align worker fixtures with shared admission * perf(sqlite): avoid repeated quarantine reads in retained scopes * docs(sqlite): define single-owner database freshness * perf(sqlite): replace runtime probes with writer publications Checkpoint the single-owner cutover, cache invalidation regressions, and request-owned read transactions. Keep explicit migration verification. Paired measurement and final validation are still in progress. * test(sqlite): align first-admission coverage and deletion fixtures Route retained existing-state writer coverage through the host-owned worker project, preserve first-admission incompatibility refusal, and match the final deletion-authority contract. Keep the gateway test under its inherited line count by moving existing pure fixture helpers. Regenerate assertion allowances without adding production assertions. * build(sqlite): include shared admission in compiled wrappers Include the thirteen transitive admission modules required by the native wrapper import-closure proof. Carry the existing birthtime through the worker validation fixture to preserve its physical-file identity. * test(sqlite): use the canonical settlement owner in publication proof * fix(sqlite): complete writer custody and snapshot cache lifetimes Preserve snapshot-local reuse without freshness queries, publish dedicated archive writes, and remove Workboard polling. Retain native authority and settlement boundaries. Checkpoint reviewed corrections and focused regression repairs; final integrated proof remains in progress. * fix(sqlite): retain integrity and worker admission through cleanup * test(sqlite): preserve reader coverage in existing fixture owners * fix(sqlite): preserve cache receipts across sibling writers and temp DDL * fix(workboard): type the replacement card-list promise * fix(sessions): reconcile listing receipts with single owner reads * perf(sessions): reuse turn preparation and publication facts * refactor(sessions): keep model context encoding in the codec * fix(sessions): bind prepared context to its physical reader * test(sessions): expect maintenance mutation conflict * test(gateway): remove unused agent mutation fixture type
What Problem This Solves
Chat turns repeatedly read session entries, participant metadata, transcript versions, and context that the current transaction or bounded hydration already established.
Stacked on #167965 (
dbasync/noprobe). Measurement baseline:a4ca20f1f8b29b5bf4f98f337ef71bf8962e84de; candidate:3015835815b489bff435ff29067326a2988f6056. The branch includes its initial main integration; this lane adds no schema migration.Stack handoff: the parent branch advanced after this lane's initial integration. Local Git reports multiple merge bases against
dbasync/noprobe; GitHub currently shows the PR as conflicting, with 274 files (+13,243/-5,298) because the comparison includes inherited changes. The measured lane diff is the 24-filea4ca20f1f8b2..3015835815b4comparison (+992/-335). The lander must reconcile the stack when the parent lands; the proof below applies to the exact measured head, not future conflict resolution.User Impact
Fewer SQLite statements and worker requests during ordinary chat turns, with no intended behavior change. Separate durable user and assistant commits, idempotency, FIFO ordering, live authority, retention, and released SDK entrypoints remain intact. No operator action is required.
Why This Change Was Made
Turn preparation and commit carry current entry and participant facts to custody and publication. Entry writers certify persisted postimages at their native transaction revision; intervening mutations and serialization hooks invalidate reuse. Transcript mutation postimages supply transaction-local version facts, with rollback and raw mutations retiring them. Assistant rebase validation now shares the append write reservation.
Bounded hydration carries its projection watermark/version. A complete, unchanged view can provide detached, sanitized initial model context, guarded by the selected physical reader's write token. The normal legacy selector still resolves through that physical reader. Single-statement lifecycle reads drop redundant transaction envelopes; composite snapshots and the final count after awaited maintenance remain current reads. No transaction spans a model, network, or file await, and no foreign-commit probes or repeated format checks are added.
Evidence
Five alternating pairs (M4,C4 through M8,C8), all on the exact pins above, passed the fixed synthetic workload. Each run has thirteen top-level turns, one awaited child, a completed cron run, compaction, and graceful shutdown. All native statements across MAIN, workers, and helper processes are counted, including background work and transaction controls. Calibration and phase/thread/SQL conservation passed, with no warmed native failures or freshness probes.
Warmed medians fall 852.2→811.1 statements and 203.3→198.6 requests. Matched changed-owner classes directly remove 25 statements and one request per turn; the remaining raw reduction includes timing-dependent background variation. One canonical-key SELECT overlaps the constants lane and must not be credited twice. The 45/3 target is an aim, not a publication gate; this lane does not reach the campaign-wide goal of fewer than 500 statements per warmed turn.
Supplementary startup-to-shutdown check
The original non-turn increases were investigated before publication. One predeclared additional alternating M9,C9 pair used the same exact source pins and unchanged workload/counting harness, after both builds finished. This is the requested entire-workload check, not a replacement for the original median series.
All 31 original growth families have equal or lower startup-to-shutdown SQL and requests in this pair. The specifically investigated memory commands remain equal/lower after combining
database.domain.executesubcommands with same-named directly dispatched commands. The additional pair meets the coordinator’s whole-workload equal/lower numeric criterion. The reductions here include runtime/timing variation and are not claimed as directly attributable implementation savings.The original cron/compaction increases are classified as timing redistribution/coalescing under this check. No additional publication/lifecycle producer work was found: the changed paths decrease, scheduling and memory-sync owners are unchanged, and all originally growing families are equal/lower over the follow-up run. Only the matched 25-statement/one-request reduction is directly credited to this implementation.
Additional pair: every phase, original growth families, and memory commands
Arrows show M9→C9; successful SQL includes all threads and helper processes. The ten warmed rows are individual observed turns, not medians.
Warmed averages: all 958.9→875, main 23.5→17.2, requests 228.2→214.6.
Every standard measured phase has a C/M duration ratio ≤1.5; the zero-work
donemarker is excluded. The host was loaded (recorded load averages approximately 62–102); these instrumented durations do not establish a latency improvement.Limits: this additional pair’s first-turn SQL rises 1215→1806, while boot+connect+first rises 5017→5099. Cron rises 1261→1271 (+10); shutdown rises 121→125 (+4). The original five-pair first-turn median remains 1822→1807 and warmed median 852.2→811.1. This supplementary whole-workload result must not be presented as every individual phase passing, or as a replacement median series.
The set is the union of positive cron/compaction family-median SQL deltas and positive SQL/request types in the representative median-run attribution.
Semantic memory commands
Domain-dispatched and directly dispatched forms are added once each. Transport labels do not create an apparent saving.
All listed memory commands combined: SQL 648→486; requests 156→119.
source.refreshis the disclosed exception among individual commands (1→2 requests, 5→10 SQL); it was not one of the original growing commands. The targeted hash/state/replace/prune/append/start commands all decrease.Both fixtures completed all 13 top-level turns, child completion, cron work, compaction, and clean shutdown. Calibration and the existing census verifier passed. Independent checks match raw compact statement counts to native-class totals and logical send-event totals to request counts. No runtime freshness probes or non-shutdown native failures were observed.
M9 recorded one failed
BEGIN IMMEDIATEduring MAIN agent-database lease release at idle close. C9 recorded the same lease-release lock refusal plus one workeraudit.writer.prunelock refusal during shutdown. These are failed native executions and excluded from successful SQL counts; all are retained in the adjacent JSON and original census. The extra audit refusal is disclosed, not counted as a savings mechanism.All six pairs retained: mixed pooled medians
Pooling M4–M9/C4–C9 does not make every median favorable. This table is included to prevent favorable-run selection; it is not a new gate definition.
The original report, additive representative attribution, and this one-pair whole-workload check remain distinct. No additional rerun was performed for this analysis.
Exact accounting of the original cron and compaction median increases
Actual median representatives are M4/C6 for cron and M5/C4 for compaction. They are not temporal pairs; this table explains the median outcomes, while paired-series and follow-up workload results govern the comparison.
06.cron: M4 → C6
SQL 915 → 982 = +67. Logical requests 185 → 214 = +29. Native groups reconcile as +87 + (-20) = +67.
07.compaction: M5 → C4
SQL 342 → 408 = +66. Logical requests 87 → 100 = +13. Native groups reconcile as +71 + (-5) = +66.
Cron's unassigned +12 is +14 MAIN (an additional
reconcilePublicationssweep: +10 state-ownership guards and +3 publication-coordinator reads;runSessionRegistryMaintenance: +1 config read) and -2 worker transaction controls. Compaction's unassigned +21 is entirely MAIN:resolveSessionIndexEntryadds 8 memory lease statements and 5 database-context PRAGMAs, while a memory-sync follow-up adds 5 lease statements and 3 revision/metadata/chunk reads.Memory worker stacks reach
manager-publication.worker.tsbind/close andmanager-source-state.ts/manager-source-index-kernel.ts; corpus/tombstone sender stacks includeprocessSessionUpdateBatch → resolveArchiveFilesForSyncTargets → listSessionCorpusEntries. Maintenance reads are issued bysession-accessor.sqlite-reclamation-run.ts, with some sender origins ending at FIFO frames. Those truncated origins remain a limitation, rather than being automatically classified as background.The memory sync/debounce, maintenance scheduling, and cron recovery source files are byte-identical to baseline. The existing memory debounce is five seconds; maintenance batches age writes for one second and repeats planning when its generation changes. This source evidence establishes a timing/coalescing mechanism, not by itself a passing measurement. The original whole-run medians were SQL 18,091→18,031, requests 3,444→3,511, and duration 88.067→106.764 seconds.
Focused owner tests passed 134 tests in 443.69 seconds with
pnpm test <owner files> --maxWorkers=1. The later codec/publication selection passed in 106.77 seconds. The normal-selector regression failed before the physical-reader fix and all six reuse/freshness cases passed afterward. Negative controls on baseline failed at the intended lifecycle-envelope and version-reread assertions. Coverage includes durable commit/custody, publication postimages, rollback and raw-write invalidation, bounded/incomplete hydration, changed views, and incognito behavior. These are local wall times; hosted CI seconds have not been measured.Three isolated Codex P2 review rounds are clean, including the final physical-reader fix. T1 is unchanged at 707. Madge, runtime import cycles, Knip, exact-head targeted lint, types, and ratchets passed. SDK comparison reports 153 reachable declaration changes, with no added or removed SDK entrypoints or exports; later edits preserve those signatures.
Known check gap: full check-changed stopped on inherited
internal-config-apiuse oftransformConfigFileWithRetryin unchangedsrc/gateway/server-methods/agents.ts. It is identical to the measurement baseline and fixed upstream by959197ba0923; remaining guards were run separately. The inheritedMockConfigfixture type error was repaired in this branch. Published-driver × candidate update cell: pending (lander). No update-proof claim is made.Production LOC versus the measurement baseline: +642/-332; tests +333/-3; docs +17. Most production growth certifies and invalidates reusable facts at the existing owners; old reread paths remain only where the certificate cannot establish freshness or authority. The anchor request and final lifecycle count remain explicit.
Original five-pair phase statement/request table
Cells are median [min–max]. Warmed values are each run's ten-turn mean. Individual owner medians need not sum to the workload median.
Direct changed-owner savings
Removed classes: turn preparation 4 (entry/owner, participant, canonical-key, cold presence); turn commit 2 (entry/owner and participant); metadata append 4 (one read envelope and two postimage reads); lifecycle authority 4 (two read envelopes); no-removal lifecycle prepare 2 (one read envelope); hydration 2 (version reads folded into projection); initial model context 7 + one worker request. No saving is credited merely for moving work to a worker.
The synthetic workload does not establish production-history, arbitrary plugin/tool-mix, or uninstrumented latency behavior. Instrumented durations and RSS include observer overhead. Proof retains compact summaries and cited logs; raw SQL streams and fixture databases are removed after aggregation. The shared workload/counting harness is unchanged.
Original five-pair instrumented durations
Seconds include observer overhead and settling; these are not uninstrumented latency claims. Warmed duration covers all ten turns.
Landing validation
Final candidate:
1a67c1acd4fd12f08182b775117e70a3ffbc98f1. Main was merged without conflicts, including the cold-rebuild retry-cooldown test fix696e8256e55f655bb23e9a6adaeba81caea6419c. Earlier lander fixes corrected one stale maintenance-error expectation and removed one unused test type import; both received clean scoped P0/P1 autoreview.Current-head CI passed. Merged through the native workflow as
da965e09656e399bbe07f91b82e385e412cc2088; no admin CI override was used. The earlier candidate run failed the damaged-archive memory test identically to scheduled main; its four cancelled jobs were not passing evidence. The subsequent main merge includes the fix for that failure.Published-driver
2026.9.9× candidatebd5eef6c9869b7fc7d751699e9141b24e84f8b5dpassed on AWS in 485 seconds: update finished,readyz=200, running version verified, and durable/incognito state preserved. Both focused test shards passed in 51.40 seconds, with clean targeted lint. This proof is reused after the main-only merge under the coordinator's explicit rule; it is not presented as a run of the new head. Tested candidate tarball SHA-256:a5fa82f164da02f78f8009a59b43f6500ef44c7415a73cf52ffbdfc1e7675987.