Skip to content

perf(runtime): reduce context copies during event delivery - #183495

Merged
steipete merged 1 commit into
mainfrom
perf/1744-agent-event-async-scope
Oct 25, 2026
Merged

steipete merged 1 commit into
mainfrom
perf/1744-agent-event-async-scope

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Streaming agent-event delivery repeatedly copies the async context frame while detaching delivery from the emitter's work lifetime. The expensive path is the two nested AsyncLocalStorage.exit() calls, not creation of a new work-scope owner per event. Earlier work-scope changes are already present in the measured baseline; this addresses the residual cost.

User Impact

There is no user-visible behavior change. Delivery retains inherited diagnostic attribution and Gateway admission, remains independent of emitter cancellation, and is still joined during Gateway shutdown.

Why This Change Was Made

Clear the two existing work-scope carriers inside the existing runWithAsyncStore boundary, restoring the caller frame once instead of restoring each carrier separately. Both singleton keys and the no-op path remain. Production grows by five lines because both shipped carrier identities must remain available during runtime replacement; no cache, new API, or parallel implementation is introduced.

This uses the helper's existing isolated-frame semantics: unrelated synchronous enterWith changes do not escape the callback. Source inspection found no internal caller relying on such propagation. The handler, delivery guard, and failure callbacks run in promise continuations; loadHandler() itself is called synchronously. The change preserves ownership and inherited diagnostic values rather than removing necessary detachment.

Evidence

The committed scripts/perf/async-work-scope-measure.ts workload delivers one million events inside a frame with 24 other context stores, checking delivery counts, detached ownership and every inherited store. Five concurrent pairs used synchronized post-warmup starts and swapped interleaved CPU placement; sampled allocation ran separately from untraced CPU timing.

Owner metric Base Candidate Mean paired change
Main-thread CPU/event 3.162 µs 1.914 µs −39.44%
Sampled allocation/event 20,521 B 11,419 B −44.36%

Two additional swapped pairs per shape checked the risk of sparse frames: with one other store, CPU/event fell 30.85% and allocation/event 34.41%; with eight stores, they fell 37.43% and 42.75%. These are owner-level savings, not whole-Gateway percentages. The motivating stack represented about 0.425% of total sampled allocation, so the expected aggregate win is small.

Built Gateway load

Baseline a36ac4e43966329ce7cf396cb0f66add46ae5676; measured candidate ca08f366bb2fb978c3d8d86e59075265f167dfcd. Both built successfully on Node 26.12.1. The published head 256ff39f5f456346cb5a3e31862ab8ae5760ee86 is a patch-identical rebase onto current main; the affected owner/helper, dispatch, subscription, and load-harness sources did not change. The load numbers above belong to the measured revisions, while PR CI validates the published head. Each revision ran the existing Gateway concurrency workload for at least ten minutes with 10,000 synthetic sessions, 40 plugins, 64 persistent WebSocket clients, 36 concurrent mock-provider tool turns, and list/search/sidebar/history churn. All turns and tool continuations were verified; no list failures. The workload's tool mode uses a two-second shell delay, with no artificial stream-chunk delay. Long streamed delivery is covered separately by the owner workload.

Untraced Gateway metric Base Candidate
Measured duration 610.81 s 612.00 s
Verified tool turns / model calls 1,135 / 3,405 1,521 / 4,482
Main-thread CPU, one core 74.32% 82.37%
Main-thread CPU / model call 133.33 ms 112.48 ms
GC time / minute 1.900 s 2.088 s
GC time / model call 5.681 ms 4.752 ms
Event-loop p99 (20 ms resolution) 136.84 ms (n=20,590) 127.14 ms (n=22,538)
sessions.list p95 / p99 217.37 / 403.14 ms (n=1,213) 169.47 / 263.83 ms (n=1,221)
Maximum GC pause, all kinds 301.07 ms 278.04 ms
RSS after / peak 4,305.81 / 4,419.39 MiB 4,100.07 / 4,520.97 MiB
Main heap before → after 462.68 → 625.34 MiB 678.46 → 842.67 MiB

These sequential local runs shared a busy host, whose outside load varied substantially. They establish sustained correctness and expose the full-load costs, but do not isolate the change's Gateway-wide effect. The candidate completed more work: raw GC rose 188 ms/min (+9.90%), while GC/model-call fell 16.35%. Heap growth was similar (162.66 vs 164.20 MiB); there is no retained-memory win claimed. Recaps account for 1,135 baseline and 1,440 candidate model calls: the existing 40-per-session hourly budget explains the candidate's remaining 81 turns without a recap.

Per-kind GC: base minor 5,564 / 17.479 s / max 301.07 ms, major 17 / 1.826 s / max 161.47 ms, incremental 17 / 0.039 s. Candidate minor 6,946 / 18.788 s / max 62.83 ms, major 22 / 2.460 s / max 278.04 ms, incremental 22 / 0.052 s. Major-GC tails are context only because each side has fewer than 50 collections. Promotion and event-loop p95 were not measured; sampled-profile timing is not used as acceptance evidence.

Separate sampled-allocation passes ran for 616.09 s (base) and 621.73 s (candidate), with 1,405/1,492 verified tool turns and 4,215/4,424 model calls. Sampled allocation was 184,977,193,312/193,303,240,280 bytes: 286.33 → 296.51 MiB/s, or 43.885 → 43.694 MB/model call (−0.44%). This small per-call difference is context, not an isolated whole-Gateway improvement claim. Both allocation runs and both untraced runs exited cleanly. Three additional auxiliary inference arrivals appeared between the candidate allocation request-log snapshot and the later mock-counter checkpoint; the profile stops after the snapshot. They are excluded from the 4,424-call denominator, leaving less than 0.07% boundary uncertainty.

Reproduction (add --heap-prof-dir <directory> only for the separate allocation pass):

node --import ./scripts/tsx.mjs scripts/bench-gateway-concurrency.ts \
  --entry dist/entry.js --duration-ms 600000 --timeout-ms 1800000 \
  --session-count 10000 --concurrency 36 --plugin-count 40 \
  --workspace-fanout --tool-events --subscribers 58 --history-clients 4 \
  --history-burst 1 --cadence-ms 500 --stream-chunk-delay-ms 20 \
  --runs 1 --warmup 0 --output <report.json>

Focused tests passed: async-work-scope.test.ts (19), async-store.test.ts (3), and server-runtime-subscriptions.test.ts (64). Changed-file format/lint and git diff --check passed. The export-name-collision guard and both import-closure files passed (22 tests). Exact-head CI run 40181395376 passed: 55 executed jobs successful, 28 scope skips, no failures or retries.

Independent subagent review (autoreview route unavailable): clean through P2. The configured autoreview helper refused to start because its requested provider route did not match the operator configuration; the authorized fresh-review fallback inspected the diff and relevant source.

Clear both work-scope carriers inside the existing async-store boundary,
restoring the caller frame once while preserving inherited attribution,
detached delivery lifetime, and the shipped singleton identities.

The standalone streamed-delivery workload reduces CPU/event by 39.44%
and sampled allocation/event by 44.36% across five synchronized paired
runs. Keep the no-op path and use the existing helper's isolated frame
semantics instead of adding a second implementation.
@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 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 25, 2026 09:37
@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-25T09:39:01.533624Z 256ff39 Draft marked ready
ℹ️ 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 25, 2026
@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Oct 25, 2026
@steipete
steipete merged commit 28b081d into main Oct 25, 2026
226 of 228 checks passed
@steipete
steipete deleted the perf/1744-agent-event-async-scope branch October 25, 2026 09:51
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
…183495)

Clear both work-scope carriers inside the existing async-store boundary,
restoring the caller frame once while preserving inherited attribution,
detached delivery lifetime, and the shipped singleton identities.

The standalone streamed-delivery workload reduces CPU/event by 39.44%
and sampled allocation/event by 44.36% across five synchronized paired
runs. Keep the no-op path and use the existing helper's isolated frame
semantics instead of adding a second implementation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawsweeper:intake:bug Preliminary submission classification; full source review pending. scripts Repository scripts size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant