Repository navigation
perf(streaming): yield across simultaneous stream starts - #177106
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ffb5dc5606
ℹ️ 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".
| if (random) { | ||
| await Promise.race([delay(initialPhaseMs, undefined, { ref: false }), stopped]); | ||
| } |
There was a problem hiding this comment.
Require a poll before accepting a seeded round
When --poll-seed is used with a list interval longer than a short measured round, this initial delay can lose the race to stopped, so that client exits without issuing any sessions.list request. With one client—or when every client's phase exceeds the workload—the script still writes a successful result with sessionsList.count: 0, while the p50/p95/p99 and p99Request values become undefined and disappear from JSON, allowing an A/B experiment to complete without measuring the latency it claims to compare. Reject an empty sample or keep the round alive until at least one poll completes.
AGENTS.md reference: AGENTS.md:L37-L38
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 60b47e5. A measured round with polling enabled now rejects an empty sample and asks for a shorter interval. Real-CLI reproduction with one stream, one client, one chunk, interval 3600000 ms and seed 42: before, exit 0 with sessionsList.count=0; after, exit 1 with the interval error and no successful result. Both runs used fresh identical synthetic fixtures and the same Gateway runtime. Independent review passed.
ffb5dc5 to
b0be864
Compare
b0be864 to
60b47e5
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 60b47e5bd5
ℹ️ 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".
| cfg.diagnostics = { ...cfg.diagnostics, enabled: true }; | ||
| cfg.plugins.entries["diagnostics-prometheus"] = { enabled: true }; |
There was a problem hiding this comment.
Enable plugins before scraping active-work metrics
When --active-work-diagnostics is used with the required team-shape fixture, scripts/perf/team-shape-fixture.ts supplies plugins.enabled: false; enabling only this entry preserves that global disable. The Gateway therefore never registers /api/diagnostics/prometheus, and readActiveWorkCounts() fails every measured round with an HTTP error instead of verifying the held streams. Set cfg.plugins.enabled = true when this option is selected, as the sibling post-restart benchmark does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is already enabled by the existing helper: transcript-broadcast-measure.ts calls applyMockOpenAiModelConfig before constructing cfg.plugins; scripts/e2e/lib/fixtures/mock-openai-config.mjs:103–106 explicitly sets plugins.enabled=true, which the subsequent spread preserves. The real benchmark also observed 80 running / 0 queued through the Prometheus endpoint in every completed cohort. An additional assignment would duplicate the helper contract, so no code change is needed for this finding.
| for await (const event of events) { | ||
| throwIfModelStreamAborted(signal); | ||
| await waitForModelStreamTurn(signal); |
There was a problem hiding this comment.
Check cancellation before pulling the next stream event
When a consumer aborts after receiving one event and then requests the next event from an upstream iterator that does not independently observe this signal, the for await loop now calls and awaits the upstream next() before reaching waitForModelStreamTurn(). The previous post-yield scheduler check rejected immediately; now cancellation can consume one extra side-effectful event or hang indefinitely on a stalled iterator. Restore an abort check after each resumed yield and before the loop pulls again.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ae94fdeb5658. iterateModelStream now checks cancellation immediately after the consumer resumes the yielded event, before requesting another upstream event. The new real-generator regression failed on the previous head with the upstream error; it now preserves the coded cancellation reason, performs only one upstream pull, and closes the generator. All 86 focused transport tests pass, and independent review found no actionable P0–P2 issue.
33abe7e to
97d7bfb
Compare
|
@clawsweeper re-review Current head: cfdfcae. All accepted review findings are fixed; the plugin-enable suggestion was resolved with source evidence. The body now includes the completed four-pair randomized comparison, the neutral-result decision, artifact limitations, persisted transcript verification, and the reproduced/repaired Bun test-clock failures (32/32 provider tests and 19/19 continuation tests). Independent P0–P2 review is clean. Exact-head CI is pending. |
|
🦞👀 Re-review progress:
|
97d7bfb to
cfdfcae
Compare
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesThis PR shares a cooperative yield budget across model-stream readiness and body events and extends the existing performance measurement tools. Example: 80 model streams become ready together.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR provides a focused fairness improvement with an explicitly accepted neutral performance result; review found no actionable introduced defect. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherProvider transports feed response hooks and streamed events into shared AI transport helpers, which deliver ordered events to agent and Gateway consumers. flowchart TD
A[Provider responses] --> B[Response hooks]
B --> C[Shared cooperative budget]
D[Provider body events] --> C
C --> E[Ordered stream delivery]
E --> F[Agent and Gateway consumers]
Technical reviewBest possible solution: Keep one shared scheduling owner with weighted readiness, preserved lifecycle ordering, and the existing benchmark’s bounded diagnostics. Do we have a high-confidence way to reproduce the issue? Current-main source independently budgets each stream and leaves readiness unbudgeted; the supplied regression records all 80 starts preceding a waiting timer on base. Is this the best way to solve the issue? The change uses the existing shared transport boundary, removes the superseded scheduler, and preserves hook, ordering, and cancellation contracts without introducing a second delivery owner. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 19ca8dd3d189. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +3, Tests +122, Docs +48, Other +221. Total +394 across 10 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 19, 2026, 4:36 AM ET / 08:36 UTC. |
…7106) * perf(streaming): share the yield budget across simultaneous streams * fix(ai): budget readiness after response hooks settle * fix(perf): reject broadcast measurements without list samples * fix(ai): stop upstream pulls when stream consumers cancel * test(ai): keep scheduler timers live in connection age coverage * test(ai): drain stream scheduling before restoring real timers
What Problem This Solves
Concurrent model streams previously had independent yield budgets, and readiness notifications bypassed those budgets. An 80-stream start could therefore publish every start before a waiting timer ran. This change replaces those independent schedulers with one process-local cooperative budget for readiness and body delivery.
The four-pair result is neutral overall, with improved list p99. It does not demonstrate the originally targeted large reduction in release-burst delay. Landing follows the operator's explicit rule permitting this requested change when measurements show no regression beyond noise. Related: #176981; its diagnostics optimization is deliberately separate.
User Impact
Streams yield collectively so other Gateway requests can run during concurrent starts. Response hooks still precede content; per-session event order and coded cancellation remain intact. No configuration or migration is required.
The shared budget is 64 units or 6ms; readiness costs eight units and body events one. Readiness claims its budget after response hooks settle, and waiters recheck the budget after waking. Cancellation is checked before delivery and before another upstream pull. Gateway synchronous reply capture and completion ownership stay with their existing owners; adding an asynchronous hop there could let finalization overtake capture.
The old per-stream scheduler is removed. Runtime production delta is +3 lines: the weighted readiness/body contract and shared wake recheck account for the small growth. The requested non-test diff is +272 lines including +269 lines of benchmark instrumentation and documentation. No second scheduler, persistent cache, schema change, or dependency is added.
Evidence and Measurement
A real isolated Gateway used synthetic SSE responses, 5,000 sessions, 6,000 retained runs, 200 approvals, 100 disabled cron jobs, 12 projects, and a 1MiB logical transcript payload. Each side ran three measured 80-stream cohorts, four viewers, and 80 chunks at 250ms; warmup was excluded. List polls use seeded independent phases plus jitter at a nominal 2-second interval. The active-work exporter must observe 80 running / 0 queued before release.
Four concurrent pairs held the exclusive measurement lock, used separate state/ports and swapped 16-core halves after each pair. Outside load was recorded. Acceptance runs had no CPU or allocation sampling; all successful captures were retained. Quantiles pool the three cohorts within each side, then compare B minus A within each pair.
Median paired deltas: list p95 +1.90ms (range −4.16…+4.69), list p99 −4.76ms (all four improved), release median p99 −0.82ms, release worst maximum −1.26ms, admission median p99 +1.29ms, admission worst maximum −50.33ms, main CPU +0.362s per 240 turns, and wall time −6.9ms. No assessed latency/CPU/wall cell regressed by more than 20%. The predeclared list gate was median p95 increase ≤5ms and at most one pair >20ms; it passes. The original material release-improvement target is unmet.
All eight persisted states passed: 640 sessions completed, 2,560 exact assistant answers including warmup, correct alternating transcript order, and zero pending inputs. Live sequence and equal fanout checks passed. Timing-dependent activity-summary delivered-frame deltas were +288, +272, −128, +128; pair four also had four fewer placement notifications. Other frame categories matched. The harness does not retain every frame for a complete normalized per-session semantic A/B comparison, so exact total-frame equality is not claimed.
Rerunnable measurement command, with fresh fixture/state per side and the appropriate paired CPU scope:
Profile and artifact limits
Separate baseline CPU profiles found busy CPU across the first 150ms after release, distributed across model publication, Gateway lifecycle projection/broadcast, and GC. Busy samples do not establish one uninterrupted task. Across three 150ms windows, top self-time sites included GC 41.54ms,
broadcastInternal11.59ms,writeBuffer9.54ms, WebSocket diagnostics 9.48ms, and agent-ID normalization 8.41ms. One 357.60ms admission RPC interval contained 286.18ms sampled GC; allocator ancestry and precise pre-dispatch time are unavailable. The acceptance histogram is primed; the original unprimed histogram was excluded from latency conclusions.A/B runtime resolution was audited, including private externalized AI packages and both sealed worker copies. The common root build is pinned to de2700c; the timed scheduler source corresponds to 60b47e5. Later rebases include terminal-receipt, preparation/helper, settings-readiness, recovery, resource-lifecycle, and sandbox-cleanup changes absent from that common root. Source audits found no changed stream-readiness/scheduler owner, but these results identify the frozen artifacts, not the entire final head. The final post-yield cancellation check is also absent from timed bytes; the campaign has no cancellations. Exact-head PR CI supplies integration proof, not a replacement timing measurement.
The first scheduler revision was rejected after four pairs: list p99 worsened +28.73ms at the paired median. Its small shared body budget was replaced by the weighted budget above. Those captures remain separate and are not part of the accepted four-pair table.
Proof and Review
The 80-start regression fails on base and passes here, preserving start/first/last order. Other focused regressions cover held response hooks, body-only shared fairness, cheap responses avoiding unnecessary yields, elapsed budget, and cancellation preserving iterator cleanup without another upstream pull. Transport tests passed 86/86 across five files (2.71s wrapper wall time); profiler fixture tests passed 8/8. The single permitted core typecheck passed on the initial implementation; changed-file formatting/lint passed. Broad proof belongs to exact-head PR CI.
Independent reviews found and verified fixes for hook settlement, body throughput, an empty-list-sample harness hole, and post-yield cancellation. The empty-sample CLI reproduction returned success/count zero before the guard and an actionable failure afterward. The plugin-enable suggestion was rejected with source and live exporter evidence: the existing mock-model helper already enables plugins.
CI exposed a connection-age test that froze scheduling timers and jumped Date 56 minutes, stranding the shared scheduler. It now fakes only Date. The original reproduces a timeout under Bun; the repaired provider file passes 32/32 in 1.64s wrapper wall time (713ms Vitest), with clean P0–P2 independent review. An obsolete
SubscriptionDeps.loadfixture was fixed upstream in 833bd27 and incorporated by rebase. An earlier dashboard hover timeout remains unclassified; later passing UI shards are not claimed as a proven fix. No CI reruns were used to chase green. No Testbox lease was allocated under the operator's compute rule.A focused timer-lifecycle audit found the same abandoned scheduler promise in the Responses continuation file: its expiry test passed, then 14 later cases timed out. That test genuinely needs the 5-minute eviction timer, so its expiry assertions remain unchanged. Teardown now closes session resources, drains remaining fake timers asynchronously, and restores real timers. The full file passes 19/19 under Bun (8.48s wrapper, 6.66s Vitest, about 0.3s test execution), with clean independent P0–P2 review. This is test-only and does not change the measured runtime.