Repository navigation
perf(sessions): reuse cold-state and participant read facts - #169989
Conversation
Reuse session-scoped cold facts across read pages and autocommit participant rows inside unchanged metadata transactions. Keep snapshot-local write guards and invalidate through existing writer receipts. Concurrent explicit archives may yield one transient empty read page; subsequent requests observe invalidation. No schema, retention, API, or update changes.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR reuses receipt-invalidated cold-storage facts and unchanged participant rows to reduce repeated session SQLite reads. Example: Read two history pages for session cold-facts without an intervening write.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this owner-directed optimization remains absent from fetched main, and review found no actionable introduced defect. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherSession accessors receive history and metadata requests, read SQLite through connection-owned snapshots and writer receipts, and return transcript rows and participant projections. flowchart TD
A[History and metadata requests] --> B[Session accessors]
B --> C[Connection read facts]
C --> D[SQLite snapshots]
E[Archive and session writers] --> F[Write receipts]
F --> C
D --> G[Transcript and participant results]
Technical reviewBest possible solution: Keep reuse within the existing receipt and snapshot owners while preserving participant freshness, write guards, and transcript bytes. Do we have a high-confidence way to reproduce the issue? Current-main source shows repeated cold-marker queries and participant rereads across transaction revisions; this read-only review executed no target code. Is this the best way to solve the issue? The patch extends existing cache and invalidation owners, and the correction preserves deferred-reader snapshots without introducing competing storage or authorization. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 3ba9c7d5ec00. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +95, Tests +128, Docs +9. Total +232 across 10 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 (3 earlier review cycles)Reviewed October 12, 2026, 1:34 PM ET / 17:34 UTC (Revision 4). |
…#169989) Reuse bounded transcript hot/cold facts under existing session write receipts, and carry participant preparation into the metadata CAS owner’s immediate write transaction. Preserve native read snapshots, archive/restore invalidation, and independent participant updates. Reduces repeated transcript and metadata-commit SELECTs without changing schemas, retained bytes, public APIs, or request routing.
What Problem This Solves
Warm transcript pages repeatedly select the same cold-archive marker, and session metadata commits reread participant rows already obtained by the operation.
User Impact
Reduces repeated SQLite reads during chat and history/usage refresh. Schemas, retained transcript bytes, public APIs, permissions, and update behavior are unchanged.
A concurrent explicit archive can make one read-only page appear empty if it commits between receipt capture and the first row read. The next request observes invalidation and reports/restores cold storage. History or usage may briefly appear incomplete; transaction-local write guards remain intact.
Why This Change Was Made
The transcript owner retains at most 128 hot/cold facts per connection under existing session-ID write receipts. Consecutive read pages reuse them. Already-open snapshots retain only snapshot-local facts; their results never become current autocommit facts. Participant projections carry the existing autocommit result only into the metadata CAS owner’s already-admitted immediate write transaction, with existing local mutation and physical write receipts invalidating it. Ordinary deferred readers perform their first SELECT to establish a real SQLite snapshot; cached rows then stay within that snapshot.
Writer coverage: the cold-storage worker archives, restores, and externalizes archives under the session-ID scope; window/node deletion scopes every affected session before FK cascades. Native writes publish the existing receipts, including rollback invalidation. Incognito uses its process-owned native handle. Doctor orphan-window cleanup runs under exclusive offline maintenance; private backup writes do not mutate the live database. There is no supported foreign-process archiver while Gateway ownership is held.
Removed checks and accepted edges:
T1 inventory in this area remains 1 → 1. The remaining
readParticipantRowsbatch query serves native incognito projection and released synchronous entry APIs. Moving it requires the incognito/API owner cutover; relabeling this mixed kernel as worker-only would be incorrect. Cold-marker helpers add no new inventory call site. Repository T1 remains 482 → 482, compatibility calls 2 → 2. Measured warmed Gateway MAIN statements are reported below.Related work: #169974 (usage refresh coalescing), #169960 (committed transcript context), and merged #169858 (exact-entry receipt preservation, included in the base). This change does not alter their scheduling, replica invalidation, or request routing.
Evidence
git diff --check: passed.f6dd2d3d8b4c, candidated6f09475c843; one pair with ten warmed turns per run, using the current reduced-proof workflow. Loaded host; no unloaded-host claim.f6dd2d3d8b4cd6f09475c843db6a8b200fc9Initial-pair per-operation attribution:
usage-costdrops 75 → 64.2 SQL/turn at 3 → 3 requests/turn;session.entry.patch.commitdrops 37 → 34 SQL/turn at 6 → 6 requests/turn. The CAS reread class disappears, while the three real operation snapshots remain. These owners save 13.8 SQL/turn, with no added requests. Request routing is unchanged; this PR does not claim a structural request-count saving.Disclosed shared-family variation: candidate ran six corpus inventory requests versus five (one primary snapshot each), 35 actor reads versus 33 (one hydration each), and 35 exact-entry requests versus 32 (three extra primary SELECTs; full-row queries remain 20 in each run). The remaining extra exact-entry read is a first-turn
session.entry.readcohort projection (session-entry-cohort.worker.ts:155: 15 → 16 over the warm window). The three other extra reads are transcript-worker lifecycle projections (12 → 15); snapshot/full-row paths remain ten each. Candidate turn 1 also includes 26 write-preparation statements and two corpus scans; base has no warmed write-preparation statements and one first-turn corpus scan. These are additional invocations, not increased SQL per affected shared operation; writer invalidation publication, scheduling, and worker routing are unchanged. Raw means include this background work, including the +0.7 requests/turn. Whole-workload totals fall 10,502 → 10,257 SQL and 1,759 → 1,752 requests. The final-head run below verifies the snapshot correction; both candidate results remain visible rather than selecting the more favorable one.Final-head confirmation: the same live workload passed on
db6a8b200fc9(146.6s runtime; 449.3s build), with exact SQL conservation, zero missing contexts, the same two unmatched startup requests, and no fixture children left running.usage-costis 75 → 62.2 SQL/turn at 3 → 3 requests;session.entry.patch.commitis 37 → 34 SQL/turn at 6 → 6 requests. These owners save 15.8 SQL/turn, including removal of all three CAS rereads and usage-page cold guards 15 → 4 per turn. The three real operation snapshots remain.Final shared-family attribution: the eight extra exact-entry primary reads over ten turns comprise five extra transcript lifecycle reads (requests 32 → 37, primary reads 12 → 17), two extra cohort projections (entry-read requests 45 → 47, cohort projections 15 → 17), and one extra read-only entry lookup (10 → 11). Both ten-query full-row paths remain at ten. The two extra snapshot loads comprise one extra corpus request (5 → 6) and one extra entry-list request (0 → 1), each with one snapshot. Actor hydration remains 45 → 45, row facts 10 → 10, and watermarks 20 → 20. Thus these increases are additional invocations, not additional reads per shared operation.
The final raw SQL median rises 5.5 while its mean falls 1.5; request median rises 4 and mean 3.2. The largest additional background component is
database.domain.publish: +69 SQL/+15 requests over ten turns, exactly accounted for by cache/index/source jobs (+58 SQL/+15 requests) and vector initialization (+11 SQL at unchanged request count). Those owners and scheduling are untouched. Whole-workload totals are 10,502 → 10,375 SQL and 1,759 → 1,777 requests. Under the campaign's attribution-over-raw rule, this is disclosed background variation; no end-to-end median or structural request reduction is claimed. Shared-family details are handed to the campaign owner.CI found a participant snapshot regression in the initial implementation: an autocommit result could enter an ordinary deferred reader without pinning its native SQLite snapshot. The follow-up commit limits this optimization to the existing immediate CAS writer, adopts the transaction revision, and strengthens the snapshot regression with a direct native read after the peer update. The exact test passed on current main and failed on the initial candidate; the corrected exact regression now passes locally (1 passed, 50 skipped; 124.67s Vitest, 158.66s test wrapper under contention). The unchanged-CAS/write-invalidation regression also passes on
db6a8b200fc9(1 passed, 7 skipped; 101ms test body, 30.13s Vitest, 58.70s wrapper). Final-head CI passed all 51 schema-facts cases (corrected snapshot case 38ms) and all 8 entry-revision cases (carry case 28ms). Final-head types, lint, source contracts, Madge and T1/dialect/worker ratchets also passed; the separate Knip scan completed with only the pre-existingsrc/infra/database-engine/contract.ts: TransactionRecipesunused type in production/full-tree scans (script scan clean). The exact same export fails in main job 114886687947, and main already contains fix4cdac89cf0b656ef90cb22bb4fd3dfa9e7205bf9; the merge retains that fix. No changed-file Knip finding remains. The mocked history-worker runtime sibling passed all 32 cases locally (530.04s wrapper, including 262.648s cold worker build). Final-head CI passed all 39 cold-owner cases as well: 3 state, 23 archive/restore, 13 cold-read. Across the five touched test files, all 98 cases passed. The table records both candidates; the final run verifies the snapshot correction retains the intended savings. Final CI run 38276056220 completed with 22 successful static jobs and 11 red test shards plus the aggregate; this is not an all-green CI claim.Broad-test disposition under the authorized relaxed landing policy: the pending-input savepoint lock, restricted-operator rewind lock, named branch-switch/cold-fork storage locks, and sticky-model catalog expectation have exact matching main failures in runs 38271415987 or 38265016301. Startup registry and history-worker reuse failures were reproduced locally at main
32c839147a80. Those failures have campaign owner handoffs. The cleared-selection archive catalog fixture is source-attributed to an unchanged upstream contract; the remaining rewind lock cases share the untouched lock stack but are not exact-main reproductions. Reclamation cleanup, agent-delete timeouts/cascading assertions, two visible-spawn cases, active-context preflight, session-create admission, and historical Doctor normalization remain unresolved broad failures; they are not labeled inherited. No remaining failure in a touched test file or proven regression in the changed owners remains. The initial snapshot regression was fixed before landing.Changed-file CI timing (case-body totals; enclosing shards include other files):
session-cold-storage-state.test.tssession-cold-storage.test.tssession-accessor.sqlite-cold-read.test.tssession-accessor.sqlite-entry-revision.test.tssqlite-schema-facts.test.tsLOC: 10 files, +322/−90; production +139/−44, with the remainder tests and ownership documentation. Live-run elapsed time: base 130.7s, candidate 140.8s; builds 308.7s and 404.8s. Local test suites were not a proof gate; focused CI-failure diagnosis is recorded separately.