Skip to content

perf(gateway): show the first chat sooner after a Gateway start - #162936

Merged
steipete merged 2 commits into
mainfrom
perf/gateway-history-worker-cold-start
Oct 1, 2026
Merged

steipete merged 2 commits into
mainfrom
perf/gateway-history-worker-cold-start

Conversation

@steipete

@steipete steipete commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

The first chat load after a Gateway start waits on the history worker loading modules: chat.startup spent about 1.2 s importing the session lookup and runtime graph before running a ~50 ms history read.

User Impact

User impact: opening a chat right after the Gateway starts or restarts shows the transcript sooner. In interleaved restart pairs at 0 ms added RTT, first-load chat.startup dropped from a 699 ms to a 57 ms median and time to visible transcript from 2,456.5 ms to 1,818.5 ms. Warm loads, history results, admission, and readiness timing are unchanged.

Why This Change Was Made

The history reader reached the full host session lookup/runtime graph only to pick candidate stores; that candidate selection now lives in its own small owner shared by host lookups and the worker. Branch snapshots and their watermark cache are likewise separated from host-side list coordination and archive restoration, so the branch worker no longer loads writer-side modules. The existing post-ready prewarm now prepares the complete history path first (readers, response encoder, read-only admission) and may overlap foreground browser loading; other prewarm items stay idle-gated, and readiness never awaits any of it. Database custody, admission, cleanup, and result validation are unchanged.

Evidence

Four interleaved restart rounds against a build of main 83a974025cbb with identical synthetic sessions (1,500 turns plus 30 × 60 turns), fresh browser profiles, and bundled UI (ms):

Measurement Main runs This PR runs Median
Cold chat.startup (server) 647, 751, 556, 1034 59, 51, 55, 89 699 → 57
Cold visible 2356, 2557, 2015, 2893 2059, 1644, 1760, 1877 2456.5 → 1818.5
Warm chat.startup (server) 11, 14, 13, 12 11, 13, 13, 13 12.5 → 13
  • CPU profile of the first chat.startup: history-worker module loading fell from 1,171 ms to 0 ms (it now completes after ready, before the request). Cold sessions.branches.list median 657.5 → 572.5 ms; branch worker bootstrap still costs time and is not claimed fixed.
  • An immediate second load measured 478 → 504 ms in the first round; follow-up rounds showed that is load-cadence noise, not a warm regression: steady loads ≥35 s after ready measured 913 → 855.5 ms median (8 rounds), and the next fresh browser on the same steady Gateway 575.5 → 522 ms (4 rounds). The history prewarm's main-thread cost is 41–54 ms of module-import CPU and ~1 ms of dispatch.
  • Listening→ready medians 674.5 → 646.5 ms; no total restart-time improvement is claimed.
  • 224 tests across 12 focused files pass. The import-boundary and foreground-prewarm regressions fail before the fix. Core/core-test/root-test typechecks, both import-cycle checks (0), all five typed lint stripes, formatting, UI build and performance checks, and independent review are clean.
  • Test cost (wrapper wall, --maxWorkers=1): session-history-read.imports 10.86 s (2 tests), server-startup-handler-prewarm 5.94 s (12 tests); session-utils.test.ts (51.46 s, 104 existing tests) only had a type import moved.

The history worker reached the full session lookup/runtime graph through
source candidate selection. Branch snapshots also imported their host list
coordinator and writer-side reexports. Extract the shared candidate owner
and isolate branch snapshots/cache from host coordination without changing
selection, admission, watermark reuse, restoration, or cleanup.

Prioritize complete history preparation, including the response encoder,
and allow only this worker operation during foreground browser loading.
Main-thread handler/optional preparation remains idle-only. Preserve the
post-ready barrier, root admission, shutdown joins, and worker custody;
ready never awaits this work. No schema, protocol, public SDK, configuration,
dependency, persistence, or update behavior changes.

Reproduction: three isolated seeded starts on Node 26, zero added RTT.
Cold chat.startup server ms: 2020,586,2041; visible ms: 4440,2246,3739.
Warm server ms: 12,12,12; visible ms: 544,12098,16714. The last two warm
outliers occurred before WebSocket connection, not in chat.startup.

Four interleaved rounds against a preserved build of main 83a9740,
same worktree/runtime paths and cloned synthetic fixtures (1500 turns plus
30 x 60 turns), fresh browser per load, immediate navigation after ready:
- Main cold server/visible ms: 647/2356,751/2557,556/2015,1034/2893.
- Candidate cold server/visible ms: 59/2059,51/1644,55/1760,89/1877.
- Main warm server/visible ms: 11/456,14/472,13/546,12/484.
- Candidate warm server/visible ms: 11/503,13/493,13/596,13/505.
Cold medians: server 699 -> 57 ms (-91.8%); visible 2456.5 -> 1818.5 ms
(-26.0%). Warm medians: server 12.5 -> 13 ms; visible 478 -> 504 ms.
Branch RPC cold medians: 657.5 -> 572.5 ms.

CPU diagnostics aligned to the first chat.startup server interval:
baseline 1171.4 ms under history-worker module loaders in a 1278 ms request;
candidate 0 ms in a 71 ms request. Candidate loading instead sampled
2635.7 ms after ready, before the request. Samples are approximate wall-time
attribution, not exclusive CPU accounting. Branch worker bootstrap still
costs time: the final loaded-host profile sampled 1079 ms loading in a
1930 ms branch RPC. No claim that branch cold loading is eliminated.

Full process-to-ready medians were 14352 -> 16372 ms on the shared host;
listening-to-ready medians were 674.5 -> 646.5 ms. Warmup remains after
ready; total restart-time improvement is not established.

Validation: 224 tests across 12 focused files pass. Import-boundary and
foreground-prewarm regressions fail before their fixes. Changed-file test
wrapper wall costs: session-history-read.imports 10.86s (2 tests),
server-startup-handler-prewarm 5.94s (12 tests), session-utils 51.46s
(104 existing tests; only its type import moved). The architecture guard
checks static worker boundaries; no timed performance assertions were added.
Core, core-test, root-test typechecks pass; both import-cycle checks report
zero; all five typed core lint stripes pass, with the affected Gateway
stripe refreshed after the final change. Full runtime/postbuild/UI builds,
UI performance checks, oxfmt, diff checks, and Codex P2 review pass.
@clawsweeper

clawsweeper Bot commented Oct 1, 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: L labels Oct 1, 2026
@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components. This comment is informational because the PR author has repository Maintain or Admin access.

  • Current SHA: 5931aa9a2e69bf46c3f8d24d860f03a10fe47d3c
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/server-methods/github-personal-authorization.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@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 Oct 1, 2026
@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 3:19 PM ET / 19:19 UTC (Revision 2).

ClawSweeper review

What this changes

The PR isolates session-history reader imports and prioritizes background worker preparation so chat transcripts load sooner after Gateway startup.

Merge readiness

✅ Ready for maintainer review

The PR remains useful beyond the earlier merged prewarm work, and no blocking correctness or security defect was found. Current main still retains the cold-load import and scheduling bottlenecks.

Priority: P2
Reviewed head: 5931aa9a2e69bf46c3f8d24d860f03a10fe47d3c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, maintainable performance improvement with convincing production-path measurements and no actionable review findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured real-Gateway restart benchmarks exercise the changed history-worker preparation through fresh-browser chat loading and show faster cold transcript delivery, with warm-load and readiness controls. The final commit only removes an unused type re-export. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured real-Gateway restart benchmarks exercise the changed history-worker preparation through fresh-browser chat loading and show faster cold transcript delivery, with warm-load and readiness controls. The final commit only removes an unused type re-export. No stored-data contract changes.
Evidence reviewed 8 items Pinned introduced change: Reviewed the merge-base-to-head delta. Store candidate selection and branch-list coordination are extracted from their existing owners; callers switch imports together. The original head's recorded parent matches the supplied identity.
Current main still needs the improvement: Pinned current-main source places history preparation after connection and handler preparation, gates it on foreground idleness, and imports candidate selection through the host lookup module. These are the specific boundaries this PR improves.
Latest release retains the earlier scheduling behavior: The supplied latest-release commit also has idle-gated history preparation after handler preparation; its source does not contain this PR's prioritization.
Findings None None.
Security None None.

How this fits together

The Gateway serves stored chat transcripts to connected clients through a read-only history worker. Startup preparation loads that worker's readers and admits existing session databases before the first foreground history request.

flowchart TD
  A[Gateway ready] --> B[Prioritized history preparation]
  B --> C[Existing database admission]
  D[Client opens chat] --> E[History worker]
  C --> E
  E --> F[Read and encode transcript]
  F --> G[Client displays history]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +3, Tests +33, Docs +8. Total +44 across 22 files.

View PR surface stats
Area Files Added Removed Net
Source 18 297 294 +3
Tests 3 36 3 +33
Docs 1 11 3 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 22 344 300 +44

Review metrics

None.

Technical review

Best possible solution:

Keep one shared store-selection owner and prepare the existing history worker after readiness while preserving foreground priority for optional discovery.

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

Yes: opening a seeded chat from a fresh browser immediately after Gateway startup is a concrete benchmark path, and current-main source retains the implicated import and idle-gating behavior. This reviewer did not execute that path.

Is this the best way to solve the issue?

Yes: extracting the shared selection and snapshot owners removes unnecessary imports, while prioritizing the existing prewarm avoids adding a competing runtime or storage path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 32dc6c861d3e.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This improves first-chat latency after startup with a bounded Gateway scheduling and import change.
  • 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 captured real-Gateway restart benchmarks exercise the changed history-worker preparation through fresh-browser chat loading and show faster cold transcript delivery, with warm-load and readiness controls. The final commit only removes an unused type re-export. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured real-Gateway restart benchmarks exercise the changed history-worker preparation through fresh-browser chat loading and show faster cold transcript delivery, with warm-load and readiness controls. The final commit only removes an unused type re-export. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head delta. Store candidate selection and branch-list coordination are extracted from their existing owners; callers switch imports together. The original head's recorded parent matches the supplied identity. (src/gateway/session-utils-store-candidates.ts:16, 5931aa9a2e69)
  • Current main still needs the improvement: Pinned current-main source places history preparation after connection and handler preparation, gates it on foreground idleness, and imports candidate selection through the host lookup module. These are the specific boundaries this PR improves. (src/gateway/server-startup-handler-prewarm.ts:41, 32dc6c861d3e)
  • Latest release retains the earlier scheduling behavior: The supplied latest-release commit also has idle-gated history preparation after handler preparation; its source does not contain this PR's prioritization. (src/gateway/server-startup-handler-prewarm.ts:41, c074824a27c9)
  • Existing prewarm lifecycle and related merged work: perf(gateway): warm the session history worker before the first transcript read #159818 is verified merged at this commit. It establishes the existing worker prewarm lifecycle rather than superseding this PR's import isolation and foreground scheduling improvement. Git history shows several preceding prewarm changes, and GitHub commit metadata identifies steipete as the author of the merged prewarm work. (src/gateway/server-startup-handler-prewarm.ts, 9ac4735581d6)
  • Real production-path performance evidence: The captured PR body records four interleaved restart pairs using built Gateways, synthetic stored sessions, fresh browser profiles, and bundled UI. Cold chat.startup median falls from 699 to 57 ms and visible transcript median from 2456.5 to 1818.5 ms. Warm and steady-load measurements, readiness measurements, and CPU profiling address the changed preparation path and its foreground cost. These are supplied observations, not reviewer-executed tests. (b0a19787ccf8)
  • Custody and stored-state compatibility: Prewarm continues through the existing retained database owner, whose dispatch and settlement checks remain intact. Extracted branch coordination preserves identity checks, lifecycle validation, watermark caching, archive restoration, and cleanup. No schema, serialized data format, configuration default, public SDK, or dependency changes are introduced. (src/config/sessions/session-transcript-worker-runtime.ts:70, 5931aa9a2e69)

Likely related people:

  • steipete: 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 (1 earlier review cycle)
  • reviewed 2026-10-01T18:57:14.059Z sha b0a1978 :: needs maintainer review before merge. :: none

Callers import GatewaySessionStoreDiscoveryCache from its new owner,
session-utils-store-candidates.ts; the session-utils barrel re-export had
no consumers and failed the production deadcode check.
@steipete
steipete merged commit fcc173f into main Oct 1, 2026
156 checks passed
@steipete
steipete deleted the perf/gateway-history-worker-cold-start branch October 1, 2026 20:48
@steipete

steipete commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Oct 1, 2026
* origin/main:
  fix(gateway): report approved-but-narrowed scope upgrades truthfully (#162951)
  fix: allow session-scoped shared publication reads (#162984)
  refactor(sessions): share session creation orchestration (#161336)
  perf(gateway): show the first chat sooner after a Gateway start (#162936)
  refactor(scripts): share npm verification command execution (#162978)
  fix(browser): clear MCP runtime cache after profile tests (#162982)
  fix(test): checkout fixture tests fail healthy runs on loaded macOS hosts (#162888)
  ci: bound PR extension lint to direct owners and smoke packages
  fix(ci): await native declaration discovery teardown
  feat(qa): drive forwarded text+photo bursts in Telegram userbot scenarios (#162906)
  build(macos): pin the app runtime to OpenClaw Bun 17c9ecf9eb (#162570)
  fix(test): frozen admission test fails with spawn ETXTBSY when a sibling test forks during the native parser copy (#162969)
  fix(ci): give direct published-driver callers the CI cell envelope (#162837)
  test(gateway): remove low-value tests (batch d136) (#162921)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…claw#162936)

* perf(gateway): prepare history workers before the first chat read

The history worker reached the full session lookup/runtime graph through
source candidate selection. Branch snapshots also imported their host list
coordinator and writer-side reexports. Extract the shared candidate owner
and isolate branch snapshots/cache from host coordination without changing
selection, admission, watermark reuse, restoration, or cleanup.

Prioritize complete history preparation, including the response encoder,
and allow only this worker operation during foreground browser loading.
Main-thread handler/optional preparation remains idle-only. Preserve the
post-ready barrier, root admission, shutdown joins, and worker custody;
ready never awaits this work. No schema, protocol, public SDK, configuration,
dependency, persistence, or update behavior changes.

Reproduction: three isolated seeded starts on Node 26, zero added RTT.
Cold chat.startup server ms: 2020,586,2041; visible ms: 4440,2246,3739.
Warm server ms: 12,12,12; visible ms: 544,12098,16714. The last two warm
outliers occurred before WebSocket connection, not in chat.startup.

Four interleaved rounds against a preserved build of main 1eea3b8,
same worktree/runtime paths and cloned synthetic fixtures (1500 turns plus
30 x 60 turns), fresh browser per load, immediate navigation after ready:
- Main cold server/visible ms: 647/2356,751/2557,556/2015,1034/2893.
- Candidate cold server/visible ms: 59/2059,51/1644,55/1760,89/1877.
- Main warm server/visible ms: 11/456,14/472,13/546,12/484.
- Candidate warm server/visible ms: 11/503,13/493,13/596,13/505.
Cold medians: server 699 -> 57 ms (-91.8%); visible 2456.5 -> 1818.5 ms
(-26.0%). Warm medians: server 12.5 -> 13 ms; visible 478 -> 504 ms.
Branch RPC cold medians: 657.5 -> 572.5 ms.

CPU diagnostics aligned to the first chat.startup server interval:
baseline 1171.4 ms under history-worker module loaders in a 1278 ms request;
candidate 0 ms in a 71 ms request. Candidate loading instead sampled
2635.7 ms after ready, before the request. Samples are approximate wall-time
attribution, not exclusive CPU accounting. Branch worker bootstrap still
costs time: the final loaded-host profile sampled 1079 ms loading in a
1930 ms branch RPC. No claim that branch cold loading is eliminated.

Full process-to-ready medians were 14352 -> 16372 ms on the shared host;
listening-to-ready medians were 674.5 -> 646.5 ms. Warmup remains after
ready; total restart-time improvement is not established.

Validation: 224 tests across 12 focused files pass. Import-boundary and
foreground-prewarm regressions fail before their fixes. Changed-file test
wrapper wall costs: session-history-read.imports 10.86s (2 tests),
server-startup-handler-prewarm 5.94s (12 tests), session-utils 51.46s
(104 existing tests; only its type import moved). The architecture guard
checks static worker boundaries; no timed performance assertions were added.
Core, core-test, root-test typechecks pass; both import-cycle checks report
zero; all five typed core lint stripes pass, with the affected Gateway
stripe refreshed after the final change. Full runtime/postbuild/UI builds,
UI performance checks, oxfmt, diff checks, and Codex P2 review pass.

* fix(gateway): drop unused discovery-cache type re-export

Callers import GatewaySessionStoreDiscoveryCache from its new owner,
session-utils-store-candidates.ts; the session-utils barrel re-export had
no consumers and failed the production deadcode check.
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 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. security-sensitive-changed size: L 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