Repository navigation
perf: per-delta cost grows with concurrent agent count because every delta walks every run's event listeners - #129174
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs real behavior proof before merge. Reviewed August 28, 2026, 7:41 AM ET / 11:41 UTC. ClawSweeper reviewWhat this changesThe branch indexes agent-event subscribers by run and moves HTTP, CLI, system-agent, and ACP stream consumers to matching run buckets to avoid unrelated callback work during concurrent runs. Merge readiness⛔ Blocked until stronger real behavior proof is added - 4 items remain Keep open as a viable partial repair: current main still dispatches through one global listener set, while this PR introduces run-indexed routing and preserves tested ordering and mutation semantics. Priority: P2 Review scores
Verification
Live VerificationCommand: Result: FAIL (failed) — step 1 Assertions:
How this fits togetherAgent runs emit streaming and lifecycle events through a shared dispatcher. Gateway HTTP streams, CLI-backed runs, and subagent relays consume those events to update the correct client stream, transcript, or parent session. flowchart LR
A[Agent run emits event] --> B[Shared event dispatcher]
B --> C[Global listeners]
B --> D[Matching run listeners]
C --> E[Process-wide observers]
D --> F[Gateway and CLI stream bridges]
F --> G[Client and parent stream output]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +80, Tests +706, Other +7. Total +793 across 14 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Land the bounded dispatcher repair after exact-head validation is green, while leaving approval-wait fanout under the open canonical issue at #129173 for its separate owner-reviewed decision. Do we have a high-confidence way to reproduce the issue? Yes. The exact-head source supplies deterministic listener-order tests and a built-Gateway concurrent-stream scenario; this read-only review did not execute them. Is this the best way to solve the issue? Yes. The shared dispatcher owns routing fanout, and this implementation keeps global observers plus the original live registration, mutation, and nested-emission semantics while routing known single-run consumers directly. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against c792a16791ca. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (10 earlier review cycles; latest 8 shown)
|
c4ce251 to
681956d
Compare
681956d to
8b47895
Compare
|
@clawsweeper re-review — added the exact-head before/after dispatcher benchmark (512→8 callbacks per delta at 64 concurrent runs, median of 7 reps, host and Node recorded) and a concurrent-run isolation trace that is byte-identical at the merge-base, both in the PR body. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…very run's closures emitAgentEvent notified one process-global listener Set. Five subscribers register a listener whose first statement discards other runs, so at N concurrent runs every assistant delta walked N run-scoped closures to do useful work in one of them - O(N) per delta, O(N^2) fleet-wide. Add a runListeners bucket beside the global Set plus onAgentEventForRun, and convert the five per-run sites (openai-http, openresponses-http, cli-backend-dispatch, system-agent/agent-turn, acp-spawn-parent-stream), keeping their runId guard as a harmless second check. Globals are notified first and keep stock ordering; empty buckets are dropped on unsubscribe. agent-job.ts stays global: it filters on stream, not runId.
…the run bucket createAgentEventBridge and observeAgentRunApprovalWait still subscribed with onAgentEvent and discarded foreign runs as their first action, so they kept the per-delta cost this branch removes. The bridge is the highest-volume instance: one CLI dispatch builds eight bridges from that shared factory, so N concurrent runs left 8N run-filtered closures on the global set. Both now subscribe with onAgentEventForRun. Their runId guards stay as a fail-closed second check, matching the six sites already converted here. Five remaining onAgentEvent callers are genuinely process-global (agent-job, subagent registry, task registry lifecycle, plugin runtime bridge, TUI backend) and are left alone.
Exercise token-authenticated Chat Completions and Responses streams through the real Gateway, agent loop, local provider, WebSocket events, and agent.wait. Expose existing startup diagnostics within the isolated test fixture. Keep approval-wait subscriptions on the existing global path pending owner review. This reduces the converted listeners' fanout but does not close the remaining concurrency-dependent fanout issue. Co-authored-by: Tran Quang <[email protected]>
Exercise nested emission and unsubscribe through the real delivery bridge. Prepare the existing runtime artifacts for the concurrent Gateway proof, and correct its lint and formatting failures without changing its budget. This diagnostic stage intentionally preserves the candidate dispatcher until CI captures the ordering regressions; it is not ready to land. Co-authored-by: Tran Quang <[email protected]>
2a40e87 to
10eb012
Compare
Merge global and matching-run subscriptions by registration order while preserving live mutations, nested dispatch, and unsubscribe semantics. Cover the observed delivery regressions and interleaved bridge isolation. Run the authenticated concurrent-stream proof through the existing built Gateway process harness with exact-checkout artifact provenance. Related: openclaw#129173 Co-authored-by: Tran Quang <[email protected]>
Use non-mutating sorting for the fresh listener cohort, initialize the unsubscribe binding at its existing assignment, and distinguish unused mapper parameters without changing the proved behavior or assertions. Co-authored-by: Tran Quang <[email protected]>
|
Merged via squash.
|
…delta walks every run's event listeners (openclaw#129174) * perf(agents): index agent-event listeners by run instead of walking every run's closures emitAgentEvent notified one process-global listener Set. Five subscribers register a listener whose first statement discards other runs, so at N concurrent runs every assistant delta walked N run-scoped closures to do useful work in one of them - O(N) per delta, O(N^2) fleet-wide. Add a runListeners bucket beside the global Set plus onAgentEventForRun, and convert the five per-run sites (openai-http, openresponses-http, cli-backend-dispatch, system-agent/agent-turn, acp-spawn-parent-stream), keeping their runId guard as a harmless second check. Globals are notified first and keep stock ordering; empty buckets are dropped on unsubscribe. agent-job.ts stays global: it filters on stream, not runId. * perf: route the shared CLI delivery bridge and approval wait through the run bucket createAgentEventBridge and observeAgentRunApprovalWait still subscribed with onAgentEvent and discarded foreign runs as their first action, so they kept the per-delta cost this branch removes. The bridge is the highest-volume instance: one CLI dispatch builds eight bridges from that shared factory, so N concurrent runs left 8N run-filtered closures on the global set. Both now subscribe with onAgentEventForRun. Their runId guards stay as a fail-closed second check, matching the six sites already converted here. Five remaining onAgentEvent callers are genuinely process-global (agent-job, subagent registry, task registry lifecycle, plugin runtime bridge, TUI backend) and are left alone. * test(gateway): cover concurrent streamed agent events Exercise token-authenticated Chat Completions and Responses streams through the real Gateway, agent loop, local provider, WebSocket events, and agent.wait. Expose existing startup diagnostics within the isolated test fixture. Keep approval-wait subscriptions on the existing global path pending owner review. This reduces the converted listeners' fanout but does not close the remaining concurrency-dependent fanout issue. Co-authored-by: Tran Quang <[email protected]> * test: capture agent event ordering regressions Exercise nested emission and unsubscribe through the real delivery bridge. Prepare the existing runtime artifacts for the concurrent Gateway proof, and correct its lint and formatting failures without changing its budget. This diagnostic stage intentionally preserves the candidate dispatcher until CI captures the ordering regressions; it is not ready to land. Co-authored-by: Tran Quang <[email protected]> * fix: preserve live order in run-indexed agent events Merge global and matching-run subscriptions by registration order while preserving live mutations, nested dispatch, and unsubscribe semantics. Cover the observed delivery regressions and interleaved bridge isolation. Run the authenticated concurrent-stream proof through the existing built Gateway process harness with exact-checkout artifact provenance. Related: openclaw#129173 Co-authored-by: Tran Quang <[email protected]> * style: satisfy event dispatch lint rules Use non-mutating sorting for the fresh listener cohort, initialize the unsubscribe binding at its existing assignment, and distinguish unused mapper parameters without changing the proved behavior or assertions. Co-authored-by: Tran Quang <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Tran Quang <[email protected]>
Reuse the canonical run-indexed event listener while preserving approval state, timeout pauses and disposal. Native event-dispatch measurements improve both eight-run and sixteen-run workloads without adding production lines. Related: #129174 Co-authored-by: Tran Quang <[email protected]>
Reuse the canonical run-indexed event listener while preserving approval state, timeout pauses and disposal. Native event-dispatch measurements improve both eight-run and sixteen-run workloads without adding production lines. Related: #129174 Co-authored-by: Tran Quang <[email protected]>
…aw#136205) Reuse the canonical run-indexed event listener while preserving approval state, timeout pauses and disposal. Native event-dispatch measurements improve both eight-run and sixteen-run workloads without adding production lines. Related: openclaw#129174 Co-authored-by: Tran Quang <[email protected]>
Related: #129173
What Problem This Solves
Reduces avoidable event-dispatch work when multiple agent runs stream concurrently. A CLI dispatch creates eight run-filtered delivery bridges; the original global subscription set invokes bridges belonging to unrelated runs for each delta.
This is a partial repair of #129173. Approval-wait subscriptions remain global and run-filtered, so the issue stays open for that owner-reviewed surface and complete end-to-end performance proof. No all-fanout O(1) or whole-turn latency improvement is claimed.
Why This Change Was Made
The canonical event owner now indexes run-specific subscribers. HTTP Chat Completions and Responses, embedded CLI dispatch, system-agent turns, ACP parent streaming, and the shared CLI delivery-bridge factory use the indexed subscription. Existing consumer matching guards remain. Global observers retain every event.
Review and actual CI caught a regression in the first version: delivering all globals before the matching run bucket changed the original mixed registration order. A later global observer could reverse an earlier bridge's outer/inner stream delivery or unsubscribe that bridge before its current event arrived. The emitter-local repair orders global and matching-run listeners by registration position and reselects after subscription or run-ID changes. It preserves live additions, deletions, re-additions, exceptions, nested emission, callback identity and unsubscribe lifecycle. It does not scan unrelated run buckets.
Selection and sorting cost O((G+K)log(G+K)), where G is global listeners and K is matching-run listeners; mutations can trigger reselection. G still includes approval-wait subscribers. Production routing is +95/-19 (net +76), including +32 for preserving observed live ordering while retaining indexing. A single global Set keeps the original fanout cost; global-first and fixed snapshots do not preserve behavior. The existing test-build prerequisite registration is +12/-5, separate from production routing and tests. No persistence schema, authentication mode, public Gateway protocol, or operator configuration surface changes.
Thanks to @quangtran88 for the implementation, regression coverage, and measurements.
Evidence
The original two ordering scenarios passed on clean baseline
871b18dff5039484e86c76d282699a8defcb1654using the real emitter and delivery bridge. Exact candidate10eb01206d0983625612e01312d8724c6c744956then failed both in secretless CI: received[inner, outer]instead of[outer, inner], and[]instead of[first]. That run tested mergebf6a7a2767bd60ed1328c1ee44af9b981619da03. Both regressions and the mutable-run identity case now pass on repaired head15e053097fb858da7154593ecaa535e5a489e180in the delivery-bridge job, testing merge10bb96a4a8cfe580503b9d68e137b47ca9a1faa5.An extended baseline replay also passed the mutable-run identity case and every distinct bridge's interleaved
a1, b1, a2output at eight bridges/run and 1, 4, 16 and 64 runs. Exact-source predicate reads for the first event were 8, 32, 128 and 512. On repaired head15e053097fb858da7154593ecaa535e5a489e180, the same four cohorts record 8, 8, 8 and 8 reads, while every individual bridge's real output sequence and foreign isolation pass. The owning shard reports 49 files and 1,085 tests passed, with one unrelated skipped test. These reads are not a general callback count or performance gate: hoisting a predicate can change them without removing a global scan. No latency claim rests on that metric.The real Gateway proof uses two simultaneously held local HTTP provider requests, authenticated Chat Completions and Responses streams, exact text and terminal counts, WebSocket agent events and
agent.waitfor the same run IDs. The previous Gateway job built runtime artifacts and loaded all 14 plugin entries natively, but source-host runtime registration still took about 260 seconds and failed the unchanged 120-second test. That is a harness failure, not successful streaming proof.The test now uses the existing isolated built-Gateway process helper, with strict entrypoint, both build-stamp and build-info checks against the actual checkout SHA before startup. The whole Gateway/runtime graph is built together; no source/dist configuration-owner mixing is introduced. The same plugin selection, provider barriers and assertions remain, without timeout increases or plugin trimming. On repaired head
15e053097fb858da7154593ecaa535e5a489e180, the built-Gateway job passes the complete concurrent-stream test in 13,149 ms, inside the unchanged 120-second budget. Its Gateway shard passes 144 files and 2,304 tests; the same job's client shard passes another 35 files and 438 tests. Both proof jobs attest read-only repository permissions and no secret source. This is real Gateway behavior with a local mock HTTP provider, not live external-provider or channel proof.Independent source reviews accepted the ordering repair and built-process fixture, including the mechanical formatting delta. A fresh full-branch-plus-overlay Codex P0/P1/P2 review also found no actionable defects. The
15e053097fb858da7154593ecaa535e5a489e180CI run completed with all test, type and build jobs passing; only three owned lint findings in two jobs, plus the aggregate gate, failed. Those findings are corrected withtoSortedon a fresh intermediate array, a const binding initialized before callback invocation, and an unused parameter rename. The exact three-line correction passed separate independent source review and a fresh P0/P1/P2 review without changing assertions or control flow.Final head
f9fdc4b9bcbd5e4e53cb1b2d1fb6ada18a67b45frepeats the successful proof in CI run 33167644535, testing merge76ba0f7917a3f5f5aff467364504e92c2dac856ainto mainca5930502984cce275bcb41a02d9d7d999da799d. The Gateway job passes the complete concurrent-stream test in 19,815 ms, with 144 files/2,305 Gateway tests and 35 files/438 client tests passing. The bridge job passes all seven ordering/isolation cases and again records 8 predicate reads at each of 1/4/16/64 runs; 49 files/1,085 tests pass, with one unrelated skip. Both complete logs attest read-only repository permissions and no secret source. Both corrected lint jobs pass. The entire final-head CI run is now completed successfully, includingopenclaw/ci-gate. Native maintainer preparation and merge verification remain; no merge is claimed. Issue #129173 remains open.The latest ClawSweeper review (August 28, 11:23 UTC, reviewed head
15e053097fb858da7154593ecaa535e5a489e180) has no source findings and reports all 19 event-owner tests passing. Its integrated-proof, positive-LOC and refreshed-CI requests are covered above. Native review initialization refreshed the main comparison toc85129f8550; affected owners are unchanged except three type-only system-agent substitutions. Main drift alone does not justify changing a behavior-proven patch.Actual CI entry command for both proof jobs:
node --import tsx scripts/ci-run-node-test-shard.mts, using the existing matrix groupsagentic-gateway-core-3andauto-reply-reply-state-routing. The Gateway job first ran the canonical full runtime prerequisite build. Local maintainer checks were source review,git diff --check, independent P0/P1/P2 review, and nativescripts/pr review-init,review-checkout-main,review-checkout-pr, andreview-artifacts-init; contributor code was not executed locally. Final native preparation uses the hosted-CI gate, not local test substitution.Contributor reproduction scripts
The original scripts below are retained as contributor-supplied dispatcher/bridge evidence. Their synthetic subscription counter and direct-emission trace do not exercise a real Gateway or account for approval-wait subscribers; the separate authenticated Gateway proof above covers the integrated streaming path.
bench-listener-fanout.mts
trace-concurrent-runs.mts
Neither script is added to the repo: they are reviewer-reproducible evidence, not product code, and committing them would add surface this PR does not need.