Skip to content

improve: reuse history worker database connections - #148972

Merged
steipete merged 2 commits into
mainfrom
codex/gateway-perf7-readonly
Sep 15, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/gateway-perf7-readonly

Conversation

@steipete

@steipete steipete commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

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 8618ee31b8b8f0ce9642d53136b0161f16a57827 and candidate b5675f0d6a0833b1fc7bcc6f2f14664c456a56f9 on 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 b5675f0d match the final tested/reviewed source; the base refresh was patch-identical.

  • Integration: c1493f0fcce8f779841e87bd00a96ba1f04e7100, based on 140ae96507aed5c58ae6c51e13cfc623c85d157a, 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 b5675f0d passed 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 cb1f9926e32b7dae787c5fd89fc164f91c971a0d combined main 2b8c9f1 with 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 00b7994960255e4a860ea10b98dd3651d5083b89 moves 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 c4a44acfc73905ba34c8c41b7f3d1a356197dd92 includes the reviewed type correction and timestamp change on 2b8c9f1. 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 as 84790e2. 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.

@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@steipete steipete self-assigned this Sep 15, 2026
@steipete
steipete marked this pull request as ready for review September 15, 2026 09:28
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Sep 15, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 15, 2026, 9:16 AM ET / 13:16 UTC (Revision 7).

ClawSweeper review

What this changes

Reuse 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
Reviewed head: 48ddfdfa9cfb867951a65dacf3fc60e4e367e929

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with strong, appropriately qualified behavior evidence and no remaining actionable findings.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (linked_artifact): Recorded public-history trials exercise the retained-reader path with matching responses and append freshness, supplemented by native Windows cleanup and live RPC-history results. Evidence retains its stated older source pins; current cleanup corrections have separate focused validation, and blocked raw-log retrieval is a reviewer limitation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): Recorded public-history trials exercise the retained-reader path with matching responses and append freshness, supplemented by native Windows cleanup and live RPC-history results. Evidence retains its stated older source pins; current cleanup corrections have separate focused validation, and blocked raw-log retrieval is a reviewer limitation.
Evidence reviewed 8 items Current-main necessity: Fetched main still uses runSessionHistoryWorkerRequest without a retained database scope. The merged companion-reader work at #148868 serves cached writers and does not implement this worker lifetime.
Retained reader validation: The retained scope checks physical identity, schema and agent ownership before reuse, uses a fresh reader for nested transactions, and leaves extension-capable and incognito paths outside the new scope.
Cleanup and queue ownership: Database custody is registered before restoration awaits; revocation is checked before dispatch and before returning results. Rotation pauses dispatch, drains active tasks, joins native exit and preserves queued work.
Findings None None.
Security None None.

How this fits together

Gateway 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
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +286, Tests +423, Docs +8. Total +717 across 30 files.

View PR surface stats
Area Files Added Removed Net
Source 7 400 114 +286
Tests 22 467 44 +423
Docs 1 10 2 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 30 877 160 +717

Review metrics

Metric Value Why it matters
Retained worker resources 1 reader; 30-minute idle retirement Reuse is bounded independently of session count, with database switches closing the previous reader.
Production versus test growth Production net +286 lines; tests and test support net +423 lines Production growth implements retained-reader custody and graceful rotation, with focused lifecycle coverage.

Technical review

Best 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.

Labels

Label justifications:

  • P2: This is a bounded history-read performance improvement with measured benefit and no demonstrated urgent production regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): Recorded public-history trials exercise the retained-reader path with matching responses and append freshness, supplemented by native Windows cleanup and live RPC-history results. Evidence retains its stated older source pins; current cleanup corrections have separate focused validation, and blocked raw-log retrieval is a reviewer limitation.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded public-history trials exercise the retained-reader path with matching responses and append freshness, supplemented by native Windows cleanup and live RPC-history results. Evidence retains its stated older source pins; current cleanup corrections have separate focused validation, and blocked raw-log retrieval is a reviewer limitation.

Evidence

What I checked:

  • Current-main necessity: Fetched main still uses runSessionHistoryWorkerRequest without a retained database scope. The merged companion-reader work at improve: reduce repeated session read stalls #148868 serves cached writers and does not implement this worker lifetime. (src/config/sessions/session-transcript-worker-runtime.ts:108, 83c1767446cb)
  • Retained reader validation: The retained scope checks physical identity, schema and agent ownership before reuse, uses a fresh reader for nested transactions, and leaves extension-capable and incognito paths outside the new scope. (src/state/openclaw-agent-db-readonly.ts:47, 48ddfdfa9cfb)
  • Cleanup and queue ownership: Database custody is registered before restoration awaits; revocation is checked before dispatch and before returning results. Rotation pauses dispatch, drains active tasks, joins native exit and preserves queued work. (src/config/sessions/session-transcript-worker-runtime.ts:181, 48ddfdfa9cfb)
  • Re-review continuity: GitHub blob identities for the history runtime, retained-reader owner and worker pool match the previous reviewed head 0eb367a. Shared contracts now live in the leaf types module. The latest cleanup correction awaits asynchronous close at both Talk reopen checkpoints and before sibling fixture removal. (src/gateway/server.talk-consult-history.test.ts:576, 48ddfdfa9cfb)
  • Recorded behavior proof and limits: The fully supplied PR body, captured under sourceRevision 32805d60c5c5379e0d0adc1b851a63ac6498a88ecf4b589a07dc1c5ff9f79357, records same-host baseline/candidate trials at b5675f0d6a0833b1fc7bcc6f2f14664c456a56f9: repeated-read latency improved 42–43%, with matching responses and external-append freshness. Alternating-agent trials were slower. It also records native Windows lifecycle proof and eight live turns with matching RPC history. These remain older-source observations, not latest-head execution or overall Gateway throughput proof. GitHub confirmed the linked campaign exists; raw-log retrieval was blocked by the reviewer network’s artifact-host allowlist. (b5675f0d6a08)
  • Behavioral regression coverage: Inspected tests exercise actual worker exit before SQLite replacement, unrelated-agent continuity, revocation during restoration, overload isolation, idle retirement, independent snapshots and changed schema ownership. Tests were not executed during this read-only review. (src/gateway/session-history-worker-lifecycle.test.ts:114, 48ddfdfa9cfb)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (6 earlier review cycles)
  • reviewed 2026-09-15T09:46:53.368Z sha b5675f0d6a0833b1fc7bcc6f2f14664c456a56f9 :: blocked before merge. :: none
  • reviewed 2026-09-15T10:08:33.313Z sha b5675f0d6a0833b1fc7bcc6f2f14664c456a56f9 :: blocked before merge. :: none
  • reviewed 2026-09-15T10:33:02.354Z sha a64e080ffd71be096505ac4c8a38fa30de9924d2 :: blocked before merge. :: none
  • reviewed 2026-09-15T10:43:05.952Z sha a64e080ffd71be096505ac4c8a38fa30de9924d2 :: needs changes before merge. :: [P2] Move shared worker contracts into the leaf types module
  • reviewed 2026-09-15T10:54:35.427Z sha a64e080ffd71be096505ac4c8a38fa30de9924d2 :: needs changes before merge. :: [P2] Move shared worker contracts into the leaf types module
  • reviewed 2026-09-15T11:51:05.443Z sha 0eb367a :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 15, 2026
@steipete
steipete force-pushed the codex/gateway-perf7-readonly branch 2 times, most recently from c1493f0 to a64e080 Compare September 15, 2026 10:22
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Sep 15, 2026
@steipete
steipete marked this pull request as draft September 15, 2026 11:35
@steipete
steipete force-pushed the codex/gateway-perf7-readonly branch from a64e080 to 00b7994 Compare September 15, 2026 11:35
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: XL and removed size: L labels Sep 15, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 15, 2026
@steipete
steipete force-pushed the codex/gateway-perf7-readonly branch from 0eb367a to 48ddfdf Compare September 15, 2026 12:55
@steipete
steipete merged commit 020be31 into main Sep 15, 2026
201 of 202 checks passed
@steipete
steipete deleted the codex/gateway-perf7-readonly branch September 15, 2026 14:29
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 16, 2026
* improve: reuse history worker database connections

* test: await retained history database cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant