Skip to content

Commit 113805d

Browse files
authored
perf(plugins): reuse snapshot alias resolvers during startup (#134812)
* perf(plugins): reuse snapshot alias resolvers during startup * test: prepare cron migration readiness runtime before workers
1 parent f54f806 commit 113805d

7 files changed

Lines changed: 120 additions & 128 deletions

‎scripts/lib/vitest-build-prerequisites.mts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ const runtimeConsumers = [
3131
mode: "runtime",
3232
dir: "src/cli",
3333
},
34+
{
35+
file: "src/commands/doctor-config-preflight.process.test.ts",
36+
configs: ["test/vitest/vitest.commands.config.ts"],
37+
mode: "runtime",
38+
dir: "src/commands",
39+
},
3440
{
3541
file: "test/e2e/qa-lab/runtime/gateway-support-export-runtime.test.ts",
3642
configs: ["test/vitest/vitest.tooling.config.ts"],

‎src/commands/doctor-config-preflight.process.test.ts‎

Lines changed: 75 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import os from "node:os";
55
import path from "node:path";
66
import { DatabaseSync } from "node:sqlite";
77
import { afterAll, describe, expect, it } from "vitest";
8-
import { testing as openclawTestInstanceTesting } from "../../test/helpers/openclaw-test-instance.js";
8+
import { createOpenClawTestInstance } from "../../test/helpers/openclaw-test-instance.js";
99
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
1010
import { resolveGatewayLockDir } from "../config/paths.js";
1111
import type { OpenClawConfig } from "../config/types.openclaw.js";
@@ -16,7 +16,6 @@ import {
1616
ensureOpenClawAgentDatabaseSchema,
1717
OPENCLAW_AGENT_SCHEMA_VERSION,
1818
} from "../state/openclaw-agent-db.js";
19-
import { getFreePort } from "../test-utils/ports.js";
2019
import {
2120
createSourceRuntime,
2221
runIsolatedModuleScript,
@@ -384,104 +383,85 @@ describe("doctor invalid config process exit", () => {
384383
// Synchronous CLI probes must not consume neighboring cases' timeout budgets.
385384
describe("gateway startup-migration refusal", () => {
386385
it("quarantines every invalid legacy automation before Gateway readiness", async () => {
387-
const root = await fs.promises.realpath(tempDirs.make("openclaw-cron-upgrade-ready-"));
388-
const stateDir = path.join(root, "state");
389-
const configPath = path.join(root, "openclaw.json");
386+
const instance = await createOpenClawTestInstance({
387+
name: "cron-upgrade-ready",
388+
startTimeoutMs: 30_000,
389+
stopTimeoutMs: 1_500,
390+
env: {
391+
NODE_ENV: undefined,
392+
NO_COLOR: "1",
393+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
394+
OPENCLAW_HOME: undefined,
395+
OPENCLAW_NO_RESPAWN: "1",
396+
OPENCLAW_SKIP_CHANNELS: "1",
397+
OPENCLAW_TEST_FAST: "1",
398+
VITEST: undefined,
399+
// Preserve full startup; the shared fixture otherwise skips sidecar readiness.
400+
OPENCLAW_GATEWAY_TOKEN: process.env.OPENCLAW_GATEWAY_TOKEN,
401+
OPENCLAW_GATEWAY_PASSWORD: process.env.OPENCLAW_GATEWAY_PASSWORD,
402+
OPENCLAW_SKIP_PROVIDERS: process.env.OPENCLAW_SKIP_PROVIDERS,
403+
OPENCLAW_SKIP_GMAIL_WATCHER: process.env.OPENCLAW_SKIP_GMAIL_WATCHER,
404+
OPENCLAW_SKIP_CRON: process.env.OPENCLAW_SKIP_CRON,
405+
OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: process.env.OPENCLAW_SKIP_BROWSER_CONTROL_SERVER,
406+
OPENCLAW_SKIP_CANVAS_HOST: process.env.OPENCLAW_SKIP_CANVAS_HOST,
407+
OPENCLAW_TEST_MINIMAL_GATEWAY: process.env.OPENCLAW_TEST_MINIMAL_GATEWAY,
408+
},
409+
});
410+
const { env, port, stateDir } = instance;
390411
const storePath = path.join(stateDir, "cron", "jobs.json");
391-
const port = await getFreePort();
392-
const runtimeRoot = createSourceRuntime(root);
393-
const env: NodeJS.ProcessEnv = {
394-
...process.env,
395-
HOME: root,
396-
USERPROFILE: root,
397-
OPENCLAW_CONFIG_PATH: configPath,
398-
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
399-
OPENCLAW_NO_RESPAWN: "1",
400-
OPENCLAW_SKIP_CHANNELS: "1",
401-
OPENCLAW_STATE_DIR: stateDir,
402-
OPENCLAW_TEST_FAST: "1",
403-
NO_COLOR: "1",
404-
};
405-
delete env.NODE_ENV;
406-
delete env.OPENCLAW_HOME;
407-
delete env.VITEST;
408-
409-
fs.mkdirSync(path.dirname(storePath), { recursive: true });
410-
fs.writeFileSync(
411-
configPath,
412-
JSON.stringify({ gateway: { mode: "local", auth: { mode: "none" } } }),
413-
);
414-
const job = {
415-
name: "Legacy automation",
416-
enabled: true,
417-
createdAtMs: 1,
418-
updatedAtMs: 1,
419-
schedule: { kind: "cron", expr: "0 9 * * *" },
420-
sessionTarget: "main",
421-
wakeMode: "now",
422-
payload: { kind: "systemEvent", text: "tick" },
423-
state: {},
424-
};
425-
fs.writeFileSync(
426-
storePath,
427-
JSON.stringify({
428-
version: 1,
429-
jobs: [
430-
{ ...job, id: "valid-job" },
431-
{ ...job, id: "invalid-state-job", state: { nextRunAtMs: -1 } },
432-
{ ...job, id: "invalid-trigger-job", trigger: { script: [] } },
433-
],
434-
}),
435-
);
436-
const stdout = openclawTestInstanceTesting.createBoundedStringLog();
437-
const stderr = openclawTestInstanceTesting.createBoundedStringLog();
438-
const gateway = spawn(
439-
process.execPath,
440-
[
441-
"--preserve-symlinks",
442-
"--preserve-symlinks-main",
443-
"--import",
444-
"tsx",
445-
path.join(runtimeRoot, "src", "entry.ts"),
446-
"gateway",
447-
"run",
448-
"--allow-unconfigured",
449-
"--port",
450-
String(port),
451-
],
452-
{ cwd: runtimeRoot, env, stdio: ["ignore", "pipe", "pipe"] },
453-
);
454-
gateway.stdout.setEncoding("utf8");
455-
gateway.stderr.setEncoding("utf8");
456-
gateway.stdout.on("data", (chunk) => openclawTestInstanceTesting.appendLogChunk(stdout, chunk));
457-
gateway.stderr.on("data", (chunk) => openclawTestInstanceTesting.appendLogChunk(stderr, chunk));
458412

459413
try {
460-
await openclawTestInstanceTesting.waitForGatewayReady(gateway, stdout, stderr, port, 30_000);
461-
const response = await fetch(`http://127.0.0.1:${port}/readyz`);
462-
await expect(response.json()).resolves.toMatchObject({ ready: true, failing: [] });
463-
} finally {
464-
expect(
465-
await openclawTestInstanceTesting.stopGatewayProcess(gateway, Date.now() + 5_000, 1_500, {
466-
forceWindowsTree: true,
414+
// Readiness must use the migration fixture without extra hooks or Control UI settings.
415+
await instance.state.writeConfig({ gateway: { mode: "local", auth: { mode: "none" } } });
416+
fs.mkdirSync(path.dirname(storePath), { recursive: true });
417+
const job = {
418+
name: "Legacy automation",
419+
enabled: true,
420+
createdAtMs: 1,
421+
updatedAtMs: 1,
422+
schedule: { kind: "cron", expr: "0 9 * * *" },
423+
sessionTarget: "main",
424+
wakeMode: "now",
425+
payload: { kind: "systemEvent", text: "tick" },
426+
state: {},
427+
};
428+
fs.writeFileSync(
429+
storePath,
430+
JSON.stringify({
431+
version: 1,
432+
jobs: [
433+
{ ...job, id: "valid-job" },
434+
{ ...job, id: "invalid-state-job", state: { nextRunAtMs: -1 } },
435+
{ ...job, id: "invalid-trigger-job", trigger: { script: [] } },
436+
],
467437
}),
468-
).toBe(true);
469-
}
438+
);
470439

471-
const loaded = await loadCronJobsStoreWithConfigJobsReadOnly(storePath, env);
472-
expect(loaded.store.jobs.map((entry) => entry.id)).toContain("valid-job");
473-
expect(
474-
loadCronQuarantinedJobs(storePath, env).map((entry) => ({
475-
sourceIndex: entry.sourceIndex,
476-
reason: entry.reason,
477-
id: entry.job?.id,
478-
})),
479-
).toEqual([
480-
{ sourceIndex: 1, reason: "invalid-state", id: "invalid-state-job" },
481-
{ sourceIndex: 2, reason: "invalid-trigger", id: "invalid-trigger-job" },
482-
]);
483-
expect(fs.existsSync(storePath)).toBe(false);
484-
expect(fs.existsSync(`${storePath}.migrated`)).toBe(true);
440+
try {
441+
await instance.startGateway();
442+
const response = await fetch(`http://127.0.0.1:${port}/readyz`);
443+
await expect(response.json()).resolves.toMatchObject({ ready: true, failing: [] });
444+
} finally {
445+
await instance.stopGateway();
446+
}
447+
448+
const loaded = await loadCronJobsStoreWithConfigJobsReadOnly(storePath, env);
449+
expect(loaded.store.jobs.map((entry) => entry.id)).toContain("valid-job");
450+
expect(
451+
loadCronQuarantinedJobs(storePath, env).map((entry) => ({
452+
sourceIndex: entry.sourceIndex,
453+
reason: entry.reason,
454+
id: entry.job?.id,
455+
})),
456+
).toEqual([
457+
{ sourceIndex: 1, reason: "invalid-state", id: "invalid-state-job" },
458+
{ sourceIndex: 2, reason: "invalid-trigger", id: "invalid-trigger-job" },
459+
]);
460+
expect(fs.existsSync(storePath)).toBe(false);
461+
expect(fs.existsSync(`${storePath}.migrated`)).toBe(true);
462+
} finally {
463+
await instance.cleanup();
464+
}
485465
}, 45_000);
486466

487467
it("repairs the stable upgrade config and additive state schema before readiness", async () => {

‎src/plugins/gateway-startup-plugin-loader.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ export function loadGatewayStartupPluginPlanWithMetadata(params: GatewayStartupP
7979
index: metadataSnapshot.index,
8080
manifestRegistry: metadataSnapshot.manifestRegistry,
8181
discovery: metadataSnapshot.discovery,
82+
normalizePluginId: metadataSnapshot.normalizePluginId,
8283
workerProviderIds: params.workerProviderIds ?? [],
8384
platform: params.platform,
8485
ambientEnvTriggers: params.ambientEnvTriggers,

‎src/plugins/gateway-startup-plugin-plan.ts‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ import {
77
} from "../channels/config-presence.js";
88
import type { OpenClawConfig } from "../config/types.openclaw.js";
99
import { listGatewayActivatedChannelIds } from "./channel-presence-policy.js";
10+
import {
11+
normalizePluginsConfigWithResolverCore,
12+
type NormalizePluginId,
13+
} from "./config-normalization-shared.js";
1014
import { resolveEffectivePluginActivationState } from "./config-state.js";
1115
import { isPluginEnabledByDefaultForPlatform } from "./default-enablement.js";
1216
import type { PluginDiscoveryResult } from "./discovery.js";
@@ -33,10 +37,7 @@ import {
3337
} from "./gateway-startup-plugin-providers.js";
3438
import { collectConfiguredSpeechProviderIds } from "./gateway-startup-speech-providers.js";
3539
import type { PluginManifestRegistry } from "./manifest-registry.js";
36-
import {
37-
createPluginRegistryIdNormalizer,
38-
normalizePluginsConfigWithRegistry,
39-
} from "./plugin-registry-contributions.js";
40+
import { createPluginRegistryIdNormalizer } from "./plugin-registry-contributions.js";
4041
import type { PluginRegistrySnapshot } from "./plugin-registry-snapshot.js";
4142
import { collectConfiguredWorkerProviderIds } from "./worker-provider-config.js";
4243
import { normalizeWorkerProviderIds } from "./worker-provider-id.js";
@@ -56,6 +57,7 @@ export function resolveGatewayStartupPluginPlanFromRegistry(params: {
5657
env: NodeJS.ProcessEnv;
5758
index: PluginRegistrySnapshot;
5859
manifestRegistry: PluginManifestRegistry;
60+
normalizePluginId?: NormalizePluginId;
5961
workerProviderIds?: readonly string[];
6062
discovery?: PluginDiscoveryResult;
6163
platform?: NodeJS.Platform;
@@ -75,16 +77,19 @@ export function resolveGatewayStartupPluginPlanFromRegistry(params: {
7577
discovery: params.discovery,
7678
}),
7779
);
78-
const pluginsConfig = normalizePluginsConfigWithRegistry(params.config.plugins, params.index, {
79-
manifestRegistry: params.manifestRegistry,
80-
});
80+
const normalizePluginId =
81+
params.normalizePluginId ??
82+
createPluginRegistryIdNormalizer(params.index, { manifestRegistry: params.manifestRegistry });
83+
const pluginsConfig = normalizePluginsConfigWithResolverCore(
84+
params.config.plugins,
85+
normalizePluginId,
86+
);
8187
// Startup must classify allowlist exceptions against the raw config snapshot,
8288
// not the auto-enabled effective snapshot, or configured-only channels can be
8389
// misclassified as explicit enablement.
84-
const activationSourcePlugins = normalizePluginsConfigWithRegistry(
90+
const activationSourcePlugins = normalizePluginsConfigWithResolverCore(
8591
activationSourceConfig.plugins,
86-
params.index,
87-
{ manifestRegistry: params.manifestRegistry },
92+
normalizePluginId,
8893
);
8994
const activationSource = {
9095
plugins: activationSourcePlugins,
@@ -113,9 +118,6 @@ export function resolveGatewayStartupPluginPlanFromRegistry(params: {
113118
...collectConfiguredWorkerProviderIds(activationSourceConfig),
114119
...normalizeWorkerProviderIds(params.workerProviderIds ?? []),
115120
]);
116-
const normalizePluginId = createPluginRegistryIdNormalizer(params.index, {
117-
manifestRegistry: params.manifestRegistry,
118-
});
119121
const memorySlotStartupPluginId = resolveMemorySlotStartupPluginId({
120122
activationSourceConfig,
121123
activationSourcePlugins,

‎src/plugins/plugin-lookup-table.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ export function loadPluginLookUpTable(params: LoadPluginLookUpTableParams): Plug
6969
index,
7070
manifestRegistry,
7171
discovery: metadataSnapshot.discovery,
72+
normalizePluginId: metadataSnapshot.normalizePluginId,
7273
workerProviderIds,
7374
ambientEnvTriggers: params.ambientEnvTriggers,
7475
});

‎src/plugins/plugin-registry-id-normalizer.ts‎

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,6 @@ export type PluginRegistryIdNormalizerOptions = {
99
lookUpTable?: Pick<{ manifestRegistry: PluginManifestRegistry }, "manifestRegistry">;
1010
};
1111

12-
function normalizePluginRegistryAlias(value: string): string {
13-
return value.trim();
14-
}
15-
16-
function normalizePluginRegistryAliasKey(value: string): string {
17-
return normalizePluginRegistryAlias(value).toLowerCase();
18-
}
19-
2012
function collectObjectKeys(value: Record<string, unknown> | undefined): readonly string[] {
2113
return value ? Object.keys(value) : [];
2214
}
@@ -46,9 +38,9 @@ export function createPluginRegistryIdNormalizer(
4638
if (!plugin.pluginId) {
4739
continue;
4840
}
49-
const pluginId = normalizePluginRegistryAlias(plugin.pluginId);
41+
const pluginId = plugin.pluginId.trim();
5042
if (pluginId) {
51-
aliases.set(normalizePluginRegistryAliasKey(pluginId), plugin.pluginId);
43+
aliases.set(pluginId.toLowerCase(), plugin.pluginId);
5244
}
5345
}
5446
const registry =
@@ -58,24 +50,24 @@ export function createPluginRegistryIdNormalizer(
5850
index,
5951
includeDisabled: true,
6052
});
61-
for (const plugin of [...registry.plugins].toSorted((left, right) =>
53+
for (const plugin of registry.plugins.toSorted((left, right) =>
6254
left.id.localeCompare(right.id),
6355
)) {
64-
const pluginId = normalizePluginRegistryAlias(plugin.id);
56+
const pluginId = plugin.id.trim();
6557
if (!pluginId) {
6658
continue;
6759
}
68-
aliases.set(normalizePluginRegistryAliasKey(pluginId), plugin.id);
60+
aliases.set(pluginId.toLowerCase(), plugin.id);
6961
for (const alias of listPluginRegistryNormalizerAliases(plugin)) {
70-
const normalizedAlias = normalizePluginRegistryAlias(alias);
71-
const normalizedAliasKey = normalizePluginRegistryAliasKey(alias);
62+
const normalizedAlias = alias.trim();
63+
const normalizedAliasKey = normalizedAlias.toLowerCase();
7264
if (normalizedAlias && !aliases.has(normalizedAliasKey)) {
7365
aliases.set(normalizedAliasKey, pluginId);
7466
}
7567
}
7668
}
7769
return (pluginId: string) => {
78-
const trimmed = normalizePluginRegistryAlias(pluginId);
79-
return aliases.get(normalizePluginRegistryAliasKey(trimmed)) ?? trimmed;
70+
const trimmed = pluginId.trim();
71+
return aliases.get(trimmed.toLowerCase()) ?? trimmed;
8072
};
8173
}

‎test/scripts/ci-node-test-plan.test.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -389,8 +389,8 @@ describe("scripts/lib/ci-node-test-plan.mts", () => {
389389
runnerBackend: "hybrid",
390390
};
391391
const fallback = createNodeTestShardBundles(options);
392-
// The whole CLI group pays 77s of tests plus its 100s runtime build.
393-
// It must stay alone; all other non-dist fallback jobs remain within 150s.
392+
// CLI and Doctor config/state each need a runtime build before their workers.
393+
// Keep them separate; other non-dist fallback jobs remain within 150s.
394394
expect(
395395
fallback
396396
.filter((shard) => !shard.requiresDist)
@@ -400,7 +400,14 @@ describe("scripts/lib/ci-node-test-plan.mts", () => {
400400
pretestBuildMode: shard.pretestBuildMode,
401401
predictedSeconds: shard.predictedSeconds,
402402
})),
403-
).toEqual([{ groups: ["agentic-cli"], pretestBuildMode: "runtime", predictedSeconds: 177 }]);
403+
).toEqual([
404+
{ groups: ["agentic-cli"], pretestBuildMode: "runtime", predictedSeconds: 177 },
405+
{
406+
groups: ["agentic-commands-doctor-config-state"],
407+
pretestBuildMode: "runtime",
408+
predictedSeconds: 158,
409+
},
410+
]);
404411
const agentChatStripes = fallback
405412
.flatMap((shard) => shard.groups)
406413
.filter((group) => group.shard_name.startsWith("agentic-control-plane-agent-chat-hosted-"));
@@ -1588,6 +1595,9 @@ describe("scripts/lib/ci-node-test-plan.mts", () => {
15881595
checkName: `checks-node-${shard.shardName}`,
15891596
configs: ["test/vitest/vitest.commands.config.ts"],
15901597
includePatterns: shard.includePatterns,
1598+
...(shard.shardName === "agentic-commands-doctor-config-state"
1599+
? { pretestBuildMode: "runtime" }
1600+
: {}),
15911601
requiresDist: false,
15921602
runner: DEFAULT_NODE_TEST_RUNNER,
15931603
shardName: shard.shardName,

0 commit comments

Comments
 (0)