Skip to content

perf: per-delta cost grows with concurrent agent count because every delta walks every run's event listeners - #129174

Merged
steipete merged 6 commits into
openclaw:mainfrom
quangtran88:perf/run-indexed-agent-event-listeners
Aug 28, 2026
Merged

steipete merged 6 commits into
openclaw:mainfrom
quangtran88:perf/run-indexed-agent-event-listeners

Conversation

@quangtran88

@quangtran88 quangtran88 commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

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 871b18dff5039484e86c76d282699a8defcb1654 using the real emitter and delivery bridge. Exact candidate 10eb01206d0983625612e01312d8724c6c744956 then failed both in secretless CI: received [inner, outer] instead of [outer, inner], and [] instead of [first]. That run tested merge bf6a7a2767bd60ed1328c1ee44af9b981619da03. Both regressions and the mutable-run identity case now pass on repaired head 15e053097fb858da7154593ecaa535e5a489e180 in the delivery-bridge job, testing merge 10bb96a4a8cfe580503b9d68e137b47ca9a1faa5.

An extended baseline replay also passed the mutable-run identity case and every distinct bridge's interleaved a1, b1, a2 output 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 head 15e053097fb858da7154593ecaa535e5a489e180, 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.wait for 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 15e053097fb858da7154593ecaa535e5a489e180 CI 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 with toSorted on 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 f9fdc4b9bcbd5e4e53cb1b2d1fb6ada18a67b45f repeats the successful proof in CI run 33167644535, testing merge 76ba0f7917a3f5f5aff467364504e92c2dac856a into main ca5930502984cce275bcb41a02d9d7d999da799d. 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, including openclaw/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 to c85129f8550; 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 groups agentic-gateway-core-3 and auto-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 native scripts/pr review-init, review-checkout-main, review-checkout-pr, and review-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
// Measures per-delta agent-event dispatch cost as concurrent run count grows.
// Runs unmodified against both revisions: it drives the real production CLI
// delivery bridge, so each revision exercises whatever subscription API that
// bridge actually uses. Emits deltas for ONE run while R runs are subscribed,
// which is exactly the claim under test.
import os from "node:os";
import path from "node:path";

const repo = process.argv[2];
if (!repo) {
  throw new Error("usage: bench-listener-fanout.mts <repo-root>");
}
const src = (p: string) => path.join(repo, "src", p);

const events = await import(src("infra/agent-events.js"));
const registry = await import(src("infra/agent-run-registry.js"));
const bridgeMod = await import(src("auto-reply/reply/agent-event-bridge.js"));

const { emitAgentEvent, resetAgentEventsForTest } = events;
const { registerAgentRunContext } = registry;
const { createAgentEventBridge } = bridgeMod;

// The bridge's own subscription entry point on this revision. Detected, not
// assumed, so the "before" revision (no run buckets) needs no separate script.
const hasRunBuckets = typeof events.onAgentEventForRun === "function";
const subscribe = hasRunBuckets
  ? (runId: string, fn: (e: unknown) => void) => events.onAgentEventForRun(runId, fn)
  : (_runId: string, fn: (e: unknown) => void) => events.onAgentEvent(fn);

const BRIDGES_PER_RUN = 8; // one CLI dispatch builds eight bridges from the shared factory
const DELTAS = 20_000;
const WARMUP = 2_000;
const CONCURRENCY = [1, 4, 16, 64];

function buildBridges(runIds: string[]) {
  const teardown: Array<() => void> = [];
  for (const runId of runIds) {
    registerAgentRunContext(runId, { sessionKey: `session-${runId}` });
    for (let b = 0; b < BRIDGES_PER_RUN; b += 1) {
      const bridge = createAgentEventBridge({
        runId,
        read: () => undefined, // no delivery: isolates dispatch fan-out from transport work
        deliver: async () => {},
      });
      teardown.push(() => bridge.unsubscribe());
    }
  }
  return teardown;
}

// Separate pass with a counter ahead of the runId filter. The bridge returns at
// that filter before its read callback, so foreign-run work is invisible from
// inside read -- the count has to be taken at the listener boundary.
function countInvocations(runIds: string[], target: string, deltas: number) {
  resetAgentEventsForTest();
  let invocations = 0;
  const teardown: Array<() => void> = [];
  for (const runId of runIds) {
    registerAgentRunContext(runId, { sessionKey: `session-${runId}` });
    for (let b = 0; b < BRIDGES_PER_RUN; b += 1) {
      teardown.push(
        subscribe(runId, (evt: any) => {
          invocations += 1;
          if (evt.runId !== runId) return;
        }),
      );
    }
  }
  for (let i = 0; i < deltas; i += 1) {
    emitAgentEvent({ runId: target, stream: "assistant", data: { text: "x" } });
  }
  for (const off of teardown) off();
  return invocations;
}

const rows: Array<Record<string, unknown>> = [];
for (const runs of CONCURRENCY) {
  resetAgentEventsForTest();
  const runIds = Array.from({ length: runs }, (_, i) => `run-${i}`);
  const target = runIds[0];
  const teardown = buildBridges(runIds);

  for (let i = 0; i < WARMUP; i += 1) {
    emitAgentEvent({ runId: target, stream: "assistant", data: { text: "w" } });
  }
  const started = process.hrtime.bigint();
  for (let i = 0; i < DELTAS; i += 1) {
    emitAgentEvent({ runId: target, stream: "assistant", data: { text: "x" } });
  }
  const elapsedNs = Number(process.hrtime.bigint() - started);
  for (const off of teardown) off();

  const invocations = countInvocations(runIds, target, DELTAS);
  rows.push({
    runs,
    subscribers: runs * BRIDGES_PER_RUN,
    nsPerDelta: Math.round(elapsedNs / DELTAS),
    totalMs: Math.round(elapsedNs / 1e6),
    callbackInvocations: invocations,
    invocationsPerDelta: invocations / DELTAS,
  });
}

console.log(
  JSON.stringify(
    {
      revision: process.env.BENCH_REV ?? "unknown",
      runBucketsAvailable: hasRunBuckets,
      node: process.version,
      platform: `${os.platform()}-${os.arch()}`,
      cpu: os.cpus()[0]?.model,
      cpus: os.cpus().length,
      deltasPerCase: DELTAS,
      bridgesPerRun: BRIDGES_PER_RUN,
      rows,
    },
    null,
    2,
  ),
);
trace-concurrent-runs.mts
// Concurrent-run isolation trace against the real production CLI delivery bridge
// and the real dispatcher. Three runs stream interleaved deltas on two streams
// each while a global lifecycle consumer watches, so the output shows both that
// per-run delivery stays isolated and that process-wide consumers still observe
// every run's lifecycle events after the routing change.
import path from "node:path";

const repo = process.argv[2];
const src = (p: string) => path.join(repo, "src", p);
const events = await import(src("infra/agent-events.js"));
const { registerAgentRunContext } = await import(src("infra/agent-run-registry.js"));
const { createAgentEventBridge } = await import(src("auto-reply/reply/agent-event-bridge.js"));
const { emitAgentEvent, onAgentEvent, resetAgentEventsForTest } = events;

resetAgentEventsForTest();
console.log(`runBucketsAvailable=${typeof events.onAgentEventForRun === "function"}`);

const RUNS = ["run-alpha", "run-beta", "run-gamma"];
const delivered = new Map<string, string[]>();
const bridges: Array<{ unsubscribe: () => void; drain: () => Promise<void> }> = [];

// Global lifecycle consumer, the shape gateway/TUI consumers use. It must keep
// seeing every run after single-run consumers move into their buckets.
const lifecycleSeen: string[] = [];
const stopLifecycle = onAgentEvent((evt: any) => {
  if (evt.stream === "lifecycle") lifecycleSeen.push(`${evt.runId}:${evt.data.phase}`);
});

for (const runId of RUNS) {
  registerAgentRunContext(runId, { sessionKey: `session-${runId}` });
  delivered.set(runId, []);
  for (const stream of ["assistant", "reasoning"]) {
    bridges.push(
      createAgentEventBridge<string>({
        runId,
        read: (evt: any) => (evt.stream === stream && typeof evt.data.text === "string" ? evt.data.text : undefined),
        deliver: async (text) => {
          delivered.get(runId)!.push(`${stream}:${text}`);
        },
      }),
    );
  }
}

// startedAt must be a finite number or enrichAgentEvent drops the start event by contract
// (agent-event-lifecycle.ts hasInvalidLifecycleStartTimestamp).
const startedAt = Date.now();
for (const runId of RUNS) {
  emitAgentEvent({ runId, stream: "lifecycle", data: { phase: "start", startedAt } });
}

// Interleaved across runs, so any cross-run leak would land in a foreign sink.
for (let turn = 1; turn <= 3; turn += 1) {
  for (const runId of RUNS) {
    const tag = runId.split("-")[1];
    emitAgentEvent({ runId, stream: "assistant", data: { text: `${tag}-a${turn}` } });
    emitAgentEvent({ runId, stream: "reasoning", data: { text: `${tag}-r${turn}` } });
  }
}
for (const runId of RUNS) emitAgentEvent({ runId, stream: "lifecycle", data: { phase: "end" } });

await Promise.all(bridges.map((b) => b.drain()));
for (const b of bridges) b.unsubscribe();
stopLifecycle();

console.log("\n--- per-run delivery (each run must contain only its own tag) ---");
let leaks = 0;
for (const runId of RUNS) {
  const tag = runId.split("-")[1];
  const got = delivered.get(runId)!;
  const foreign = got.filter((entry) => !entry.includes(tag));
  leaks += foreign.length;
  console.log(`${runId}: ${got.join(" ")}`);
  if (foreign.length) console.log(`  !! foreign entries: ${foreign.join(" ")}`);
}
console.log("\n--- global lifecycle consumer ---");
console.log(lifecycleSeen.join(" "));
console.log(`\ncrossRunLeaks=${leaks}`);
console.log(`lifecycleEventsSeen=${lifecycleSeen.length} expected=${RUNS.length * 2}`);
console.log(
  `VERDICT=${leaks === 0 && lifecycleSeen.length === RUNS.length * 2 ? "PASS" : "FAIL"}`,
);

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.

@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@quangtran88
quangtran88 marked this pull request as ready for review August 25, 2026 08:53
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: S labels Aug 25, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 25, 2026
@clawsweeper

clawsweeper Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 28, 2026, 7:41 AM ET / 11:41 UTC.

ClawSweeper review

What this changes

The 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
Reviewed head: f9fdc4b9bcbd5e4e53cb1b2d1fb6ada18a67b45f

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) PR readiness rating was derived from proof quality, review findings, security review, and reviewer confidence.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: ClawSweeper live verification failed on the reviewed terminal surface. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: ClawSweeper live verification failed on the reviewed terminal surface. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 7 items Current-main behavior: Current main still stores listeners in one global Set and emits to that whole set, so the central performance problem is not already implemented on main.
Dispatcher ownership: The PR replaces the global listener set with global and per-run maps, then merges only global and matching-run listeners by their registration position.
Consumer coverage: The shared CLI delivery bridge uses the run-specific subscription, and the introduced diff similarly changes the Gateway HTTP, embedded CLI, system-agent, and ACP stream consumers.
Findings None None.
Security None None.

Live Verification

Command: pnpm test src/gateway/gateway-concurrent-streams.test.ts

Result: FAIL (failed) — step 1 expect_output [test] passed: terminal command failed with exit status 1: "pnpm test src/gateway/gateway-concurrent-streams.test.ts"

[failure]
terminal command failed with exit status 1: "pnpm test src/gateway/gateway-concurrent-streams.test.ts"

[command 1 combined output]
$ node --import ./scripts/tsx.mjs scripts/test-projects.mts src/gateway/gateway-concurrent-streams.test.ts
[test] preparing runtime runtime before Vitest workers
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 399.96 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 103.88 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ
… output truncated …
n every run 29ms
   → ENOENT: no such file or directory, open '/tmp/clawsweeper-live-proof-129174-T3sOKZ/target/dist/build-info.json'

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯

 FAIL   gateway-core  ../../src/gateway/gateway-concurrent-streams.test.ts › Gateway concurrent HTTP streams › keeps both streams isolated while global observer
s retain every run
Error: ENOENT: no such file or directory, open '/tmp/clawsweeper-live-proof-129174-T3sOKZ/target/dist/build-info.json'
 ❯ ../../src/gateway/gateway-concurrent-streams.test.ts:55:34
     53|       expect(metadata.head, stamp).toBe(checkoutSha);
     54|     }
     55|     const buildInfo = JSON.parse(await fs.readFile(path.join(cwd, "dis…
       |                                  ^
     56|     expect(buildInfo.commit).toBe(checkoutSha);
     57|     const token = ˋfanout-${randomUUID()}ˋ;

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { errno: -2, code: 'ENOENT', syscall: 'open', path: '/tmp/clawsweeper-live-proof-129174-T3sOKZ/target/dist/build-info.json' }
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯


 Test Files  1 failed (1)
      Tests  1 failed (1)
   Start at  11:42:32
   Duration  8.37s (transform 6.65s, setup 856ms, import 7.17s, tests 32ms, environment 0ms)


::error file=/tmp/clawsweeper-live-proof-129174-T3sOKZ/target/src/gateway/gateway-concurrent-streams.test.ts,title=[gateway-core] ../../src/gateway/gateway-conc
urrent-streams.test.ts › Gateway concurrent HTTP streams › keeps both streams isolated while global observers retain every run,line=55,column=34::Error: ENOENT:
 no such file or directory, open '/tmp/clawsweeper-live-proof-129174-T3sOKZ/target/dist/build-info.json'%0A ❯ ../../src/gateway/gateway-concurrent-streams.test.
ts:55:34%0A%0A⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯%0ASerialized Error: { errno: -2, code: 'ENOENT', syscall: 'open', path: '/tmp/clawsweeper-live-proof-129174-T3sOKZ/
target/dist/build-info.json' }%0A
[test] failed 1 Vitest shard in 33.22s
[ELIFECYCLE] Test failed. See above for more details.

Assertions:

  • FAIL expect_output: [test] passed

How this fits together

Agent 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]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: ClawSweeper live verification failed on the reviewed terminal surface. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - This changes a hot dispatcher used by stream delivery and lifecycle consumers; merge should wait for exact-head Gateway and event-dispatch checks, even though the prior built-Gateway proof is strong.
  • Resolve merge risk (P1) - The PR adds net production logic to preserve live listener ordering and mutation behavior; the added state-machine complexity is justified only while its focused invariant coverage remains green.
  • Complete next step (P2) - No discrete repair remains from this review; await exact-head CI and maintainer merge review.
Agent review details

Security

None.

PR surface

Source +80, Tests +706, Other +7. Total +793 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 8 99 19 +80
Tests 5 712 6 +706
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 12 5 +7
Total 14 823 30 +793

Review metrics

Metric Value Why it matters
Production versus test LOC production +95/-19; tests and test-support +728/-11 The production growth is concentrated in the dispatcher’s ordering-preserving run index; the accompanying coverage exercises its mutation and Gateway-stream boundaries.
Run-scoped stream consumers 6 converted; approval wait intentionally retained globally The PR removes the high-volume stream callbacks from unrelated-run fanout without claiming to complete the separate approval-wait surface.

Merge-risk options

Maintainer options:

  1. Complete exact-head stream validation (recommended)
    Require the final head’s Gateway concurrent-stream and listener-order checks to pass before merge, preserving the proven delivery and lifecycle invariants.

Technical review

Best 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.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦞 diamond lobster.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: ClawSweeper live verification failed on the reviewed terminal surface. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • remove proof: sufficient: Current real behavior proof status is insufficient, not sufficient.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: 📣 needs proof.

Label justifications:

  • P2: This is a bounded multi-agent throughput improvement with no reported user-visible correctness loss.
  • merge-risk: 🚨 message-delivery: The changed dispatcher routes callbacks that produce HTTP and CLI stream output, so an ordering or selection defect could suppress or reorder deltas.
  • merge-risk: 🚨 session-state: Lifecycle and tool-event consumers share this dispatcher, so preserving listener ordering and matching is relevant to transcript and session projections.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦞 diamond lobster.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: ClawSweeper live verification failed on the reviewed terminal surface. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current-main behavior: Current main still stores listeners in one global Set and emits to that whole set, so the central performance problem is not already implemented on main. (src/infra/agent-events.ts:87, c792a16791ca)
  • Dispatcher ownership: The PR replaces the global listener set with global and per-run maps, then merges only global and matching-run listeners by their registration position. (src/infra/agent-events.ts:341, f9fdc4b9bcbd)
  • Consumer coverage: The shared CLI delivery bridge uses the run-specific subscription, and the introduced diff similarly changes the Gateway HTTP, embedded CLI, system-agent, and ACP stream consumers. (src/auto-reply/reply/agent-event-bridge.ts:48, f9fdc4b9bcbd)
  • Ordering and lifecycle tests: New tests cover matching-run isolation, mixed registration order, additions, removals, re-additions, nested dispatch, run-ID mutation, and owner-scoped emission. (src/infra/agent-events.run-listeners.test.ts:18, f9fdc4b9bcbd)
  • Built Gateway proof: The reviewed PR body documents a successful built-Gateway concurrent-stream run at repaired head 15e0530, exercising authenticated Chat Completions and Responses streams with a local provider, WebSocket events, and agent.wait. (src/gateway/gateway-concurrent-streams.test.ts:42, 15e053097fb8)
  • Area provenance: Blame on current main attributes the pre-change global listener state and emitter calls to the recent agent-events maintenance commit, making Peter Steinberger the strongest routing contact. (src/infra/agent-events.ts:87, a65668b9b7fe)

Likely related people:

  • steipete: Current-main blame attributes the listener state and global emission path to Peter Steinberger's recent agent-events work; he also authored the ordering-preservation revision in this PR. (role: recent event-dispatch contributor; confidence: high; commits: a65668b9b7fe, 15e053097fb8, f9fdc4b9bcbd; files: src/infra/agent-events.ts, src/gateway/openai-http.ts, src/gateway/openresponses-http.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add after-fix proof from a real setup, such as a short recording, terminal output, linked artifact, or redacted logs.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-26T09:31:54.920Z sha 681956de1f327ee35747c28d3c0eece2ed948461 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-26T10:13:40.105Z sha 681956de1f327ee35747c28d3c0eece2ed948461 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-27T09:24:52.054Z sha 8b4789579b400d9036226e8ecd94214437a972ca :: needs real behavior proof before merge. :: [P2] Publish an exact-head concurrent-run benchmark
  • reviewed 2026-08-27T09:58:14.159Z sha 8b4789579b400d9036226e8ecd94214437a972ca :: needs real behavior proof before merge. :: [P2] Publish an exact-head concurrent-run trace
  • reviewed 2026-08-27T10:42:29.842Z sha 8b4789579b400d9036226e8ecd94214437a972ca :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T09:24:28.976Z sha 2a40e870113e188e2a9520d8646f1585ac4fe6b2 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-28T10:20:16.389Z sha 10eb012 :: needs real behavior proof before merge. :: [P1] Preserve mixed listener registration order
  • reviewed 2026-08-28T11:23:40.983Z sha 15e0530 :: needs maintainer review before merge. :: none

@quangtran88
quangtran88 force-pushed the perf/run-indexed-agent-event-listeners branch from c4ce251 to 681956d Compare August 26, 2026 09:24
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 26, 2026
@quangtran88
quangtran88 force-pushed the perf/run-indexed-agent-event-listeners branch from 681956d to 8b47895 Compare August 27, 2026 09:16
@quangtran88

Copy link
Copy Markdown
Contributor Author

@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.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 27, 2026
@clawsweeper clawsweeper Bot removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 28, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 28, 2026
quangtran88 and others added 4 commits August 28, 2026 02:36
…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]>
@steipete
steipete force-pushed the perf/run-indexed-agent-event-listeners branch from 2a40e87 to 10eb012 Compare August 28, 2026 10:07
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]>
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 28, 2026
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]>
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 28, 2026
@steipete
steipete merged commit 70c44ce into openclaw:main Aug 28, 2026
268 of 270 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 29, 2026
…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]>
steipete added a commit that referenced this pull request Sep 2, 2026
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]>
steipete added a commit that referenced this pull request Sep 2, 2026
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 3, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants