Skip to content

perf(ai): avoid fulfilled promises for ready stream events - #184222

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-redacted-frames-attribution-20260919
Oct 26, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-redacted-frames-attribution-20260919

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

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/dist locations because its code-location allowlist covers root src/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.

Metric per 160,000 events Baseline Candidate
Main-thread CPU 272.7 ms 244.0 ms
Sampled allocation/event 1,878.7 B 1,516.0 B
GC time 42.1 ms 25.6 ms
Minor collections 44 36
Wall time 6,006 ms 4,905 ms
End RSS 92.0 MiB 91.8 MiB
End used heap 24.8 MiB 23.5 MiB

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) and iterateModelStream (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.

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review October 26, 2026 04:52
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T05:13:10.494803Z 3242554 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: S labels Oct 26, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: Main-thread CPU averages 272.7 ms and sampled allocation averages 1,878.7 bytes per event.
  • After: Main-thread CPU averages 244.0 ms and sampled allocation averages 1,516.0 bytes per event.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is focused and source-consistent, with useful scheduler measurements and successful CI; evidence remains limited to an in-process workload.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence exercises the production scheduler through synthetic in-process streams on Node 26.12.1, while completed Gateway workload evidence is absent.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Concurrent model streaming spends avoidable CPU and allocation on events that can already be admitted.
Reason: The maintainer-authored direction removes measured work with a small runtime change; the added options affect benchmark tooling rather than user configuration.

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

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No completed isolated Gateway streaming run is supplied to establish end-to-end performance or latency effects.
Agent review details

How this fits together

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

Technical review

Best 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

  • Shared scheduler admission and readiness keeps the original intent (0c90292: Share cooperative work limits across simultaneous streams, budget readiness after response hooks, and preserve cancellation before another upstream pull.)
  • Cooperative model-stream iteration keeps the original intent (d2f8f44: Keep buffered provider events from monopolizing the event loop while preserving stream delivery.)
  • Gateway benchmark model configuration keeps the original intent (test(perf): measure RPC allocation promotion and reconnect recovery #178075: Extend the existing isolated benchmark owner for allocation and transport measurements; the new continuation flag is opt-in and leaves its default behavior intact.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Introduced change and current-main behavior: The pinned introduction changes both admission callers to await conditionally, preserves the shared limits, and re-enters the scheduler after delayed admission; fetched main still uses unconditional async admission. (packages/ai/src/transports/transport-stream-shared.ts:257, af2ee49c316b)
  • Original scheduler contract: perf(streaming): yield across simultaneous stream starts #177106 established the shared 64-unit/6-ms budget, readiness weighting, post-wake budget checks, and cancellation before another upstream pull; this PR retains those decisions. (packages/ai/src/transports/transport-stream-shared.ts:257, 0c90292ac661)
  • Performance evidence and regression coverage: The full body reports counterbalanced synthetic scheduler measurements and a base/head checkpoint comparison; the added benchmark directly exercises the production scheduler and readiness wrapper. Body source identity supplied by the host is b48acf6d2aeee2292065529cea9601c4f63e1acfe86889b2282f07d2b33b8e8f. (scripts/perf/model-stream-scheduler-measure.ts:32, af2ee49c316b)
  • Exact-head CI: Both check-run pages were inspected: no failed checks were returned; two auxiliary jobs were cancelled. The openclaw/ci-gate, dependency-review, and security-sensitive-review statuses are successful for the reviewed head. (af2ee49c316b)
  • Feature ownership and history limit: History across the current and former src/agents path identifies Peter Steinberger's initial cooperative scheduler and later shared-budget implementation. An unrelated older blob needed by the move-commit stat was unavailable from the partial clone; the relevant scheduler patches and current-main blame were readable. (packages/ai/src/transports/transport-stream-shared.ts:257, d03f1d391b9b)

PR surface

Source +3, Tests +41, Other +120. Total +164 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 16 13 +3
Tests 1 41 0 +41
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 120 0 +120
Total 4 177 13 +164

Labels

Label changes:

  • add P2: This is a bounded streaming CPU and allocation improvement without an established urgent user-facing failure.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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 bounded streaming CPU and allocation improvement without an established urgent user-facing failure.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Add a completed isolated Gateway streaming comparison to establish the optimization's end-to-end effect.

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 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.
@steipete
steipete force-pushed the steipete/perf-micro-redacted-frames-attribution-20260919 branch from af2ee49 to 3242554 Compare October 26, 2026 05:11
@steipete
steipete merged commit 6eb1ddd into main Oct 26, 2026
108 checks passed
@steipete
steipete deleted the steipete/perf-micro-redacted-frames-attribution-20260919 branch October 26, 2026 05:27
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…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
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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: S 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