Repository navigation
perf(gateway): keep reload and recovery machinery off gateway cold start - #119094
Conversation
|
Codex review: needs maintainer review before merge. Reviewed August 4, 2026, 4:04 AM ET / 08:04 UTC. ClawSweeper reviewWhat this changesThe PR retargets two eagerly primed gateway lifecycle exports to their defining modules and adds static boundary coverage so reload and recovery runtime graphs stay off cold start. Merge readinessKeep open. This is a correct, narrow gateway cold-start optimization: it preserves the lifecycle hub’s exports while avoiding two facade-only dependency graphs. The branch is mergeable but behind, with exact-head checks still running; let normal merge gates finish. Priority: P3 Review scores
Verification
How this fits togetherGateway startup eagerly loads a lifecycle export hub before installing signal handlers so restarts continue to work after an in-place package upgrade. The hub’s static exports therefore determine how much code is evaluated before the HTTP listener can accept connections. flowchart LR
A[Gateway startup] --> B[Gateway run loop]
B --> C[Primed lifecycle hub]
C --> D[Reload contracts]
C --> E[Session restart marking]
C --> F[Signal handlers]
F --> G[HTTP listener]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +3, Tests +37. Total +40 across 3 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the lifecycle hub’s direct leaf exports while leaving the full reload and recovery facades for their existing lazy consumers, then land after exact-head checks complete. Do we have a high-confidence way to reproduce the issue? Not applicable as an issue reproduction: this PR has direct source evidence and exact-head build/import-boundary proof for a behavior-neutral cold-start optimization. Is this the best way to solve the issue? Yes. Re-exporting from the modules that own the required symbols removes only the unwanted facade edges while preserving the existing lifecycle hub and canonical shared state. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against b1f2aae3034f. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
The run loop primes cli/gateway-cli/lifecycle.runtime.ts before installing signal handlers, so every symbol that hub re-exports loads before the HTTP listener binds. Two of those re-exports resolved through forwarding modules: gateway/server-reload-handlers.ts also re-exports the hot-reload and managed reloader modules, and agents/main-session-restart-recovery.ts also re-exports its -runtime sibling. ESM evaluates the whole forwarding module, so priming the hub pulled both graphs onto the cold-start path. Re-export each symbol from the module that defines it instead. abortPendingChannelReloads lives in gateway/server-reload-contracts.ts, whose own imports are all type-only, and markRestartAbortedMainSessions lives in agents/main-session-restart-recovery-marking.ts. Both retargets resolve to the same module instances, so shared reload-generation state and behavior are unchanged, and the eager priming that protects signal handlers from dist chunk rotation stays in place. Add a CLI-lane import-boundary test so these re-exports cannot be routed back through a forwarding module, and point the two run-loop test mocks at the defining modules.
10a4569 to
f354a17
Compare
|
Refreshed for the P1/P2 before-merge items. Rebased onto main None of the 13 commits between the old base and that head touched Gate re-run on this exact head: Targeted set: Import-boundary proof re-run on this head, walking static edges only from the freshly built The emitted hub chunk imports One note on staleness: main advanced another 29 commits while this validation was running, so the branch reads as behind again. None of those commits touch the hub, the reload contracts/handlers/hot/managed modules, or the recovery marking/runtime modules, so the proof above still describes the merge result. I stopped there rather than re-rebasing, per
AI-assisted. |
|
@clawsweeper so how come the issues this fixes are P1, but this is P3? |
|
Merged via squash.
|
* origin/main: (22 commits) refactor(plugins): consolidate lifecycle hook dispatch (#119429) fix(ci): stabilize TUI PTY proof ownership (#119420) test(system-agent): reduce suite setup overhead (#119424) fix(ui): keep session rail pill status from overlapping the headline (#119397) fix(discord): avoid doctor runtime loading (#119391) fix(media): decouple playback cache retention (#119417) fix(slack): infer upload filename extensions from MIME types (#119399) refactor(channels): unify configured binding resolution (#119414) refactor(google-meet): unify gateway and tool dispatch (#119413) test(state): reuse legacy database fixtures (#119423) fix(reset): preserve bootstrap guidance for dynamic models (#119179) fix(chutes): honor serving context limits (#119196) refactor(status): consolidate scan projections and lazy loaders (#119412) fix(status): status --all slows down with missing plugins (#119203) refactor(gateway): consolidate usage reporting and caches (#119409) perf(gateway): keep reload and recovery machinery off gateway cold start (#119094) fix(cli): align TaskFlow controller columns for wide text (#118801) fix: make startup migration restart guidance install-neutral (#119406) fix(ci): preserve cache warmer shard envelopes (#119403) fix(sessions): preserve compatible auth profiles on model changes (#117550) ...
…art (openclaw#119094) The run loop primes cli/gateway-cli/lifecycle.runtime.ts before installing signal handlers, so every symbol that hub re-exports loads before the HTTP listener binds. Two of those re-exports resolved through forwarding modules: gateway/server-reload-handlers.ts also re-exports the hot-reload and managed reloader modules, and agents/main-session-restart-recovery.ts also re-exports its -runtime sibling. ESM evaluates the whole forwarding module, so priming the hub pulled both graphs onto the cold-start path. Re-export each symbol from the module that defines it instead. abortPendingChannelReloads lives in gateway/server-reload-contracts.ts, whose own imports are all type-only, and markRestartAbortedMainSessions lives in agents/main-session-restart-recovery-marking.ts. Both retargets resolve to the same module instances, so shared reload-generation state and behavior are unchanged, and the eager priming that protects signal handlers from dist chunk rotation stays in place. Add a CLI-lane import-boundary test so these re-exports cannot be routed back through a forwarding module, and point the two run-loop test mocks at the defining modules.
Related: #119087
Related: #106680
AI-assisted.
What Problem This Solves
Starting a gateway from cold does measurably more work than it needs to before it can accept its first connection. Operators on container platforms pay this on every cold start, where the gap between process start and
http server listeningdecides whether a readiness probe passes or the platform kills and retries the container.The gateway run loop deliberately primes
cli/gateway-cli/lifecycle.runtime.tsbefore it installs signal handlers, so everything that hub re-exports is loaded before the listener binds. Two of those re-exports resolved through modules that only forward symbols onward, so priming the hub also evaluated the gateway hot-reload machinery, the managed config reloader, and the main-session recovery runtime — none of which the primed hub calls, and none of which are needed to start serving.This is one of two contributors we isolated while investigating a ~2.5x gateway boot regression between 2026.7.1-beta.1 and 2026.7.2-beta.7 (#119087). It does not resolve that regression — this edge exists in 2026.7.1 too, and the regression's larger driver is the growth of the default startup plugin set, which overlaps #106680. What this change does is make the pre-bind window smaller on every release.
Why This Change Was Made
Re-export each symbol from the module that defines it instead of from a forwarding module:
abortPendingChannelReloadsis a three-line generation bump defined ingateway/server-reload-contracts.ts. It was reached throughgateway/server-reload-handlers.ts, which also re-exportscreateGatewayReloadHandlers(server-reload-hot.ts) andstartManagedGatewayConfigReloader(server-reload-managed.ts). ESM evaluates the whole forwarding module, so a three-line function pulled both reload graphs onto cold start.markRestartAbortedMainSessionsis defined inagents/main-session-restart-recovery-marking.ts. It was reached throughagents/main-session-restart-recovery.ts, which also re-exports the-runtimesibling.Both are re-export retargets, not copies: each resolves to the same module instance as before, so module-level state (
abortGeneration/currentReloadGenerationin the reload contracts) stays shared and behavior is unchanged. The eager priming itself is untouched, so the dist chunk-hash-rotation protection it exists for still holds — the boundary test added here asserts the priming still happens before signal handlers are installed.Both targets already have in-repo precedent as direct import sites:
gateway/server-reload-managed.tsimportsabortPendingChannelReloadsfromserver-reload-contracts.js, andgateway/server-startup-post-attach.tsimports frommain-session-restart-recovery-marking.js.Non-goal:
server-reload-handlers.tsis left in place as the reload surface for its remaining consumers. Retiring the forwarding modules entirely is a larger ownership decision and is not attempted here.User Impact
Less work between process start and the gateway accepting connections. No user-visible behavior change: same functions, same module instances, same state.
The hub's own static import closure, measured from source on this branch by walking the non-erased import/export graph (type-only edges dropped,
import()treated as a boundary):That closure number is the hub in isolation; most of those modules are also reachable from other boot work, so it is an upper bound, not the boot saving. The honest boot-path figure comes from counting modules the process actually loads before
http server listeningon a 1-vCPUnode:24.18.0-bookworm-slimcontainer (ESM loader hook plus aModule._loadwrapper for CommonJS), with the reload edge cut:http server listeningstarting...->starting HTTP server...windowOn wall-clock time this change is not separable from run-to-run noise on our bench. Median time to listen was 11.1 s stock vs 10.0 s patched over 6 interleaved runs, but stock ranged 6.7-28.0 s, so we are not claiming that as a result. The defensible statement is the module census: about a quarter of the bytes loaded in the pre-bind hand-off window go away, and module counts are deterministic where these timings are not.
Evidence
Emitted chunk graph after
pnpm buildon this branch. Walking static edges only (soimport()is a boundary) from the built hub chunkdist/cli/gateway-lifecycle.runtime.js:The hub chunk's own import list now reads
from "../server-reload-contracts-*.js"andfrom "../main-session-restart-recovery-marking-*.js", and rolldown emittedserver-reload-contractsas a 1-chunk, 2 KiB leaf — so the leaf really is a leaf after bundling, not merged back into the reload machinery.Same build, for scale: the forwarding chunks still exist for their lazy consumers, and their static closures are
server-reload-handlers1,407 chunks / 19.34 MiB andmain-session-restart-recovery588 chunks / 7.87 MiB. Adding the chunks those graphs would make statically reachable back onto the hub gives 1,424 chunks / 19.52 MiB, i.e. this change takes -750 chunks / -10.87 MiB off the hub's eager chunk closure. (That pre-change figure is computed by unioning the facade graphs into the hub closure rather than by rebuilding with the old edge, so exact chunk boundaries could shift slightly on a real rebuild; the categorical result above — the machinery is not reachable — is measured directly.)Validation run locally on this branch (macOS, Node 24.16.0, pnpm 11.15.1):
Targeted suites for the touched surface, all passing:
The new boundary test was confirmed non-vacuous: reverting both re-exports to the forwarding modules makes it fail with
expected ... to contain 'from "../../gateway/server-reload-contracts.js"', and restoring them makes it pass.I did not run the full
pnpm testlocally — this checkout has 8,952 test files and no remote test box was available to me — so the full matrix is left to CI. One note in case it shows up: on a firstpnpm test:changedrun, while this machine was still busy with a concurrent build,src/cli/help-exit.process.test.tsfailed because aslow SQLite transaction lock waitwarning (state.schema.ensure, 2,209 ms) landed on stderr and that test asserts stderr is empty. It passes 25/25 in isolation and on a repeat run of the whole lane on an idle machine; the file has no reference to anything this PR touches. Flagging it as a load-sensitive test rather than something this PR caused.Method notes:
node:24.18.0-bookworm-slim,docker --cpus=1,NODE_DISABLE_COMPILE_CACHE=1, token auth, no channels, browser disabled, update checks off; interleaved runs with the page cache warmed first. The same instrument runs against every build, so its overhead cancels.-44 modules / -1.04 MiBcensus figure was produced by cutting the reload edge in a published 2026.7.2-beta.7 bundle, which emulates this source change; it covers the reload edge only, not the recovery-marking edge.src/cli/gateway-cli/lifecycle-import-boundary.test.tsis added so a future edit cannot quietly route these re-exports back through a forwarding module. It follows the existingsrc/gateway/server-import-boundary.test.tsidiom and stays in the CLI lane so PR change classification selects it with the file it guards.autoreviewskill is present in this checkout, so that step could not be run.