Repository navigation
improve: reuse history worker database connections - #148972
Conversation
|
🦞👀 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 maintainer review before merge. Reviewed September 15, 2026, 9:16 AM ET / 13:16 UTC (Revision 7). ClawSweeper reviewWhat this changesReuse one SQLite connection for successive chat-history reads, coordinate worker retirement with database cleanup, and update lifecycle tests and documentation. Merge readiness✅ Ready for maintainer review This remains useful, maintainer-sponsored work that current main does not provide. The prior type-cycle finding and reported cleanup failures are addressed; no remaining actionable patch defect was found. Priority: P2 Review scores
Verification
How this fits togetherGateway history requests send session selectors to a background worker, which reads the agent’s SQLite database and returns paginated messages. The database lifecycle owner coordinates cleanup so retained readers stop before database replacement. flowchart TD
A[Gateway history request] --> B[Capture database and admission]
B --> C[Bounded history queue]
C --> D[Reusable history worker]
D --> E[Validate database and read fresh snapshot]
E --> F[Return history page]
G[Database cleanup or idle expiry] --> H[Drain and retire worker]
H --> D
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +286, Tests +423, Docs +8. Total +717 across 30 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep connection reuse bounded to the history worker while preserving fresh read admission and canonical asynchronous database cleanup. Do we have a high-confidence way to reproduce the issue? Not applicable to a correctness defect: this is a performance improvement, supported by recorded repeated-read comparisons rather than a newly reproduced failure. Is this the best way to solve the issue? Yes. It extends the existing reader and database lifecycle owners without adding another persistence format or changing history selection semantics. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 83c1767446cb. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (6 earlier review cycles)
|
c1493f0 to
a64e080
Compare
a64e080 to
00b7994
Compare
00b7994 to
0eb367a
Compare
0eb367a to
48ddfdf
Compare
|
Merged via squash.
|
* improve: reuse history worker database connections * test: await retained history database cleanup
What Problem This Solves
Busy Gateways repeatedly open and close the same agent database while serving chat history across many sessions.
User Impact
The history worker retains its last database connection, reducing repeated-read latency. Each request still takes a fresh snapshot and checks identity, schema, ownership, and admission. The parent closes the idle worker after 30 minutes, as explicitly requested.
One connection is retained: switching agents closes the previous connection. This favors many sessions on one agent; alternating agents showed measurable overhead. There is no schema, configuration, data-retention, or migration change. Other read-only callers keep their existing behavior.
Why This Change Was Made
The existing read-only scope owns connection reuse; the canonical database lifecycle owns revocation and cleanup. Worker rotation drains active work, preserves queued requests, and waits for native exit before releasing custody, including Windows file replacement. Main's committed-reader companion and the history worker keep their distinct lifetimes while sharing validation. Cleanup uses the canonical asynchronous close owner, and its retired production listing helper moves to test support.
Evidence
Repeated-read comparison: fixed baseline/candidate/candidate/baseline trials used baseline
8618ee31b8b8f0ce9642d53136b0161f16a57827and candidateb5675f0d6a0833b1fc7bcc6f2f14664c456a56f9on one dedicated Testbox. All 40 samples were retained. For 128 repeated calls, paired median latency improved 42–43% and process CPU 34–41%. Alternating-agent latency worsened 0.5% and 10.3%; CPU worsened 3.5% and 17.1%. Response and external-append freshness checks matched. These standalone public-history measurements include response checks and diagnostics; they are not Gateway-throughput results. An earlier separate constructor census recorded one open versus 128 for hot reads, and 127 versus 128 when alternating agents.Linux and Windows: 45 selected behavioral cases and 17 final initialization-guard tests passed, with typed lint, affected type graphs, guards, and formatting. Native Windows/Node 26.8.2 passed four lifecycle cases covering actual worker exit before SQLite copy/rename/reopen, unrelated-agent continuity, revocation, and idle expiry. Captured processes exited; the wrapper's retained temporary namespace remains preserved with its non-group cleanup qualification. Independent reviews found no actionable P0–P2 issues. The 25 changed files at
b5675f0dmatch the final tested/reviewed source; the base refresh was patch-identical.Integration:
c1493f0fcce8f779841e87bd00a96ba1f04e7100, based on140ae96507aed5c58ae6c51e13cfc623c85d157a, passed 42 integration cases, production types, all 19 dependency-selected test-type groups, dead-export/docs/format guards, and fresh P2 review. The 42 tests preceded an equivalent conditional-format cleanup; final lint/types checked the resulting bytes. Reviewed hashes survived commit unchanged. These functional checks do not reassign the earlier benchmark's source pin.Gateway/live proof: campaign 34953883478 at
b5675f0dpassed a 1,000-session mock workload and eight live OpenAI turns with matching streamed, final, RPC-history, and persisted results. All 126 artifact hashes and frozen source/harness/compiled bytes verified. Its observer recorded 12 Responses creations, two embedding requests, and 11 UNKNOWN transport errors; these are neither billing nor failed-turn counts. Owned groups exited and the lease completed; scenario receipts, rather than shutdown-related workflow cancellation, establish completion.Composed-source limits: campaign 34957921006 at
cb1f9926e32b7dae787c5fd89fc164f91c971a0dcombined main2b8c9f1with history and timestamp changes. Its 1,000-session/96-turn mock and eight live turns passed; 48 artifacts, 43,151 source files, process cleanup, and lease completion verified. Normal indexing/recaps remained enabled; dreaming was disabled. Main-thread saturation remained and all 128 readiness samples were degraded. No overall throughput improvement is claimed. Observer totals—11 Responses creations, one embedding request, ten UNKNOWN events—retain the same transport qualification.Static correction: reviewed commit
00b7994960255e4a860ea10b98dd3651d5083b89moves public types into the leaf owner, fixing this PR's Madge cycle. Architecture reports zero cycles; targeted lint, core/SDK types, dead exports, and review pass. Both files emit identical JavaScript under esbuild and TypeScript. This correction is not relabeled as live execution of a newer head.Allocation capture: mock-only campaign 34960684602 at
c4a44acfc73905ba34c8c41b7f3d1a356197dd92includes the reviewed type correction and timestamp change on2b8c9f1. All probes passed; 38 artifact hashes, exact inventory, 43,151 source files and compiled/harness bytes verified. Gateway/archive exited 0, owned groups died, the fixture was removed, and the lease completed. Six worker profiles completed; one retired target is missing, with no sampler errors. Approximately 15.009 GB of cumulative main allocation sampling is neither retained heap, exact allocation, leak/GC-causality proof nor timing evidence; a follow-up serializer prototype was rejected because representative transcript cases and peak memory regressed.Current source: 48ddfdf, based on e00500a. The production patch is identical to reviewed
00b7994; the refresh also includes the reviewed cleanup correction originally committed as84790e2. Range-diff confirms both commits retained identical patches. Earlier live and timing evidence retain their stated source pins; no latest-head live execution or overall Gateway speedup is claimed.The previous CI run 34964922246 passed Windows suites, build, production types and architecture, but failed four lanes: checkout before execution; six inherited auth-fixture failures now repaired by #149049 on this base; config observation rejecting with
STATE_DATABASE_READ_ADMISSION_INVALIDATED; and four Talk-history reopen cases introduced by this PR's incomplete caller migration. Existing #148839 addresses the config-observation retirement and remains separate, unmerged work. That inherited failure is not claimed repaired here.The caller correction awaits canonical asynchronous close at both Talk reopen checkpoints and before two sibling history fixtures remove temporary databases. The original Talk file reproduced four failures; all 63 cases across the corrected files passed. Selected Gateway test types, formatting, guards, dead-export scans, lint, and fresh independent review passed; committed file hashes match the reviewed/tested source. No assertions or deadlines changed.
Fresh exact-head CI run 34971792232 passed on
48ddfdfa9cfb867951a65dacf3fc60e4e367e929, including the history cleanup, config-inspection, and inherited-auth lanes. The native preparation gates passed on that same unchanged head.