Skip to content

perf(gateway): prewarm first Control UI requests while idle - #158555

Merged
steipete merged 6 commits into
mainfrom
perf/l15-idle-prewarm-20260925
Sep 26, 2026
Merged

steipete merged 6 commits into
mainfrom
perf/l15-idle-prewarm-20260925

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The first Control UI connections, history reads, and chat turns after Gateway startup can pause other clients while loading shared modules and scanning primary-workspace skills.

User Impact

An idle Gateway prepares the common chat paths before clients need them. Foreground requests retain priority, including requests arriving while an optional module import is pending. Immediate requests continue to use the normal authoritative loaders.

Why This Change Was Made

One sequenced idle owner now prepares connection, history, send, session-list, and agent-event modules, local primary-workspace skill discovery, and the existing context cache. Skill watcher acquisition precedes discovery so first-turn watcher setup does not discard the warmed cache. Remote workspace discovery stays request-owned. Plugin-catalog preparation follows the chat work so its network fetch cannot hold up skill preparation.

The separate context-cache scheduler is removed. Its five-second minimum delay, current-config lookup, foreground priority, cancellation, and shutdown join are retained. Prewarm does not execute requests, construct connection-bound handlers, or fetch live provider catalogs. No protocol, configuration, or database schema changes.

Evidence

  • Focused Gateway tests: 129 passed across server-startup-handler-prewarm.test.ts, server-idle-task.lifecycle.test.ts, and server-startup-post-attach.test.ts; command wall time 54.57 seconds with node scripts/run-vitest.mjs <files> --maxWorkers=1.
  • The new first-use regression fails against the original prewarm owner because it only prepares plugin data, then passes with this change.
  • Initial fixture failures were corrected by draining fake timers together with dynamic imports, using an independent foreground admission, and updating the expected sidecar count after consolidation. No timing thresholds, retries, or assertions were weakened.
  • Source-level Node/tsx microbenchmark (synthetic 200-skill workspace; 50 concurrent handler/snapshot callers): first-use module main-thread CPU 1,240.00 → 2.63 ms; first skill-snapshot CPU 309.93 → 21.40 ms after the actual idle owner completed. Both probes exited cleanly and closed their Skills watchers. Cold TypeScript loading is included, so these are preparation-cost measurements, not production client-latency estimates.
  • Required pnpm build completed runtime and declaration generation, CLI bootstrap import guard, plugin SDK export guard, and UI performance budgets. Its final CLI startup-metadata step timed out rendering source nodes help at 120 seconds; that exact step passed separately in 114.03 seconds after build work settled. Aggregate build wall time was 8,082.60 seconds; the aggregate command did not exit green.
  • The final test-only type correction passed all 8 prewarm tests in 42.27 seconds and the Gateway test type graph in 7.15 seconds. Production typechecking previously passed in 37.16 seconds.
  • Startup proof: the initial default and skip-channels cases timed out before listening at 120 seconds. A skip-channels probe after the build stopped reached /healthz in 91.30 seconds and /readyz in 115.74 seconds, used 20.65 seconds CPU and 605.7 MiB max RSS, and shut down cleanly. This demonstrates startup/shutdown, not a passing startup latency budget. A clean Testbox attempt was cancelled while staging local sources, before any lease or remote command; its owned wrapper completed cleanup.
  • Startup latency budget remains unverified: incidentCombined --runs 1 --warmup 0 --timeout-ms 60000 failed to reach either health endpoint within the existing 60-second budget. Its 80,000-file fixture was fully removed; the whole command took 1,212.47 seconds including fixture setup/cleanup. A clean-machine startup-budget run is still needed.
  • node scripts/check-changed.mjs: passed in 3,966.06 seconds, including all 25 selected core test type graphs, core lint, dead-export scans, and runtime import-cycle guards.
  • Production +73/-62 (net +11); tests/support +173/-105 (net +68); docs +9. The production increase adds the new bounded warmup entries after deleting the 52-line duplicate context scheduler.
  • Diff-scoped deslop completed. Independent Codex review of the final head: scoped-clean through P2, no actionable findings. Two auth-only-route review attempts failed before producing a report; the configured authenticated OpenAI route completed under the same managed isolation.

Landing reconciliation

Merged current main (including #158563) into the branch without rebasing. Control UI handlers, local skills, the delayed context cache, Memory Core retrieval, and plugin catalog preparation share one sequential idle owner. Memory retrieval also observes the existing foreground/shutdown cancellation predicate after awaited imports.

  • Focused prewarm, idle-lifecycle, and post-attach tests: 131 passed in 39.18 seconds wall time (node scripts/run-vitest.mjs src/gateway/server-startup-handler-prewarm.test.ts src/gateway/server-idle-task.lifecycle.test.ts src/gateway/server-startup-post-attach.test.ts --maxWorkers=1).
  • The initial merged fixture had two deterministic failures because a table repeated cold-import assertions after Vitest cached those modules. First-import and active-memory ordering proof now runs once; inactive-plugin selection has separate cases. All original assertions remain covered.
  • Gateway server test type graph passed in 22.69 seconds; scoped lint and diff whitespace checks passed. Final independent Codex review: scoped-clean through P2.
  • Earlier hosted CI run 36212543016 failed on the obsolete Telegram format-render.ts scenario reference. Main commit a991028 (refactor: share filesystem admission and cleanup with fs-safe #158313), included by this merge, removes that stale reference. No hosted run was rerun to obtain green.
  • The prior overloaded-host startup-budget timeout remains a limitation of local evidence. Hosted CI, including any selected startup-budget job, is the landing gate.

Hosted run 36216839983 failed in check-test-types-core-1 with TS2459 in the unchanged retained-assets E2E fixture: ControlUiRootState was imported from the former owner. This reproduced on clean main. The type-only correction passed the entire original --stripe 1/5 --concurrency 2 typecheck selection in 51.02 seconds. Another maintainer landed the identical repair as da8149b while verification completed; the branch now incorporates that fix by merging main. All 131 focused prewarm/lifecycle/post-attach tests passed again in 40.13 seconds on the merged candidate. No failed CI run was rerun.

The maintainer landing decision retains the reviewed prewarm design. ClawSweeper's remaining P2 concerns are retained performance limitations: an individual local skill scan is synchronous once started, and foreground interruption may leave an optional context fill unfinished until request-time loading. The context owner clears the failed/cancelled load promise and retains the authoritative request path; this does not corrupt or permanently poison the cache. Worker-backed skill discovery and rescheduling interrupted optional fills remain possible follow-ups, outside this approved reconciliation.

@clawsweeper

clawsweeper Bot commented Sep 26, 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 labels Sep 26, 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: 🦐 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 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 26, 2026, 12:37 AM ET / 04:37 UTC (Revision 4).

ClawSweeper review

What this changes

The branch prepares Control UI connection and chat handlers, local skills, context data, and memory retrieval in a sequenced idle task after Gateway readiness.

Merge readiness

✅ Ready for maintainer review

Keep this PR open. Current main still lacks the proposed first-use Gateway preparation, and the related merged memory warmup covers a different cold path. The latest merge left the reviewed prewarm implementation unchanged; the PR body records acceptance of its two known performance limits.

Priority: P2
Reviewed head: d03f675a02c6d5d4bc3e6a7ed4570fb1d7ee5bad

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation and tests are useful, while the supplied measurements stop short of concurrent client latency proof.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: The Repository State classifies this as member-authored, so the contributor proof gate does not apply. The PR reports before-and-after CPU measurements through the production idle owner in a synthetic workspace and a successful Gateway readiness probe; concurrent Control UI latency and the startup budget were not established by those measurements. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The Repository State classifies this as member-authored, so the contributor proof gate does not apply. The PR reports before-and-after CPU measurements through the production idle owner in a synthetic workspace and a successful Gateway readiness probe; concurrent Control UI latency and the startup budget were not established by those measurements. No stored-data contract changes.
Evidence reviewed 9 items Introduced behavior: The pinned branch adds idle preparation for connection and chat modules, local skill discovery, and a delayed context fill.
Current main remains distinct: Current main prepares memory retrieval and plugin data in this idle sequence, but does not prepare the Control UI handlers or local skills proposed here.
Request path retained: Lazy handlers still prepare their actual request handler at entry; idle preparation does not execute a request.
Findings None None.
Security None None.

How this fits together

The Gateway receives Control UI connections and chat requests, then loads handlers and agent workspace data needed to serve them. This change moves some of that first-use work into idle time while keeping normal request loaders authoritative.

flowchart LR
  A[Gateway ready] --> B[Idle task]
  C[Foreground requests] --> D{Gateway busy?}
  D -->|Yes| B
  B --> D
  D -->|No| E[Prepare handlers and local skills]
  E --> F[Prepare context and memory]
  F --> G[First Control UI request]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +14, Tests +109. Total +123 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 3 77 63 +14
Tests 7 221 112 +109
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 298 175 +123

Review metrics

Metric Value Why it matters
Code balance production +73/−62; tests and support +173/−105 The modest production growth is explained by added warmup entries and removal of the separate context scheduler.

Technical review

Best possible solution:

Keep the unified idle sequence and authoritative request loaders; revisit worker-backed local skill discovery if production Gateway traces show material client stalls.

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

No high-confidence full-client reproduction was established in this read-only review. Current main shows deferred first-use loaders, and the PR reports a scoped before-and-after component benchmark.

Is this the best way to solve the issue?

Yes. The branch extends the existing idle owner and keeps request-time loading authoritative; its remaining synchronous scan limitation is explicitly recorded.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against b458b9f1c6bc.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded improvement to first-use Gateway responsiveness.
  • merge-risk: 🚨 availability: An idle local skill scan can still synchronously occupy the Gateway event loop; the captured maintainer decision retains that known limitation.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The Repository State classifies this as member-authored, so the contributor proof gate does not apply. The PR reports before-and-after CPU measurements through the production idle owner in a synthetic workspace and a successful Gateway readiness probe; concurrent Control UI latency and the startup budget were not established by those measurements. No stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jason (Json): 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 (3 earlier review cycles)
  • reviewed 2026-09-26T01:53:58.670Z sha 85820b5 :: blocked before merge. :: [P2] Move idle skill discovery off the Gateway event loop | [P2] Do not abandon an admitted context-cache refresh on foreground work
  • reviewed 2026-09-26T02:50:00.153Z sha 85820b5 :: blocked before merge. :: [P2] Move idle skill discovery off the Gateway event loop | [P2] Retry an admitted context-cache fill after foreground work
  • reviewed 2026-09-26T04:13:56.526Z sha a3ddd0a :: blocked before merge. :: [P2] Move idle local-skill discovery off the Gateway thread | [P2] Retry context preparation after foreground interruption

@steipete
steipete marked this pull request as ready for review September 26, 2026 02:42
Merge origin/main into the reviewed Control UI prewarm branch. Keep Memory Core retrieval in the shared idle sequence and honor foreground cancellation after imports. Preserve cold-import proof separately from inactive-plugin selection so Vitest module caching does not invalidate the fixture.
Merge main with the retained-assets type import correction da8149b. The prewarm implementation and focused tests are unchanged; all 131 focused tests pass again. The prior hosted failure was reproduced on main and its exact typecheck stripe passes with the owning repair.
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 26, 2026
@steipete
steipete merged commit 430ea3c into main Sep 26, 2026
214 checks passed
@steipete
steipete deleted the perf/l15-idle-prewarm-20260925 branch September 26, 2026 05:04
@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 27, 2026
…#158555)

* perf(gateway): prewarm first-use chat paths while idle

* fix(gateway): validate idle prewarm handler lookup

* test(gateway): normalize idle prewarm fixture paths

* test(gateway): narrow prewarm call order assertion
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 merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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