Skip to content

perf(gateway): reduce scope-entry copies during stream dispatch - #183552

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-stream-delta-dispatch-scope-20261025
Oct 25, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-stream-delta-dispatch-scope-20261025

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Streamed assistant events still copy the full ambient async context repeatedly when the observer enters its work scope, after #183495 optimized detached delivery.

User Impact

Reduces allocation and CPU spent dispatching streamed events. Pending-work registration, cancellation, errors, and shutdown/drain behavior remain owned by the same scope; there is no batching or new cache.

Why This Change Was Made

On Node 26, each AsyncLocalStorage.run copies the context on entry and again on restoration. Scope entry nests two such calls. Use the existing runWithAsyncStore boundary to restore the caller's frame once and enter the two carriers inside it. Keep the existing same-owner fast path and #183495 unchanged.

Runtime production LOC: +1 (4 added, 3 removed). The existing helper needs an explicit callback body/return to set the ancestry carrier; no new owner, state, retained data, or compatibility path. The larger script addition is a rerunnable owner benchmark, with usage in its header.

This also restores unrelated caller context after a scope callback changes it, including throws. Both new regression cases fail on main with scope continuation leaking into the caller, and pass with this change.

Evidence

Baseline: 2f95e977c77d74ba463cdfee9436da1004778fcc, including #183495. Node 26.12.1, macOS; five sequential alternating pairs, 240,000 events per side per pair, 48 interleaved streams and 24 ambient stores. Every side delivered and observed every event. Allocation uses collected-object sampling in a separate pass; promotion uses a separately traced pass with explicit measurement boundaries. Timing and GC gates use untraced runs. Acceptance follows the predeclared campaign rules: meaningful CPU/allocation improvement, no material absolute GC or latency regression, no new retained cache.

Metric (mean across five pairs) Main Candidate Absolute delta Mean paired delta
Sampled allocation, bytes/event 29,780.41 20,659.90 −9,120.51 −30.63%
Main-thread CPU, µs/event 6.1428 4.3552 −1.7876 −29.03%
Total GC, ms/1,000 events 0.3042 0.2133 −0.0910 −29.19%
Delivery latency p95, ms 2.3757 1.6875 −0.6881 −28.90%
Delivery latency p99, ms 2.9221 2.1582 −0.7639 −24.89%
Event-loop p95, ms 3.7536 2.8004 −0.9531 −24.44%
Event-loop p99, ms (context only) 5.1495 4.1939 −0.9556 −17.19%
Promotion, bytes/event (traced) 131.5435 131.5117 −0.0318 +1.83%

Delivery tails have 240,000 samples per side/pair; loop tails have 499, so loop p99 is context only. Allocation sample counts by pair, main/candidate: 431420/300193, 432372/299716, 431695/299360, 431986/300110, 432712/299408. Promotion has mixed signs; the signed absolute mean is essentially flat (−0.024% of the mean baseline), rather than the misleading mean relative percentage. No GC/promotion rejection is claimed and no A/A rejection controls were needed.

Pair Minor collections main/candidate Major collections main/candidate Maximum minor pause, ms main/candidate Maximum major pause, ms main/candidate
1 348 / 176 4 / 4 0.759 / 0.530 1.652 / 1.514
2 348 / 173 4 / 3 0.548 / 1.015 1.396 / 2.361
3 348 / 180 4 / 3 0.937 / 1.201 2.037 / 2.185
4 345 / 176 4 / 4 13.582 / 1.214 1.361 / 1.335
5 360 / 181 2 / 3 0.832 / 0.792 1.402 / 1.960
GC kind Collections across five runs main/candidate GC ms/1,000 events main/candidate Mean per-run p95 ms main/candidate Mean per-run p99 ms main/candidate
Minor 1749 / 886 0.28269 / 0.19249 0.310 / 0.435 0.537 / 0.767
Major 18 / 17 0.01990 / 0.01938 1.570 / 1.871 1.570 / 1.871
Incremental 18 / 17 0.00164 / 0.00141 0.140 / 0.109 0.140 / 0.109

Counts are totals for reporting, not pooled samples used to turn underpowered per-run tails into gates. All GC tails in this table are context only under the per-run sample/materiality rules.

Minor pause p95/p99 increases are sub-millisecond and candidate collection counts are below 200; major tails are context only with fewer than 50 collections. No candidate maximum approaches 50 ms. Per-kind totals and tails are emitted by the benchmark.

A separate subscription-boundary probe exercised the real emitAgentEvent → runtime subscriptions → observer path with a controlled chat sink: all 48,000 events delivered; sampled scope-stack allocation 20,257 → 10,599 bytes/event (−47.7%), overall 34,394 → 25,359 bytes/event (−26.3%). This corroborates the residual owner; it is not a WebSocket or live-model load claim.

Commands:

  • node --expose-gc --import ./scripts/tsx.mjs scripts/perf/stream-dispatch-scope-measure.ts (also separate --allocations and Node --trace-gc-nvp passes).
  • OPENCLAW_VITEST_RUNTIME=node node scripts/run-vitest.mjs src/shared/async-work-scope.test.ts src/shared/async-store.test.ts src/gateway/server-runtime-subscriptions.test.ts src/gateway/server-runtime-subscriptions.shutdown.test.ts --maxWorkers=1: 92 passed, 86.08 s including preparation; scope tests 1.00 s wall / 21 cases. CI seconds pending.

Additional proof: pnpm tsgo:core; scoped lint and oxfmt for the three files; git diff --check; export-name-collision guard; eager-import and PR-wrapper closure tests (22 passed, 39.80 s). Independent subagent review (autoreview route unavailable): scoped-clean, no P0–P2 findings. The autoreview helper refused the configured provider route before inference; no configuration was changed. GitHub Codex review also completed on c92be16ae37e3889b07c1667f2ac2229335f35f6 with no findings.

Simplification pass: one existing restoration owner replaces nested restoration; no parallel fast path or cache. Runtime +1 LOC, regression tests +26 LOC, standalone benchmark +186 LOC. Exact-head CI is green: run 40188393424 succeeded for c92be16ae37e3889b07c1667f2ac2229335f35f6; 77 checks passed, 54 intentionally skipped, none failed or pending. No CI retries.

No Testbox leases or production changes. Whole-Gateway/WebSocket throughput and Linux runtime measurements remain unmeasured; the lead should look for fewer context-copy allocations beneath AsyncWorkScope.track at unchanged delta volume, with unchanged drain/error behavior. Please leave this PR for the lead to merge.

@clawsweeper

clawsweeper Bot commented Oct 25, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T11:21:36.504238Z c92be16 PR opened
ℹ️ 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 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces nested async-context restoration with the existing shared restoration helper and adds regression coverage and a benchmark.

Example: A scope callback changes an unrelated async store from "caller" to "scope continuation" and then returns or throws.

  • Before: The changed value escapes into the caller.
  • After: The caller sees "caller" again.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and source-consistent with successful exact-head gates; performance evidence remains limited to owner and subscription harnesses.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied Node 26 macOS measurements exercise AsyncWorkScope and the real subscription owner with a controlled sink, without establishing whole-Gateway transport performance.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated context copies consume CPU and allocate memory while streamed assistant events enter observer work scopes.
Reason: The maintainer-authored direction removes measured waste with minimal runtime change and preserves the existing ownership contract.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR makes a focused, measured optimization that current main lacks; no actionable correctness or security defect was found.

Priority: P2
Reviewed head: c92be16ae37e3889b07c1667f2ac2229335f35f6

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Whole-Gateway streamed delivery through a real transport remains unmeasured; supplied evidence covers the scope and subscription-owner boundaries.
Agent review details

How this fits together

Gateway event subscriptions enqueue observer callbacks through AsyncWorkScope, which supplies inherited work ownership and tracks accepted promises through cancellation and drain.

flowchart TD
  A[Streamed agent event] --> B[Runtime subscriptions]
  B --> C[Observer event queue]
  C --> D[AsyncWorkScope entry]
  D --> E[Shared async store boundary]
  E --> F[Callback and descendants]
  D --> G[Pending work and drain]
Loading

Technical review

Best possible solution:

Use the existing isolated restoration helper while preserving scope identity, ancestry, admission, and drain ownership.

Do we have a high-confidence way to reproduce the issue?

Current main visibly performs nested scope-entry restoration, and the added cases isolate unrelated-store leakage; supplied benchmark and red/green results were inspected but not rerun during this read-only review.

Is this the best way to solve the issue?

The patch is the smallest complete change: reuse the existing restoration boundary, set ancestry inside it, and preserve the established lifecycle owner without a cache or parallel implementation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4ca976fb8899.

Provenance checked

  • Scope ancestry and restoration changes intended behavior with a stated reason (e8ced6b: Separate ancestry preserves shipped carrier identity and detects nested cleanup ownership across runtime replacement.)
  • Same-owner entry fast path keeps the original intent (8181c58: Avoid redundant context entry when work already executes under the same owner.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 8181c58 adds src/shared/async-work-scope.ts:41 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8181c588ac11; files: src/shared/async-work-scope.ts)

PR surface

Source +1, Tests +26, Other +186. Total +213 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 4 3 +1
Tests 1 26 0 +26
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 186 0 +186
Total 3 216 3 +213

Review metrics

Metric Value Why it matters
Runtime versus regression code Runtime +4/-3 lines; regression tests +26 lines The one-line net runtime growth reuses the existing restoration owner; the two test cases protect restoration after normal return and throw.

Labels

Label changes:

  • add P2: A measured streaming dispatch optimization with limited demonstrated scope and no 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: A measured streaming dispatch optimization with limited demonstrated scope and no 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.

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 25, 2026, 7:34 AM ET / 11:34 UTC.

@steipete
steipete merged commit cf258d0 into main Oct 25, 2026
145 of 146 checks passed
@steipete
steipete deleted the steipete/perf-stream-delta-dispatch-scope-20261025 branch October 25, 2026 11:39
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
RomneyDa added a commit that referenced this pull request Oct 28, 2026
RomneyDa added a commit that referenced this pull request Oct 29, 2026
Mirror main's Knip entries for files added by beta.5 backports:
- scripts/perf/{node-event-session-source-measure.mjs,
  stream-dispatch-scope-measure.ts,system-prompt-report-retention.ts}
  as path-invoked script roots (#183931, #183552, #183010);
- the Telegram ingress context Worker fixture loaded by URL (#178909) in
  production ignoreFiles.
Also register scripts/test-security-mail-parser.mjs, the standalone
nodemailer sender-parsing regression added by #187301 (release-only).
RomneyDa added a commit that referenced this pull request Oct 29, 2026
…eadcode after backports (#187570)

* refactor: keep Teams allowlist sentinel private (#185484)

The Microsoft Teams fail-closed allowlist sentinel now remains module-private while preserving its exact restrictive projection and lifecycle coverage.

(cherry picked from commit 59b1ddd)

* test: teach the live-wrapper fake Bun to answer --revision

Partial cherry-pick of the test/scripts/test-live.test.ts hunk only.
#173807 (backported as e72f868) made the CI Bun --revision probe
mandatory; the fake Bun fixture must answer it from the checkout pin.

(cherry picked from commit 08dd80a)

* test(ci): expect watchdog exit 124 from wedged run-tsgo

#184639 (backported as d9a91b5) intentionally changed the run-tsgo
watchdog exit from 1 to 124 so CI collectors stop admitting work. Main
realigned this case in run-tsgo-worktree.test.ts (9b14a38); on the
release branch the same watchdog case lives in run-tsgo.test.ts and was
not realigned by the backport.

* test(vitest): keep gateway database-worker routes in canonical order

The beta.5 adaptation of #178415 (23a2bcd) prepended three
integration proofs to gatewayDatabaseWorkerTestFiles. Canonical project
ownership compares that list against sorted discovery, so the
out-of-order entries failed vitest-cli-ownership. Move them to their
sorted positions; routing membership is unchanged.

* refactor: keep Slack reconnect policy private (#181690)

Keeps Slack reconnect policy details module-private while preserving the exact invalid-auth cutoff, reset, and blocked-status behavior.

(cherry picked from commit cd65901)

* fix: keep retired Telegram throttler release private

Telegram hunk of 09f9ec8 (#183086) only. The release-only test
called the private helper directly; its surviving-alias case is already
asserted through releaseRemovedTelegramAccountThrottler, so drop the
duplicate direct call.

(cherry picked from commit 09f9ec8, partial)

* refactor: keep Claude partial-message measurement private

src/agents/cli-output-stream-limits.ts hunk of 28e2774 (#184686) only;
the backport of #184352 left this export without a consumer.

(cherry picked from commit 28e2774, partial)

* refactor: keep managed plugin cache selector private

src/plugins/management-catalog.ts hunk of 2c0c30b (#185269) only;
the backport of #184921 left this export without a consumer.

(cherry picked from commit 2c0c30b, partial)

* refactor(agents): keep requester settle batch callbacks type private

The backport of #181260 (2f7589a) moved RequesterSettleWakeParams
into the state module, leaving RequesterSettleWakeBatchCallbacks exported
only for a test fixture. Main keeps it module-private; type the fixture
through RequesterSettleWakeParams instead.

* refactor(infra): drop unconsumed streaming UTF-8 decoder

The minimal backport of #180861 (8d3183d) added decodeUtf8Chunks as
a prerequisite, but its main consumers (streaming state-migration
importers) were intentionally not backported, so production Knip flags
it. Remove the export and its unit case; decodeUtf8Input is unchanged.

* refactor(scripts): keep pinned Bun CI detection private

The minimal #172625 backport (e6c3639) deferred the dev-tool,
test-runtime and run-format callers that consume isCiEnvironment on main,
so the export has no consumer on the release branch.

* test(update): drop orphaned recovery version-mismatch fixture

The #185692 backport in 39f9bde removed the last consumer of
recoveryVersionMismatch from update-cli.plugin-convergence.test.ts. Main
removed the same fixture in eae9bc4 (#181717).

* test(gateway): type config removal mocks through inline module imports

The release adaptation of #152052 (41aa7a6, de41770) typed its
partial mocks through type-only namespace imports. Knip treats the
secrets runtime namespace as the only consumer of its exports, so the
full-tree scan reported prepareSecretsRuntimeSnapshotRestore and
SecretResolverWarning as unused. Use main's inline typeof import() form.

* refactor(shared): drop unconsumed async-store helper

The backport of #179213 (6d9852d, plus f3fb0e9 registering it
as a wrapper component) took the runWithAsyncStore helper and its test
without the plugin-instance-invocation consumer, leaving
src/shared/async-store.ts unused in production. Remove the helper, its
test and its wrapper-components entry rather than complete a perf change
during beta stabilization.

* chore(knip): model backported perf scripts and Telegram worker fixture

Mirror main's Knip entries for files added by beta.5 backports:
- scripts/perf/{node-event-session-source-measure.mjs,
  stream-dispatch-scope-measure.ts,system-prompt-report-retention.ts}
  as path-invoked script roots (#183931, #183552, #183010);
- the Telegram ingress context Worker fixture loaded by URL (#178909) in
  production ignoreFiles.
Also register scripts/test-security-mail-parser.mjs, the standalone
nodemailer sender-parsing regression added by #187301 (release-only).

* refactor(doctor): keep dashboard migration guard at the repair boundary

Release adaptation of 50b532d (#183153). The backport of #182345
(51f63cb) exported isUnstampedDashboardRoot only for its unit test.
Main made it private and drove the eligibility cases through
repairLegacyDashboardChatTypes using a canonical-repair fixture this
branch does not carry. Keep every accepted and rejected row case, now
asserted through the repair boundary with the branch's session accessor.

* test(agents): hold requester preparation for the settle capacity case after #181260 backport

Backport 2f7589a (#181260) filters delivered child findings from
settle wakes (needsRequesterSettleFindings), so this delivered-row case
no longer reads the child transcript where it injected worker capacity
and failed with 'expected findTranscriptEvent to be called'. Main
realigned the same case in 411b2e6 (#178104): inject capacity at
captureRequesterSessionEntryCurrent and assert the delivered result is
not repeated in the resumed wake. Apply that realignment; the
'Already delivered child results' wording that main also asserts belongs
to #178104's message change, which this branch does not carry.

(adapted from commit 411b2e6)

---------

Co-authored-by: Shakker <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scripts Repository scripts size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant