Repository navigation
perf(sessions): shorten cold transcript writer holds - #200076
Conversation
|
🦞👀 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 Summary: ✅ CompletedThis 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. |
|
Codex review: needs maintainer review before merge. What this changesThis PR publishes cold transcript archives atomically, then releases the writer between bounded navigation and search-index cleanup transactions. Example: Archiving a 50,000-event session while foreground transcript appends are queued.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR is ready for normal landing: the previous classifier and upgrade-proof blockers are resolved, current-head CI passes, and no additional blocking defect was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherGateway maintenance selects inactive sessions, prepares durable archives, and uses the existing agent database writer to publish archives and clean derived rows while foreground writes share admission. flowchart TD
A[Gateway maintenance] --> B[Archive preparation worker]
B --> C[Durable archive files]
C --> D[Atomic cold marker publication]
D --> E[Bounded cleanup transactions]
F[Foreground transcript writes] --> G[Agent database writer]
E --> G
D --> H[Cold history readers]
Technical reviewBest possible solution: Land atomic per-session archive publication and bounded cleanup through the existing writer, retaining exact restoration and cold-marker recovery. Do we have a high-confidence way to reproduce the issue? The baseline source performs whole-session navigation conversion and FTS deletion under one writer transaction, matching the supplied interleaved baseline measurements; no target code was executed during this read-only review. Is this the best way to solve the issue? The change addresses writer monopolization at its existing owner while preserving atomic archive publication and restoration; the extracted mutation adapter retains a complex existing boundary, and no competing durable cleanup owner is introduced. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against e69daeb6bc3d. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +309, Tests +245, Docs +7, Other +868. Total +1429 across 27 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
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 November 17, 2026, 5:15 PM ET / 22:15 UTC (Revision 4). |
Preserve native SQLite method descriptors in the benchmark and await the interactive write directly in the sweep test. Align the inherited CLI JSON failure assertion with its existing reported-error contract.
Prepared identity and active-event inserts saved about 18 ms of query compilation in a 12 s restore; drop them to keep the change focused on the measured archive holds.
Publish archives per session, then clear navigation payloads and FTS rows in separately admitted units capped at 256 rows. Resume interrupted cleanup through the existing cold marker and clear embedded chunks individually. Split cold operation labels and distinguish native statement time from callback work. Preserve synchronous commit sections and atomic restoration. Validated with 37.3 GiB synthetic A/A/B and concurrent transcript appends, allocation and CPU profiles, focused backend and Control UI tests, check:changed, and independent review.
7ba585e to
1268ef1
Compare
|
The completed follow-up is pushed at The remaining large-session gap is addressed by 256-row navigation/FTS units with separate admission, per-unit cold-marker checks and one-child blob cleanup, and read-only interrupted-cleanup discovery. Distinct transaction labels and existing statement attribution separate native SQL from application work. The body now contains five-cycle A/A/B on 37.3 GiB synthetic state with real concurrent transcript appends: maximum cold hold 1518/1506/104 ms; median per-run p99 queue wait 2018/2005/171 ms; maximum candidate native SQL 15 ms. Throughput, CPU and allocation costs are retained. Local checks, 66 focused backend tests, 21 UI browser/e2e tests and independent Codex review are green. Foreground restore and read-snapshot limitations remain explicit. Exact-head CI is pending. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1268ef13aa
ℹ️ 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".
| return retainSessionColdNavigationInTransaction( | ||
| database, | ||
| input.sessionId, | ||
| input.afterSeq, | ||
| input.maxRows, |
There was a problem hiding this comment.
Update frozen-target detection for the bounded navigation writer
When this commit is selected for frozen-target validation, scripts/lib/frozen-target-compat.sh:360-368 no longer recognizes its cold-storage contract: it searches for the exact string retainSessionColdNavigationInTransaction(database, sessionId), which this refactor removes. Both its navigation and legacy predicates therefore become false, entering the error case and returning status 2. The frozen-target runs of scripts/e2e/openai-chat-tools-docker.sh and scripts/e2e/session-runtime-context-docker.sh consequently stop before running their scenarios. Update the classifier and its fixtures alongside the new bounded call while preserving detection of older shipped implementations.
AGENTS.md reference: AGENTS.md:L55-L55
Useful? React with 👍 / 👎.
|
@clawsweeper re-review The previous request was superseded while the required PR-context headings were corrected. The body is now settled, native preparation is complete, and head remains |
|
🦞👀 Re-review progress:
|
|
Addressing all three open items against 4192350:
Validation: 32 consumer tests, tooling test typecheck, shell syntax, @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4192350504
ℹ️ 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".
| .selectFrom("transcript_events") | ||
| .select(["event_json", "event_zstd", "event_utf8_bytes", "navigation_json"]) | ||
| .where("session_id", "=", cold.session_id) | ||
| .where((eb) => | ||
| eb.or([eb("event_json", "is not", null), eb("event_zstd", "is not", null)]), |
There was a problem hiding this comment.
Bound cleanup discovery for already-clean cold sessions
For stores with substantial archived history, every maintenance pass now scans the retained transcript rows of every fully cleaned cold session. Once its FTS rows and embedded chunks are gone, hasCleanup is false, so this query must inspect the session's rows to establish that no removable payload remains; the existing (session_id, seq) index cannot filter by payload presence. The pending.length limit never bounds this work when sessions are clean. Because Gateway maintenance runs every 60 seconds, even an idle store repeatedly reads its entire cold transcript inventory, introducing growing CPU and I/O costs precisely after archival completes. Make completed-session discovery indexable or bound the recovery scan with resumable progress instead of rescanning all completed history each pass.
AGENTS.md reference: AGENTS.md:L70-L70
Useful? React with 👍 / 👎.
|
Addressing the sole remaining open item on
The earlier classifier and provenance items remain fixed and covered by the 32 passing consumer tests. No source changed after the last review. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
* perf(sessions): shorten cold transcript writer holds * perf(sessions): repair cold storage proof checks Preserve native SQLite method descriptors in the benchmark and await the interactive write directly in the sweep test. Align the inherited CLI JSON failure assertion with its existing reported-error contract. * perf(sessions): keep cold restore record inserts unchanged Prepared identity and active-event inserts saved about 18 ms of query compilation in a 12 s restore; drop them to keep the change focused on the measured archive holds. * perf(sessions): bound cold cleanup writer units Publish archives per session, then clear navigation payloads and FTS rows in separately admitted units capped at 256 rows. Resume interrupted cleanup through the existing cold marker and clear embedded chunks individually. Split cold operation labels and distinguish native statement time from callback work. Preserve synchronous commit sections and atomic restoration. Validated with 37.3 GiB synthetic A/A/B and concurrent transcript appends, allocation and CPU profiles, focused backend and Control UI tests, check:changed, and independent review. * fix(ci): recognize bounded cold navigation targets
* fix(update): include cold archives in candidate snapshots Co-authored-by: steipete <[email protected]> * fix(update): preserve file archives in rehearsal snapshots Co-authored-by: steipete <[email protected]> * fix(update): preserve source WAL state during archive inventory Classify cold archive SQL under its existing candidate-state subprocess owner. Preserve incomplete WAL source families so header inspection retains private cleanup custody. Co-authored-by: steipete <[email protected]> --------- Co-authored-by: steipete <[email protected]> Release adaptation: the baseline does not contain the #195487 header-cleanup suite. Keep that unrelated suite absent; carry the new incomplete-WAL inventory assertions into the existing inventory suite instead. Add a per-change 214-line allocation for the source regression, chunk fallback, and WAL preservation tests. No schema, updater protocol, authority, or archive-integrity changes. Companion audit at 9e917f0: - #200733 is selected as the next dependency-closure repair: missing archives must warn instead of blocking updates, and Windows copies must not share live read-only inode attributes. Do not qualify this intermediate checkpoint alone. - #200076 and #200930 are independent cold-history performance changes, not prerequisites for this snapshot repair. - #201009, #200994, #200866, #200577, #200805, #200802, and #200732 overlap only adjacent update documentation and independent repair flows; not prerequisites. Proof on base 309067b: - New production-subprocess regression: 4/4 fail before, 4/4 pass after. - Cold archives, chunks, and inventory: 31/31 pass after. - Additional budget/cleanup/import siblings: 46/47 pass. Configured-cache containment fails identically on the unchanged base at budget.test.ts:737; retained as an independent failure, not weakened or repaired here. - Targeted lint and format, documentation links, SQLite worker ratchet, and test-line ratchet pass. SQLite T1 counts remain 170; compatibility 15. - Worker typecheck was blocked at dependency custody, without guard bypass. Parent canonical core typecheck, typed lint (five files), and formatting passed with its owned dependencies. Full installed-upgrade/FRV proof remains pending the assembled candidate, including selected companion #200733. (cherry picked from commit 802e3f7) Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vincentkoc <[email protected]>
What Problem This Solves
Background cold transcript archival held the per-agent SQLite writer while converting an entire large session to navigation rows and removing its search index. Queued transcript appends could not run until that work committed.
This completes the original implementation in this PR and retains its commits. Publication is atomic per session: every archive chunk is durable before the cold marker becomes visible. Readers select that complete archive immediately. Navigation payload cleanup and FTS deletion then use separately admitted transactions capped at 256 rows, with feedback targeting 20 ms. Embedded child blobs are cleared one chunk per transaction. Each unit rechecks the cold marker; queued foreground writes can run between units, and restoration cancels further cleanup. Read-only selection discovers interrupted cleanup, including sessions whose FTS rows are already gone.
Unqualified transcript projections reconcile through their existing owner before archive preparation. Idle maintenance stays read-only. No schema, index, configuration, retention, cache, or data-format change.
Cold operations now use distinct
session.cold.batch,.restore,.sweep, and.maintaintransaction labels. Their existing statement attribution records nativestatementExecutionMsseparately fromcallbackOtherMs; legacysqlMsincluded application work and cannot alone identify the cost of SQL execution.Evidence
Predeclared rule: five serial, interleaved A1/A2/B cycles from identical closed synthetic fixtures; both A arms use pinned main
ea94eb3bd38e29d17df08a957a08fa2866355110. B must beat both controls on maximum writer hold and p99 append queue wait. A throughput or CPU regression of 20% or more blocks landing. SQL-work target is 50 ms, with a fixed row ceiling rather than a promised elapsed deadline under arbitrary I/O stalls. Report every sample.Fixture: 37.30 GiB, 2,401 sessions, 6.05 million events. One eligible session has 50,000 events and 220,291,661 raw UTF-8 bytes; 2,400 hot siblings have 2,500 events each. Actual maintenance runs alongside 100 transcript appends, scheduled at 5 ms intervals after archival begins. The initial 200-append setup exceeded the existing 128-pending-task pool capacity and is retained as failed setup, not accepted timing evidence. No production data or systems were accessed.
Host: Apple M3 Ultra, 512 GiB RAM, Node 24.22.1, APFS. This reproduces database scale, not btrfs or a particular production I/O-pressure tail. Payloads are deliberately compressible; this is not an incompressible-file stress result. Workspace files are not traversed by this flow. Fresh cloned fixtures and fresh processes are used; warm-up precedes timing, and host load is recorded for every run.
Writer hold includes COMMIT and excludes BEGIN wait. Append queue wait sums the preparation and mutation admissions belonging to each real append; it is not just the final write admission. Complete-pass throughput includes preparation, publication, cleanup and page reclamation. B lowers maximum cold hold about 93% and median p99 queue wait about 91%. Throughput is 8–9% lower and CPU 8–12% higher, within the declared threshold. Commit latency dominates B's longest holds; its largest native-SQL unit is 14.92 ms.
Separate instrumented A/A/B runs captured 28 allocation and CPU profiles per arm, with files verified for every observed transaction thread before teardown. Allocation sampling includes collected objects and startup/warm-up; these are allocated-byte estimates, not retained heap or latency measurements. B allocates about 7% more. Cold-owner CPU samples total 1.72 / 1.79 / 1.45 seconds; total process CPU still rises because separately admitted units add commit/admission work.
The earlier 128-row candidate was rejected: it reduced holds but increased median CPU 23% against A2. The 256-row ceiling roughly halves cleanup transaction count while preserving short native-SQL units. Its complete results remain retained alongside the accepted series.
All five samples per arm
At five samples, nearest-rank p95 is the observed maximum. No samples were discarded.
Correctness and validation
The navigation regression fails on pinned main (eight unbounded updates instead of the bounded update, with untouched rows required to retain their exact payloads). Statement-attribution regression cases also fail on main. Tests cover interrupted navigation and FTS cleanup, restart with no FTS rows remaining, atomic rollback, exact restoration after partial cleanup, embedded-chunk recovery, foreground admission between units, and idle read-only maintenance.
Local proof is green: 66 focused backend tests (cold storage, crash recovery, admission, search worker, and native-SQL diagnostics), 17 affected Control UI browser tests, 4 transcript-search UI e2e tests,
pnpm check:changed --base ea94eb3bd38e2, changed-script lint/format, andgit diff --check. Codex autoreview is scoped-clean on the final staged implementation and profiling fix. The frozen-target follow-up at419235050498c31ba7f24e576212c431ea36626balso passes 32 consumer tests, the tooling test typecheck, shell syntax,pnpm check:changed --base 1268ef13, and scoped-clean Codex review through P2. It changes no runtime storage code, so the A/A/B and affected UI proof remain applicable. Hosted CI and ClawSweeper must qualify the exact final head before landing.Limits and implementation cost
Foreground restoration remains one atomic transaction and can still be long. File verification remains inside archive publication; statement attribution now exposes that application cost separately. Archive preparation still holds a long read snapshot, and recovery discovery can scan completed cold navigation rows outside writer admission; this PR does not claim to bound every read or every filesystem delay. Existing primary keys support the bounded write ranges, so no index proposal is required for this fix.
Production TypeScript delta against main is +309 lines, including the original PR's implementation. Growth implements the shared bounded cleanup operation, recovery selection and admission flow; extraction of the existing mutation adapter into its own file is mechanical. There is no second state owner or durable cleanup queue.
Reproduction uses the committed scripts (all directories must be new synthetic paths):
Existing-data compatibility: pre-fix main
ea94eb3bd38e29d17df08a957a08fa2866355110created and archived two synthetic sessions with 3,000 events. The candidate restored those persisted archives with an identical SHA-256 over transcript bytes, navigation, metadata and search rows, and unchanged settings. Additional running-Gateway and stable-to-candidate state-upgrade proof is recorded below. Frozen-target detection now accepts both old and bounded navigation call shapes, preserving the legacy archival distinction from #190716; both Docker consumers have red-before/green-after regression cases.Running Gateway and stable-data upgrade
Built exact head
419235050498c31ba7f24e576212c431ea36626bwithpnpm build:ci-artifacts. An isolated running Gateway receivedsessions.storage.runand concurrentchat.injectRPCs: 10,003 events / 45,272,371 bytes archived, 122 foreground appends completed, 27 appends completed between the archived session’s 82 cold write transactions. Observer classification was restricted to the archived session ID so foreground FTS inserts were not counted as cold work. Subsequent RPC restoration preserved every original transcript byte and timestamp. This is product-boundary correctness/interleaving proof, not another latency benchmark.The published 2026.11.5 Gateway imported synthetic sessions, archived two of them in its older archive format, and retained disabled cold-storage settings with the seven-day policy. After a clean stop, the candidate Gateway started on that same state, served all histories, and restored both archives through
chat.inject; all nine original events and timestamps and the selected configuration sections survived exactly. Both Gateways stopped cleanly. This tests the persisted-state upgrade through a binary switch, not the package updater itself.Main’s package version is 2026.11.4, behind the published baseline. The initial direct start correctly refused a downgrade. For the proof only, a separate copy of the exact built artifact was relabeled to 2026.11.5 with the existing
stampFixtureVersionhelper used bypublished-driver.mjs; commit/build identity and compiled code were preserved. No downgrade override, source version change, release, or live-state access was used. The initial stable harness also correctly exposed the legacy no-hot-row archive dialect; the final verifier checks exact restored data rather than imposing current navigation layout on stable.Sanitized proof output:
{"gatewayRpc":true,"events":10003,"rawTranscriptBytes":45272371,"concurrentAppends":122,"appendCompletionsBetweenColdTransactions":27,"coldTransactions":82,"exactRestoration":true} {"baseline":"2026.11.5","candidate":"419235050498c31ba7f24e576212c431ea36626b","settingsUnchanged":true,"archivedSessionsRestored":2,"originalTranscriptEventsPreserved":9,"gatewayUpgradePassed":true}