Skip to content

Commit c60db01

Browse files
authored
fix(gateway): reduce control-plane stalls during concurrent turns (#133683)
* fix(gateway): reduce control-plane stalls during concurrent turns * fix(bench): validate timeline evidence after gateway cleanup * test(gateway): await account startup after lifecycle handoff
1 parent c29f34d commit c60db01

24 files changed

Lines changed: 906 additions & 469 deletions

‎docs/diagnostics/flags.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,12 @@ counts, event-loop delay samples, provider operation names, child-process exit
150150
state, and startup error names/messages. Treat timeline files as local
151151
diagnostics artifacts; review before sharing them outside your machine.
152152

153+
Timeline writes batch adjacent events with the same destination into a bounded
154+
64 KiB buffer, flushed on the next event-loop turn, at capacity, or on normal
155+
process exit. Event timestamps reflect emission time. Writes remain best-effort;
156+
a forced kill can lose pending output. External harnesses should read the final
157+
artifact after the process exits and must not truncate it while the process runs.
158+
153159
## Where logs go
154160

155161
Flags emit logs into the standard diagnostics log file. By default:

‎scripts/bench-gateway-concurrency.ts‎

Lines changed: 416 additions & 382 deletions
Large diffs are not rendered by default.

‎src/agents/embedded-agent-runner/run/attempt.model-diagnostic-lifecycle.test.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@ import { isRecord } from "@openclaw/normalization-core/record-coerce";
66
import type { StreamFn } from "openclaw/plugin-sdk/agent-core";
77
import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
88
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
9-
import { useAutoCleanupTempDirTracker } from "../../../../test/helpers/temp-dir.js";
9+
import { createTempDirTracker } from "../../../../test/helpers/temp-dir.js";
1010
import {
1111
onInternalDiagnosticEvent,
1212
resetDiagnosticEventsForTest,
1313
type DiagnosticEventPayload,
1414
} from "../../../infra/diagnostic-events.js";
1515
import { createDiagnosticTraceContext } from "../../../infra/diagnostic-trace-context.js";
1616
import { registerDiagnosticTracePropagationBridge } from "../../../infra/diagnostic-trace-propagation.js";
17+
import { flushDiagnosticsTimeline } from "../../../infra/diagnostics-timeline.js";
1718
import {
1819
resetDiagnosticRunActivityForTest,
1920
startDiagnosticRunActivityTracking,
@@ -26,7 +27,7 @@ import { createHookRunnerWithRegistry } from "../../../plugins/hooks.test-fixtur
2627
import { withEnvAsync } from "../../../test-utils/env.js";
2728
import { wrapStreamFnWithDiagnosticModelCallEvents } from "./attempt.model-diagnostic-events.js";
2829

29-
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
30+
const tempDirs = createTempDirTracker();
3031

3132
async function collectModelCallEvents(run: () => Promise<void>): Promise<DiagnosticEventPayload[]> {
3233
// Diagnostics are emitted asynchronously; collect only public model-call
@@ -93,6 +94,7 @@ async function collectProviderTimelineEvents(run: () => Promise<void>) {
9394
},
9495
run,
9596
);
97+
flushDiagnosticsTimeline();
9698
return readFileSync(timelinePath, "utf8")
9799
.trim()
98100
.split("\n")
@@ -110,6 +112,8 @@ describe("wrapStreamFnWithDiagnosticModelCallEvents lifecycle", () => {
110112
});
111113

112114
afterEach(() => {
115+
flushDiagnosticsTimeline();
116+
tempDirs.cleanup();
113117
resetDiagnosticEventsForTest();
114118
resetGlobalHookRunner();
115119
resetDiagnosticRunActivityForTest();

‎src/agents/embedded-agent-runner/run/preparation-timing.test.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,17 @@ import { join } from "node:path";
44
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
55
import { afterEach, describe, expect, it, vi } from "vitest";
66
import { createDeferred } from "../../../../test/helpers/promise.js";
7-
import { useAutoCleanupTempDirTracker } from "../../../../test/helpers/temp-dir.js";
7+
import { createTempDirTracker } from "../../../../test/helpers/temp-dir.js";
8+
import { flushDiagnosticsTimeline } from "../../../infra/diagnostics-timeline.js";
89
import { createEmbeddedAttemptPreparation } from "./attempt-preparation.js";
910
import { measureEmbeddedAgentPreparation } from "./preparation-timing.js";
1011

11-
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
12+
const tempDirs = createTempDirTracker();
13+
14+
afterEach(() => {
15+
flushDiagnosticsTimeline();
16+
tempDirs.cleanup();
17+
});
1218

1319
async function createTimelineEnv() {
1420
const dir = tempDirs.make("openclaw-agent-preparation-");
@@ -22,6 +28,7 @@ async function createTimelineEnv() {
2228
}
2329

2430
async function readTimeline(path: string) {
31+
flushDiagnosticsTimeline();
2532
return (await readFile(path, "utf8"))
2633
.trim()
2734
.split("\n")

‎src/agents/startup-timing.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
22
import { tmpdir } from "node:os";
33
import { join } from "node:path";
44
import { afterEach, describe, expect, it } from "vitest";
5+
import { flushDiagnosticsTimeline } from "../infra/diagnostics-timeline.js";
56
import { measureAgentStartup } from "./startup-timing.js";
67

78
const tempDirs: string[] = [];
89

910
afterEach(async () => {
11+
flushDiagnosticsTimeline();
1012
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
1113
});
1214

@@ -24,6 +26,7 @@ describe("measureAgentStartup", () => {
2426
"ready",
2527
);
2628

29+
flushDiagnosticsTimeline();
2730
const events = (await readFile(path, "utf8"))
2831
.trim()
2932
.split("\n")

‎src/cli/command-startup-timing.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
22
import { tmpdir } from "node:os";
33
import { join } from "node:path";
44
import { afterEach, describe, expect, it } from "vitest";
5+
import { flushDiagnosticsTimeline } from "../infra/diagnostics-timeline.js";
56
import { measureCliCommandStartup } from "./command-startup-timing.js";
67

78
const tempDirs: string[] = [];
89

910
afterEach(async () => {
11+
flushDiagnosticsTimeline();
1012
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
1113
});
1214

@@ -34,6 +36,7 @@ describe("measureCliCommandStartup", () => {
3436
measureCliCommandStartup("config-ready", async () => "ready", { env }),
3537
).resolves.toBe("ready");
3638

39+
flushDiagnosticsTimeline();
3740
const events = (await readFile(path, "utf8"))
3841
.trim()
3942
.split("\n")

‎src/cli/gateway-cli/run-loop.test.ts‎

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// Gateway run loop tests cover foreground gateway lifecycle and restart behavior.
2+
import { existsSync, readFileSync } from "node:fs";
3+
import { join } from "node:path";
24
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { createTempDirTracker } from "../../../test/helpers/temp-dir.js";
36
import type { GatewayServer } from "../../gateway/server-public.js";
47
import type { GatewayBonjourBeacon } from "../../infra/bonjour-discovery.js";
58
import type { GatewayActiveWorkSnapshot } from "../../infra/gateway-active-work.js";
@@ -685,24 +688,49 @@ describe("runGatewayLoop", () => {
685688
await withIsolatedSignals(async ({ captureSignal }) => {
686689
const { close, start, runtime, exited } = await createSignaledLoopHarness();
687690
const sigterm = captureSignal("SIGTERM");
691+
const { emitDiagnosticsTimelineEvent, flushDiagnosticsTimeline } =
692+
await import("../../infra/diagnostics-timeline.js");
693+
const tempDirs = createTempDirTracker();
694+
const timelinePath = join(tempDirs.make("openclaw-gateway-stop-"), "timeline.jsonl");
695+
let timelineAtLogFlush: string | undefined;
696+
close.mockImplementationOnce(async () => {
697+
emitDiagnosticsTimelineEvent(
698+
{ type: "mark", name: "gateway.stop" },
699+
{
700+
env: {
701+
OPENCLAW_DIAGNOSTICS: "timeline",
702+
OPENCLAW_DIAGNOSTICS_TIMELINE_PATH: timelinePath,
703+
},
704+
},
705+
);
706+
});
688707
flushLogger.mockImplementationOnce(async () => {
689708
expect(runtime.exit).not.toHaveBeenCalled();
709+
timelineAtLogFlush = existsSync(timelinePath)
710+
? readFileSync(timelinePath, "utf8")
711+
: undefined;
690712
});
691713

692-
sigterm();
714+
try {
715+
sigterm();
693716

694-
await expect(exited).resolves.toBe(0);
695-
expect(close).toHaveBeenCalledWith({
696-
reason: "gateway stopping",
697-
restartExpectedMs: null,
698-
});
699-
expect(start).toHaveBeenCalledWith({
700-
startupStartedAt: expect.any(Number),
701-
requestHotReloadRecovery: requestGatewayRestartWithSignalAdmission,
702-
});
703-
expect(runtime.exit).toHaveBeenCalledWith(0);
704-
expect(flushLogger).toHaveBeenCalledOnce();
705-
expect(armShutdownHardExitWatchdog).not.toHaveBeenCalled();
717+
await expect(exited).resolves.toBe(0);
718+
expect(close).toHaveBeenCalledWith({
719+
reason: "gateway stopping",
720+
restartExpectedMs: null,
721+
});
722+
expect(start).toHaveBeenCalledWith({
723+
startupStartedAt: expect.any(Number),
724+
requestHotReloadRecovery: requestGatewayRestartWithSignalAdmission,
725+
});
726+
expect(runtime.exit).toHaveBeenCalledWith(0);
727+
expect(flushLogger).toHaveBeenCalledOnce();
728+
expect(timelineAtLogFlush).toContain('"name":"gateway.stop"');
729+
expect(armShutdownHardExitWatchdog).not.toHaveBeenCalled();
730+
} finally {
731+
flushDiagnosticsTimeline();
732+
tempDirs.cleanup();
733+
}
706734
});
707735
});
708736

‎src/cli/gateway-cli/run-loop.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
startGatewayRestartTrace,
1313
} from "../../gateway/restart-trace.js";
1414
import type { startGatewayServer } from "../../gateway/server.js";
15+
import { flushDiagnosticsTimeline } from "../../infra/diagnostics-timeline.js";
1516
import { formatErrorMessage } from "../../infra/errors.js";
1617
import {
1718
GATEWAY_BOOT_REASON_MAX_UTF16_CODE_UNITS,
@@ -175,6 +176,7 @@ export async function runGatewayLoop(params: {
175176
let ownerToCommit = initialOwner;
176177
let commitOutcome = initialOutcome;
177178
// Graceful signal/restart paths call process.exit(), which skips beforeExit.
179+
flushDiagnosticsTimeline();
178180
let flushTimer: ReturnType<typeof setTimeout> | undefined;
179181
const flushed = await Promise.race([
180182
flushLogger().then(() => true),

‎src/cli/plugin-registry-loader.test.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
import { readFile } from "node:fs/promises";
33
import { join } from "node:path";
44
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
5-
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
5+
import { createTempDirTracker } from "../../test/helpers/temp-dir.js";
6+
import { flushDiagnosticsTimeline } from "../infra/diagnostics-timeline.js";
67
import { measureCliCommandStartup } from "./command-startup-timing.js";
78

89
const ensurePluginRegistryLoadedMock = vi.hoisted(() => vi.fn());
910
const readRegistryMock = vi.hoisted(() =>
1011
vi.fn(async (): Promise<{ entries: Array<{ backendId?: string }> }> => ({ entries: [] })),
1112
);
12-
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
13+
const tempDirs = createTempDirTracker();
1314

1415
vi.mock("./plugin-registry.js", () => ({
1516
ensurePluginRegistryLoaded: ensurePluginRegistryLoadedMock,
@@ -37,6 +38,8 @@ describe("plugin-registry-loader", () => {
3738
});
3839

3940
afterEach(() => {
41+
flushDiagnosticsTimeline();
42+
tempDirs.cleanup();
4043
loggingState.forceConsoleToStderr = originalForceStderr;
4144
vi.unstubAllEnvs();
4245
});
@@ -125,6 +128,7 @@ describe("plugin-registry-loader", () => {
125128
}),
126129
);
127130

131+
flushDiagnosticsTimeline();
128132
const events = (await readFile(timelinePath, "utf8"))
129133
.trim()
130134
.split("\n")

‎src/cli/plugins-cli.marketplace-entries.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { mkdtemp, readFile } from "node:fs/promises";
33
import { tmpdir } from "node:os";
44
import path from "node:path";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6+
import { flushDiagnosticsTimeline } from "../infra/diagnostics-timeline.js";
67
import { ExpectedCliError, formatCliJsonFailure } from "./failure-output.js";
78
import { createHostedMarketplaceFeedFixture } from "./plugins-marketplace-feed.test-support.js";
89

@@ -54,6 +55,7 @@ async function createTimelinePath(): Promise<string> {
5455
}
5556

5657
async function readTimeline(pathname: string): Promise<Record<string, unknown>[]> {
58+
flushDiagnosticsTimeline();
5759
const content = await readFile(pathname, "utf8");
5860
return content
5961
.trim()
@@ -73,6 +75,7 @@ describe("plugins marketplace entries", () => {
7375
});
7476

7577
afterEach(() => {
78+
flushDiagnosticsTimeline();
7679
vi.unstubAllEnvs();
7780
});
7881

0 commit comments

Comments
 (0)