perf(startup): measure default resolve path and gate debug-capture imports (#131181)

The startup-memory CI gate injected its RSS hook via --import, which since
#128663 declines the dist ESM resolve fast path, so the gate measured a
non-default slow-resolution configuration (~400 MB on Blacksmith) instead of
what plain invocations pay (~243 MB). The bench now runs the launcher
in-process from a wrapper with a clean execArgv and self-reports max RSS at
exit.

CLI bootstrap also imported proxy-capture/runtime and coverage on every
non-help invocation even though capture init, finalize, and coverage warnings
all no-op unless OPENCLAW_DEBUG_PROXY_ENABLED/REQUIRE is set; the import graph
(sqlite capture store, proxyline, undici) now loads only when the env requests
capture. Config reads import the gateway-startup metadata module directly
instead of the facade that also re-exports the startup loader.
This commit is contained in:
Peter Steinberger authored and GitHub committed 2026-08-27 15:00:45 -07:00
1 parent a65668b9b7
commit f49d25052e
5 files changed
+61 -37

No files matched your search

+25 -19
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env node
// Measures CLI startup memory with an isolated home and RSS hook.
// Measures CLI startup memory with an isolated home and an in-process bench entry.
import { spawnSync as defaultSpawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
@@ -17,7 +17,7 @@ const COMMAND_TIMEOUT_MS = readPositiveIntEnv(
DEFAULT_COMMAND_TIMEOUT_MS,
);
let tmpHome = null;
let rssHookPath = null;
let benchEntryPath = null;
const PASS = "pass";
const FAIL = "fail";
function readPositiveIntEnv(name, fallback, env = process.env) {
@@ -226,8 +226,8 @@ function buildBenchEnv(homeDir = tmpHome) {
return env;
}
function runCaseSample(testCase, sampleIndex, params = {}) {
if (!rssHookPath) {
throw new Error("RSS hook path is not initialized");
if (!benchEntryPath) {
throw new Error("bench entry path is not initialized");
}
if (!tmpHome) {
throw new Error("temporary home is not initialized");
@@ -237,18 +237,14 @@ function runCaseSample(testCase, sampleIndex, params = {}) {
const env = buildBenchEnv(sampleHome);
const spawn = params.spawnSync ?? defaultSpawnSync;
const timeoutMs = params.timeoutMs ?? COMMAND_TIMEOUT_MS;
const result = spawn(
process.execPath,
["--import", nodeImportSpecifierForPath(rssHookPath), ...testCase.args],
{
cwd: repoRoot,
env,
encoding: "utf8",
maxBuffer: 20 * 1024 * 1024,
timeout: timeoutMs,
killSignal: "SIGKILL",
},
);
const result = spawn(process.execPath, [benchEntryPath, ...testCase.args.slice(1)], {
cwd: repoRoot,
env,
encoding: "utf8",
maxBuffer: 20 * 1024 * 1024,
timeout: timeoutMs,
killSignal: "SIGKILL",
});
const stderr = String(result.stderr ?? "");
const stdout = String(result.stdout ?? "");
const maxRssMb = parseMaxRssMb(stderr);
@@ -372,14 +368,24 @@ function runStartupMemoryCheck(argv = process.argv.slice(2), params = {}) {
}
const options = parseArgs(argv);
tmpHome = mkdtempSync(path.join(os.tmpdir(), "openclaw-startup-memory-"));
rssHookPath = path.join(tmpHome, "measure-rss.mjs");
benchEntryPath = path.join(tmpHome, "bench-entry.mjs");
// Run the real launcher in-process so peak RSS is self-reported at exit
// without --import/--require flags: the entry declines its dist ESM resolve
// fast path when preload hooks may be registered, so an injected hook would
// measure a slower non-default resolution configuration instead of what a
// plain `node openclaw.mjs ...` invocation pays.
const launcherPath = path.join(repoRoot, "openclaw.mjs");
writeFileSync(
rssHookPath,
benchEntryPath,
[
"process.on('exit', () => {",
" const usage = typeof process.resourceUsage === 'function' ? process.resourceUsage() : null;",
` if (usage && typeof usage.maxRSS === 'number') console.error('${MAX_RSS_MARKER}' + String(usage.maxRSS));`,
"});",
`const launcherPath = ${JSON.stringify(launcherPath)};`,
"// The launcher and entry expect argv[1] to be the launcher path itself.",
"process.argv[1] = launcherPath;",
`await import(${JSON.stringify(nodeImportSpecifierForPath(launcherPath))});`,
"",
].join("\n"),
"utf8",
@@ -394,7 +400,7 @@ function runStartupMemoryCheck(argv = process.argv.slice(2), params = {}) {
if (tmpHome) {
rmSync(tmpHome, { recursive: true, force: true });
tmpHome = null;
rssHookPath = null;
benchEntryPath = null;
}
}
const failure = results.find((result) => result.status !== "pass");
+3 -1
View File
@@ -3504,13 +3504,15 @@ describe("runCli exit behavior", () => {
const processOnceSpy = vi.spyOn(process, "once");
try {
const runPromise = runCli(["node", "openclaw", "plugins", "marketplace", "list"]);
// Only the managed-proxy kill hook registers here: the debug-capture
// finalize hook stays unloaded unless the capture env requests it.
await vi.waitFor(() => {
expect(
processOnceSpy.mock.calls.reduce(
(count, [event]) => count + (event === "exit" ? 1 : 0),
0,
),
).toBe(2);
).toBe(1);
});
const exitHandler = processOnceSpy.mock.calls.find(([event]) => event === "exit")?.[1];
+23 -14
View File
@@ -851,11 +851,15 @@ async function ensureCliEnvProxyDispatcher(): Promise<void> {
}
}
function shouldBootstrapCliProxyBeforeFastPath(env: NodeJS.ProcessEnv = process.env): boolean {
if (
function isDebugProxyCaptureEnvEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
return (
isTruthyEnvValue(env.OPENCLAW_DEBUG_PROXY_ENABLED) ||
isTruthyEnvValue(env.OPENCLAW_DEBUG_PROXY_REQUIRE)
) {
);
}
function shouldBootstrapCliProxyBeforeFastPath(env: NodeJS.ProcessEnv = process.env): boolean {
if (isDebugProxyCaptureEnvEnabled(env)) {
return true;
}
return CLI_PROXY_ENV_KEYS.some((key) => {
@@ -1032,20 +1036,25 @@ async function bootstrapCliProxyCaptureAndDispatcher(
startupTrace: ReturnType<typeof createGatewayDispatchStartupTrace>,
options: { ensureDispatcher?: boolean } = {},
): Promise<void> {
const [
{ initializeDebugProxyCapture, finalizeDebugProxyCapture },
{ maybeWarnAboutDebugProxyCoverage },
] = await startupTrace.measure("proxy-imports", () =>
Promise.all([import("../proxy-capture/runtime.js"), import("../proxy-capture/coverage.js")]),
);
initializeDebugProxyCapture("cli");
process.once("exit", () => {
finalizeDebugProxyCapture();
});
// Capture init, exit finalize, and coverage warnings all no-op unless the
// debug-proxy env requests capture; importing their sqlite-store graph anyway
// costs ~100 MB RSS on metadata-only commands such as `plugins list --json`.
if (isDebugProxyCaptureEnvEnabled()) {
const [
{ initializeDebugProxyCapture, finalizeDebugProxyCapture },
{ maybeWarnAboutDebugProxyCoverage },
] = await startupTrace.measure("proxy-imports", () =>
Promise.all([import("../proxy-capture/runtime.js"), import("../proxy-capture/coverage.js")]),
);
initializeDebugProxyCapture("cli");
process.once("exit", () => {
finalizeDebugProxyCapture();
});
maybeWarnAboutDebugProxyCoverage(undefined, (message) => console.warn(message));
}
if (options.ensureDispatcher !== false) {
await startupTrace.measure("proxy-dispatcher", () => ensureCliEnvProxyDispatcher());
}
maybeWarnAboutDebugProxyCoverage(undefined, (message) => console.warn(message));
}
export async function runCli(
+4 -1
View File
@@ -10,7 +10,10 @@ import {
shouldDeferShellEnvFallback,
shouldEnableShellEnvFallback,
} from "../infra/shell-env.js";
import { createConfigValidationMetadataPluginIdScope } from "../plugins/gateway-startup-plugin-ids.js";
// Import the metadata module directly: the gateway-startup-plugin-ids facade
// also re-exports the startup loader and embedding providers, which config
// reads must not drag into every CLI invocation.
import { createConfigValidationMetadataPluginIdScope } from "../plugins/gateway-startup-plugin-metadata.js";
import type { PluginManifestRegistry } from "../plugins/manifest-registry.js";
import {
rebasePluginMetadataSnapshotManifestRegistry,
@@ -335,8 +335,12 @@ describe("check-cli-startup-memory", () => {
expect(seenArgs).toHaveLength(testing.cases.length * testing.sampleCount);
expect(new Set(seenHomes).size).toBe(seenArgs.length);
for (const args of seenArgs) {
expect(args[0]).toBe("--import");
expect(args[1]).toMatch(/^file:/u);
// The bench entry runs the launcher in-process instead of preloading an
// --import hook, which would disable the dist ESM resolve fast path and
// measure a non-default resolution configuration.
expect(args[0]).toMatch(/bench-entry\.mjs$/u);
expect(args[0]).not.toBe("--import");
expect(args[1]).not.toBe("openclaw.mjs");
}
});
});