Skip to content

perf(infra): reduce agent event dispatch allocations - #179149

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-agent-event-dispatch-20260919
Oct 21, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-agent-event-dispatch-20260919

Conversation

@steipete

@steipete steipete commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Agent streaming rebuilds and sorts the same listener cohort on every emitted event, even when subscriptions have not changed.

User Impact

Less allocation during agent event dispatch, with no event-payload or subscription API change. Registration order, recursive emissions, live unsubscribe checks, per-event delivery authority, and failure isolation remain unchanged.

Why This Change Was Made

The registration owner now publishes ordered readonly arrays on subscribe/unsubscribe. Dispatch merges the global and run snapshots directly. The old per-event spread, toSorted, and unconditional delivery map are removed; capture state is allocated only for registrations that capture delivery. A live registration flag preserves removal/replacement behavior without keeping a second listener index.

This was requested as an allocation redesign. Production code grows by 38 lines across the dispatcher and its existing types module: preserving cross-bucket registration order and independent recursive cohorts without per-event materialization requires the two-index merge and copy-on-write subscription updates. Private types move into the existing type module to keep the dispatcher within its size limit. The new benchmark is proof tooling. No cache, config, database, SDK, or durability contract is added.

The optional plugin full-stream redesign is excluded. That SDK explicitly promises detached mutable payloads per subscription, including non-JSON structured-clone values; a shared frozen view would change its contract.

Evidence

The owner-allocation acceptance rule was written before implementation; the promotion/GC/tail gates were strengthened on October 21 before follow-up measurements: real emitAgentEvent, 2,000 warmup events, 20,000 measured events per sample, five interleaved A/B pairs per shape. Sample all allocations at a 1 KiB interval, including objects collected by minor/major GC; validate exact listener/capture counts and no unrelated-run deliveries. Require at least 10% lower owner bytes/event and no regression beyond paired noise in main-isolate V8-trace promotion MB/turn, minor or major GC seconds/minute, event-loop p99, or turn p99. A sampled allocation reduction cannot compensate for a promotion or GC regression. Cold startup is outside the claim.

Listener shape Base bytes/event median / p95 Candidate bytes/event median / p95 Median change
8 global/run listeners 3,510 / 3,552 1,800 / 1,837 −48.7%
8 plus 1 runtime capture 3,539 / 3,577 2,095 / 2,122 −40.8%
24 global/run listeners 3,693 / 3,763 1,773 / 1,818 −52.0%

Every sample delivered the exact expected count (160,000, 180,000, or 480,000), with 20,000 captures when enabled. Allocation includes the real enrichment/dispatch path, not only container operations.

Reproduce each shape with:

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/agent-event-dispatch-measure.ts --events 20000 --listeners 8 --captures 0

Local wall time was noisy under shared host load. Final median / p95 ns per event: 8 listeners 13,270 / 18,445 → 7,125 / 17,334; capture enabled 9,136 / 22,268 → 7,879 / 19,237; 24 listeners 9,854 / 18,609 → 6,093 / 6,925. These instrumented local timings are context, not a reliable Gateway latency claim; paired Gateway measurements gate landing.

Isolated Linux Gateway validation uses scripts/perf/transcript-broadcast-measure.ts --scenario chat.send --allocations --chunks 500 --rounds 5 --clients 1 --runs 1, with exactly two concurrent A/B pairs under the shared exclusive lock and swapped 16-core halves. Allocation mode also captures V8 GC traces and window diagnostics in the same run. Each side has a separate identical synthetic fixture: 5,000 sessions, 6,000 retained runs, 64 MiB logical transcript data, and 247,369,728 bytes of database files. Both variants load 19 bundled plugins; profiles confirm provider/auth calls, memory hooks, and browser-tool schema preparation. This covers the exercised chat/tool/provider path, not every plugin or live external integration action. Measurements cover main-isolate allocation, not worker heaps, external memory, or cold startup.

The source-run comparison pins base 4f0dc4c7f654b462c6b387702ca8563652da9d5c and the dispatcher change; the final type-only cleanup and patch-identical rebase do not change the measured runtime. Exact-head PR CI covers the integrated source.

Both pairs completed five measured turns per side, after warmup. Each side used identical fresh state; pair 2 swapped CPU halves. The values below retain adverse movements as well as improvements. MB is decimal; five-turn p95/p99 is the observed maximum, not a well-resolved population tail. Event-loop figures are median/max of the five window p99s.

Metric (base → candidate) Pair 1 Pair 2, CPUs swapped
Sampled allocation MB/turn, median / p95 192.23 / 218.88 → 190.78 / 227.74 193.12 / 237.65 → 186.81 / 240.18
Promotion MB/turn, median / p95 16.54 / 16.77 → 17.19 / 17.43 16.51 / 17.79 → 16.48 / 17.88
Minor GC seconds/minute, full measured windows 0.2003 → 0.1976 0.2062 → 0.2020
Major GC seconds/minute 0 → 0 0 → 0
Event-loop p99 ms, median / max 27.43 / 37.55 → 28.13 / 35.36 28.93 / 48.33 → 28.79 / 32.49
Turn p99 ms 5,741.67 → 5,764.99 5,750.30 → 5,756.00
chat.send RPC p99 ms 28.38 → 28.63 25.96 → 29.46

Assessment: the owner allocation improvement is reproducible; Gateway-wide speedup is not claimed. Promotion increased persistently within pair 1, then was effectively flat after swapping cores: independent process-pair median differences +0.648 and −0.039 MB/turn. That does not demonstrate a repeatable increase beyond the observed pair variation, but two pairs cannot exclude a smaller underlying regression. The pair range is descriptive, not a confidence interval. Whole-window minor-GC rates improved in both pairs; per-round maximum rates rose 0.2968 → 0.3137 and 0.2361 → 0.2677 seconds/minute. No major collections occurred, so this is not long-run major-GC proof. Turn p99 moved +23.32 / +5.70 ms on roughly 5.75-second turns; RPC shifts include a +3.50 ms maximum alongside mixed-sign round deltas. These bounded captures show no repeatable tail regression outside their observed variability.

Promotion comes from main-isolate v8-trace-gc-nvp records, excluding worker isolates. Minor/major GC rates use summed diagnostic GC time divided by the corresponding measured windows (about 36 seconds per side/pair), excluding the profiler's forced final collection. Every turn completed one tool call/result, four durable message events, thirteen agent events and two tool events; paired session-change counts matched. Transport chat coalescing varied by one frame. Owner selection was verified in all 20 profiles.

The first simultaneous start differed by 2 ms; each pair recorded the shared-host load with mpstat. CPU-half busy time was 9.41% / 4.13% in pair 1 and 19.53% / 19.08% in pair 2; these readings include the benchmark itself. A queued follow-up was canceled before acquisition under the two-pair measurement cap; no additional pair ran.

Focused proof: 122 tests passed across src/infra/agent-events.test.ts, src/infra/agent-events.routing.test.ts, src/gateway/server-runtime-subscriptions.test.ts, and src/gateway/server-runtime-subscriptions.access.test.ts (366 s wall time, dominated by cold worker compilation; dispatcher/routing shard 7.79 s). Changed-file format/lint and core typecheck passed after correcting loop narrowing. Final independent Codex review found no actionable P0–P2 findings. The final dispatcher/routing rerun passed 48 tests; both script-closure guards passed 22 tests, and the export-name collision guard passed. Broad proof is PR CI; no Testbox lease or local full suite/build was run.

Exact-head CI run 39556067758 passed, including openclaw/ci-gate. GitHub Codex review and ClawSweeper found no actionable code findings; The requested paired Gateway evidence and its promotion/GC/tail limitations are recorded above.

@clawsweeper

clawsweeper Bot commented Oct 21, 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 21, 2026 06:32
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-21T06:35:25.409141Z a317342 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: M labels Oct 21, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature 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:feature Preliminary submission classification; full source review pending. labels Oct 21, 2026
@clawsweeper

clawsweeper Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR prepares listener snapshots when subscriptions change and merges them during dispatch instead of rebuilding and sorting a cohort for every event.

Example: Emit 20,000 assistant events with eight global/run listeners.

  • Before: The supplied benchmark reports a median of 3,510 allocated bytes per event.
  • After: The supplied benchmark reports 1,800 bytes per event, with all 160,000 expected deliveries.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, source-correct optimization with meaningful dispatcher measurements and passing CI, awaiting its declared integrated performance evidence.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Streaming events repeatedly allocate listener containers even when subscriptions have not changed.
Reason: The maintainer-directed change has substantial reported owner-level allocation savings and keeps the public event and subscription contracts intact.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it offers a focused allocation reduction, preserves the established dispatch contract, and has no actionable correctness findings.

Priority: P2
Reviewed head: a317342553ef5b46ce4bc9e87503d8dafd613633

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The declared paired isolated Gateway chat.send workload with 500 chunks still needs recorded after-fix allocation, delivery, and latency results.
Agent review details

How this fits together

The process-wide agent event owner enriches producer events, selects global and matching-run subscriptions, captures runtime delivery guards, and invokes listeners consumed by Gateway publication and other streaming clients.

flowchart LR
  A[Agent event producers] --> B[Event enrichment]
  C[Subscription owner] --> D[Ordered listener snapshots]
  B --> E[Capture delivery guards]
  D --> E
  E --> F[Merge and invoke listeners]
  F --> G[Gateway and streaming consumers]
Loading

Technical review

Best possible solution:

Keep ordered subscription snapshots in the existing event owner, preserving fixed cohorts, mixed registration order, live removal, recursive dispatch, and captured delivery checks.

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

Current-main source directly establishes repeated cohort allocation and sorting, and the supplied benchmark exercises the real emitter; measurements were not rerun during this read-only review.

Is this the best way to solve the issue?

The change removes repeated preparation at the existing subscription owner without introducing a competing dispatcher, and its snapshots preserve the mutation semantics established by prior maintainer decisions.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Fixed cohorts and callback-time mutation semantics keeps the original intent (1248e1e: Simplify speculative reselection machinery while intentionally making new subscriptions begin with the next event.)
  • Per-event captured runtime delivery guards keeps the original intent (a2a9ff2: Prevent terminal events from an earlier registration from settling or publishing through its replacement.)
  • Direct callback loops and failure isolation keeps the original intent (f08002d: Remove temporary callback wrappers while retaining event ordering and isolated listener failures.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Introduced change: The pinned introduction changes only the dispatcher, its existing types and tests, and a new allocation measurement script; base-only Gateway and Codex changes are outside this PR. (src/infra/agent-events.ts:580, a317342553ef)
  • Current-main allocation path: Fetched main still materializes and sorts the combined cohort and allocates a delivery Map for every emitted event. (src/infra/agent-events.ts:603, a6f48263b712)
  • Intentional fixed-cohort contract: refactor: simplify state and process worker lifecycles #169648 explicitly accepted next-event subscription additions and fixed run selection while retaining ordering, unsubscribe behavior, indexing, and live delivery authority; this PR preserves that decision. (src/infra/agent-events.ts:580, 1248e1eaa663)
  • Capture and delivery checks retained: Runtime capture remains before ordinary callbacks, and delivery still checks both registration liveness and the captured current-delivery predicate; the Gateway consumer retains its registration guard through deferred dispatch. (src/infra/agent-events.ts:587, a317342553ef)
  • Supplied performance evidence: The full PR body reports five interleaved benchmark pairs per listener shape and 40.8–52.0% lower median allocation, but explicitly leaves isolated Gateway paired results pending. (scripts/perf/agent-event-dispatch-measure.ts:54, a317342553ef)
  • Exact-head CI: The reviewed head has a successful openclaw/ci-gate check and successful aggregate statuses; older cancelled dispatch/context jobs do not establish a patch failure. (a317342553ef)

PR surface

Source +38, Tests +22, Other +96. Total +156 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 91 53 +38
Tests 1 22 0 +22
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 96 0 +96
Total 4 209 53 +156

Review metrics

Metric Value Why it matters
Production versus test growth Production net +38 LOC; tests +22 LOC Growth implements subscription-time snapshots and an ordered merge within the existing owner; the added test protects removal and replacement during capture.

Labels

Label changes:

  • add P2: This is a bounded streaming allocation improvement without evidence of an 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 allocation improvement without evidence of an 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 21, 2026, 2:50 AM ET / 06:50 UTC.

@steipete
steipete merged commit a6b339e into main Oct 21, 2026
247 of 249 checks passed
@steipete
steipete deleted the steipete/perf-micro-agent-event-dispatch-20260919 branch October 21, 2026 07:33
steipete added a commit that referenced this pull request Oct 21, 2026
Keep live local types and protocol enrichment private, delete unused wiki aliases and the uncalled cron-history test helper, and move test-only WhatsApp metadata into its fixture.

The lost-consumer audit follows #179048, #179101, #179127, #179149 and #179180. Register the development-loop benchmark documented and invoked by #179175 as a real Knip entrypoint.

Proof: all three deadcode wrappers pass at base 5ceb735; 231 focused tests pass with one worker; targeted typecheck, lint, format and independent P2 review pass. Subsequent main changes do not overlap the repair.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 22, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 22, 2026
Keep live local types and protocol enrichment private, delete unused wiki aliases and the uncalled cron-history test helper, and move test-only WhatsApp metadata into its fixture.

The lost-consumer audit follows openclaw#179048, openclaw#179101, openclaw#179127, openclaw#179149 and openclaw#179180. Register the development-loop benchmark documented and invoked by openclaw#179175 as a real Knip entrypoint.

Proof: all three deadcode wrappers pass at base 8a4943d; 231 focused tests pass with one worker; targeted typecheck, lint, format and independent P2 review pass. Subsequent main changes do not overlap the repair.
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: M 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