Skip to content

Commit 15e0530

Browse files
steipetequangtran88
andcommitted
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: #129173 Co-authored-by: Tran Quang <[email protected]>
1 parent 10eb012 commit 15e0530

5 files changed

Lines changed: 359 additions & 119 deletions

File tree

‎src/auto-reply/reply/agent-event-bridge.test.ts‎

Lines changed: 70 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -21,25 +21,53 @@ describe("agent event delivery bridge", () => {
2121
resetAgentEventsForTest();
2222
});
2323

24-
test("delivers only its own run's events while two CLI runs stream concurrently", async () => {
25-
registerAgentRunContext("run-a", { sessionKey: "session-a" });
26-
registerAgentRunContext("run-b", { sessionKey: "session-b" });
27-
const deliveredA: string[] = [];
28-
const deliveredB: string[] = [];
29-
const bridgeA = textBridge("run-a", deliveredA);
30-
const bridgeB = textBridge("run-b", deliveredB);
31-
32-
emitAgentEvent({ runId: "run-a", stream: "assistant", data: { text: "a1" } });
33-
emitAgentEvent({ runId: "run-b", stream: "assistant", data: { text: "b1" } });
34-
emitAgentEvent({ runId: "run-a", stream: "assistant", data: { text: "a2" } });
35-
await bridgeA.drain();
36-
await bridgeB.drain();
37-
bridgeA.unsubscribe();
38-
bridgeB.unsubscribe();
39-
40-
expect(deliveredA).toEqual(["a1", "a2"]);
41-
expect(deliveredB).toEqual(["b1"]);
42-
});
24+
test.each([1, 4, 16, 64])(
25+
"isolates every delivery bridge while %s CLI runs stream interleaved events",
26+
async (runs) => {
27+
let predicateReads = 0;
28+
const bridges = Array.from({ length: runs }, (_, runIndex) => {
29+
const runId = `run-${runIndex}`;
30+
registerAgentRunContext(runId, { sessionKey: `session-${runIndex}` });
31+
return Array.from({ length: 8 }, (_, bridgeIndex) => {
32+
const delivered: string[] = [];
33+
const bridge = createAgentEventBridge<string>({
34+
get runId() {
35+
predicateReads++;
36+
return runId;
37+
},
38+
read: (event) => (typeof event.data.text === "string" ? event.data.text : undefined),
39+
deliver: async (text) => {
40+
delivered.push(text);
41+
},
42+
});
43+
return { ...bridge, delivered, runIndex, bridgeIndex };
44+
});
45+
}).flat();
46+
try {
47+
predicateReads = 0;
48+
emitAgentEvent({ runId: "run-0", stream: "assistant", data: { text: "a1" } });
49+
// Source-pinned work measurement only: hoisting the filter can change this
50+
// count without changing dispatch complexity. Output assertions own the test.
51+
console.info("bridge predicate-read diagnostic (not latency)", {
52+
runs,
53+
bridgesPerRun: 8,
54+
predicateReads,
55+
});
56+
emitAgentEvent({ runId: "run-1", stream: "assistant", data: { text: "b1" } });
57+
emitAgentEvent({ runId: "run-0", stream: "assistant", data: { text: "a2" } });
58+
await Promise.all(bridges.map((bridge) => bridge.drain()));
59+
for (const { delivered, runIndex, bridgeIndex } of bridges) {
60+
expect(delivered, `run-${runIndex}/bridge-${bridgeIndex}`).toEqual(
61+
runIndex === 0 ? ["a1", "a2"] : runIndex === 1 ? ["b1"] : [],
62+
);
63+
}
64+
} finally {
65+
for (const bridge of bridges) {
66+
bridge.unsubscribe();
67+
}
68+
}
69+
},
70+
);
4371

4472
test("keeps stream delivery order when a later global listener emits another event", async () => {
4573
registerAgentRunContext("run-nested", { sessionKey: "session-nested" });
@@ -80,27 +108,29 @@ describe("agent event delivery bridge", () => {
80108
}
81109
});
82110

83-
test("subscribes into its run's bucket rather than the global listener set", () => {
84-
registerAgentRunContext("run-scope", { sessionKey: "session-scope" });
85-
const order: string[] = [];
86-
// Registered first, so insertion order alone would run the bridge first.
87-
// Run-indexed listeners always follow every global listener, so the bridge
88-
// trailing here is what proves it is no longer a global subscriber that
89-
// every other run's events would still have to walk.
90-
const bridge = createAgentEventBridge<string>({
91-
runId: "run-scope",
92-
read: () => {
93-
order.push("bridge");
94-
return undefined;
95-
},
96-
deliver: async () => {},
111+
test("routes a changed event identity only to later matching bridges", async () => {
112+
registerAgentRunContext("run-a", { sessionKey: "session-a" });
113+
registerAgentRunContext("run-b", { sessionKey: "session-b" });
114+
const earlierB: string[] = [];
115+
const laterB: string[] = [];
116+
const laterA: string[] = [];
117+
const first = textBridge("run-b", earlierB);
118+
const stopGlobal = onAgentEvent((event) => {
119+
event.runId = "run-b";
97120
});
98-
const stopGlobal = onAgentEvent(() => order.push("global"));
99-
100-
emitAgentEvent({ runId: "run-scope", stream: "assistant", data: { text: "hi" } });
101-
stopGlobal();
102-
bridge.unsubscribe();
103-
104-
expect(order).toEqual(["global", "bridge"]);
121+
const second = textBridge("run-b", laterB);
122+
const third = textBridge("run-a", laterA);
123+
try {
124+
emitAgentEvent({ runId: "run-a", stream: "assistant", data: { text: "changed" } });
125+
await Promise.all([first.drain(), second.drain(), third.drain()]);
126+
expect(earlierB).toEqual([]);
127+
expect(laterB).toEqual(["changed"]);
128+
expect(laterA).toEqual([]);
129+
} finally {
130+
stopGlobal();
131+
first.unsubscribe();
132+
second.unsubscribe();
133+
third.unsubscribe();
134+
}
105135
});
106136
});

‎src/gateway/gateway-concurrent-streams.test.ts‎

Lines changed: 73 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
1-
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
1+
import { execFileSync, spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
22
import { randomUUID } from "node:crypto";
33
import fs from "node:fs/promises";
4-
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import path from "node:path";
5+
import { describe, expect, it, vi } from "vitest";
6+
import { PROTOCOL_VERSION } from "../../packages/gateway-protocol/src/index.js";
57
import { stopChild } from "../../scripts/lib/gateway-bench-child.js";
68
import { getFreePort } from "../../scripts/lib/gateway-bench-probes.js";
9+
import { createGatewayWsClient } from "../../scripts/lib/gateway-ws-client.js";
10+
import {
11+
BUILD_STAMP_FILE,
12+
RUNTIME_POSTBUILD_STAMP_FILE,
13+
} from "../../scripts/lib/local-build-metadata-paths.mts";
14+
import { createOpenClawTestInstance } from "../../test/helpers/openclaw-test-instance.js";
715
import type { OpenClawConfig } from "../config/types.openclaw.js";
816
import type { AgentEventPayload } from "../infra/agent-events.js";
9-
import { resetAgentEventsForTest } from "../infra/agent-events.js";
1017
import { hasErrnoCode } from "../infra/errno.js";
11-
import { resetLogger } from "../logging/logger.js";
12-
import { createOpenClawTestState } from "../test-utils/openclaw-test-state.js";
13-
import { disconnectGatewayClient, startGatewayWithClient } from "./test-helpers.e2e.js";
1418
import { buildMockOpenAiResponsesProvider } from "./test-openai-responses-model.js";
1519

1620
type StreamFrame = {
@@ -34,15 +38,27 @@ const cases = [
3438
},
3539
] as const;
3640

37-
afterEach(() => {
38-
resetAgentEventsForTest({ preserveListeners: true });
39-
resetLogger();
40-
});
41-
4241
describe("Gateway concurrent HTTP streams", () => {
4342
it("keeps both streams isolated while global observers retain every run", async () => {
44-
const state = await createOpenClawTestState({
45-
label: "concurrent-streams",
43+
const cwd = process.cwd();
44+
const checkoutSha = execFileSync("git", ["rev-parse", "HEAD"], {
45+
cwd,
46+
encoding: "utf8",
47+
}).trim();
48+
// Require this checkout's complete runtime before the shared helper can
49+
// prepare a source fallback. The child must own one coherent built graph.
50+
await fs.access(path.join(cwd, "dist/index.js"));
51+
for (const stamp of [BUILD_STAMP_FILE, RUNTIME_POSTBUILD_STAMP_FILE]) {
52+
const metadata = JSON.parse(await fs.readFile(path.join(cwd, "dist", stamp), "utf8"));
53+
expect(metadata.head, stamp).toBe(checkoutSha);
54+
}
55+
const buildInfo = JSON.parse(await fs.readFile(path.join(cwd, "dist/build-info.json"), "utf8"));
56+
expect(buildInfo.commit).toBe(checkoutSha);
57+
const token = `fanout-${randomUUID()}`;
58+
const gateway = await createOpenClawTestInstance({
59+
name: "concurrent-streams",
60+
cwd,
61+
gatewayToken: token,
4662
env: {
4763
OPENCLAW_GATEWAY_TOKEN: undefined,
4864
OPENCLAW_GATEWAY_PASSWORD: undefined,
@@ -59,20 +75,12 @@ describe("Gateway concurrent HTTP streams", () => {
5975
OPENCLAW_DISABLE_BUNDLED_PLUGINS: undefined,
6076
},
6177
});
62-
// Startup spans use the subsystem logger; discard Vitest's cached silent
63-
// settings after entering the isolated fixture so stalled startup is visible.
64-
resetLogger();
65-
const mockPort = await getFreePort();
78+
const { state, port } = gateway;
6679
const controlPath = state.path("response-control.json");
6780
const requestLogPath = state.path("provider-requests.jsonl");
68-
const provider = buildMockOpenAiResponsesProvider(
69-
`http://127.0.0.1:${mockPort}/v1`,
70-
"gpt-5.6-luna",
71-
);
72-
const token = `fanout-${randomUUID()}`;
7381
const events: AgentEventPayload[] = [];
7482
const abort = new AbortController();
75-
let gateway: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined;
83+
let client: ReturnType<typeof createGatewayWsClient> | undefined;
7684
let mock: ChildProcessWithoutNullStreams | undefined;
7785
const streams: Array<{
7886
item: (typeof cases)[number];
@@ -104,6 +112,12 @@ describe("Gateway concurrent HTTP streams", () => {
104112
: [];
105113
};
106114
try {
115+
expect(await gateway.entrypoint()).toEqual(["dist/index.js"]);
116+
const mockPort = await getFreePort();
117+
const provider = buildMockOpenAiResponsesProvider(
118+
`http://127.0.0.1:${mockPort}/v1`,
119+
"gpt-5.6-luna",
120+
);
107121
await writeControl(true);
108122
mock = spawn(process.execPath, ["scripts/e2e/mock-openai-server.mjs"], {
109123
cwd: process.cwd(),
@@ -122,11 +136,14 @@ describe("Gateway concurrent HTTP streams", () => {
122136
});
123137
const cfg = {
124138
gateway: {
139+
port,
125140
auth: { mode: "token", token },
141+
controlUi: { enabled: false },
126142
http: {
127143
endpoints: { chatCompletions: { enabled: true }, responses: { enabled: true } },
128144
},
129145
},
146+
hooks: { enabled: false },
130147
agents: {
131148
defaults: {
132149
workspace: state.workspaceDir,
@@ -151,20 +168,37 @@ describe("Gateway concurrent HTTP streams", () => {
151168
plugins: { slots: { memory: "none" } },
152169
tools: { profile: "minimal" },
153170
} satisfies OpenClawConfig;
154-
gateway = await startGatewayWithClient({
155-
cfg,
156-
configPath: state.configPath,
157-
token,
158-
scopes: ["operator.admin", "operator.read", "operator.write"],
171+
await state.writeConfig(cfg);
172+
await gateway.startGateway();
173+
client = createGatewayWsClient({
174+
url: gateway.url,
159175
onEvent: (event) => {
160176
if (event.event === "agent") {
161177
events.push(event.payload as AgentEventPayload);
162178
}
163179
},
164180
});
165-
const { port, client } = gateway;
181+
await client.waitOpen();
182+
const connected = await client.request("connect", {
183+
minProtocol: PROTOCOL_VERSION,
184+
maxProtocol: PROTOCOL_VERSION,
185+
client: {
186+
id: "gateway-client",
187+
displayName: "concurrent-stream-proof",
188+
version: "dev",
189+
platform: process.platform,
190+
mode: "backend",
191+
},
192+
role: "operator",
193+
scopes: ["operator.admin", "operator.read", "operator.write"],
194+
auth: { token },
195+
});
196+
expect(connected.ok, JSON.stringify(connected.error)).toBe(true);
166197
for (const [index, item] of cases.entries()) {
167-
await client.request("sessions.messages.subscribe", { key: item.sessionKey });
198+
const subscribed = await client.request("sessions.messages.subscribe", {
199+
key: item.sessionKey,
200+
});
201+
expect(subscribed.ok, JSON.stringify(subscribed.error)).toBe(true);
168202
const body = {
169203
model: "openclaw:main",
170204
stream: true,
@@ -224,11 +258,12 @@ describe("Gateway concurrent HTTP streams", () => {
224258
frame.type === "response.completed" || frame.choices?.[0]?.finish_reason === "stop",
225259
);
226260
expect(terminals).toHaveLength(1);
227-
const result = await client.request<{ status: string }>("agent.wait", {
261+
const result = await client.request("agent.wait", {
228262
runId,
229263
timeoutMs: 10_000,
230264
});
231-
expect(result.status).toBe("ok");
265+
expect(result.ok, JSON.stringify(result.error)).toBe(true);
266+
expect(result.payload).toMatchObject({ status: "ok" });
232267
await vi.waitFor(() => {
233268
const own = events.filter((event) => event.runId === runId);
234269
const lifecycle = own.filter((event) => event.stream === "lifecycle");
@@ -241,24 +276,22 @@ describe("Gateway concurrent HTTP streams", () => {
241276
}
242277
});
243278
}
279+
} catch (error) {
280+
console.error(gateway.logs());
281+
throw error;
244282
} finally {
245283
abort.abort();
246284
try {
247-
if (gateway) {
248-
try {
249-
await disconnectGatewayClient(gateway.client);
250-
} finally {
251-
await gateway.server.close({ reason: "concurrent stream proof cleanup" });
252-
}
253-
}
285+
client?.close();
286+
await gateway.stopGateway();
254287
} finally {
255288
try {
256289
if (mock) {
257290
await stopChild(mock);
258291
}
259292
await Promise.all(streams.map((stream) => stream.settled));
260293
} finally {
261-
await state.cleanup();
294+
await gateway.cleanup();
262295
}
263296
}
264297
}

0 commit comments

Comments
 (0)