Repository navigation
perf(infra): reduce agent event dispatch allocations - #179149
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis 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.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +38, Tests +22, Other +96. Total +156 across 4 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 21, 2026, 2:50 AM ET / 06:50 UTC. |
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.
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.
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.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:
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
4f0dc4c7f654b462c6b387702ca8563652da9d5cand 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.
chat.sendRPC p99 msAssessment: 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-nvprecords, 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, andsrc/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.