Skip to content

perf(gateway): retain history readers across agent switches - #150519

Merged
steipete merged 1 commit into
mainfrom
codex/perf-history-retention-5152
Sep 17, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf-history-retention-5152

Conversation

@steipete

@steipete steipete commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Related: #145579

What Problem This Solves

Reading conversation history across multiple agents repeatedly closes and reopens their databases, even though the history worker stays alive for 30 minutes.

User Impact

History reads across agents reuse open connections while preserving current database admission and committed-data visibility. No configuration or stored-data migration is required. The single history worker retains at most 64 database connections, evicts the least recently used target at capacity, and closes its connections after 30 minutes without pending history work. This is a worker idle timeout; activity for another agent can keep retained connections open.

Why This Change Was Made

Keep successful per-target read scopes in the existing serialized worker and report confirmed closures to the existing parent resource owner. Missing stores consume no retained slots. Explicit database cleanup and worker failures still revoke custody and join native worker exit. An empty worker created by missing-store reads also expires after 30 minutes without inventing database custody.

The tradeoff is additional open handles: the 32-agent fixture observed 223 file descriptors versus 192 after warmup; both returned to 44 after owned cleanup. RSS varied across fresh processes and does not isolate the connection cost. Persistent storage, schema, row selection and read transaction boundaries are unchanged.

Evidence

  • 42 focused tests passed, covering admission and identity rechecks, committed snapshots, queued history, cross-target cleanup, 64-target eviction, missing stores and both idle retirement cases. Typed lint and independent P0–P2 review passed.
  • Actual history entry-point census at base 13c6d9e: for 128 warm reads, alternating targets went from 127 physical opens to zero; rotating 32 targets went from 128 to zero. Full result checksums matched and an external append remained visible after switching targets. Both census processes exited successfully and their groups/fixtures were absent.
  • The fully joined baseline/candidate timing pair measured alternating-agent median latency 612.081 → 300.405 ms and 32-agent rotation 547.981 → 316.281 ms per 128 reads. These are standalone entry-point measurements including response validation, not Gateway throughput. Single-agent results were mixed. All samples were retained; a supporting second pair has an explicitly unknown candidate exit code because external FD sampling failed during teardown, despite complete results and verified cleanup. Concurrent host work may have affected the later baseline arm.
  • 28 selected non-type guards passed, including formatting/docs checks, dead exports, import cycles, storage guards and diff checks. The first dead-export attempt could not resolve UI workspace dependencies; adding the missing task-only link to already-installed dependencies allowed its single retry to pass. Local production types stopped before compilation because the maintained declaration checker rejects ancestor-install resolution in this nested worktree; exact-head hosted type/build gates remain required before landing.

Updated onto main at 26d2daa2c294b4f260187e4edb5ecea224ce876c, which includes the landed Qwen CI repair #150523. All files in this PR retain their previously reviewed and tested bytes; the duplicate local clock-fixture change is removed. Fresh exact-head checks validate the updated base.

@steipete steipete self-assigned this Sep 17, 2026
@steipete
steipete marked this pull request as ready for review September 17, 2026 02:41
@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Sep 17, 2026
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 17, 2026
@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 16, 2026, 11:26 PM ET / September 17, 2026, 03:26 UTC (Revision 2).

ClawSweeper review

What this changes

Retain up to 64 history database connections across agent switches, with least-recently-used eviction, tracked cleanup, and idle worker retirement.

Merge readiness

✅ Ready for maintainer review

This remains a useful performance improvement: current main still closes the previous connection when switching agents. No actionable correctness or security findings were identified, and all five touched files match the previously reviewed head.

Priority: P2
Reviewed head: 5c2994940b0c5a3044cbcdd5a1b58cef0393e3cb

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with relevant entry-point measurements, meaningful lifecycle coverage, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured production history-entry-point census demonstrates cross-agent connection reuse, matching responses, external-append freshness, and completed cleanup. The fully joined timing pair supports the improvement; inspected native-worker tests supplement lifecycle coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured production history-entry-point census demonstrates cross-agent connection reuse, matching responses, external-append freshness, and completed cleanup. The fully joined timing pair supports the improvement; inspected native-worker tests supplement lifecycle coverage.
Evidence reviewed 9 items Current main still has the switching cost: The fetched main worker uses one historyDatabaseScope for both history pages and row-presence reads. Switching its target closes the previous connection, so the proposed cross-agent reuse is not already implemented.
Bounded retention and confirmed closure: The worker retains successful scopes by database target, excludes missing connections, and closes the least recently used scope after exceeding 64 retained targets. The parent releases custody only for a reported closure whose sequence has not been superseded.
Existing admission and read boundaries remain authoritative: The retained scope still checks physical identity and schema ownership before reuse. The history reader performs canonical admission and projection reads for each invocation; connection retention does not retain an authorization result or transaction.
Findings None None.
Security None None.

How this fits together

The Gateway serves conversation history through a serialized worker that reads per-agent SQLite databases. This change reuses database connections while preserving fresh snapshots and per-request admission checks.

flowchart TD
  A[History or presence request] --> B[Parent database custody]
  B --> C[Serialized history worker]
  C --> D[Retained connection pool]
  D --> E[Identity and admission checks]
  E --> F[Fresh database read]
  F --> G[History or presence result]
  D --> H[Eviction or joined worker cleanup]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +44, Tests +67, Docs +1. Total +112 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 101 57 +44
Tests 1 84 17 +67
Docs 1 5 4 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 190 78 +112

Review metrics

Metric Value Why it matters
Connection retention 1 → 64 targets; 30-minute worker idle timeout unchanged The bound reduces cross-agent reopen work while limiting retained native resources.
Observed handle cost 32-agent fixture: 192 → 223 descriptors; both returned to 44 The recorded measurement makes the additional-handle tradeoff and cleanup result explicit.
Production versus test growth Production net +44 lines; tests net +67 lines Production growth implements bounded retention and custody reporting; tests cover eviction and worker retirement.

Technical review

Best possible solution:

Keep connection reuse inside the existing serialized history worker, with bounded retention and the existing per-read validation and joined cleanup owners.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a functional bug reproduction: this optimizes existing behavior. Current-main source confirms connection churn on target switches, and the supplied entry-point census measures it.

Is this the best way to solve the issue?

Yes. Extending the existing worker's connection retention avoids a parallel reader owner and preserves the established snapshot, admission, and cleanup contracts.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9843b937e354.

Labels

Label justifications:

  • P2: This is a bounded Gateway history performance improvement with measured benefits for multi-agent reads.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured production history-entry-point census demonstrates cross-agent connection reuse, matching responses, external-append freshness, and completed cleanup. The fully joined timing pair supports the improvement; inspected native-worker tests supplement lifecycle coverage.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured production history-entry-point census demonstrates cross-agent connection reuse, matching responses, external-append freshness, and completed cleanup. The fully joined timing pair supports the improvement; inspected native-worker tests supplement lifecycle coverage.

Evidence

What I checked:

  • Current main still has the switching cost: The fetched main worker uses one historyDatabaseScope for both history pages and row-presence reads. Switching its target closes the previous connection, so the proposed cross-agent reuse is not already implemented. (src/config/sessions/session-transcript.worker.ts:94, 9843b937e354)
  • Bounded retention and confirmed closure: The worker retains successful scopes by database target, excludes missing connections, and closes the least recently used scope after exceeding 64 retained targets. The parent releases custody only for a reported closure whose sequence has not been superseded. (src/config/sessions/session-transcript.worker.ts:98, 5c2994940b0c)
  • Existing admission and read boundaries remain authoritative: The retained scope still checks physical identity and schema ownership before reuse. The history reader performs canonical admission and projection reads for each invocation; connection retention does not retain an authorization result or transaction. (src/state/openclaw-agent-db-readonly-scope.ts:56, 5c2994940b0c)
  • Lifecycle regression coverage: The complete test file exercises real Worker instances and SQLite fixtures, including cleanup of retained A while B remains active, 65-target eviction, missing-store reads, and idle retirement with and without database custody. These tests were inspected, not executed during this read-only review. (src/gateway/session-history-worker-lifecycle.test.ts:248, 5c2994940b0c)
  • Recorded production entry-point proof: The captured PR body reports actual history-entry-point runs: alternating and 32-agent warm reads reduced physical opens to zero, complete response checksums matched, and an external append remained visible after switching targets. The fully joined timing pair and cleanup results support the changed behavior; the separately qualified timing pair is not treated as independent completion proof. Captured context revision: e59cefeaadd1afaae4c6a392ffdd6e9440823ee993470505356ec3b991c985fe.
  • Previous review continuity verified: GitHub contents queries for each of the five touched files at the earlier reviewed head returned blob identities identical to the current checkout's git ls-tree results. This recovered continuity verification after local access to the earlier commit failed; no prior findings or published rank-up moves remain outstanding. (src/config/sessions/session-transcript.worker.ts, 69a675df63fb)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • 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 (1 earlier review cycle)
  • reviewed 2026-09-17T02:50:17.081Z sha 69a675df63fb6d7f9eae986e986368bd52202e4e :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/perf-history-retention-5152 branch from 9a7ef99 to 5c29949 Compare September 17, 2026 03:19
@steipete
steipete merged commit b0b7441 into main Sep 17, 2026
214 of 215 checks passed
@steipete
steipete deleted the codex/perf-history-retention-5152 branch September 17, 2026 03:44
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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: M 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