Skip to content

Commit f40e5f2

Browse files
authored
fix(test): prepare runtime before plugin batch readers (#131778)
1 parent a696e4f commit f40e5f2

10 files changed

Lines changed: 592 additions & 152 deletions

‎scripts/lib/extension-test-plan.mts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,7 @@ export function resolveExtensionTestPlan(params: { cwd?: string; targetArg?: str
406406

407407
type ResolvedExtensionTestPlan = ReturnType<typeof resolveExtensionTestPlan>;
408408

409-
function mergeTestPlans(plans: ResolvedExtensionTestPlan[]): ExtensionBatchPlan {
409+
export function mergeExtensionTestPlans(plans: ResolvedExtensionTestPlan[]): ExtensionBatchPlan {
410410
const groupsByConfig = new Map<string, ExtensionTestPlanGroup>();
411411

412412
const testPlans = plans.filter((plan) => plan.hasTests);
@@ -462,7 +462,9 @@ export function resolveExtensionBatchPlan(params: { cwd?: string; extensionIds?:
462462
resolveExtensionTestPlan({ cwd, targetArg: extensionId }),
463463
);
464464

465-
return mergeTestPlans(hasExplicitExtensionIds ? plans : plans.filter((plan) => plan.hasTests));
465+
return mergeExtensionTestPlans(
466+
hasExplicitExtensionIds ? plans : plans.filter((plan) => plan.hasTests),
467+
);
466468
}
467469

468470
type PendingExtensionTestShard = {
@@ -523,7 +525,7 @@ export function createExtensionTestShards(
523525
Object.assign(
524526
{},
525527
{ index, checkName: `checks-node-extensions-shard-${index + 1}` },
526-
mergeTestPlans(shard.plans),
528+
mergeExtensionTestPlans(shard.plans),
527529
),
528530
)
529531
.filter((shard) => shard.hasTests);

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

Lines changed: 58 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
import { spawn } from "node:child_process";
2-
import { matchesGlob } from "node:path";
2+
import path from "node:path";
3+
import { matchesVitestCliSelection } from "../../test/vitest/vitest.pattern-file.ts";
34
import { fullSuiteVitestShards } from "../../test/vitest/vitest.test-shards.mjs";
5+
import { runManagedCommand } from "./managed-child-process.mts";
46

57
export type VitestPretestBuildMode = "private-qa" | "runtime";
68
type SetupCommandRunner = (args: string[], env: NodeJS.ProcessEnv) => Promise<number>;
79

810
type TestSelection = {
911
configs?: readonly string[];
1012
includePatterns?: readonly string[] | null;
13+
cli?: { args: string[]; dir: string; env: NodeJS.ProcessEnv };
1114
};
1215

1316
// These process tests consume built runtime artifacts. Prepare their strongest
@@ -19,41 +22,80 @@ const runtimeConsumers = [
1922
file: "extensions/qa-lab/src/suite-process-lifecycle.test.ts",
2023
configs: ["test/vitest/vitest.extension-qa.config.ts"],
2124
mode: "private-qa",
25+
dir: "extensions",
2226
},
2327
{
2428
file: "test/e2e/qa-lab/runtime/gateway-support-export-runtime.test.ts",
2529
configs: ["test/vitest/vitest.tooling.config.ts"],
2630
mode: "runtime",
31+
dir: "",
2732
},
2833
{
2934
file: "src/gateway/gateway-concurrent-streams.test.ts",
3035
configs: ["test/vitest/vitest.gateway-core.config.ts", "test/vitest/vitest.gateway.config.ts"],
3136
mode: "runtime",
37+
dir: "src/gateway",
3238
},
3339
] as const;
3440

41+
function includesRuntimeConfig(configs: readonly string[] | undefined, config: string) {
42+
return configs?.some(
43+
(selected) =>
44+
selected === config ||
45+
selected === "vitest.config.ts" ||
46+
selected === "test/vitest/vitest.config.ts" ||
47+
fullSuiteVitestShards.some(
48+
(shard) => shard.config === selected && shard.projects.includes(config),
49+
),
50+
);
51+
}
52+
53+
export function resolveVitestRuntimeCliSelections(
54+
config: string,
55+
args: string[],
56+
env: NodeJS.ProcessEnv,
57+
): TestSelection[] {
58+
return runtimeConsumers
59+
.filter((consumer) =>
60+
consumer.configs.some((candidate) => includesRuntimeConfig([config], candidate)),
61+
)
62+
.map((consumer) => ({ configs: consumer.configs, cli: { args, dir: consumer.dir, env } }));
63+
}
64+
3565
export function resolveVitestPretestBuildMode(
3666
selections: readonly TestSelection[],
3767
): VitestPretestBuildMode | undefined {
3868
return runtimeConsumers.find(({ file, configs: consumerConfigs }) =>
39-
selections.some(({ configs, includePatterns }) =>
40-
includePatterns
41-
? includePatterns.some((pattern) => matchesGlob(file, pattern))
42-
: configs?.some(
43-
(selected) =>
44-
consumerConfigs.some((config) => selected === config) ||
45-
selected === "vitest.config.ts" ||
46-
selected === "test/vitest/vitest.config.ts" ||
47-
fullSuiteVitestShards.some(
48-
(shard) =>
49-
shard.config === selected &&
50-
consumerConfigs.some((config) => shard.projects.includes(config)),
51-
),
52-
),
53-
),
69+
selections.some(({ configs, includePatterns, cli }) => {
70+
const included = includePatterns
71+
? includePatterns.some((pattern) => path.matchesGlob(file, pattern))
72+
: consumerConfigs.some((config) => includesRuntimeConfig(configs, config));
73+
// Only project the canonical consumers; config loading and test discovery
74+
// stay with Vitest. Include-file overrides still intersect emitted filters.
75+
return cli
76+
? matchesVitestCliSelection(file, included ? [file] : [], cli.args, cli.dir, cli.env)
77+
: included;
78+
}),
5479
)?.mode;
5580
}
5681

82+
export async function prepareVitestRuntime(
83+
selections: readonly TestSelection[],
84+
env: NodeJS.ProcessEnv = process.env,
85+
): Promise<number> {
86+
const mode = resolveVitestPretestBuildMode(selections);
87+
if (!mode) {
88+
return 0;
89+
}
90+
console.error(`[test] preparing ${mode} runtime before Vitest workers`);
91+
return runManagedCommand({
92+
bin: process.execPath,
93+
args: ["scripts/run-node.mjs", "--version"],
94+
cwd: path.resolve(import.meta.dirname, "../.."),
95+
env: { ...env, ...(mode === "private-qa" ? { OPENCLAW_BUILD_PRIVATE_QA: "1" } : {}) },
96+
});
97+
}
98+
5799
export function isE2eBuildSkipped(env: NodeJS.ProcessEnv) {
58100
return env.OPENCLAW_E2E_SKIP_BUILD === "1" || env.OPENCLAW_E2E_USE_PREBUILT_DIST === "1";
59101
}

‎scripts/run-vitest.mts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ import { createGatewayServerTestTargetChunks } from "./lib/gateway-server-test-p
2020
import { signalExitCode } from "./lib/managed-child-process.mts";
2121
import { resolveRepoRoot } from "./lib/repo-root.mjs";
2222
import { spawnTestProjectsRunner } from "./lib/test-projects-delegation.mts";
23+
import {
24+
resolveVitestRuntimeCliSelections,
25+
prepareVitestRuntime,
26+
} from "./lib/vitest-build-prerequisites.mts";
2327
import { resolveVitestProcessEnv } from "./lib/vitest-process-env.mts";
2428
import {
2529
createVitestUnhandledErrorDetector,
@@ -1410,6 +1414,29 @@ async function main(
14101414

14111415
const vitestArgs = resolveImplicitVitestArgs(argv);
14121416
const invocations = resolveBoundedVitestInvocations(vitestArgs, { env });
1417+
const config = resolveVitestConfigArg(vitestArgs);
1418+
const relativeConfig = config ? toRepoRelativeArg(path.resolve(config), repoRoot) : "";
1419+
// Canonical configs have known project scopes. Custom roots/projects keep
1420+
// their own setup; never infer their runtime selection from a config name.
1421+
if (
1422+
config &&
1423+
!hasAlternateVitestRootArg(vitestArgs) &&
1424+
!hasExplicitVitestProjectArg(vitestArgs) &&
1425+
!hasNonRunVitestSubcommand(vitestArgs) &&
1426+
!hasExplicitDisabledRunFlag(vitestArgs) &&
1427+
!vitestArgs.some((arg) => ["--help", "-h", "--version", "-v"].includes(arg))
1428+
) {
1429+
const code = await prepareVitestRuntime(
1430+
invocations.flatMap((cliArgs) =>
1431+
resolveVitestRuntimeCliSelections(relativeConfig, cliArgs, env),
1432+
),
1433+
env,
1434+
);
1435+
if (code !== 0) {
1436+
process.exitCode = code;
1437+
return;
1438+
}
1439+
}
14131440
let vitestCliEntry;
14141441
try {
14151442
vitestCliEntry = resolveVitestCliEntry();

‎scripts/test-extension-batch.mts‎

Lines changed: 67 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// Runs grouped Vitest plans for one or more bundled plugins.
44
import path from "node:path";
55
import pMap from "p-map";
6+
import { collectVitestExcludePatterns } from "../test/vitest/vitest.pattern-file.ts";
67
import {
78
createExtensionTestProcessTargetChunks,
89
listExtensionTestFilesForRoots,
@@ -19,6 +20,7 @@ import {
1920
import { parsePositiveInt } from "./lib/numeric-options.mjs";
2021
import { isDirectScriptRun, runVitestBatch } from "./lib/vitest-batch-runner.mts";
2122
import type { VitestBatchRunParams } from "./lib/vitest-batch-runner.mts";
23+
import { prepareVitestRuntime } from "./lib/vitest-build-prerequisites.mts";
2224

2325
const FS_MODULE_CACHE_PATH_ENV_KEY = "OPENCLAW_VITEST_FS_MODULE_CACHE_PATH";
2426
const PARALLEL_ENV_KEY = "OPENCLAW_EXTENSION_BATCH_PARALLEL";
@@ -141,25 +143,9 @@ function addExactExcludePath(excludePaths: Set<string>, value: string) {
141143
*/
142144
export function parseExactVitestExcludePaths(vitestArgs: string[]) {
143145
const excludePaths = new Set<string>();
144-
for (let index = 0; index < vitestArgs.length; index += 1) {
145-
const arg = vitestArgs[index];
146-
if (arg === undefined) {
147-
break;
148-
}
149-
if (arg === "--exclude") {
150-
const value = vitestArgs[index + 1];
151-
if (value && isExactExcludePath(value)) {
152-
addExactExcludePath(excludePaths, value);
153-
}
154-
index += 1;
155-
continue;
156-
}
157-
const prefix = "--exclude=";
158-
if (arg.startsWith(prefix)) {
159-
const value = arg.slice(prefix.length);
160-
if (value && isExactExcludePath(value)) {
161-
addExactExcludePath(excludePaths, value);
162-
}
146+
for (const value of collectVitestExcludePatterns(vitestArgs)) {
147+
if (isExactExcludePath(value)) {
148+
addExactExcludePath(excludePaths, value);
163149
}
164150
}
165151
return excludePaths;
@@ -178,46 +164,49 @@ function resolveGroupTargets(group: ExtensionTestPlanGroup, exactExcludePaths: S
178164
return testFiles.filter((file) => !exactExcludePaths.has(file));
179165
}
180166

181-
async function runPlanGroup(
167+
function preparePlanGroup(
182168
group: ExtensionTestPlanGroup,
183-
params: {
184-
env: NodeJS.ProcessEnv;
185-
groupIndex: number;
186-
runGroup: (params: VitestBatchRunParams) => Promise<number>;
187-
exactExcludePaths: Set<string>;
188-
allowEmptyAfterExclude: boolean;
189-
useDedicatedCache: boolean;
190-
vitestArgs: string[];
191-
},
169+
groupIndex: number,
170+
env: NodeJS.ProcessEnv,
171+
vitestArgs: string[],
172+
exactExcludePaths: Set<string>,
173+
useDedicatedCache: boolean,
174+
) {
175+
const targets = resolveGroupTargets(group, exactExcludePaths);
176+
const targetChunks =
177+
targets.length === 0
178+
? []
179+
: exactExcludePaths.size > 0
180+
? shouldSplitExtensionTestProcesses(group.config, vitestArgs)
181+
? splitExtensionTestProcessTargets(group.config, targets)
182+
: [targets]
183+
: createExtensionTestProcessTargetChunks(group.config, group.roots, vitestArgs);
184+
return {
185+
group,
186+
invocations: targetChunks.map((chunk) => ({
187+
args: relativizeExtensionVitestArgs(vitestArgs),
188+
config: group.config,
189+
env: createGroupEnv({ baseEnv: env, group, groupIndex, useDedicatedCache }),
190+
targets: chunk.map((target) => relativizeExtensionVitestPath(target)),
191+
})),
192+
};
193+
}
194+
195+
async function runPlanGroup(
196+
{ group, invocations }: ReturnType<typeof preparePlanGroup>,
197+
runGroup: (params: VitestBatchRunParams) => Promise<number>,
198+
allowEmptyAfterExclude: boolean,
192199
) {
193-
const targets = resolveGroupTargets(group, params.exactExcludePaths);
194-
if (targets.length === 0) {
200+
if (invocations.length === 0) {
195201
console.error(`[test-extension-batch] ${group.config}: no test files remain after excludes`);
196-
return params.allowEmptyAfterExclude ? 0 : 1;
202+
return allowEmptyAfterExclude ? 0 : 1;
197203
}
198-
199-
const targetChunks =
200-
params.exactExcludePaths.size > 0
201-
? shouldSplitExtensionTestProcesses(group.config, params.vitestArgs)
202-
? splitExtensionTestProcessTargets(group.config, targets)
203-
: [targets]
204-
: createExtensionTestProcessTargetChunks(group.config, group.roots, params.vitestArgs);
205204
let finalExitCode = 0;
206-
for (const [index, chunk] of targetChunks.entries()) {
205+
for (const [index, invocation] of invocations.entries()) {
207206
console.log(
208-
`[test-extension-batch] ${group.config}: ${group.extensionIds.join(", ")} (${chunk.length} targets${targetChunks.length > 1 ? `, chunk ${index + 1}/${targetChunks.length}` : ""})`,
207+
`[test-extension-batch] ${group.config}: ${group.extensionIds.join(", ")} (${invocation.targets.length} targets${invocations.length > 1 ? `, chunk ${index + 1}/${invocations.length}` : ""})`,
209208
);
210-
const exitCode = await params.runGroup({
211-
args: relativizeExtensionVitestArgs(params.vitestArgs),
212-
config: group.config,
213-
env: createGroupEnv({
214-
baseEnv: params.env,
215-
group,
216-
groupIndex: params.groupIndex,
217-
useDedicatedCache: params.useDedicatedCache,
218-
}),
219-
targets: chunk.map((target) => relativizeExtensionVitestPath(target)),
220-
});
209+
const exitCode = await runGroup(invocation);
221210
if (exitCode !== 0 && finalExitCode === 0) {
222211
finalExitCode = exitCode;
223212
}
@@ -232,14 +221,19 @@ export async function runExtensionBatchPlan(
232221
batchPlan: ExtensionBatchPlan,
233222
params: {
234223
allowEmptyAfterExclude?: boolean;
224+
expandExactExcludes?: boolean;
235225
env?: NodeJS.ProcessEnv;
236226
runGroup?: (params: VitestBatchRunParams) => Promise<number>;
237227
vitestArgs?: string[];
238228
} = {},
239229
) {
240230
const env = params.env ?? process.env;
241231
const vitestArgs = params.vitestArgs ?? [];
242-
const exactExcludePaths = parseExactVitestExcludePaths(vitestArgs);
232+
// Single-plugin CLI historically leaves exact exclusions to Vitest.
233+
const exactExcludePaths =
234+
params.expandExactExcludes === false
235+
? new Set<string>()
236+
: parseExactVitestExcludePaths(vitestArgs);
243237
const runGroup = params.runGroup ?? runVitestBatch;
244238
const parallelism = resolveExtensionBatchParallelism(batchPlan.planGroups.length, env);
245239
const orderedGroups = orderPlanGroups(batchPlan.planGroups, parallelism);
@@ -250,22 +244,31 @@ export async function runExtensionBatchPlan(
250244
console.log(`[test-extension-batch] Running up to ${parallelism} config groups in parallel`);
251245
}
252246

247+
const preparedGroups = orderedGroups.map((group, index) =>
248+
preparePlanGroup(group, index, env, vitestArgs, exactExcludePaths, useDedicatedCache),
249+
);
250+
// No reader may start while a shared generation is being replaced. Select
251+
// from the exact emitted chunks, including existing exact-exclude expansion.
252+
const preparationCode = await prepareVitestRuntime(
253+
preparedGroups.flatMap(({ invocations }) =>
254+
invocations.map(({ config, args, targets }) => ({
255+
configs: [config],
256+
cli: { args: [...args, ...targets], dir: "extensions", env },
257+
})),
258+
),
259+
env,
260+
);
261+
if (preparationCode !== 0) {
262+
return preparationCode;
263+
}
253264
let exitCode = 0;
254265
await pMap(
255-
orderedGroups,
256-
async (group, groupIndex) => {
266+
preparedGroups,
267+
async (group) => {
257268
if (exitCode !== 0) {
258269
return;
259270
}
260-
const groupExitCode = await runPlanGroup(group, {
261-
env,
262-
groupIndex,
263-
runGroup,
264-
exactExcludePaths,
265-
allowEmptyAfterExclude,
266-
useDedicatedCache,
267-
vitestArgs,
268-
});
271+
const groupExitCode = await runPlanGroup(group, runGroup, allowEmptyAfterExclude);
269272
if (groupExitCode !== 0 && exitCode === 0) {
270273
exitCode = groupExitCode;
271274
}

0 commit comments

Comments
 (0)