Repository navigation
perf(ai): avoid fulfilled promises for ready stream events - #184222
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
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. |
|
Codex review: needs maintainer review before merge. What this changesThis PR avoids creating and awaiting fulfilled admission promises when the shared streaming scheduler has capacity. Example: The reported synthetic workload delivers 20,000 events on each of eight concurrent streams.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR provides a focused performance improvement that current main still lacks, with no actionable correctness or security findings. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe AI transport layer admits provider readiness and body events through one process-wide cooperative scheduler before downstream stream consumers receive them. flowchart LR
A[Provider streams] --> B[Response lifecycle hooks]
B --> C[Shared admission scheduler]
C --> D[Ready admission]
C --> E[Timer wait and recheck]
E --> C
D --> F[Stream consumers]
Technical reviewBest possible solution: Retain the existing scheduler owner and conditionally await only admissions that exhaust its shared budget. Do we have a high-confidence way to reproduce the issue? Current main unconditionally awaits an async admission function even when capacity is available; the supplied base/head checkpoint comparison supports the extra-work diagnosis, but no target code was executed during this review. Is this the best way to solve the issue? The patch removes unnecessary async work at its existing owner, updates both callers, and preserves fairness and cancellation without adding runtime state or a parallel implementation. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d03f1d391b9b. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +3, Tests +41, Other +120. Total +164 across 4 files. Added test files: 0. View PR surface stats
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
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 26, 2026, 1:08 AM ET / 05:08 UTC. |
Preserve shared cooperative admission and cancellation while awaiting only exhausted turns. Add a checkpoint regression and reproducible allocation/CPU measurement. Synthetic eight-stream runs reduce sampled allocation per event by 19.3% and paired main-thread CPU by 10.4%; production diagnostic redaction is unchanged.
af2ee49 to
3242554
Compare
…184222) * perf(ai): avoid fulfilled promises for ready stream events Preserve shared cooperative admission and cancellation while awaiting only exhausted turns. Add a checkpoint regression and reproducible allocation/CPU measurement. Synthetic eight-stream runs reduce sampled allocation per event by 19.3% and paired main-thread CPU by 10.4%; production diagnostic redaction is unchanged. * test(perf): keep stream benchmark scoped to its owner
What Problem This Solves
Streaming provider responses allocate and schedule an extra fulfilled promise for every event, even when the shared cooperative scheduler can admit it immediately.
User Impact
Less allocation and main-thread CPU during concurrent model streaming. Event ordering, cancellation, and shared fairness limits remain unchanged. No configuration or diagnostics-redaction changes.
Why This Change Was Made
The scheduler returns a promise only when it must wait. Both event iteration and provider readiness consume that result conditionally. Delayed admissions re-enter the same owner to check cancellation and current capacity. The shared 64-unit/6-ms budget, readiness weighting, and cancellation before the next upstream pull remain intact.
Diagnostics hides workspace
packages/ai/distlocations because its code-location allowlist covers rootsrc/dist, Node internals, and dependency labels. Function-name restrictions and URL query/fragment rules also redact frames. The supplied allocation summary's hidden scheduler and iterator rows account for approximately 6.61 and 5.33 MiB over 30 seconds. Local raw profiling now directly identifies both owners. Production redaction is unchanged.The largest supplied hidden row is continuation-state serialization (23.71 MiB). A separate counting prototype reduced allocation but increased CPU for small requests, so it is not included. This PR removes ready-admission promise work; it does not claim to eliminate all hidden allocation.
Runtime production delta: +3 lines (16 added, 13 removed), because both callers explicitly distinguish ready admission from waiting. No new cache, state owner, dependency, or compatibility path. The checkpoint regression adds 41 lines; the standalone benchmark adds 113 lines (non-test total: +116). The shared Gateway benchmark is unchanged.
Evidence
Owner baseline:
29397d2a185c29d4b4d79d2ad41af0f7cf1f6a9b. Node 26.12.1 on a shared Mac. Eight concurrent synthetic provider streams, 20,000 events each, including provider readiness. Four timing pairs alternate AB/BA; allocation uses two separate AB/BA inspector passes with a 4,096-byte sampling interval and collected objects included.CPU improves in all four pairs (mean paired change −10.4%); allocation falls 19.3% in the separate sampling passes. Host one-minute load ranged 71–93, so wall time and endpoint memory are context. Baseline/candidate maximum GC pauses by pair: 6.97/4.42, 12.58/4.29, 10.50/3.45, 12.07/13.49 ms; no major collections. No tail-latency claim is made from these short owner runs. The earlier short sequential batch had noisy CPU/wall results; the larger counterbalanced protocol above is the decision evidence.
The regression compares observable microtask progress with an equivalent async-iterator control: baseline takes 84 checkpoints versus 68 for 16 events, candidate adds none. All 18 focused scheduler tests pass, including shared swarms, delayed-budget reset, ordering, lifecycle, and coded cancellation. Export-name collision guard passed; eager-import and PR-wrapper source closure: 22/22 passed. Changed-file formatting and type-aware lint pass. Independent subagent review (autoreview route unavailable) found no actionable P0–P2 findings, including the final simplification. The configured autoreview route's preflight rejected a provider/config mismatch; operator configuration was unchanged.
A built-baseline Gateway raw capture passed with 10,800 sessions, a 40-plugin allowlist, 65 clients, 24 foreground turns and 24 tool calls/results, zero failed turns or RPC errors. It directly exposes
waitForModelStreamTurn(0.376 MiB) anditerateModelStream(1.160 MiB). A separate single-client chat capture completed two rounds of eight turns/tool cycles without errors and identified continuation accounting (1.925/2.042 MiB). That chat mode resolves current AI source through the canonical loader; it is explicitly baseline core plus candidate AI source, confirmed by raw frame URLs and source hash, and supplies functional candidate smoke/attribution only.The scoped fast-path protocol omits a long multi-pair Gateway campaign: scheduling limits are unchanged, and owner work/allocations are measured directly. Neither traced capture is a whole-Gateway performance comparison.
Traced baseline Gateway context and remaining cost
The 75.65-second baseline capture sampled 5.867 GB (77.55 MB/s); main-thread CPU 32.68%, GC 2.371 s/min, event-loop p99 193.46 ms (2,095 samples), client sessions.list p99 2,741 ms and server handler p99 2,720 ms (149 samples, context only), ending RSS 3.200 GB and used heap 751 MB. Final host load averages were 61.85/68.06/68.29. These are one traced baseline, not acceptance comparisons; no adverse inference or Gateway speedup is claimed.
The local profile also shows a larger residual in diagnostic credential projection (
projectValue, 60.40 MiB); that redaction owner/policy is unchanged. First-run fixture preparation initially prevented startup; supported Doctor repair resolved it. A temporary diagnostic harness copy extended startup readiness from 150 to 600 seconds without changing measured windows or liveness/admission checks. All owned Gateways exited. Raw profiles and experimental attribution configuration remain local; no production service was stressed or changed.