Skip to content

perf(streaming): yield across simultaneous stream starts - #177106

Merged
steipete merged 6 commits into
mainfrom
steipete/perf-micro-stream-start-event-loop-burst-20260919
Oct 19, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/perf-micro-stream-start-event-loop-burst-20260919

Conversation

@steipete

@steipete steipete commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

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.

Pair List p95 A → B (ms) List p99 A → B (ms) Release p99, cohort median A → B (ms) Release worst max A → B (ms) Main CPU A → B (s)
1 37.69 → 38.02 72.20 → 52.18 55.02 → 53.67 57.80 → 55.48 59.764 → 60.966
2 33.59 → 38.29 61.99 → 56.78 53.84 → 53.54 56.49 → 60.03 61.950 → 64.565
3 42.55 → 38.39 76.70 → 72.39 63.05 → 54.46 63.24 → 59.02 68.817 → 65.263
4 38.45 → 41.92 58.16 → 54.49 55.05 → 56.69 58.23 → 58.03 68.508 → 68.029

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:

node --import ./scripts/tsx.mjs scripts/perf/transcript-broadcast-measure.ts \
  --state-dir <state> --entry <frozen-install>/dist/entry.js \
  --port <loopback-port> --mock-port <mock-port> \
  --runs 80 --clients 4 --chunks 80 --chunk-interval-ms 250 --rounds 3 \
  --diagnostics --stream-start-diagnostics --active-work-diagnostics \
  --list-interval-ms 2000 --poll-seed <pair-seed> --start-at <shared-epoch>

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, broadcastInternal 11.59ms, writeBuffer 9.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.load fixture 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.

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@steipete
steipete marked this pull request as ready for review October 19, 2026 07:44
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T08:39:38.967605Z cfdfcae New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: M labels Oct 19, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +1152 to +1154
if (random) {
await Promise.race([delay(initialPhaseMs, undefined, { ref: false }), stopped]);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@steipete
steipete force-pushed the steipete/perf-micro-stream-start-event-loop-burst-20260919 branch from ffb5dc5 to b0be864 Compare October 19, 2026 07:57
@steipete
steipete force-pushed the steipete/perf-micro-stream-start-event-loop-burst-20260919 branch from b0be864 to 60b47e5 Compare October 19, 2026 08:03

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +174 to +175
cfg.diagnostics = { ...cfg.diagnostics, enabled: true };
cfg.plugins.entries["diagnostics-prometheus"] = { enabled: true };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 301 to +302
for await (const event of events) {
throwIfModelStreamAborted(signal);
await waitForModelStreamTurn(signal);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@steipete
steipete force-pushed the steipete/perf-micro-stream-start-event-loop-burst-20260919 branch 3 times, most recently from 33abe7e to 97d7bfb Compare October 19, 2026 08:21
@steipete

steipete commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@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.

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. label Oct 19, 2026
@steipete
steipete force-pushed the steipete/perf-micro-stream-start-event-loop-burst-20260919 branch from 97d7bfb to cfdfcae Compare October 19, 2026 08:27
@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: All 80 start notifications can publish before a waiting timer runs.
  • After: Readiness notifications share a weighted budget and yield between batches while preserving each stream’s start and content order.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, useful scheduling change with substantive Gateway evidence, acknowledged measurement limits, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its supplied isolated-Gateway results exercise real SSE transport, 80-stream cohorts, list polling, completion, ordering, and fanout, while identifying frozen scheduler artifacts rather than the complete final head and covering the final cancellation guard only with focused generator proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Concurrent stream starts can delay other Gateway requests despite per-stream cooperative yielding.
Reason: The maintainer-authored direction explicitly accepts neutral overall performance under the recorded gate, and collective scheduling addresses a source-demonstrable fairness gap.

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
Reviewed head: cfdfcaecce5cfdd546e16a31a631fa7a2ed869ba

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The timed Gateway campaign excludes cancellation and does not execute the complete final head.
Agent review details

How this fits together

Provider 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]
Loading

Technical review

Best 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

  • Cooperative stream scheduling changes intended behavior with a stated reason (d2f8f44: Give buffered Anthropic and managed OpenAI streams regular opportunities to process other I/O.)
  • Response-hook lifecycle keeps the original intent (9bbbeb0: Complete response hooks before start/body delivery inside the first-event deadline, preserving cancellation and unread-stream cleanup.)
  • Transcript broadcast benchmark keeps the original intent (838360f: Provide a reusable production-Gateway workload for transcript publication performance comparisons.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +3, Tests +122, Docs +48, Other +221. Total +394 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 37 34 +3
Tests 4 161 39 +122
Docs 1 49 1 +48
Config 0 0 0 0
Generated 0 0 0 0
Other 4 245 24 +221
Total 10 492 98 +394

Review metrics

Metric Value Why it matters
Benchmark controls 5 new CLI options Adds CPU profiling, stream-start diagnostics, active-work diagnostics, chunk interval, and seeded polling to the existing internal benchmark; no product configuration option is added.

Labels

Label changes:

  • add P2: This is a normal-priority concurrency responsiveness improvement with a neutral accepted performance result.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a normal-priority concurrency responsiveness improvement with a neutral accepted performance result.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 19, 2026, 4:36 AM ET / 08:36 UTC.

@steipete
steipete merged commit 0c90292 into main Oct 19, 2026
135 checks passed
@steipete
steipete deleted the steipete/perf-micro-stream-start-event-loop-burst-20260919 branch October 19, 2026 08:37
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: L 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