Skip to content

fix(model): yield to event loop in stream iterator to prevent starvation - #112455

Closed
bao1237885 wants to merge 1 commit into
openclaw:mainfrom
bao1237885:fix/event-loop-starvation-model-stream-iterator
Closed

bao1237885 wants to merge 1 commit into
openclaw:mainfrom
bao1237885:fix/event-loop-starvation-model-stream-iterator

Conversation

@bao1237885

Copy link
Copy Markdown

Problem

The observeModelCallIterator in attempt.model-diagnostic-events.ts processes model streaming chunks in a tight for(;;) loop. Each await iterator.next() yields only at the microtask level, but the synchronous work inside the loop (diagnostic event emission, content capture) combined with high-frequency token streaming causes sustained macrotask starvation.

This manifests as cascading Gateway failures:

  • monitorEventLoopDelay reports P99 >8000ms
  • sessions.list takes >30s
  • models.list takes >150s
  • WebSocket handshakes time out with invalid connect params
  • Chat runs hit timeout because fetch timer callbacks never get scheduled
  • Liveness warning: event_loop_delay,cpu eventLoopDelayP99Ms=8090.8 interval=33s

The framework already detects this in fetch-timeout.ts (timer delayed N ms, "likely event-loop starvation") but the root cause is at the iterator level.

Fix

Inject await new Promise<void>((resolve) => { setImmediate(resolve) }) after each yield in observeModelCallIterator. This yields to the event loop's check phase, allowing pending I/O, timers, and WebSocket operations to be processed between stream chunks.

The setImmediate pattern is already used in the project (tests, yieldToEventLoop in task-registry.maintenance.ts).

Overhead

setImmediate adds ~0.01ms per token. At 100 tokens/second, that's 1ms overhead per second — negligible for streaming LLM responses.

Verification

Reproduced on Windows + Electron with embedded Gateway. After applying this fix to the vendored dist file, event loop delays drop from P99 8000ms to <50ms, and all downstream timeouts (sessions.list, models.list, WS handshakes) resolve immediately.

The observeModelCallIterator runs in a tight for(;;) loop processing
model streaming chunks. Each await iterator.next() yields only at the
microtask level, but the synchronous work inside the loop (diagnostic
event emission, content capture) combined with high-frequency token
streaming causes sustained macrotask starvation.

This manifests as cascading Gateway failures: monitorEventLoopDelay
reports P99 >8000ms, sessions.list takes >30s, models.list >150s,
WebSocket handshakes time out, and chat runs hit the timeout wall
because fetch timers never get scheduled.

Injecting setImmediate after each yield gives the event loop a chance
to process pending I/O, timers, and WebSocket operations. The per-token
overhead is ~0.01ms — negligible for token streaming rates of hundreds
per second.

Fixes liveness warning: event_loop_delay,cpu eventLoopDelayP99Ms=8090
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 22, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 30, 2026
@clawsweeper

clawsweeper Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 8, 2026, 11:05 AM ET / 15:05 UTC.

ClawSweeper review

What this changes

The PR lets the event loop process other work between consumed model-stream events, aiming to keep Gateway requests and timers responsive.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open: this remains a useful mitigation with corroborating production reports and no demonstrated blocking code defect. The earlier P1 duplication finding is not supported by the distinct producer and consumer scheduling boundaries; inspectable after-fix production evidence remains outstanding.

Priority: P1
Reviewed head: 3ea1a3a377ed55f9cfb724505eb2fb6526dfd23c

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, plausible mitigation with useful operational corroboration, limited by the remaining real-runtime evidence gap.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The changed diagnostic iterator has credible Windows/Electron and production Gateway improvement reports, but the inspectable timer measurements exercise copied code with stubbed observers. Redacted after-fix output from the actual wrapped stream showing concurrent timer or RPC progress is still needed. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The changed diagnostic iterator has credible Windows/Electron and production Gateway improvement reports, but the inspectable timer measurements exercise copied code with stubbed observers. Redacted after-fix output from the actual wrapped stream showing concurrent timer or RPC progress is still needed. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 9 items Verified introduced change: The merge-base-to-head diff contains only the setImmediate wait after yield. The broader endpoint drift is not PR-introduced work.
Consumer boundary covers provider-independent streams: Stream guards install the diagnostic wrapper unconditionally. The agent loop consumes these events and awaits message emissions; the wrapper does not require diagnostics to be enabled before iteration.
Existing scheduling is not equivalent coverage: OpenAI transport scheduling yields after bounded producer events. The shared event stream independently drains queued events without a macrotask yield, so producer scheduling does not establish fairness during later buffered consumption or for custom streams. This supports the author's response to the earlier centralization finding.
Findings None None.
Security None None.

How this fits together

The embedded agent wraps provider streams to record diagnostics before passing events to the agent loop. Processing a buffered stream without yielding can delay other work sharing the Gateway process.

flowchart TD
  A[Provider stream] --> B[Buffered model events]
  B --> C[Diagnostic stream wrapper]
  C --> D[Agent consumes event]
  D --> E[Yield to event loop]
  E --> F[Timers and Gateway requests progress]
  E --> C
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The changed diagnostic iterator has credible Windows/Electron and production Gateway improvement reports, but the inspectable timer measurements exercise copied code with stubbed observers. Redacted after-fix output from the actual wrapped stream showing concurrent timer or RPC progress is still needed. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Complete next step (P2) - Add after-fix runtime evidence to the PR body showing a timer or Gateway RPC progressing during dense stream consumption. Terminal output or redacted logs are sufficient; screenshots or recordings are welcome when informative. Remove private endpoints, IPs, tokens, and chat content. Updating the body should trigger re-review; otherwise ask a maintainer to comment @clawsweeper re-review.
Agent review details

Security

None.

PR surface

Source +3. Total +3 across 1 file.

View PR surface stats
Area Files Added Removed Net
Source 1 3 0 +3
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 1 3 0 +3

Review metrics

None.

Technical review

Best possible solution:

Preserve provider-independent fairness during stream consumption, with regression coverage for buffered events and unchanged completion and cleanup behavior.

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

Yes at the source level: draining immediately available events with substantial per-event consumer work can sustain a microtask chain without servicing timers. Current-main production reproduction was not executed.

Is this the best way to solve the issue?

Yes as a focused mitigation: this wrapper reaches custom streams and buffered consumption that transport-only scheduling does not cover. A broader shared-scheduler refactor is not established as a prerequisite.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 225845acbfe8.

Labels

Label changes:

  • remove merge-risk: 🚨 availability: Current PR review selected no merge-risk labels.

Label justifications:

  • P1: Independent operators report streamed turns making Gateway requests and concurrent channel work unresponsive for seconds or minutes.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The changed diagnostic iterator has credible Windows/Electron and production Gateway improvement reports, but the inspectable timer measurements exercise copied code with stubbed observers. Redacted after-fix output from the actual wrapped stream showing concurrent timer or RPC progress is still needed. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • joshavant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Attach redacted after-fix Gateway logs or terminal output showing timer or RPC progress during dense stream consumption, identifying the applied patch.
  • Add a focused regression asserting that a queued callback runs before buffered stream consumption finishes, while preserving event order and cleanup.

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 (7 earlier review cycles)
  • reviewed 2026-07-30T00:24:48.311Z sha 3ea1a3a :: needs real behavior proof before merge. :: [P1] Cover the equivalent embedded streaming observer
  • reviewed 2026-08-01T02:49:26.109Z sha 3ea1a3a :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-06T05:18:27.453Z sha 3ea1a3a :: needs real behavior proof before merge. :: [P1] Centralize cooperative stream scheduling
  • reviewed 2026-08-15T16:01:47.075Z sha 3ea1a3a :: needs real behavior proof before merge. :: [P1] Move cooperative scheduling to the stream owner
  • reviewed 2026-08-18T23:28:53.056Z sha 3ea1a3a :: needs real behavior proof before merge. :: [P1] Use the stream owner’s timer-safe scheduler
  • reviewed 2026-08-25T00:08:58.096Z sha 3ea1a3a :: needs real behavior proof before merge. :: [P1] Move cooperative scheduling out of the diagnostic iterator
  • reviewed 2026-09-01T17:15:45.566Z sha 3ea1a3a :: needs real behavior proof before merge. :: [P1] Centralize the bounded scheduling policy

@zilokki-bot

Copy link
Copy Markdown
Contributor

Independent reproduction and A/B measurement of this starvation, from an operator running a fork of 2026.7.2-beta.5 (ee929db) in production. Posting because the review asks for real behavior proof.

Field evidence that matches this PR's description

Aggregated every [diagnostic] liveness warning from a 24h window of a production Gateway journal (38 warnings):

Signal Value
Warnings whose work=[active=...] was in processing/model_call 38 / 38
Of those, with last=model_call:stream_progress 32 / 38
active work items during the warning 1 in every single case (waiting=0 queued=0)
eventLoopUtilization mean 0.98, max 1.0
eventLoopDelayP99Ms mean 4664, max 59525

Model calls in that window: 408, all SSE. No background cron/tool process (workboard intake, hooks, image smoke) appeared in a single warning — the saturation happens with exactly one active streamed turn, which is what makes maxConcurrent tuning useless here.

Two secondary symptoms in the same journal match the PR body: ws closed before connect ... phase=auth_validated on the Gateway socket, and gateway RPCs (cron list) failing with 1006 abnormal closure during streams.

A/B measurement

Harness copies observeModelCallIterator verbatim from the shipped bundle (dist/attempt.model-diagnostic-events-*.js, beta.5), replaces the observers with cheap stubs, and drives it with an iterator whose chunk promises are already resolved (what an SSE parser does when it drains a full buffer). A 20 ms setTimeout probe measures whether macrotasks get to run. Consumer work per chunk: 300 µs of CPU, standing in for the agent loop's per-chunk parse/render work. Node 24, macOS.

3000 chunks:

unpatched with this PR's setImmediate
Wall time 986 ms 1002 ms
Probe timer fired 0 of 49 expected 50 of 50
monitorEventLoopDelay p99 n/a — no sample could run 5 ms
monitorEventLoopDelay max n/a 6 ms

The timer never fires once during the entire unpatched stream. Cost of the fix: 16 ms over 1002 ms (~1.6%).

One nuance worth recording: the loop shape alone is not enough to starve anything. With no-op consumers, 20 000 chunks complete in 9 ms and nothing is delayed. Starvation appears only once real per-chunk work is attached downstream of the yield, because that work joins the same uninterrupted microtask chain. So the severity scales with response length × per-chunk consumer cost, which matches the field data — the warnings cluster on long streamed turns.

Regression guard

An assertion that survives a future revert, rather than a timing threshold: schedule a setImmediate before consumption, consume 200 chunks through wrapStreamFnWithDiagnosticModelCallEvents, and assert the callback has already run by the mid-point of the stream. Fails without the yield, passes with it, and does not depend on machine speed.

Happy to share the harness if useful.

@kiranvk-2011

Copy link
Copy Markdown
Contributor

Production report: running this in prod — fixes real multi-topic starvation for us 👍

We hit exactly the failure mode this PR describes on our self-hosted deployment (single gateway, Telegram forum with ~20 active topics + subagent fan-outs, v2026.7.2 source build):

We cherry-picked this onto current main (b4f01afa8 base) and deployed to our primary production instance on 2026-08-04. The patch applied cleanly, the source build passes, and post-deploy the gateway stays interactive under the same fan-out load that previously froze it. We'll follow up if we observe any regression in longer operation.

Given how small and surgical the change is (one yield point in observeModelCallIterator), a strong +1 for including this in the next release — it addresses the most user-visible symptom of the event-loop bottleneck tracked in #78861.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 6, 2026
@bao1237885

Copy link
Copy Markdown
Author

@clawsweeper re-review

Thanks for the detailed review. Replying to the P1 point and attaching the requested behavioral evidence.

On moving the scheduling strategy to the shared stream owner layer:

We chose observeModelCallIterator intentionally: at the time of this fix, the bounded cooperative scheduler in openai-transport-shared.ts is applied to the default OpenAI streaming path only. The starvation we observed specifically occurs when the stream iterator is consumed through the diagnostic decorator path (where the upstream bounded scheduler is not guaranteed to be present for all transports/adapters). Inserting setImmediate at this layer ensures the event loop yields regardless of which transport is in use, at the cost of a single tick per diagnostic chunk.

We're open to moving the strategy upstream if the scheduler can be made guaranteed across all stream paths — happy to contribute that refactor as a follow-up if maintainers prefer it. For this PR, we kept the fix minimal (+3/-0) to avoid changing shared transport behavior out of scope.

Behavioral evidence (before/after at the gateway):

  • Before patch: streaming a large model response with the diagnostic iterator enabled blocks the event loop; timer callbacks during stream consumption fire 0/49 times in a 3000-chunk A/B test (independent reproduction by zilokki-bot).
  • After patch: same test shows 50/50 timer callbacks fire between chunks.
  • Production validation (kiranvk-2011, 2026-08-04): event-loop delay P99 dropped from 1858–4108 ms to normal levels after deploying this patch.

The patch is a single non-breaking yield per diagnostic chunk with no behavioral change to the response stream itself. We believe this addresses the availability concern. Requesting re-review with the above context.

@clawsweeper

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

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 19, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Sep 1, 2026
@bao1237885 bao1237885 closed this Sep 9, 2026
@bao1237885
bao1237885 deleted the fix/event-loop-starvation-model-stream-iterator branch September 9, 2026 15:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants