Skip to content

improve: keep Gateway responsive while loading session history - #147363

Merged
steipete merged 2 commits into
mainfrom
codex/session-history-read-workers
Sep 13, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/session-history-read-workers

Conversation

@steipete

@steipete steipete commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Related: #138042
Builds on: #147234

What Problem This Solves

Loading large or concurrent session-history pages occupies the Gateway event loop with SQLite reads and display preparation, delaying other requests.

User Impact

History preparation leaves more time for the Gateway to serve other requests. Equivalent queued requests share work; later reads take fresh snapshots. Incognito and bound CLI history retain their local behavior. No configuration, schema, or transcript-format change is required.

This has a resource tradeoff: measured cold history reads take 424–477 ms, versus 10–34 ms locally, and can recur after the existing 60-second worker idle retirement. Warm whole-process RSS is about 270 MiB higher. Distinct requests use more CPU, and small-page tail latency can increase. Large-page responsiveness improves substantially; this does not eliminate other Gateway stalls. The bounded worker is an intentional resource tradeoff for responsiveness during history bursts.

Why This Change Was Made

Use one page-preparation implementation for local and worker reads, returning completed display pages across the worker boundary. Coalesce only equivalent queued requests and charge every retained caller, including canceled callers until settlement. Current profile overlays, cold restoration, reconciliation, and final identity/access checks remain with their existing Gateway owners. Worker failures produce explicit retryable responses.

Move synchronous preview preparation out of the history read module, load CLI history support only for bound sessions, and share pure error-presentation functions without importing the live provider/plugin loader. Shared worker data types live in a leaf contract, avoiding a dependency cycle through Gateway implementations. Superseded raw-snapshot and duplicate test helpers are removed.

Evidence

Three alternating baseline/candidate process pairs on the same Linux Testbox (4 available CPUs, Node 24.19.0). Each process contains 1,200 synthetic messages of 1,024 characters, five warm samples per workload, and eight concurrent requests. All 972 measured responses match expected contents; append/reset checks and process cleanup pass.

Workload History latency p50, baseline → candidate Median worst readiness latency per batch Median paired CPU change
Equivalent 20-message pages 15.9 → 9.8 ms 12.1 → 4.6 ms −18%
Distinct 20-message pages 13.4 → 12.1 ms 8.7 → 3.5 ms +36%
Equivalent 1,000-message pages 114.0 → 85.3 ms 92.0 → 63.3 ms −27%
Distinct 1,000-message pages 96.8 → 80.1 ms 76.2 → 11.2 ms +33%

CPU changes use the median effect across the three matched process pairs; the first baseline process was noisier. CPU includes workers and readiness probes and is sampled in 10 ms kernel ticks. RSS is sampled at batch endpoints, not measured as a peak. Small-page p95 latency is mixed: equivalent pages 26.5 → 45.2 ms; distinct pages 28.5 → 31.2 ms.

The earlier worker version took 535–621 ms on first reads. The final dependency cut brought this to 424–477 ms on the reused host, a directional comparison across successive runs. It retains an explicit cold-start cost.

The real Gateway proof passes all 12 API cases with 466 synthetic writes and zero history retries: RPC/startup pages, exact anchors, UTF-8/byte budgets, JSON/SSE agreement, cursor/reset behavior, and persistence across process replacement. The combined workload completes all 400 history reads, 12 turns, 40 session updates, and expected control-plane probes. Its history p95 is 467 ms and maximum 585 ms; rolling event-loop samples still report pressure. The repaired built-CLI SQLite lifecycle proof also passes. These use synthetic provider responses with real Gateway/storage/transports, with memory indexing disabled in the history measurement; no browser-rendering or external-provider claim is made.

Remote proof: https://github.com/openclaw/openclaw/actions/runs/34779458989 . All Gateway processes and the owned Testbox lease are stopped and independently verified. The measured staged source tree is e05403707184f99aa3d3b79d152b1e7188b64322, based on a250dd68; it includes the final presentation cut. Subsequent repairs move types without changing emitted production JavaScript and update test observation points. Commit 0dd2ab2bdc583bc7778d7698aadfbd8db3fe2d22 is bound to this evidence: the four changed production modules emit identical JavaScript, the other measured runtime sources are byte-identical, and the new type contract has no runtime imports or statements. The final rebase, 6fee6b081992b4f27862a07d35a6350df7d0a82b, keeps 57 of 58 PR-owned files byte-identical and combines the worker read-only option with main’s independently landed async cold-retry fix. Package and lockfile are unchanged; current-main integration has separate checks rather than a claim that all transitive inputs were unchanged.

Local validation includes 290 worker/CLI/Talk/profile cases, then 262 presentation/classification/history cases. Independent reviews found no actionable P0–P2 issues. CI exposed stale profile-reader mocks, a main-thread spy that cannot observe worker projection, a type-only dependency cycle, and a proof assuming a concurrent reset/read always succeeds. The repairs preserve assertions, move the linear-work guard onto the shared read kernel, break the type cycle with the shared contract, and verify fresh reset/deletion history after the exact retryable superseded-read outcome. The final repair pass passes all 240 cases in the nine affected files and all selected type, lint, cycle, SQLite, and dead-export checks. The sparse-work guard was shown to reject a repeated-prefix projection mutation (5,625 rows against a 3,000 limit), then passed after exact source restoration. After that main refresh, all 28 selected cold-reader, storage, and native-worker cases pass, and a fresh complete-branch review is scoped-clean through P2. Exact-head CI passed for 6fee6b081992b4f27862a07d35a6350df7d0a82b: https://github.com/openclaw/openclaw/actions/runs/34784416641 .

@steipete
steipete marked this pull request as ready for review September 13, 2026 20:02
@clawsweeper

clawsweeper Bot commented Sep 13, 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 agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 13, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 13, 2026, 5:49 PM ET / 21:49 UTC (Revision 3).

ClawSweeper review

What this changes

Moves disk-backed session-history reads and display preparation into a bounded worker, preserving local incognito and CLI-import behavior and rechecking access before publishing results.

Merge readiness

⛔ Blocked before merge - 1 item remains

This PR remains useful and has no identified blocking correctness defect. The final rebase preserves cold-read recovery, and the discussion explicitly accepts the resource tradeoff raised in the previous review.

Priority: P2
Reviewed head: 6fee6b081992b4f27862a07d35a6350df7d0a82b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent implementation with strong comparative runtime evidence, no blocking finding, and explicitly accepted resource costs.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied Linux observations exercise real Gateway RPC/HTTP history, SQLite storage, cursor/reset behavior, and process replacement with synthetic provider responses, showing correct contents and improved readiness. The verified 57-file identity comparison preserves the prior proof assessment; the remaining cold-retry integration has separately reported targeted validation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied Linux observations exercise real Gateway RPC/HTTP history, SQLite storage, cursor/reset behavior, and process replacement with synthetic provider responses, showing correct contents and improved readiness. The verified 57-file identity comparison preserves the prior proof assessment; the remaining cold-retry integration has separately reported targeted validation.
Evidence reviewed 9 items Current main still needs the history worker: At fetched main, the transcript worker supports model-context reads and background session-entry preparation, while chat-history pages still invoke transcript reading and display preparation locally. The merged indexing work at #147234 addresses a different workload.
Worker admission and storage ownership: The new history pool has one worker. Equivalent requests share only queued execution; every retained caller consumes capacity until settlement. Worker reads use the existing read-only SQLite path, while restoration and projection reconciliation remain in the Gateway.
Final publication checks: HTTP JSON responses, SSE snapshots, refreshes, and inline updates pass through current authentication, scope, session-identity, lifecycle, and visibility checks before publication. RPC delta responses also recheck sharing after awaited restoration. Focused coverage withholds payloads following revocation, replacement, or reset.
Findings None None.
Security None None.

How this fits together

The Gateway serves conversation history to RPC and HTTP clients from SQLite transcripts. History preparation produces display-ready messages, while the Gateway retains responsibility for storage recovery, current profile information, and permission checks.

flowchart TD
  A[RPC and HTTP history requests] --> B[Select history source]
  B --> C[Incognito or CLI local reader]
  B --> D[Bounded history worker]
  E[SQLite transcripts] --> D
  D --> F[Prepared display page]
  C --> F
  F --> G[Gateway profile and access checks]
  G --> H[History response or retryable error]
Loading

Before merge

  • Resolve merge risk (P1) - Smaller-host headroom remains unmeasured: the accepted worker design adds about 270 MiB warm RSS and 424–477 ms cold reads, potentially recurring after idle retirement; distinct-request CPU and small-page tail latency can also increase.
Agent review details

Security

None.

PR surface

Source +467, Tests +705, Docs +2. Total +1174 across 58 files.

View PR surface stats
Area Files Added Removed Net
Source 30 1047 580 +467
Tests 27 1460 755 +705
Docs 1 3 1 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 58 2510 1336 +1174

Review metrics

Metric Value Why it matters
Large distinct-page readiness 76.2 → 11.2 ms The reported median worst readiness latency per batch measures the central responsiveness benefit.
Production versus test growth Production net +467 lines; tests and test support net +705 lines Production growth has a stated purpose: bounded worker admission, shared contracts, and publication safeguards.

Merge-risk options

Maintainer options:

  1. Retain the accepted resource tradeoff (recommended)
    Proceed under the explicit acceptance already recorded in discussion, keeping the memory and cold-start costs visible without claiming smaller-host validation.

Technical review

Best possible solution:

Retain one bounded history worker and the shared page kernel, with Gateway-owned recovery and final access checks under the documented, accepted resource tradeoff.

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

Yes for the main-thread history-work mechanism: current main performs SQLite reads and display preparation through local async APIs, and the supplied paired measurements exercise that workload. This review did not reproduce the original multi-minute incidents.

Is this the best way to solve the issue?

Yes. Reusing the existing page kernel and worker infrastructure moves expensive preparation off the Gateway thread while preserving storage and publication ownership.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 7944cd5c8263.

Labels

Label justifications:

  • P2: This is a bounded Gateway performance improvement with measured benefit, without proof that it resolves every reported multi-minute stall.
  • merge-risk: 🚨 availability: The additional worker increases memory and cold-start costs, leaving smaller-host capacity uncertain despite explicit acceptance of the tradeoff.
  • 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 (live_output): The supplied Linux observations exercise real Gateway RPC/HTTP history, SQLite storage, cursor/reset behavior, and process replacement with synthetic provider responses, showing correct contents and improved readiness. The verified 57-file identity comparison preserves the prior proof assessment; the remaining cold-retry integration has separately reported targeted validation.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied Linux observations exercise real Gateway RPC/HTTP history, SQLite storage, cursor/reset behavior, and process replacement with synthetic provider responses, showing correct contents and improved readiness. The verified 57-file identity comparison preserves the prior proof assessment; the remaining cold-retry integration has separately reported targeted validation.

Evidence

What I checked:

  • Current main still needs the history worker: At fetched main, the transcript worker supports model-context reads and background session-entry preparation, while chat-history pages still invoke transcript reading and display preparation locally. The merged indexing work at improve: reduce Gateway stalls during session indexing #147234 addresses a different workload. (src/config/sessions/session-transcript-worker-runtime.ts:18, 7944cd5c8263)
  • Worker admission and storage ownership: The new history pool has one worker. Equivalent requests share only queued execution; every retained caller consumes capacity until settlement. Worker reads use the existing read-only SQLite path, while restoration and projection reconciliation remain in the Gateway. (src/config/sessions/session-history-worker-runtime.ts:42, 6fee6b081992)
  • Final publication checks: HTTP JSON responses, SSE snapshots, refreshes, and inline updates pass through current authentication, scope, session-identity, lifecycle, and visibility checks before publication. RPC delta responses also recheck sharing after awaited restoration. Focused coverage withholds payloads following revocation, replacement, or reset. (src/gateway/sessions-history-http.ts:233, 6fee6b081992)
  • Re-review continuity verified: A complete GitHub tree comparison against previously reviewed 0dd2ab2bdc583bc7778d7698aadfbd8db3fe2d22 found 57 of 58 PR-owned files byte-identical. The sole changed file preserves the worker read-only option and main's async cold-read retry. The earlier object was unavailable locally; GitHub tree and contents reads supplied the comparison. (src/config/sessions/session-cold-storage-read.ts:36, 6fee6b081992)
  • Real Gateway measurements: The supplied body snapshot, sourceRevision 441a18534dd47b2779841a7ce093b705146825d28cdabdc82d31dafe0464891b, reports three paired Linux runs, 972 matching history responses, 12 real Gateway API cases, and a combined workload completing 400 history reads. It identifies measured tree e05403707184f99aa3d3b79d152b1e7188b64322 and explains its binding to the previously reviewed commit. Synthetic provider responses were used with real Gateway, SQLite, and transports; browser rendering and external-provider behavior are outside the claim. (0dd2ab2bdc58)
  • Prior resource decision resolved: The comment at improve: keep Gateway responsive while loading session history #147363 (comment) explicitly accepts the measured cold-start, RSS, distinct-request CPU, and small-page tail costs. It also records 28 targeted checks after the rebase. This resolves the previous review's acceptance question without claiming suitability for smaller hosts. (6fee6b081992)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • Josh Lehman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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 (2 earlier review cycles)
  • reviewed 2026-09-13T20:13:17.700Z sha a250dd6 :: blocked before merge. :: none
  • reviewed 2026-09-13T21:30:11.207Z sha 0dd2ab2bdc583bc7778d7698aadfbd8db3fe2d22 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 13, 2026
@steipete
steipete force-pushed the codex/session-history-read-workers branch from 0dd2ab2 to 6fee6b0 Compare September 13, 2026 21:38
@steipete

Copy link
Copy Markdown
Contributor Author

The measured resource tradeoff is accepted for this change: a single bounded history worker improves large-read responsiveness, with the documented cold-start, RSS, distinct-request CPU, and small-page tail costs. The PR body keeps those costs visible; it does not claim uniformly faster requests or measured suitability for smaller hosts.

The only merge conflict was main independently landing the async cold-transcript retry repair. It is resolved in 6fee6b0, preserving the read-only worker path and main's retry behavior. The other 57 PR-owned files and package/lock inputs are unchanged. All 28 targeted integration checks pass, and a fresh complete-branch independent review has no actionable P0–P2 findings. Exact-head CI is running: https://github.com/openclaw/openclaw/actions/runs/34784416641 .

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete
steipete merged commit 4acd0eb into main Sep 13, 2026
200 of 202 checks passed
@steipete
steipete deleted the codex/session-history-read-workers branch September 13, 2026 22:01
@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

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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