Skip to content

Commit c1ee660

Browse files
authored
perf(cli): trace startup phases in diagnostics (#117702)
1 parent 0e49684 commit c1ee660

4 files changed

Lines changed: 338 additions & 11 deletions

File tree

‎src/cli/run-main.ts‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,9 @@ async function tryRunGatewayRunFastPath(
249249
{ beforeRun },
250250
);
251251
try {
252-
await startupTrace.measure("gateway-run-parse", () => program.parseAsync(argv));
252+
await startupTrace.measure("gateway-run-parse", () => program.parseAsync(argv), {
253+
timeline: false,
254+
});
253255
} catch (error) {
254256
if (!isCommanderParseExit(error)) {
255257
throw error;
@@ -1190,6 +1192,17 @@ async function runCliWithPreparedOutputMode(
11901192
}
11911193
return await bestEffortConfigPromise;
11921194
};
1195+
const startupTraces = [startupTrace, options.additionalStartupTrace].filter(
1196+
(trace): trace is ReturnType<typeof createGatewayStartupTrace> => Boolean(trace),
1197+
);
1198+
if (
1199+
(await Promise.all(startupTraces.map((trace) => trace.requiresDiagnosticsConfig()))).some(
1200+
Boolean,
1201+
)
1202+
) {
1203+
const config = await withConsoleLogsRoutedToStderr(readBestEffortCliConfig);
1204+
await Promise.all(startupTraces.map((trace) => trace.configureDiagnosticsTimeline(config)));
1205+
}
11931206
if (
11941207
!isHelpOrVersionInvocation &&
11951208
normalizedInvocation.primary &&
@@ -1418,10 +1431,13 @@ async function runCliWithPreparedOutputMode(
14181431
}
14191432

14201433
const { tryRouteCli } = await startupTrace.measure("route-import", () => import("./route.js"));
1421-
const routed = await startupTrace.measure("route", () =>
1422-
options.builtInMachineOutput
1423-
? tryRouteCli(normalizedArgv, { machineOutput: true })
1424-
: tryRouteCli(normalizedArgv),
1434+
const routed = await startupTrace.measure(
1435+
"route",
1436+
() =>
1437+
options.builtInMachineOutput
1438+
? tryRouteCli(normalizedArgv, { machineOutput: true })
1439+
: tryRouteCli(normalizedArgv),
1440+
{ timeline: false },
14251441
);
14261442
if (routed) {
14271443
return;
@@ -1571,7 +1587,9 @@ async function runCliWithPreparedOutputMode(
15711587

15721588
let completedHelpOrVersion = false;
15731589
try {
1574-
await startupTrace.measure("parse", () => program.parseAsync(parseArgv));
1590+
await startupTrace.measure("parse", () => program.parseAsync(parseArgv), {
1591+
timeline: false,
1592+
});
15751593
completedHelpOrVersion = isHelpOrVersionInvocation;
15761594
} catch (error) {
15771595
if (!isCommanderParseExit(error)) {

‎src/cli/startup-trace.test.ts‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import type { OpenClawConfig } from "../config/types.openclaw.js";
6+
import { createGatewayStartupTrace } from "./startup-trace.js";
7+
8+
function readTimelineEvents(timelinePath: string): Record<string, unknown>[] {
9+
return fs
10+
.readFileSync(timelinePath, "utf8")
11+
.trim()
12+
.split("\n")
13+
.map((line) => JSON.parse(line) as Record<string, unknown>);
14+
}
15+
16+
describe("CLI startup trace", () => {
17+
afterEach(() => {
18+
vi.unstubAllEnvs();
19+
});
20+
21+
it("records entry marks and measured spans in the diagnostics timeline", async () => {
22+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-startup-trace-"));
23+
const timelinePath = path.join(dir, "timeline.jsonl");
24+
vi.stubEnv("OPENCLAW_DIAGNOSTICS", "timeline");
25+
vi.stubEnv("OPENCLAW_DIAGNOSTICS_TIMELINE_PATH", timelinePath);
26+
27+
const trace = createGatewayStartupTrace(["node", "openclaw", "agent", "--local"], "entry");
28+
trace.mark("bootstrap");
29+
await trace.measure("run-main-import", async () => {
30+
await Promise.resolve();
31+
});
32+
await expect(
33+
trace.measure("command-execution", async () => "done", { timeline: false }),
34+
).resolves.toBe("done");
35+
36+
const events = readTimelineEvents(timelinePath);
37+
expect(events).toEqual(
38+
expect.arrayContaining([
39+
expect.objectContaining({
40+
type: "mark",
41+
name: "entry.bootstrap",
42+
phase: "cli.startup",
43+
durationMs: expect.any(Number),
44+
attributes: expect.objectContaining({ totalMs: expect.any(Number) }),
45+
}),
46+
expect.objectContaining({
47+
type: "span.start",
48+
name: "entry.run-main-import",
49+
phase: "cli.startup",
50+
}),
51+
expect.objectContaining({
52+
type: "span.end",
53+
name: "entry.run-main-import",
54+
phase: "cli.startup",
55+
durationMs: expect.any(Number),
56+
}),
57+
]),
58+
);
59+
expect(events).not.toEqual(
60+
expect.arrayContaining([
61+
expect.objectContaining({
62+
name: "entry.command-execution",
63+
}),
64+
]),
65+
);
66+
});
67+
68+
it("flushes buffered startup phases when config enables the timeline", async () => {
69+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-startup-trace-config-"));
70+
const timelinePath = path.join(dir, "timeline.jsonl");
71+
vi.stubEnv("OPENCLAW_DIAGNOSTICS", "");
72+
vi.stubEnv("OPENCLAW_DIAGNOSTICS_TIMELINE_PATH", timelinePath);
73+
74+
const trace = createGatewayStartupTrace(["node", "openclaw", "agent", "--local"], "entry");
75+
trace.mark("bootstrap");
76+
await trace.measure("run-main-import", async () => "loaded");
77+
78+
expect(await trace.requiresDiagnosticsConfig()).toBe(true);
79+
expect(fs.existsSync(timelinePath)).toBe(false);
80+
81+
await trace.configureDiagnosticsTimeline({
82+
diagnostics: { flags: ["timeline"] },
83+
} as OpenClawConfig);
84+
85+
expect(readTimelineEvents(timelinePath)).toEqual(
86+
expect.arrayContaining([
87+
expect.objectContaining({
88+
type: "mark",
89+
name: "entry.bootstrap",
90+
phase: "cli.startup",
91+
}),
92+
expect.objectContaining({
93+
type: "span.end",
94+
name: "entry.run-main-import",
95+
phase: "cli.startup",
96+
durationMs: expect.any(Number),
97+
}),
98+
]),
99+
);
100+
});
101+
});

‎src/cli/startup-trace.ts‎

Lines changed: 178 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,47 @@
1-
// Shared gateway startup tracing for the entry wrapper and CLI dispatcher.
1+
// Shared startup tracing for the entry wrapper and CLI dispatcher.
22
import process from "node:process";
3+
import type { OpenClawConfig } from "../config/types.openclaw.js";
34
import { isTruthyEnvValue } from "../infra/env.js";
45

56
type GatewayStartupTraceSource = "entry" | "cli.main";
67
type GatewayStartupTraceLineFormatter = (message: string) => string;
8+
type DiagnosticsTimelineModule = typeof import("../infra/diagnostics-timeline.js");
9+
type StartupTraceMeasureOptions = {
10+
timeline?: boolean;
11+
};
12+
type PendingTimelineEvent =
13+
| {
14+
type: "mark";
15+
name: string;
16+
durationMs: number;
17+
totalMs: number;
18+
}
19+
| {
20+
type: "span";
21+
name: string;
22+
durationMs: number;
23+
};
24+
25+
const CLI_STARTUP_TIMELINE_PHASE = "cli.startup";
26+
27+
function hasDiagnosticsTimelinePath(env: NodeJS.ProcessEnv): boolean {
28+
return Boolean(env.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH?.trim());
29+
}
730

831
export function createGatewayStartupTrace(
932
argv: string[],
1033
source: GatewayStartupTraceSource,
1134
): {
1235
enabled: boolean;
36+
requiresDiagnosticsConfig(): Promise<boolean>;
37+
configureDiagnosticsTimeline(config: OpenClawConfig): Promise<void>;
1338
setLineFormatter(formatter: GatewayStartupTraceLineFormatter): void;
1439
mark(name: string): void;
15-
measure<T>(name: string, run: () => T | PromiseLike<T>): Promise<T>;
40+
measure<T>(
41+
name: string,
42+
run: () => T | PromiseLike<T>,
43+
options?: StartupTraceMeasureOptions,
44+
): Promise<T>;
1645
} {
1746
const enabled =
1847
isTruthyEnvValue(process.env.OPENCLAW_GATEWAY_STARTUP_TRACE) &&
@@ -21,6 +50,100 @@ export function createGatewayStartupTrace(
2150
let last = started;
2251
let lineFormatter: GatewayStartupTraceLineFormatter | null = null;
2352
let pendingMessages: string[] = [];
53+
const timelineModule = hasDiagnosticsTimelinePath(process.env)
54+
? import("../infra/diagnostics-timeline.js").catch(() => null)
55+
: null;
56+
let timelineActivation: "unknown" | "enabled" | "disabled" = timelineModule
57+
? "unknown"
58+
: "disabled";
59+
let timelineConfig: OpenClawConfig | undefined;
60+
let timelineConfigResolved = false;
61+
const pendingTimelineEvents: PendingTimelineEvent[] = [];
62+
let pendingTimelineWrites = Promise.resolve();
63+
const timelineName = (name: string) => `${source}.${name}`;
64+
const resolveTimelineActivation = async (): Promise<typeof timelineActivation> => {
65+
if (timelineActivation !== "unknown" || !timelineModule) {
66+
return timelineActivation;
67+
}
68+
const module = await timelineModule;
69+
if (!module) {
70+
timelineActivation = "disabled";
71+
return timelineActivation;
72+
}
73+
if (module.isDiagnosticsTimelineEnabled({ env: process.env })) {
74+
timelineActivation = "enabled";
75+
return timelineActivation;
76+
}
77+
if (timelineConfigResolved) {
78+
timelineActivation = module.isDiagnosticsTimelineEnabled({
79+
config: timelineConfig,
80+
env: process.env,
81+
})
82+
? "enabled"
83+
: "disabled";
84+
}
85+
return timelineActivation;
86+
};
87+
const writeTimelineEvent = (
88+
module: DiagnosticsTimelineModule,
89+
event: PendingTimelineEvent,
90+
): void => {
91+
const commonOptions = {
92+
...(timelineConfig ? { config: timelineConfig } : {}),
93+
env: process.env,
94+
};
95+
if (event.type === "mark") {
96+
module.emitDiagnosticsTimelineEvent(
97+
{
98+
type: "mark",
99+
name: event.name,
100+
phase: CLI_STARTUP_TIMELINE_PHASE,
101+
durationMs: event.durationMs,
102+
attributes: { totalMs: event.totalMs },
103+
},
104+
commonOptions,
105+
);
106+
return;
107+
}
108+
module.emitCompletedDiagnosticsTimelineSpan(event.name, event.durationMs, {
109+
phase: CLI_STARTUP_TIMELINE_PHASE,
110+
...commonOptions,
111+
});
112+
};
113+
const flushPendingTimelineEvents = async (): Promise<void> => {
114+
const activation = await resolveTimelineActivation();
115+
if (activation === "unknown") {
116+
return;
117+
}
118+
if (activation === "disabled") {
119+
pendingTimelineEvents.length = 0;
120+
return;
121+
}
122+
const module = await timelineModule;
123+
if (!module) {
124+
pendingTimelineEvents.length = 0;
125+
return;
126+
}
127+
const events = pendingTimelineEvents.splice(0);
128+
for (const event of events) {
129+
writeTimelineEvent(module, event);
130+
}
131+
};
132+
const enqueueTimelineEvent = (event: PendingTimelineEvent): void => {
133+
if (!timelineModule || timelineActivation === "disabled") {
134+
return;
135+
}
136+
if (timelineActivation === "unknown") {
137+
pendingTimelineEvents.push(event);
138+
return;
139+
}
140+
pendingTimelineWrites = pendingTimelineWrites.then(async () => {
141+
const module = await timelineModule;
142+
if (module) {
143+
writeTimelineEvent(module, event);
144+
}
145+
});
146+
};
24147
const flushPending = (formatter: GatewayStartupTraceLineFormatter) => {
25148
const queued = pendingMessages;
26149
pendingMessages = [];
@@ -55,22 +178,72 @@ export function createGatewayStartupTrace(
55178
};
56179
return {
57180
enabled,
181+
async requiresDiagnosticsConfig() {
182+
await flushPendingTimelineEvents();
183+
return timelineActivation === "unknown";
184+
},
185+
async configureDiagnosticsTimeline(config) {
186+
timelineConfig = config;
187+
timelineConfigResolved = true;
188+
await flushPendingTimelineEvents();
189+
await pendingTimelineWrites;
190+
},
58191
setLineFormatter(formatter) {
59192
lineFormatter = formatter;
60193
process.off("exit", flushPendingPlainOnExit);
61194
flushPending(formatter);
62195
},
63196
mark(name: string) {
64197
const now = performance.now();
65-
emit(name, now - last, now - started);
198+
const durationMs = now - last;
199+
const totalMs = now - started;
200+
emit(name, durationMs, totalMs);
201+
enqueueTimelineEvent({
202+
type: "mark",
203+
name: timelineName(name),
204+
durationMs,
205+
totalMs,
206+
});
66207
last = now;
67208
},
68-
async measure<T>(name: string, run: () => T | PromiseLike<T>): Promise<T> {
209+
async measure<T>(
210+
name: string,
211+
run: () => T | PromiseLike<T>,
212+
options: StartupTraceMeasureOptions = {},
213+
): Promise<T> {
69214
const before = performance.now();
215+
let bufferCompletedTimelineSpan = false;
216+
let completed = false;
70217
try {
71-
return await run();
218+
if (timelineModule && options.timeline !== false) {
219+
await flushPendingTimelineEvents();
220+
const module = await timelineModule;
221+
if (module && timelineActivation === "enabled") {
222+
await pendingTimelineWrites;
223+
return await module.measureDiagnosticsTimelineSpan(
224+
timelineName(name),
225+
() => Promise.resolve(run()),
226+
{
227+
phase: CLI_STARTUP_TIMELINE_PHASE,
228+
...(timelineConfig ? { config: timelineConfig } : {}),
229+
env: process.env,
230+
},
231+
);
232+
}
233+
bufferCompletedTimelineSpan = timelineActivation === "unknown";
234+
}
235+
const result = await run();
236+
completed = true;
237+
return result;
72238
} finally {
73239
const now = performance.now();
240+
if (bufferCompletedTimelineSpan && completed) {
241+
enqueueTimelineEvent({
242+
type: "span",
243+
name: timelineName(name),
244+
durationMs: now - before,
245+
});
246+
}
74247
emit(name, now - before, now - started);
75248
last = now;
76249
}

0 commit comments

Comments
 (0)