Skip to content

fix(gateway): prevent multi-agent startup stalls - #116261

Merged
fuller-stack-dev merged 1 commit into
openclaw:mainfrom
fuller-stack-dev:codex/gateway-prepared-runtime-scaling
Jul 30, 2026
Merged

fuller-stack-dev merged 1 commit into
openclaw:mainfrom
fuller-stack-dev:codex/gateway-prepared-runtime-scaling

Conversation

@fuller-stack-dev

@fuller-stack-dev fuller-stack-dev commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

Related: #116039

What Problem This Solves

Fixes an issue where users with several configured agents could wait minutes for a fresh gateway or onboarding TUI to become ready because gateway startup eagerly rebuilt broad model-discovery state once per agent.

On the affected 12-agent shape (11 agents sharing one workspace and one agent using another workspace), the old path consumed one CPU core, reached roughly 1.2-1.5 GiB RSS, delayed the event loop during local discovery work, and could exceed the prepared-runtime publication deadline.

Why This Change Was Made

Gateway admission now prepares only turn-critical configured-model facts. Process/config facts are captured once per generation, workspace/plugin facts are built once per distinct workspace, and the resulting immutable facts are projected into isolated per-agent runtime snapshots.

The full model catalog is no longer built during static gateway startup. Explicit catalog consumers load it lazily through a generation-bound single-flight path with concurrency 1, while live/full runtime refresh remains bounded. Publication stays atomic, stale generations cannot publish, auth/config/plugin invalidation remains owner-scoped, and a failed or timed-out build cannot overlap its successor.

This deliberately does not include Wilfred's temporary 300-second publication-deadline mitigation.

User Impact

Fresh onboarding and gateway startup no longer scale pathologically with configured agent count. Agents that share a workspace reuse immutable preparation facts without sharing agent auth or configured-model state, and lower-resource hosts avoid the previous CPU, filesystem, memory, and GC fanout.

The complete model catalog remains available for explicit control-plane operations such as model listing, selection, and diagnostics; it is simply not correctness-critical for admitting the gateway or starting an agent turn.

Evidence

Representative startup benchmark:

Shape Before completion After completion Before prepared runtime After prepared runtime Before CPU After CPU Before peak RSS After peak RSS
1 agent 5.765 s 0.982 s 1.956 s 0.190 s 8 s 4 s 945.9 MiB 919 MiB
12 agents, 2 workspaces 24.869 s 5.035 s 17.302 s 0.459 s 32 s 10 s 1535.7 MiB 878.4 MiB

For the 12-agent fixture, prepared-runtime time fell by about 97.3%, end-to-end completion by 79.8%, CPU by 68.8%, and peak RSS by 42.8%. Deterministic discovery counts changed from repeated agent-scale work (static calls=9, plugin loader calls=70 in the baseline run) to workspace-scale work (static calls=2, plugin loader calls=2) for the two-workspace fixture.

Focused regression proof covers:

  • eleven shared-workspace agents plus one distinct workspace;
  • per-agent configured model and auth isolation;
  • workspace/plugin fact sharing and deterministic call-count scaling;
  • bounded static/live/full build concurrency;
  • stale config generations and superseded auth owners;
  • lazy full-catalog single-flight, lifecycle invalidation, and completed-snapshot validity;
  • atomic publication and no overlap after timeout/failure;
  • provider metadata, prepared registry, and transport propagation.

Validation:

Design Notes

Alternatives considered and rejected:

  • Raising or removing the timeout only hides the duplicate work.
  • A broad cache obscures lifecycle ownership and risks stale auth/plugin/config state.
  • Unbounded parallel fanout reduces wall time on large hosts while worsening CPU, RSS, filesystem contention, GC, and event-loop stalls on constrained hosts.
  • Merely moving the same synchronous discovery behind an async task still blocks the event loop.
  • Lazily deferring all preparation would move correctness-critical work onto the first agent turn.

#116039 reduced repeated resolver creation inside static catalog preparation, but did not remove the per-agent owner duplication addressed here. Searches for open PRs/issues covering prepared-runtime workspace grouping and lazy full-catalog publication found no duplicate implementation.

Remaining uncertainty: general plugin bootstrap still dominates part of end-to-end startup in the many-agent benchmark and is outside this prepared-runtime owner-boundary fix. Wall-clock values vary by host; the workspace-scaled call-count and concurrency assertions are deterministic regression guards.

AI-assisted implementation and review; no agent transcript is included.

@fuller-stack-dev
fuller-stack-dev requested a review from a team as a code owner July 30, 2026 06:20
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Jul 30, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Jul 30, 2026
@clawsweeper

clawsweeper Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 30, 2026, 3:21 AM ET / 07:21 UTC.

ClawSweeper review

What this changes

The PR changes gateway prepared-runtime startup to share immutable workspace discovery work across agents, preserve per-agent model and auth facts, and defer full model-catalog discovery until an explicit control-plane request.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

Keep this PR open for explicit maintainer handling. It is authored by a repository member and carries the protected maintainer label; the prior exact-head review found no discrete patch defect, but this broad startup refactor still needs owner confirmation that provider catalog, auth, and control-plane behavior remain upgrade-safe.

Priority: P1
Reviewed head: 922f7014eefe75302102e6e73e8e7096593d8689
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The PR has substantial stated validation and no prior exact-head finding, but the broad compatibility boundary still needs current-main owner confirmation.
Proof confidence 🌊 off-meta tidepool Not applicable: This is member-authored work, so the external-contributor real-behavior-proof gate does not apply; the PR body nevertheless supplies Testbox and benchmark evidence for maintainers to verify.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This is member-authored work, so the external-contributor real-behavior-proof gate does not apply; the PR body nevertheless supplies Testbox and benchmark evidence for maintainers to verify.
Evidence reviewed 3 items Protected maintainer handling: The PR author association is MEMBER and the item has the protected maintainer label, so this cleanup workflow must not auto-close it.
Prior exact-head review: The latest completed ClawSweeper cycle reviewed the current head and reported no line-level findings, while retaining a human review gate for compatibility across provider, plugin, model-selection, and diagnostics paths.
Related merged predecessor: The related merged PR #116039 removed repeated resolver creation, while this PR describes a distinct remaining source of per-agent duplicate startup work.
Findings None None.
Security None None.

How this fits together

Gateway startup publishes prepared model-runtime snapshots used by agent turns, onboarding, and model-aware services. Configuration, plugin metadata, workspace facts, and auth inputs enter this layer; it emits isolated per-agent snapshots and can later materialize a full catalog for listing, selection, and diagnostics.

flowchart LR
  A[Gateway configuration] --> B[Prepared runtime startup]
  C[Plugin and workspace facts] --> B
  D[Agent auth and configured models] --> B
  B --> E[Isolated agent snapshots]
  E --> F[Agent turns and onboarding]
  E --> G[Lazy full catalog request]
  G --> H[Model selection and diagnostics]
Loading

Decision needed

Question Recommendation
Do gateway and provider owners approve moving full catalog materialization out of startup while accepting the resulting lifecycle and compatibility boundary for existing multi-agent installations? Approve after refreshed owner review: Rebase or refresh against current main, then approve only if owners confirm the startup and explicit-catalog contracts remain compatible.

Why: The patch crosses gateway publication, agent auth, plugin catalog ownership, provider request metadata, and control-plane model discovery; deciding the permanent boundary is a maintainer responsibility rather than a mechanical repair.

Before merge

  • Resolve merge risk (P1) - Merging changes when full model catalogs materialize can alter provider/plugin catalog, model-selection, and diagnostics behavior for existing configurations even if startup improves.
  • Resolve merge risk (P1) - Per-agent auth isolation and the propagation of prepared provider metadata need owner review because mistakes could apply the wrong credentials or request policy after a runtime refresh.
  • Resolve merge risk (P1) - The branch is behind current main; refresh the merge result and re-check the changed lifecycle paths before landing.
  • Complete next step (P2) - A protected, member-authored PR with cross-cutting runtime compatibility risk needs maintainer owner review rather than automated repair or closure.
Agent review details

Security

None.

PR surface

Source +1948, Tests +1780, Other +161. Total +3889 across 56 files.

View PR surface stats
Area Files Added Removed Net
Source 30 2650 702 +1948
Tests 25 1979 199 +1780
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 182 21 +161
Total 56 4811 922 +3889

Review metrics

None.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/agents/models-config.ts, migration/backfill/repair: src/agents/plugin-model-catalog.test.ts, migration/backfill/repair: src/flows/doctor-core-checks.runtime.ts, serialized state: src/agents/models-config.write-serialization.test.ts, serialized state: src/agents/sessions/model-registry.test.ts, serialized state: src/agents/sessions/model-registry.ts, and 15 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Refresh and prove upgrade-sensitive paths (recommended)
    Rebase onto current main and provide focused current-head evidence for configured providers, lazy full catalogs, diagnostics, and auth isolation before merge.
  2. Accept the lifecycle boundary deliberately
    Maintainership may accept the behavior change after confirming that deferred full catalogs are the intended control-plane contract.
  3. Pause for owner design review
    Pause the PR if the intended compatibility contract for plugin catalogs and provider metadata remains unsettled.

Technical review

Best possible solution:

Land only after a current-main owner review confirms that configured-model startup stays lightweight while explicit full-catalog consumers, plugin static catalogs, auth isolation, provider request policy, model selection, and diagnostics retain their established behavior.

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

No: the PR provides benchmark and Testbox claims for the multi-agent shape, but this read-only review could not independently execute or inspect the current checkout after the local inspection sandbox failed.

Is this the best way to solve the issue?

Unclear: sharing workspace-scoped immutable facts and deferring non-critical catalog work is a plausible solution, but maintainers must confirm it is the best permanent provider/plugin lifecycle boundary rather than only a performance improvement.

AGENTS.md: unclear because the file could not be read completely.

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

Labels

Label justifications:

  • P1: The PR addresses a gateway startup stall that can delay multi-agent operation and onboarding.
  • merge-risk: 🚨 compatibility: It changes when model discovery and generated catalog data are built and consumed across existing startup and control-plane paths.
  • merge-risk: 🚨 auth-provider: It refactors ambient and per-agent credential preparation and carries provider metadata into request-policy resolution.
  • merge-risk: 🚨 session-state: It changes publication, invalidation, and replacement of prepared runtime snapshots associated with agents.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is member-authored work, so the external-contributor real-behavior-proof gate does not apply; the PR body nevertheless supplies Testbox and benchmark evidence for maintainers to verify.

Evidence

What I checked:

Likely related people:

  • fuller-stack-dev: Authored the current prepared-runtime refactor and the related merged prepared-runtime startup optimization. (role: recent area contributor; confidence: high; commits: 46ec7a43a8af, 922f7014eefe; files: src/agents/prepared-model-runtime.owner.ts, src/agents/prepared-model-runtime.build.ts, src/gateway/server-startup-post-attach.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Refresh the branch against current main and re-run the focused prepared-runtime lifecycle proof.
  • Confirm configured provider, plugin catalog, model-selection, diagnostics, and auth-isolation behavior on the refreshed head.

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-07-30T06:55:49.547Z sha 321c0dd784cbc5dada7769cda68e9eed1f6e2081 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-30T07:14:06.848Z sha 922f701 :: needs maintainer review before merge. :: none

@fuller-stack-dev
fuller-stack-dev force-pushed the codex/gateway-prepared-runtime-scaling branch from 321c0dd to 8974785 Compare July 30, 2026 06:59
@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jul 30, 2026
@fuller-stack-dev
fuller-stack-dev force-pushed the codex/gateway-prepared-runtime-scaling branch from 8974785 to 922f701 Compare July 30, 2026 07:05
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

Current-head closeout for 922f7014eefe75302102e6e73e8e7096593d8689 on canonical main 3e67671d92b60dfa3c756e010a2bb14f4ace591c:

  • Configured-model startup: representative 12-agent / 2-workspace benchmark and deterministic grouping/call-count tests remain green; startup prepares only configured facts, grouped by lifecycle workspace/config/plugin generation.
  • Explicit full catalog: generation-bound lazy full-catalog loading remains covered, single-flight and concurrency-limited, without replacing the atomically published turn snapshot.
  • Auth/plugin invalidation: focused owner/lifecycle tests cover per-agent auth isolation, config/auth/plugin generation invalidation, supersession, failed/timed-out build serialization, and workspace-specific plugin behavior.
  • Exact failed CI lane fix: removed two unused internal type re-exports; pnpm deadcode:full passed on Blacksmith Testbox tbx_01kyrxbvwqfn1f57q2een725as (Actions run 30521619760).
  • Exact-head autoreview is clean; TruffleHog clean; no actionable findings.

This also satisfies the prior review’s optional rank-up moves: rebased to current main, prior required-lane failures resolved, and concise current-main lifecycle proof provided.

@clawsweeper

clawsweeper Bot commented Jul 30, 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 repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@fuller-stack-dev
fuller-stack-dev merged commit a67ad03 into openclaw:main Jul 30, 2026
258 of 262 checks passed
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Merged via squash.

@fuller-stack-dev
fuller-stack-dev deleted the codex/gateway-prepared-runtime-scaling branch July 30, 2026 07:41
vincentkoc added a commit that referenced this pull request Jul 30, 2026
…n-dedupe

* origin/main: (25 commits)
  fix(qqbot): use Gateway timezone for reminders (#116294)
  test(openai): cover out-of-order named mark acks
  docs(openai): clarify cumulative playback marks
  test(openai): cover sustained unnamed mark acknowledgements
  fix(openai): preserve playback acknowledgement order
  test(openai): verify bounded playback acknowledgements
  fix(openai): bound realtime playback marks
  test(agents): mock incremental registry persistence (#116307)
  fix(memory-core): MEMORY.md compaction deletes user notes written under a promotion-style heading (#116180)
  feat(reply): annotate recent history images (#100866)
  chore(ios): refresh native i18n inventory
  fix(ios): isolate capability router handlers
  docs(ios): cut 2026.7.22 release notes
  docs(hooks): document validation responses
  test(qa): assert hook account rejection reasons
  fix(gateway): validate hook delivery accounts
  perf(gateway): bound prepared runtime startup work (#116261)
  fix(agents): prevent registry stalls during large fan-outs (#116286)
  fix(sqlite): preserve replaced snapshot targets on Windows (#116284)
  fix(ci): load frozen shard runner without repository fetch (#116273)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 31, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 31, 2026
…n-dedupe

* origin/main: (25 commits)
  fix(qqbot): use Gateway timezone for reminders (openclaw#116294)
  test(openai): cover out-of-order named mark acks
  docs(openai): clarify cumulative playback marks
  test(openai): cover sustained unnamed mark acknowledgements
  fix(openai): preserve playback acknowledgement order
  test(openai): verify bounded playback acknowledgements
  fix(openai): bound realtime playback marks
  test(agents): mock incremental registry persistence (openclaw#116307)
  fix(memory-core): MEMORY.md compaction deletes user notes written under a promotion-style heading (openclaw#116180)
  feat(reply): annotate recent history images (openclaw#100866)
  chore(ios): refresh native i18n inventory
  fix(ios): isolate capability router handlers
  docs(ios): cut 2026.7.22 release notes
  docs(hooks): document validation responses
  test(qa): assert hook account rejection reasons
  fix(gateway): validate hook delivery accounts
  perf(gateway): bound prepared runtime startup work (openclaw#116261)
  fix(agents): prevent registry stalls during large fan-outs (openclaw#116286)
  fix(sqlite): preserve replaced snapshot targets on Windows (openclaw#116284)
  fix(ci): load frozen shard runner without repository fetch (openclaw#116273)
  ...
zeroaltitude added a commit to zeroaltitude/openclaw that referenced this pull request Aug 3, 2026
Upstream openclaw#116261 bounded prepared-runtime startup work, deferring model
catalog preparation to first use — measured cost on an agent's first
message: ~16s inside loadResolvedPublishedModelCatalogOwner (live
provider discovery with 5s/provider timeouts plus a manifest-model scan)
before the reply pipeline's first traced phase, with no typing indicator.

Warm each agent's catalog owner from the post-ready prewarm scheduler,
after the runtime plugin registries it depends on: boot stays bounded
(off the startup critical path) and first messages hit a warm catalog.
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 maintainer Maintainer-authored PR merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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