Skip to content

Commit 20e2117

Browse files
committed
fix(agents): trace slow embedded run startup stages
1 parent bbf985d commit 20e2117

5 files changed

Lines changed: 202 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ Docs: https://docs.openclaw.ai
2323
- CLI/models: restore provider-filtered `models list --all --provider <id>` rows for providers without manifest/static catalog coverage, including Anthropic and Amazon Bedrock, while keeping the compatibility fallback off expensive availability and resolver paths. Thanks @shakkernerd.
2424
- CLI/tools: keep the Gateway `tools.*` RPC namespace out of plugin command discovery and managed proxy startup, so stray commands like `openclaw tools effective` fail quickly instead of cold-loading plugin metadata. Refs #73477. Thanks @oromeis.
2525
- CLI/status: keep default text `openclaw status --usage` on metadata-only channel scans unless `--deep` or `--all` is set, and send stray `openclaw tools --help` through the precomputed root-help fast path so latency-triage commands avoid plugin/runtime cold loads before printing. Refs #73477 and #74220. Thanks @oromeis and @NianJiuZst.
26+
- Agents/diagnostics: log slow embedded-run startup and preparation stage timings before model I/O, so Docker/VPS latency reports can identify whether plugin loading, auth/model resolution, tool inventory, bootstrap, MCP/LSP, resource loading, or stream setup is dominating pre-run latency. Refs #73428. Thanks @Dimaoggg, @quangtran88, and @Heyvhuang.
2627
- Plugins/runtime-deps: memoize packaged bundled runtime dist-mirror preparation after the first successful pass while keeping source-checkout mirrors refreshable, so constrained Docker/VPS installs avoid repeated root scans before chat turns. Refs #73428, #73421, #73532, and #73477. Thanks @Dimaoggg, @oromeis, @oadiazp, @jmfraga, @bstanbury, @antoniusfelix, and @jkobject.
2728
- Channels/Discord: treat bare numeric outbound targets that match the effective Discord DM allowlist as user DMs while preserving account-specific legacy `dm.allowFrom` precedence over inherited root `allowFrom`. (#74303) Thanks @Squirbie.
2829
- Control UI: make the chat sidebar split divider focusable, keyboard-resizable, ARIA-described, and pointer-event based so sidebar resizing works without a mouse. Thanks @BunsDev.

‎src/agents/pi-embedded-runner/run.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,11 @@ import { log } from "./logger.js";
9090
import { resolveModelAsync } from "./model.js";
9191
import { createEmbeddedRunReplayState, observeReplayMetadata } from "./replay-state.js";
9292
import { handleAssistantFailover } from "./run/assistant-failover.js";
93+
import {
94+
createEmbeddedRunStageTracker,
95+
formatEmbeddedRunStageSummary,
96+
shouldEmitEmbeddedRunStageSummary,
97+
} from "./run/attempt-stage-timing.js";
9398
import { forgetPromptBuildDrainCacheForRun } from "./run/attempt.prompt-helpers.js";
9499
import { createEmbeddedRunAuthController } from "./run/auth-controller.js";
95100
import { resolveAuthProfileFailureReason } from "./run/auth-profile-failure-policy.js";
@@ -324,6 +329,20 @@ export async function runEmbeddedPiAgent(
324329
return enqueueGlobal(async () => {
325330
throwIfAborted();
326331
const started = Date.now();
332+
const startupStages = createEmbeddedRunStageTracker();
333+
let startupStagesEmitted = false;
334+
const emitStartupStageSummary = (phase: string) => {
335+
const summary = startupStages.snapshot();
336+
const message = formatEmbeddedRunStageSummary(
337+
`embedded run startup stages: runId=${params.runId} sessionId=${params.sessionId} phase=${phase}`,
338+
summary,
339+
);
340+
if (shouldEmitEmbeddedRunStageSummary(summary)) {
341+
log.warn(message);
342+
} else if (log.isEnabled("debug")) {
343+
log.debug(message);
344+
}
345+
};
327346
params.onExecutionStarted?.();
328347
const workspaceResolution = resolveRunWorkspaceDir({
329348
workspaceDir: params.workspaceDir,
@@ -344,11 +363,13 @@ export async function runEmbeddedPiAgent(
344363
`[workspace-fallback] caller=runEmbeddedPiAgent reason=${workspaceResolution.fallbackReason} run=${params.runId} session=${redactedSessionId} sessionKey=${redactedSessionKey} agent=${workspaceResolution.agentId} workspace=${redactedWorkspace}`,
345364
);
346365
}
366+
startupStages.mark("workspace");
347367
ensureRuntimePluginsLoaded({
348368
config: params.config,
349369
workspaceDir: resolvedWorkspace,
350370
allowGatewaySubagentBinding: params.allowGatewaySubagentBinding,
351371
});
372+
startupStages.mark("runtime-plugins");
352373

353374
let provider = (params.provider ?? DEFAULT_PROVIDER).trim() || DEFAULT_PROVIDER;
354375
let modelId = (params.model ?? DEFAULT_MODEL).trim() || DEFAULT_MODEL;
@@ -407,6 +428,7 @@ export async function runEmbeddedPiAgent(
407428
provider = hookSelection.provider;
408429
modelId = hookSelection.modelId;
409430
const legacyBeforeAgentStartResult = hookSelection.legacyBeforeAgentStartResult;
431+
startupStages.mark("hooks");
410432
const agentHarness = selectAgentHarness({
411433
provider,
412434
modelId,
@@ -453,6 +475,7 @@ export async function runEmbeddedPiAgent(
453475
});
454476
const ctxInfo = resolvedRuntimeModel.ctxInfo;
455477
let effectiveModel = resolvedRuntimeModel.effectiveModel;
478+
startupStages.mark("model-resolution");
456479

457480
const authStore = pluginHarnessOwnsTransport
458481
? createEmptyAuthProfileStore()
@@ -611,6 +634,7 @@ export async function runEmbeddedPiAgent(
611634
} else if (lockedProfileId) {
612635
lastProfileId = lockedProfileId;
613636
}
637+
startupStages.mark("auth");
614638
const { sessionAgentId } = resolveSessionAgentIds({
615639
sessionKey: params.sessionKey,
616640
config: params.config,
@@ -745,6 +769,7 @@ export async function runEmbeddedPiAgent(
745769
agentDir,
746770
workspaceDir: resolvedWorkspace,
747771
});
772+
startupStages.mark("context-engine");
748773
try {
749774
let activeSessionId = params.sessionId;
750775
let activeSessionFile = params.sessionFile;
@@ -892,6 +917,11 @@ export async function runEmbeddedPiAgent(
892917
fastMode: params.fastMode,
893918
},
894919
});
920+
if (!startupStagesEmitted) {
921+
startupStages.mark("attempt-dispatch");
922+
emitStartupStageSummary("attempt-dispatch");
923+
startupStagesEmitted = true;
924+
}
895925

896926
const rawAttempt = await runEmbeddedAttemptWithBackend({
897927
sessionId: activeSessionId,
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { describe, expect, it } from "vitest";
2+
import {
3+
createEmbeddedRunStageTracker,
4+
formatEmbeddedRunStageSummary,
5+
shouldEmitEmbeddedRunStageSummary,
6+
} from "./attempt-stage-timing.js";
7+
8+
describe("embedded run stage timing", () => {
9+
it("captures stage duration and elapsed time", () => {
10+
let clock = 10;
11+
const tracker = createEmbeddedRunStageTracker({ now: () => clock });
12+
13+
clock = 25;
14+
tracker.mark("workspace");
15+
clock = 40;
16+
tracker.mark("tools");
17+
clock = 45;
18+
19+
expect(tracker.snapshot()).toEqual({
20+
totalMs: 35,
21+
stages: [
22+
{ name: "workspace", durationMs: 15, elapsedMs: 15 },
23+
{ name: "tools", durationMs: 15, elapsedMs: 30 },
24+
],
25+
});
26+
});
27+
28+
it("emits only slow stage summaries", () => {
29+
expect(
30+
shouldEmitEmbeddedRunStageSummary(
31+
{
32+
totalMs: 1_999,
33+
stages: [{ name: "auth", durationMs: 999, elapsedMs: 999 }],
34+
},
35+
{ totalThresholdMs: 2_000, stageThresholdMs: 1_000 },
36+
),
37+
).toBe(false);
38+
expect(
39+
shouldEmitEmbeddedRunStageSummary(
40+
{
41+
totalMs: 2_000,
42+
stages: [{ name: "auth", durationMs: 10, elapsedMs: 10 }],
43+
},
44+
{ totalThresholdMs: 2_000, stageThresholdMs: 1_000 },
45+
),
46+
).toBe(true);
47+
expect(
48+
shouldEmitEmbeddedRunStageSummary(
49+
{
50+
totalMs: 10,
51+
stages: [{ name: "auth", durationMs: 1_000, elapsedMs: 1_000 }],
52+
},
53+
{ totalThresholdMs: 2_000, stageThresholdMs: 1_000 },
54+
),
55+
).toBe(true);
56+
});
57+
58+
it("formats summaries compactly for logs", () => {
59+
expect(
60+
formatEmbeddedRunStageSummary("embedded run startup stages: runId=r1", {
61+
totalMs: 80,
62+
stages: [
63+
{ name: "workspace", durationMs: 25, elapsedMs: 25 },
64+
{ name: "tools", durationMs: 55, elapsedMs: 80 },
65+
],
66+
}),
67+
).toBe(
68+
"embedded run startup stages: runId=r1 totalMs=80 stages=workspace:25ms@25ms,tools:55ms@80ms",
69+
);
70+
});
71+
});
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
export type EmbeddedRunStageTiming = {
2+
name: string;
3+
durationMs: number;
4+
elapsedMs: number;
5+
};
6+
7+
export type EmbeddedRunStageSummary = {
8+
totalMs: number;
9+
stages: EmbeddedRunStageTiming[];
10+
};
11+
12+
export type EmbeddedRunStageTracker = {
13+
mark: (name: string) => void;
14+
snapshot: () => EmbeddedRunStageSummary;
15+
};
16+
17+
export function createEmbeddedRunStageTracker(options?: {
18+
now?: () => number;
19+
}): EmbeddedRunStageTracker {
20+
const now = options?.now ?? Date.now;
21+
const startedAt = now();
22+
let previousAt = startedAt;
23+
const stages: EmbeddedRunStageTiming[] = [];
24+
25+
const toMs = (value: number) => Math.max(0, Math.round(value));
26+
27+
return {
28+
mark(name) {
29+
const currentAt = now();
30+
stages.push({
31+
name,
32+
durationMs: toMs(currentAt - previousAt),
33+
elapsedMs: toMs(currentAt - startedAt),
34+
});
35+
previousAt = currentAt;
36+
},
37+
snapshot() {
38+
return {
39+
totalMs: toMs(now() - startedAt),
40+
stages: stages.slice(),
41+
};
42+
},
43+
};
44+
}
45+
46+
export function shouldEmitEmbeddedRunStageSummary(
47+
summary: EmbeddedRunStageSummary,
48+
options?: {
49+
totalThresholdMs?: number;
50+
stageThresholdMs?: number;
51+
},
52+
): boolean {
53+
const totalThresholdMs = options?.totalThresholdMs ?? 2_000;
54+
const stageThresholdMs = options?.stageThresholdMs ?? 1_000;
55+
return (
56+
summary.totalMs >= totalThresholdMs ||
57+
summary.stages.some((stage) => stage.durationMs >= stageThresholdMs)
58+
);
59+
}
60+
61+
export function formatEmbeddedRunStageSummary(
62+
prefix: string,
63+
summary: EmbeddedRunStageSummary,
64+
): string {
65+
const stages =
66+
summary.stages.length > 0
67+
? summary.stages
68+
.map((stage) => `${stage.name}:${stage.durationMs}ms@${stage.elapsedMs}ms`)
69+
.join(",")
70+
: "none";
71+
return `${prefix} totalMs=${summary.totalMs} stages=${stages}`;
72+
}

‎src/agents/pi-embedded-runner/run/attempt.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,11 @@ import {
242242
shouldRotateCompactionTranscript,
243243
} from "../compaction-successor-transcript.js";
244244
import { configureEmbeddedAttemptHttpRuntime } from "./attempt-http-runtime.js";
245+
import {
246+
createEmbeddedRunStageTracker,
247+
formatEmbeddedRunStageSummary,
248+
shouldEmitEmbeddedRunStageSummary,
249+
} from "./attempt-stage-timing.js";
245250
import {
246251
assembleAttemptContextEngine,
247252
buildLoopPromptCacheInfo,
@@ -589,6 +594,19 @@ export async function runEmbeddedAttempt(
589594
log.debug(
590595
`embedded run start: runId=${params.runId} sessionId=${params.sessionId} provider=${params.provider} model=${params.modelId} thinking=${params.thinkLevel} messageChannel=${params.messageChannel ?? params.messageProvider ?? "unknown"}`,
591596
);
597+
const prepStages = createEmbeddedRunStageTracker();
598+
const emitPrepStageSummary = (phase: string) => {
599+
const summary = prepStages.snapshot();
600+
const message = formatEmbeddedRunStageSummary(
601+
`embedded run prep stages: runId=${params.runId} sessionId=${params.sessionId} phase=${phase}`,
602+
summary,
603+
);
604+
if (shouldEmitEmbeddedRunStageSummary(summary)) {
605+
log.warn(message);
606+
} else if (log.isEnabled("debug")) {
607+
log.debug(message);
608+
}
609+
};
592610

593611
await fs.mkdir(resolvedWorkspace, { recursive: true });
594612

@@ -610,6 +628,7 @@ export async function runEmbeddedAttempt(
610628
config: params.config,
611629
agentId: params.agentId,
612630
});
631+
prepStages.mark("workspace-sandbox");
613632

614633
let restoreSkillEnv: (() => void) | undefined;
615634
let aborted = Boolean(params.abortSignal?.aborted);
@@ -645,6 +664,7 @@ export async function runEmbeddedAttempt(
645664
workspaceDir: effectiveWorkspace,
646665
agentId: sessionAgentId,
647666
});
667+
prepStages.mark("skills");
648668

649669
const sessionLabel = params.sessionKey ?? params.sessionId;
650670
const contextInjectionMode = resolveContextInjectionMode(params.config);
@@ -760,6 +780,7 @@ export async function runEmbeddedAttempt(
760780
});
761781
return applyEmbeddedAttemptToolsAllow(allTools, params.toolsAllow);
762782
})();
783+
prepStages.mark("core-plugin-tools");
763784
const toolsEnabled = supportsModelTools(params.model);
764785
const bootstrapHasFileAccess = toolsEnabled && toolsRaw.some((tool) => tool.name === "read");
765786
const bootstrapRouting = await resolveAttemptWorkspaceBootstrapRouting({
@@ -803,6 +824,7 @@ export async function runEmbeddedAttempt(
803824
runKind: params.bootstrapContextRunKind,
804825
}),
805826
});
827+
prepStages.mark("bootstrap-context");
806828
const remappedContextFiles = remapInjectedContextFilesToWorkspace({
807829
files: resolvedContextFiles,
808830
sourceWorkspaceDir: resolvedWorkspace,
@@ -935,6 +957,7 @@ export async function runEmbeddedAttempt(
935957
warn: (message) => log.warn(message),
936958
});
937959
const effectiveTools = [...tools, ...filteredBundledTools];
960+
prepStages.mark("bundle-tools");
938961
const allowedToolNames = collectAllowedToolNames({
939962
tools: effectiveTools,
940963
clientTools,
@@ -1221,6 +1244,7 @@ export async function runEmbeddedAttempt(
12211244
bootstrapMode,
12221245
contextFiles: remappedContextFiles,
12231246
});
1247+
prepStages.mark("system-prompt");
12241248

12251249
// Keep the session lock scoped to transcript/session mutations. Cold plugin
12261250
// and tool setup can be slow, and holding the lock there blocks CLI fallback
@@ -1345,6 +1369,7 @@ export async function runEmbeddedAttempt(
13451369
cfg: params.config,
13461370
contextTokenBudget: params.contextTokenBudget,
13471371
});
1372+
prepStages.mark("session-resource-loader");
13481373

13491374
// Get hook runner early so it's available when creating tools
13501375
const hookRunner = getGlobalHookRunner();
@@ -1441,6 +1466,7 @@ export async function runEmbeddedAttempt(
14411466
}
14421467
session.setActiveToolsByName(sessionToolAllowlist);
14431468
const activeSession = session;
1469+
prepStages.mark("agent-session");
14441470
if (isRawModelRun) {
14451471
// Raw model probes should measure exactly the requested prompt against
14461472
// the selected provider/model. Reset clears restored transcript state
@@ -1692,6 +1718,8 @@ export async function runEmbeddedAttempt(
16921718
`(${params.provider}/${params.modelId})`,
16931719
);
16941720
}
1721+
prepStages.mark("stream-setup");
1722+
emitPrepStageSummary("stream-ready");
16951723

16961724
const cacheObservabilityEnabled = Boolean(cacheTrace) || log.isEnabled("debug");
16971725
const promptCacheToolNames = collectPromptCacheToolNames(

0 commit comments

Comments
 (0)