Skip to content

fix(gateway): server tests time out when a parallel shard starts cold - #171289

Merged
steipete merged 3 commits into
mainfrom
fix/gateway-parallel-startup-sessions-create
Oct 14, 2026
Merged

steipete merged 3 commits into
mainfrom
fix/gateway-parallel-startup-sessions-create

Conversation

@steipete

@steipete steipete commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: Gateway server tests time out (and then cascade into fixture-ownership and EnvironmentTeardownError failures) when the parallel gateway-server shard starts cold, e.g. agentic-control-plane-runtime-state-hosted-3 in run 38385657488 (checks-node-changed-compact-small-2-1) and the same 21-file plan replayed locally on main.

User Impact

No user-visible product change. sessions.create without an initial turn no longer loads the chat-dispatch and embedded-agent execution graphs on its request path, which shortens the first cold sessions.create after Gateway start. CI and local Gateway server shards stop failing the first test in each worker on cold module loading.

Why This Change Was Made

The gateway-server project runs files in forks with isolate: false, so each worker pays the Gateway's cold module evaluation once — and that cost was landing inside the first test's 30 s body budget or the first RPC's 10 s budget. Timestamped profiles of the replayed shard showed:

  • Cold startup in test budgets. A test-only model-catalog reset (resetPreparedGatewayModelCatalogForTest) imported server-start.ts just to clear caches; removing that incidental import is right, but the startup graph still has to load somewhere. The Gateway test fixture now loads server-start.ts (the same graph the production gateway-prewarm entry compiles) once per worker in its setup hooks, so behavior budgets measure behavior. The model-catalog reset now only resets owners that are already loaded, via the existing global test-API pattern.
  • Over-broad sessions.create imports. sessions-create.ts statically imported initial-turn chat dispatch, and session-create-service.ts imported the embedded-agent.ts barrel for one predicate, pulling the embedded runner, queued compaction, harness and tools into every session creation. Chat dispatch now loads only when an initial turn is requested (authority rechecked after that await), and the predicate is imported from its owner embedded-agent-runner/active-run-projections.ts. Measured first sessions-create family import: 7.26 s → 1.22 s. An import-boundary test guards both edges.
  • Teardown after a timeout. Vitest timeouts do not cancel the body, so a timed-out file's in-flight startup and lazy imports kept running into the next file of the same worker (fixture "open/closing" errors) and past environment teardown (Cannot load '/src/config/io.ts' … after the environment was torn down). Fixture ownership now starts before listener/module acquisition; teardown joins setup, reset, late acquisition and native close before releasing state. A normal test or suite that leaks a Gateway still fails (after it is closed so successors stay clean); native close failure still retains ownership.

Ruled out with timestamps: post-ready handler prewarm contention (64 ms overlap with the first worker RPC; disabling it did not fix the timeout) and config-reload/hot-apply waits after writeConfigFile (reload RPCs ~0.3 s; MCP fixture has no reloader). Production prewarm and reload behavior are unchanged.

No timeout, hook budget, RPC deadline, worker count, isolation list, serial pin, retry, schema, config, or public surface changes.

Evidence

Shard replay of the exact 21-file plan from the failing CI job via scripts/ci-run-node-test-shard.mts (gateway-server config, OPENCLAW_VITEST_MAX_WORKERS=2, forks, isolate:false) on a shared macOS host (32 cores, background load avg 25–60 from other jobs):

Head Wall Result
main 0f13444 333 s 20/21 — portals.session timed out (32.1 s), app-sdk-composed-resources 30.2 s
main 6eb2675 (rebase base) 207 s 20/21 — worker-placement-startup-context timed out (45.3 s)
this branch, run A 186 s 21/21, 59/59
this branch, run B 184 s 21/21, 59/59
this branch, run C (same-base A/B with the 207 s main run) 210 s 20/21 — one warm plugin.approval.resolve RPC timeout in native-hook-request-lifetime

Every main run fails the first full-startup file in a worker (the reported class); no branch run did, and no branch run showed fixture-fence or EnvironmentTeardownError cascades. worker-placement-startup-context first case: 45.3 s timeout on main → 21.7 s on the branch. Whole-shard wall time is not a controlled comparison on this shared host: cold module evaluation moved into setup hooks rather than disappearing, except for the narrowed sessions.create graph.

Remaining gap: under heavy host load, isolated warm RPCs can still stall (run C above; a 2-file probe also caught a 13 s sessions.create snapshot stall). Probes attributed those intervals to SQLite worker ↔ host admission exchanges waiting ~1.3 s with <0.3 ms worker CPU — a starved host thread, not a request awaiting unrelated work — so no product change was made for them. PR CI on dedicated runners is the broad proof.

Focused tests (pnpm test <file> --maxWorkers=1, wall on the loaded host):

  • src/agents/prepared-model-runtime.test-support.test.ts — 2 passed, 4.5 s
  • src/gateway/server-import-boundary.test.ts — 3 passed, 8.2 s
  • src/gateway/test-helpers.acquisition.test.ts — 13 passed, 37.4 s
  • src/gateway/server.sessions.fixture-lifecycle.test.ts — 13 passed, 62.6 s (includes the existing real retained-close subprocess)
  • src/gateway/server-methods/sessions-create-timeout.test.ts — 3 passed, 76 s (initial-turn dispatch still reaches chat dispatch with forwarded timeouts)
  • src/gateway/session-create-preparation.test.ts — 18 passed, 63 s (active-run checks unchanged)

New fixture regressions failed on the pre-fix implementation (setup not joining the startup import; leaked servers silently accepted) and pass now. pnpm tsgo:core, touched-test typecheck shards, oxfmt, focused boundary lint, and git diff --check pass; pnpm build passed on the first commit. Independent Codex autoreview of the final branch: scoped-clean at P0–P2. Changelog: none (release-generated for this repo); release-note context is this PR.

Post-rebase evidence

Rebased onto 976cc974fab1; rebased head a111d541b981. The conflict repair is mechanical: retain worker-backed target reads and memory-only incognito ownership from main while preserving lazy initial-turn dispatch, its authority recheck, and the fixture ownership changes. Main had already removed the obsolete normalization import. No new callers of the deleted reset helper remain. The prior independent P0–P2 review remains applicable; range-diff shows no new logic.

Affected local proof on the shared host (load average reached 110 on 32 cores):

Check Wall Result
fixture lifecycle 200.94 s 12 passed, 1 failed
import boundaries 96.43 s 3 passed
acquisition 396.56 s 12 passed, 1 failed
unloaded-model reset 31.99 s 2 passed
initial-turn timeout forwarding 389.61 s 1 passed, 2 failed
session preparation 129.60 s 19 passed
core typecheck 59.69 s passed
touched-file oxfmt 0.45 s passed

The two retained-close subprocesses reached their existing 90 s managed-command deadline before producing proof journals. Their PIDs were subsequently observed exited, and the harness retained its claims/cache as designed. Cold compiler preparation took up to 155 s; one child reached startup preparation only after 76.8 s. These observations suggest substantial host contention but do not establish baseline attribution or a fix.

The timeout-forwarding suite also failed fixture settlement with one remaining root-work admission, then encountered a missing isolated shared-state database through the worker-backed session projection. The drain and workspace-settlement helpers are unchanged across the rebase. No safe causal repair is established; host-load versus fixture/product attribution remains unresolved. These are recorded as investigated local failures, not passing proof. No retries, timeout increases, assertion weakening, skips, or scheduling changes were made. Exact-head PR CI remains required under the normal landing gates.

CI repair

Latest head: f885e225ea30. CI run 38503496679 on the rebased head failed only checks-fast-baseline-ratchets and its aggregate gate. The report classified it as new: the catalog test-API registration added one unannotated type assertion. The failure reproduced locally. The repair replaces the asserted global write with Reflect.set, retaining the same symbol and API object without an assertion, baseline change, or exemption.

The repaired assertion-safety check passed (207.03 s on the loaded host), along with core types (21.33 s) and touched-file format (0.57 s). Fresh independent P0–P2 Codex review found only that the repair was not yet staged; the reviewed working-tree fix was then staged and its bytes verified before commit. No additional code findings were established. The six earlier file-run results and unresolved local failures above remain preserved evidence; no retry or passing replay is claimed. New exact-head CI remains the broad gate.

Landing blocker

CI run 38506173118 on f885e225ea30 completed with a failed checks-node-changed-compact-small-19-1 and aggregate gate. The sole reported test was sessions.list yields for bulk metadata and later serves previews without repairing titles in server.sessions.list-changed.test.ts, which exceeded its existing 120 s test budget. The native failure report classifies it as unknown, with no matching job on main.

The maintainer land decision remains in place, but the mechanics are held under the requested stop condition: no safe causal repair within this PR's intent has been established, and the inherited-only exception is not supported by this evidence. No CI rerun, timeout increase, sleep, retry, skip, scheduling pin, or new configuration was introduced. The exact-head review artifact records NEEDS WORK for this gate blocker.

@clawsweeper

clawsweeper Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-14T02:57:55.570361Z a111d54 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: M labels Oct 13, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c0105d954b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/model-catalog.ts Outdated
Comment on lines +69 to +72
if (process.env.VITEST || process.env.NODE_ENV === "test") {
(globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw.modelCatalogTestApi")] = {
resetModelCatalogBuilderCacheForTest,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove the test-only global catalog API

Whenever the catalog loads under Vitest or NODE_ENV=test, production code now installs a mutable, symbol-addressed API on globalThis solely for prepared-model-runtime.test-support.ts. This creates an undocumented test-only production seam whose lifetime can outlast module isolation and makes cache ownership depend on ambient global state; keep the reset behind a test-owned boundary or an explicit owner interface instead.

AGENTS.md reference: AGENTS.md:L73-L75

Useful? React with 👍 / 👎.

Reset only loaded prepared-model and catalog owners instead of importing
Gateway startup to clear test state. Load chat dispatch only when session
creation requests an initial turn, and recheck authority after the import.

Register fixture ownership before listener and module acquisition. Join
setup, reset, startup, and native-close work before releasing the fixture
environment, while preserving retention after a real close failure.

Two parallel-shard replays still exceed cold first-start/RPC budgets
(249s and 280s wall); no timeout or pool-policy changes were made.
Prepare the Gateway startup implementation in fixture hooks before test
behavior budgets begin. Session creation reads active-run projections
without loading the execution and compaction graph.

Drain leaked fixture servers and release their state before reporting
ordinary test or suite leaks, while interrupted cases still join cleanup.
@steipete
steipete force-pushed the fix/gateway-parallel-startup-sessions-create branch from c0105d9 to a111d54 Compare October 14, 2026 02:54
Preserve the symbol-owned catalog reset API while removing the unnecessary globalThis cast rejected by assertion-safety CI for PR #171289.
@steipete
steipete merged commit a6f7f6c into main Oct 14, 2026
150 of 153 checks passed
@steipete
steipete deleted the fix/gateway-parallel-startup-sessions-create branch October 14, 2026 06:18
@steipete

steipete commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

Admitted unrelated intermittent: checks-node-changed-compact-small-19-1, job 115664564995, specifically server.sessions.list-changed.test.ts > sessions.list yields for bulk metadata and later serves previews without repairing titles. Run 38506173118 attempt 1 remains failed; the exception does not claim green CI or a repaired race.

The same shard and named case passed at prior head a111d541b981 in run 38503496679, job 115656003792, with 25/25 files passing. The only subsequent source delta is the two-line assertion-free Reflect.set catalog test-API registration, preserving its symbol and value. The failing case and its observer/projection/backfill inputs are unchanged by this PR; nine named inputs also match between the recorded CI main parent and tested merge. The lead attributed the future-only observer installed after await request to an unrelated intermittent and is tracking its root cause separately.

On exact head f885e225ea30, the full list-changed file passed 12/12 locally (738 s), and initial-turn timeout forwarding passed 3/3 (423 s). These passes support attribution, not a repair claim. All 69/69 other executed jobs passed; 25 were skipped and none cancelled. The only other failed job was downstream openclaw/ci-gate (115667725275).

vincentkoc added a commit that referenced this pull request Oct 14, 2026
* commit '98116a50c5e3191283f12ee210aa774273f2b8fc': (4815 commits)
  chore(ui): refresh control ui locales (#171839)
  fix(gateway): server tests time out when a parallel shard starts cold (#171289)
  fix(agentsapi): allow shared compaction tuning in hosted sessions (#171813)
  test(live): prepare runtime config for admitted fixtures
  test(update): stub state-read retry in restart module fixture
  fix(test): pnpm test fails on small cloud containers (#171732)
  fix(code-mode): recover safely from invalid wait IDs (#128886)
  test(update): load acquisition owner in restart regression
  perf(gateway): avoid full row warmup for project and catalog pickers (#171714)
  fix(telegram): voice mentions are ignored in groups when audio scope rules match on chat type (#163746)
  fix(workboard): only promote todo cards to ready (#171743)
  perf(sqlite): avoid repeated admission registry publication (#171788)
  perf: skip unused size accounting for sole session actors (#171777)
  improve(ollama): cover literal fenced command replies (#166561)
  refactor(talk): admit cross-store voice writes once (#171721)
  fix(gateway): recover a Gateway stuck in startup instead of blocking every start (#171678)
  fix(muse): offer Muse Code sign-in from Provider Access (#171790)
  perf: avoid full device lists during silent pairing (#171703)
  docs(cloud): one coherent zero-setup cloud environments guide (#171767)
  fix(test): include cloud move in sidebar action inventory
  ...
vincentkoc added a commit that referenced this pull request Oct 14, 2026
* commit '98116a50c5e3191283f12ee210aa774273f2b8fc': (185 commits)
  chore(ui): refresh control ui locales (#171839)
  fix(gateway): server tests time out when a parallel shard starts cold (#171289)
  fix(agentsapi): allow shared compaction tuning in hosted sessions (#171813)
  test(live): prepare runtime config for admitted fixtures
  test(update): stub state-read retry in restart module fixture
  fix(test): pnpm test fails on small cloud containers (#171732)
  fix(code-mode): recover safely from invalid wait IDs (#128886)
  test(update): load acquisition owner in restart regression
  perf(gateway): avoid full row warmup for project and catalog pickers (#171714)
  fix(telegram): voice mentions are ignored in groups when audio scope rules match on chat type (#163746)
  fix(workboard): only promote todo cards to ready (#171743)
  perf(sqlite): avoid repeated admission registry publication (#171788)
  perf: skip unused size accounting for sole session actors (#171777)
  improve(ollama): cover literal fenced command replies (#166561)
  refactor(talk): admit cross-store voice writes once (#171721)
  fix(gateway): recover a Gateway stuck in startup instead of blocking every start (#171678)
  fix(muse): offer Muse Code sign-in from Provider Access (#171790)
  perf: avoid full device lists during silent pairing (#171703)
  docs(cloud): one coherent zero-setup cloud environments guide (#171767)
  fix(test): include cloud move in sidebar action inventory
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 15, 2026
…openclaw#171289)

* fix(gateway): defer initial-turn imports and drain fixture startup

Reset only loaded prepared-model and catalog owners instead of importing
Gateway startup to clear test state. Load chat dispatch only when session
creation requests an initial turn, and recheck authority after the import.

Register fixture ownership before listener and module acquisition. Join
setup, reset, startup, and native-close work before releasing the fixture
environment, while preserving retention after a real close failure.

Two parallel-shard replays still exceed cold first-start/RPC budgets
(249s and 280s wall); no timeout or pool-policy changes were made.

* fix(gateway): prepare startup fixtures and narrow session run checks

Prepare the Gateway startup implementation in fixture hooks before test
behavior budgets begin. Session creation reads active-run projections
without loading the execution and compaction graph.

Drain leaked fixture servers and release their state before reporting
ordinary test or suite leaks, while interrupted cases still join cleanup.

* fix(agents): register catalog test API without a type assertion

Preserve the symbol-owned catalog reset API while removing the unnecessary globalThis cast rejected by assertion-safety CI for PR openclaw#171289.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant