Repository navigation
fix(model): yield to event loop in stream iterator to prevent starvation - #112455
bao1237885 wants to merge 1 commit into
Conversation
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
|
Codex review: needs real behavior proof before merge. Reviewed September 8, 2026, 11:05 AM ET / 15:05 UTC. ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherThe 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
Before merge
Agent review detailsSecurityNone. PR surfaceSource +3. Total +3 across 1 file. View PR surface stats
Review metricsNone. Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (7 earlier review cycles)
|
|
Independent reproduction and A/B measurement of this starvation, from an operator running a fork of Field evidence that matches this PR's descriptionAggregated every
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 Two secondary symptoms in the same journal match the PR body: A/B measurementHarness copies 3000 chunks:
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 Regression guardAn assertion that survives a future revert, rather than a timing threshold: schedule a Happy to share the harness if useful. |
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 ( Given how small and surgical the change is (one yield point in |
|
@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 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):
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. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Problem
The
observeModelCallIteratorinattempt.model-diagnostic-events.tsprocesses model streaming chunks in a tightfor(;;)loop. Eachawait 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:
monitorEventLoopDelayreports P99 >8000mssessions.listtakes >30smodels.listtakes >150sinvalid connect paramsfetchtimer callbacks never get scheduledevent_loop_delay,cpu eventLoopDelayP99Ms=8090.8 interval=33sThe 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 eachyieldinobserveModelCallIterator. This yields to the event loop's check phase, allowing pending I/O, timers, and WebSocket operations to be processed between stream chunks.The
setImmediatepattern is already used in the project (tests,yieldToEventLoopintask-registry.maintenance.ts).Overhead
setImmediateadds ~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.