Skip to content

Commit 530b33e

Browse files
authored
fix: keep gateway control traffic responsive under concurrent turns (#123608)
* fix(gateway): preserve control-plane responsiveness under load * fix(plugins): accept prepared readonly manifests * refactor(plugins): prepare workspace ownership before metadata reuse * chore: leave changelog updates to release flow * fix(gateway): finish control-plane load repair * perf(gateway): reuse prepared workspace root facts * perf(gateway): coalesce workspace root preparation * test(gateway): calibrate control-plane load bound
1 parent 83d5304 commit 530b33e

38 files changed

Lines changed: 1004 additions & 284 deletions

‎scripts/bench-gateway-concurrency.ts‎

Lines changed: 132 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,18 @@ type GatewaySample = {
7070
sessionsList: TimedProbe;
7171
};
7272

73+
type FreshConnectionProbe = {
74+
error: string | null;
75+
latencyMs: number;
76+
ok: boolean;
77+
};
78+
7379
type GatewayRpc = <T>(method: string, params: unknown, timeoutMs?: number) => Promise<T>;
7480

7581
type BenchmarkRun = {
7682
controlUi: ControlUiProbe[];
7783
durationMs: number;
84+
freshConnection: FreshConnectionProbe;
7885
probeWarmup: {
7986
durationMs: number;
8087
samples: GatewaySample[];
@@ -92,12 +99,15 @@ type CliOptions = {
9299
cpuProfDir?: string;
93100
entry: string;
94101
json: boolean;
102+
maxControlMs?: number;
103+
maxHandshakeMs?: number;
95104
output?: string;
96105
pluginCount: number;
97106
runs: number;
98107
timeoutMs: number;
99108
toolEvents: boolean;
100109
warmup: number;
110+
workspaceFanout: boolean;
101111
};
102112

103113
const DEFAULT_CADENCE_MS = 100;
@@ -119,12 +129,14 @@ const PROBE_WARMUP_TARGET_MS = 1_000;
119129
const PROBE_WARMUP_RETRY_DELAY_MS = 100;
120130
const GATEWAY_STDERR_TAIL_LINES = 20;
121131
const AGENT_WAIT_RPC_GRACE_MS = 5_000;
122-
const BOOLEAN_FLAGS = new Set(["--help", "-h", "--json", "--tool-events"]);
132+
const BOOLEAN_FLAGS = new Set(["--help", "-h", "--json", "--tool-events", "--workspace-fanout"]);
123133
const VALUE_FLAGS = new Set([
124134
"--cadence-ms",
125135
"--concurrency",
126136
"--cpu-prof-dir",
127137
"--entry",
138+
"--max-control-ms",
139+
"--max-handshake-ms",
128140
"--output",
129141
"--plugin-count",
130142
"--runs",
@@ -176,6 +188,22 @@ function parseOptions(argv: string[] = process.argv.slice(2)): CliOptions {
176188
cpuProfDir: resolveOutputPath(parseFlagValue(argv, "--cpu-prof-dir")),
177189
entry: resolveEntry(parseFlagValue(argv, "--entry"), DEFAULT_ENTRY),
178190
json: hasFlag(argv, "--json"),
191+
maxControlMs: parseFlagValue(argv, "--max-control-ms")
192+
? parseBoundedPositiveInt(
193+
parseFlagValue(argv, "--max-control-ms"),
194+
2_000,
195+
"--max-control-ms",
196+
30_000,
197+
)
198+
: undefined,
199+
maxHandshakeMs: parseFlagValue(argv, "--max-handshake-ms")
200+
? parseBoundedPositiveInt(
201+
parseFlagValue(argv, "--max-handshake-ms"),
202+
2_000,
203+
"--max-handshake-ms",
204+
30_000,
205+
)
206+
: undefined,
179207
output: resolveOutputPath(parseFlagValue(argv, "--output")),
180208
pluginCount: parseBoundedNonNegativeInt(
181209
parseFlagValue(argv, "--plugin-count"),
@@ -197,6 +225,7 @@ function parseOptions(argv: string[] = process.argv.slice(2)): CliOptions {
197225
"--warmup",
198226
MAX_WARMUP,
199227
),
228+
workspaceFanout: hasFlag(argv, "--workspace-fanout"),
200229
};
201230
}
202231

@@ -217,6 +246,9 @@ Options:
217246
--entry <path> Gateway CLI entry file (default: ${DEFAULT_ENTRY})
218247
--plugin-count <n> Configure synthetic plugins through plugins.load.paths (default: 0)
219248
--tool-events Make every synthetic turn execute a tool before replying
249+
--workspace-fanout Bind each turn to a distinct workspace
250+
--max-control-ms Fail when any load-phase health/control probe exceeds this bound
251+
--max-handshake-ms Fail when a fresh authenticated connection exceeds this bound
220252
--output <path> Write machine-readable JSON to a file
221253
--json Emit machine-readable JSON
222254
--help, -h Show this text
@@ -498,7 +530,7 @@ function buildConfig(
498530
return writeGatewayBenchConfig(root, config, { pluginFixtures });
499531
}
500532

501-
async function connectGateway(port: number, deadlineAt: number) {
533+
async function connectGateway(port: number, deadlineAt: number, subscribeSessions = true) {
502534
let requestDeadlineAt = deadlineAt;
503535
const client = createGatewayWsClient({
504536
handshakeTimeoutMs: Math.min(8_000, requireRemainingMs(deadlineAt, "connecting WebSocket")),
@@ -547,7 +579,9 @@ async function connectGateway(port: number, deadlineAt: number) {
547579
scopes: ["operator.read", "operator.write", "operator.admin"],
548580
caps: [],
549581
});
550-
await requestRpc("sessions.subscribe", {});
582+
if (subscribeSessions) {
583+
await requestRpc("sessions.subscribe", {});
584+
}
551585
return {
552586
close: client.close,
553587
request: requestRpc,
@@ -562,16 +596,18 @@ async function runTurn(
562596
index: number,
563597
deadlineAt: number,
564598
toolEvents = false,
599+
options?: { onStarted?: () => void; sessionKey?: string },
565600
): Promise<void> {
566601
const requestedRunId = randomUUID();
567602
const started = await rpc<{ runId?: string; status?: string }>("agent", {
568-
sessionKey: `agent:main:gateway-concurrency-${index + 1}`,
603+
sessionKey: options?.sessionKey ?? `agent:main:gateway-concurrency-${index + 1}`,
569604
message: toolEvents
570605
? `OPENCLAW_E2E_DRAFTPROOF benchmark tool stream ${index + 1}.`
571606
: `Reply with benchmark stream ${index + 1}.`,
572607
deliver: false,
573608
idempotencyKey: requestedRunId,
574609
});
610+
options?.onStarted?.();
575611
if (started.status === "ok") {
576612
return;
577613
}
@@ -738,6 +774,7 @@ async function runGatewaySample(options: {
738774
cpuProfDir?: string;
739775
pluginCount: number;
740776
toolEvents: boolean;
777+
workspaceFanout: boolean;
741778
}): Promise<BenchmarkRun> {
742779
const root = mkdtempSync(path.join(tmpdir(), "openclaw-gateway-concurrency-"));
743780
const [port, mockPort] = await Promise.all([getFreePort(), getFreePort()]);
@@ -820,20 +857,63 @@ async function runGatewaySample(options: {
820857
});
821858
const loadDeadlineAt = options.deadlineAt + probeWarmup.durationMs;
822859
client.setDeadlineAt(loadDeadlineAt);
860+
const workspaceSessionKeys = options.workspaceFanout
861+
? await Promise.all(
862+
Array.from({ length: options.concurrency }, async (_, index) => {
863+
const workspaceDir = path.join(root, `workspace-${index + 1}`);
864+
mkdirSync(workspaceDir, { recursive: true });
865+
const sessionKey = `agent:main:gateway-concurrency-${index + 1}`;
866+
await rpc("sessions.create", {
867+
key: sessionKey,
868+
agentId: "main",
869+
cwd: workspaceDir,
870+
});
871+
return sessionKey;
872+
}),
873+
)
874+
: [];
823875
// The benchmark compares runtime event work, so discard startup and lazy-import spans.
824876
writeFileSync(timelinePath, "");
825877

826878
const controlUi: ControlUiProbe[] = [];
827879
const readyz: ReadyProbe[] = [];
828880
const sessionsList: TimedProbe[] = [];
829881
let turnsDone = false;
882+
let startedTurnCount = 0;
883+
let resolveAllTurnsStarted!: () => void;
884+
const allTurnsStarted = new Promise<void>((resolve) => {
885+
resolveAllTurnsStarted = resolve;
886+
});
830887
const turnsStartedAt = performance.now();
831888
const turns = Promise.all(
832889
Array.from({ length: options.concurrency }, (_, index) =>
833-
runTurn(rpc, index, loadDeadlineAt, options.toolEvents),
890+
runTurn(rpc, index, loadDeadlineAt, options.toolEvents, {
891+
onStarted: () => {
892+
startedTurnCount += 1;
893+
if (startedTurnCount === options.concurrency) {
894+
resolveAllTurnsStarted();
895+
}
896+
},
897+
...(workspaceSessionKeys[index] ? { sessionKey: workspaceSessionKeys[index] } : {}),
898+
}),
834899
),
835900
).finally(() => {
836901
turnsDone = true;
902+
resolveAllTurnsStarted();
903+
});
904+
const freshConnection = allTurnsStarted.then(async (): Promise<FreshConnectionProbe> => {
905+
const startedAt = performance.now();
906+
try {
907+
const freshClient = await connectGateway(port, loadDeadlineAt, false);
908+
freshClient.close();
909+
return { error: null, latencyMs: performance.now() - startedAt, ok: true };
910+
} catch (error) {
911+
return {
912+
error: describeProbeError(error),
913+
latencyMs: performance.now() - startedAt,
914+
ok: false,
915+
};
916+
}
837917
});
838918
const sampler = (async () => {
839919
for (;;) {
@@ -859,11 +939,13 @@ async function runGatewaySample(options: {
859939
}
860940
})();
861941
await Promise.all([turns, sampler]);
942+
const freshConnectionResult = await freshConnection;
862943
const turnsDurationMs = performance.now() - turnsStartedAt;
863944

864945
return {
865946
controlUi,
866947
durationMs: performance.now() - runStartedAt,
948+
freshConnection: freshConnectionResult,
867949
probeWarmup,
868950
pluginMetadataScans: summarizePluginMetadataScans(readDiagnosticsTimelineSpans(timelinePath)),
869951
readyz,
@@ -877,6 +959,16 @@ async function runGatewaySample(options: {
877959
} finally {
878960
client?.close();
879961
if (gateway) {
962+
if (options.cpuProfDir && gateway.exitCode === null && gateway.signalCode === null) {
963+
// V8 flushes the main-isolate CPU profile on its normal interrupt path.
964+
const profileFlushed = new Promise<void>((resolve) => {
965+
gateway!.once("exit", () => {
966+
resolve();
967+
});
968+
});
969+
gateway.kill("SIGINT");
970+
await Promise.race([profileFlushed, delay(2_000)]);
971+
}
880972
await stopChild(gateway);
881973
}
882974
if (mockProvider) {
@@ -904,6 +996,8 @@ function summarizeRuns(runs: readonly BenchmarkRun[]) {
904996
eventLoopUtilization: summarizeNumbers(
905997
readyz.flatMap((sample) => (sample.utilization == null ? [] : [sample.utilization])),
906998
),
999+
freshConnectionFailedRuns: runs.filter((run) => !run.freshConnection.ok).length,
1000+
freshConnectionLatencyMs: summarizeNumbers(runs.map((run) => run.freshConnection.latencyMs)),
9071001
pluginMetadataScanCount: runs.reduce((sum, run) => sum + run.pluginMetadataScans.count, 0),
9081002
pluginMetadataScanTotalDurationMs: runs.reduce(
9091003
(sum, run) => sum + run.pluginMetadataScans.totalDurationMs,
@@ -969,6 +1063,7 @@ async function main(): Promise<void> {
9691063
runs,
9701064
summary: summarizeRuns(runs),
9711065
toolEvents: options.toolEvents,
1066+
workspaceFanout: options.workspaceFanout,
9721067
};
9731068
if (options.output) {
9741069
mkdirSync(path.dirname(options.output), { recursive: true });
@@ -977,6 +1072,38 @@ async function main(): Promise<void> {
9771072
if (options.json || !options.output) {
9781073
console.log(JSON.stringify(payload, null, 2));
9791074
}
1075+
if (options.maxHandshakeMs !== undefined) {
1076+
const violation = runs.find(
1077+
(run) => !run.freshConnection.ok || run.freshConnection.latencyMs > options.maxHandshakeMs!,
1078+
);
1079+
if (violation) {
1080+
throw new Error(
1081+
`fresh Gateway connection exceeded ${options.maxHandshakeMs}ms: ` +
1082+
`ok=${violation.freshConnection.ok} ` +
1083+
`latencyMs=${violation.freshConnection.latencyMs.toFixed(1)} ` +
1084+
`error=${violation.freshConnection.error ?? "none"}`,
1085+
);
1086+
}
1087+
}
1088+
if (options.maxControlMs !== undefined) {
1089+
const controlSamples: Array<{ name: string; sample: TimedProbe }> = [];
1090+
for (const run of runs) {
1091+
controlSamples.push(
1092+
...run.readyz.map((sample) => ({ name: "readyz", sample })),
1093+
...run.sessionsList.map((sample) => ({ name: "sessions.list", sample })),
1094+
);
1095+
}
1096+
const violation = controlSamples.find(
1097+
({ sample }) => !sample.ok || sample.latencyMs > options.maxControlMs!,
1098+
);
1099+
if (violation) {
1100+
throw new Error(
1101+
`Gateway ${violation.name} probe exceeded ${options.maxControlMs}ms: ` +
1102+
`ok=${violation.sample.ok} latencyMs=${violation.sample.latencyMs.toFixed(1)} ` +
1103+
`error=${violation.sample.error ?? "none"}`,
1104+
);
1105+
}
1106+
}
9801107
}
9811108

9821109
export const testing = {

‎scripts/check-gateway-cpu-scenarios.mts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,13 @@ async function runGatewayCpuScenarios(
455455
"scripts/bench-gateway-concurrency.ts",
456456
"--concurrency",
457457
String(DEFAULT_GATEWAY_CONCURRENCY),
458+
"--workspace-fanout",
459+
// Post-fix readyz/sessions.list p100 is 1.3-2.6s across environments;
460+
// 4s still catches the pre-fix 8s+ stalls and handshake timeouts.
461+
"--max-control-ms",
462+
"4000",
463+
"--max-handshake-ms",
464+
"2000",
458465
"--runs",
459466
String(options.runs),
460467
"--warmup",

‎src/agents/embedded-agent-runner/run/auth-plan.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ export async function prepareEmbeddedRunAuthPlan(params: {
148148
env: process.env,
149149
agentDir: params.agentDir,
150150
workspaceDir: params.workspaceDir,
151+
metadataSnapshot: params.preparedModelRuntime?.metadataSnapshot,
151152
authProfileStore: attemptAuthProfileStore,
152153
sessionAuthProfileId: preferredProfileId,
153154
sessionAuthProfileSource: runParams.authProfileIdSource,

‎src/agents/openclaw-plugin-tools.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
* auth profiles, and the current runtime config snapshot.
66
*/
77
import type { OpenClawConfig } from "../config/types.openclaw.js";
8+
import { getActivePluginRegistry } from "../plugins/runtime.js";
9+
import { getPluginRuntimeGatewayRequestScope } from "../plugins/runtime/gateway-request-scope.js";
810
import { resolvePluginTools } from "../plugins/tools.js";
911
import { resolveApiKeyForProfile, resolveAuthProfileOrder } from "./auth-profiles.js";
1012
import type { AuthProfileStore } from "./auth-profiles/types.js";
@@ -138,6 +140,8 @@ export function resolveOpenClawPluginToolsForOptions(params: {
138140
: undefined;
139141
const existingToolNames = new Set(params.existingToolNames ?? []);
140142
const preparedModelRuntime = params.options?.preparedModelRuntime;
143+
const runtimeRegistry =
144+
getPluginRuntimeGatewayRequestScope()?.pluginRegistry ?? getActivePluginRegistry() ?? undefined;
141145
const pluginTools = resolvePluginTools({
142146
...pluginToolInputs,
143147
context: {
@@ -151,6 +155,7 @@ export function resolveOpenClawPluginToolsForOptions(params: {
151155
toolDenylist: params.options?.pluginToolDenylist,
152156
allowGatewaySubagentBinding: params.options?.allowGatewaySubagentBinding,
153157
...(hasAuthForProvider ? { hasAuthForProvider } : {}),
158+
...(runtimeRegistry ? { runtimeRegistry } : {}),
154159
...(preparedModelRuntime
155160
? {
156161
preparedRuntime: {

‎src/agents/openclaw-tools.browser-plugin.integration.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import {
99
makeRegistry,
1010
} from "../config/plugin-auto-enable.test-helpers.js";
1111
import * as pluginMetadata from "../plugins/plugin-metadata-snapshot.js";
12+
import { createEmptyPluginRegistry } from "../plugins/registry-empty.js";
13+
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../plugins/runtime.js";
1214
import { activateSecretsRuntimeSnapshot, clearSecretsRuntimeSnapshot } from "../secrets/runtime.js";
1315
import { getRuntimeAuthProfileStoreCredentialsRevision } from "./auth-profiles/runtime-snapshots.js";
1416
import { resolveOpenClawPluginToolsForOptions } from "./openclaw-plugin-tools.js";
@@ -44,6 +46,7 @@ describe("createOpenClawTools browser plugin integration", () => {
4446
vi.unstubAllEnvs();
4547
clearSecretsRuntimeSnapshot();
4648
resetConfigRuntimeState();
49+
resetPluginRuntimeStateForTest();
4750
});
4851

4952
it("keeps the browser tool returned by plugin resolution", () => {
@@ -165,6 +168,20 @@ describe("createOpenClawTools browser plugin integration", () => {
165168
expect(firstResolvePluginToolsParams().allowGatewaySubagentBinding).toBe(true);
166169
});
167170

171+
it("forwards the lifecycle registry to workspace-scoped plugin tools", () => {
172+
hoisted.resolvePluginTools.mockReturnValue([]);
173+
const config = { plugins: { enabled: true } } as OpenClawConfig;
174+
const pluginRegistry = createEmptyPluginRegistry();
175+
setActivePluginRegistry(pluginRegistry, "gateway", "gateway-bindable", "/gateway-workspace");
176+
177+
resolveOpenClawPluginToolsForOptions({
178+
options: { config, workspaceDir: "/session-workspace" },
179+
resolvedConfig: config,
180+
});
181+
182+
expect(firstResolvePluginToolsParams().runtimeRegistry).toBe(pluginRegistry);
183+
});
184+
168185
it("forwards lifecycle-prepared plugin facts to plugin resolution", () => {
169186
hoisted.resolvePluginTools.mockReturnValue([]);
170187
const config = { plugins: { enabled: true } } as OpenClawConfig;

0 commit comments

Comments
 (0)