Skip to content

Commit 3efa9e8

Browse files
authored
fix(test): keep complete multi-project JSON reports (#133309)
* fix(test): retain reports across native test processes Preserve per-attempt native JSON, blob and coverage evidence across project and plugin-batch processes. Merge accepted disjoint case inventories through Vitest, retain originals and actual outcomes, and keep metadata child-owned. Fixes #133305. * test: preserve pnpm bootstrap in report fixtures
1 parent f9fe148 commit 3efa9e8

11 files changed

Lines changed: 1622 additions & 156 deletions

‎docs/reference/test.md‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,54 @@ If `pnpm test` flakes on a loaded host, rerun once before treating it as a regre
272272
- `OPENCLAW_VITEST_MAX_WORKERS=1 pnpm test`
273273
- `OPENCLAW_VITEST_FS_MODULE_CACHE_PATH=/tmp/openclaw-vitest-cache pnpm test:changed`
274274

275+
## JSON reports across native processes
276+
277+
For a multi-project or chunked run, explicitly request native JSON with an output
278+
file, for example:
279+
280+
```bash
281+
pnpm test test/vitest/vitest.unit-fast-isolated.config.ts test/vitest/vitest.agents-embedded-agent.config.ts --reporter=verbose --reporter=json --outputFile=.artifacts/test-results.json
282+
```
283+
284+
The project runner and plugin batch runner give each attempt separate native JSON
285+
and blob files, then publish the requested JSON from Vitest's native report merge.
286+
They print a companion `<output>.reports-<unique>` directory. Keep that directory:
287+
it contains original reports, per-attempt coverage files when coverage is enabled,
288+
and an `index.json` with child exit codes, signals, timeouts and unstarted work.
289+
Only the accepted retry attempt contributes to the aggregate.
290+
291+
The aggregate preserves the accepted case inventory, but is not a lossless
292+
replacement for the originals. Native merging does not restore snapshot summaries
293+
or JSON `coverageMap`, and its `startTime` is the merge time. Passing snapshot tests
294+
still succeed. Read native originals for those details and the index for process
295+
outcomes: JSON `success` does not encode every wrapper or unhandled-error failure.
296+
Separate built-in coverage reports remain per attempt in the companion directory.
297+
Custom coverage providers/reporters and coverage reporter tuple options require
298+
separate invocations with unique destinations.
299+
300+
A complete failed-test aggregate is retained with a failing command exit. Missing
301+
or invalid evidence, cancellation, unstarted required work, or publication failure
302+
does not publish a complete aggregate; an existing output file is not proof of the
303+
new run. The diagnostic prints the retained report-set location. Report sets are
304+
not automatically swept.
305+
306+
Overlapping selections can share native task IDs, so merging them can replace
307+
independent failure details even when case counts match. Such report sets retain
308+
their originals and fail publication. Select each configuration once, or run
309+
overlapping selections separately with distinct output files.
310+
311+
This ownership applies to explicit CLI JSON file requests with named, file-based
312+
Node projects and native console reporters. Scalar `--outputFile` and
313+
`--outputFile.json` both work. Config-owned reporter options, other file formats,
314+
custom reporters and inline/browser project composition require separate native
315+
invocations with unique output destinations. Do not assume those outputs are
316+
aggregated. Single-process and console-only runs keep their existing native behavior.
317+
Native help and other non-test controls stay with the child CLI and do not allocate
318+
report sets. `run --version` still runs tests, as it does in native Vitest.
319+
Config-only reporters are not intercepted: multiple children can still overwrite
320+
the same configured file. Run those configurations separately with distinct paths;
321+
adding `--reporter=json` alone does not override a reporter tuple's own `outputFile`.
322+
275323
## Test performance tooling
276324

277325
- `pnpm test:perf:imports`: enables Vitest import-duration + import-breakdown reporting, while still using scoped lane routing for explicit file/directory targets. `pnpm test:perf:imports:changed` scopes the same profiling to files changed since `origin/main`.

‎scripts/lib/vitest-batch-runner.mts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@ import { fileURLToPath, pathToFileURL } from "node:url";
44
import { createPnpmRunnerSpawnSpec } from "../pnpm-runner.mts";
55
import { installVitestProcessGroupCleanup } from "../vitest-process-group.mts";
66
import { spawnOwnedVitestProcess } from "./vitest-process.mts";
7+
import type { VitestReportOutcome } from "./vitest-report-owner.mts";
78

89
export type VitestBatchRunParams = {
910
args: string[];
1011
config: string;
1112
env?: NodeJS.ProcessEnv;
1213
targets: string[];
14+
onComplete?: (outcome: VitestReportOutcome) => void;
1315
};
1416

1517
const scriptFile = fileURLToPath(import.meta.url);
@@ -40,6 +42,12 @@ export async function runVitestBatch(params: VitestBatchRunParams): Promise<numb
4042
});
4143
completion.finally(teardownChildCleanup).then((result) => {
4244
const { code, signal } = result;
45+
if (params.onComplete) {
46+
const outcome = { code: code ?? 1, signal: forwardedSignal ?? signal };
47+
params.onComplete(outcome);
48+
resolve(outcome.code);
49+
return;
50+
}
4351
if (forwardedSignal) {
4452
process.kill(process.pid, forwardedSignal);
4553
return;
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
import assert from "node:assert/strict";
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
import type { Reporter, TestModule, TestProject, TestSpecification, Vitest } from "vitest/node";
5+
6+
function projectIdentity(project: TestProject) {
7+
return {
8+
name: project.name,
9+
root: project.config.root,
10+
config: project.vite.config.configFile,
11+
pool: project.config.pool,
12+
};
13+
}
14+
15+
function moduleIdentity(spec: TestSpecification) {
16+
return {
17+
...projectIdentity(spec.project),
18+
file: spec.moduleId,
19+
pool: spec.pool,
20+
taskId: spec.taskId,
21+
};
22+
}
23+
24+
// Native Istanbul reporter destinations (istanbul-reports/lib/*/index.js).
25+
// Tuple options/custom reporters can select their own paths and need a separate contract.
26+
const coverageFiles: Record<string, string[]> = {
27+
text: [],
28+
"text-summary": [],
29+
"text-lcov": [],
30+
teamcity: [],
31+
none: [],
32+
json: ["coverage-final.json"],
33+
"json-summary": ["coverage-summary.json"],
34+
lcov: ["lcov.info", "lcov-report/index.html"],
35+
lcovonly: ["lcov.info"],
36+
html: ["index.html"],
37+
"html-spa": ["index.html"],
38+
clover: ["clover.xml"],
39+
cobertura: ["cobertura-coverage.xml"],
40+
};
41+
42+
export type VitestReportCapture = {
43+
pid: number;
44+
command: string[];
45+
root: string;
46+
projects: ReturnType<typeof projectIdentity>[];
47+
modules: ReturnType<typeof moduleIdentity>[];
48+
coverageDirectory: string | null;
49+
coverageFiles: string[];
50+
coverageOnFailure: boolean;
51+
processTimedOut: boolean;
52+
passWithNoTests: boolean;
53+
ignoreUnhandledErrors: boolean;
54+
ended?: { reason: string; unhandledErrors: number; failedModules: number };
55+
};
56+
57+
const sorted = (values: unknown[]) => values.map((value) => JSON.stringify(value)).toSorted();
58+
59+
/** Observe native loading and replay; never replace reporters or reconstruct native tasks. */
60+
export default class VitestReportCaptureReporter implements Reporter {
61+
private output = "";
62+
private capture!: VitestReportCapture;
63+
private expected: VitestReportCapture[];
64+
65+
constructor(options: { expected?: VitestReportCapture[] } = {}) {
66+
this.expected = options.expected ?? [];
67+
}
68+
69+
onInit(ctx: Vitest) {
70+
const output = ctx.config.outputFile;
71+
assert(output && typeof output === "object" && typeof output.json === "string");
72+
this.output = `${output.json}.capture.json`;
73+
for (const reporter of ctx.config.reporters) {
74+
if (Array.isArray(reporter) && ["json", "blob"].includes(reporter[0])) {
75+
assert(
76+
!("outputFile" in reporter[1] && reporter[1].outputFile != null) &&
77+
!("filterMeta" in reporter[1] && reporter[1].filterMeta != null),
78+
"Multi-invocation JSON cannot preserve config-owned reporter options. Run each config separately with its own native output file.",
79+
);
80+
}
81+
}
82+
const projects = ctx.projects.map(projectIdentity);
83+
assert(
84+
projects.every(
85+
(project, index) =>
86+
project.name && project.config && !ctx.projects[index]!.isBrowserEnabled(),
87+
),
88+
"Multi-invocation JSON requires named file-based Node projects; run inline/browser configurations separately.",
89+
);
90+
const coverage = ctx.config.coverage;
91+
const expectedCoverage = coverage.enabled
92+
? coverage.reporter.flatMap(([name, options]) => {
93+
assert(
94+
(coverage.provider === "v8" || coverage.provider === "istanbul") &&
95+
Object.hasOwn(coverageFiles, name) &&
96+
Object.keys(options).length === 0,
97+
"Multi-invocation JSON cannot own custom coverage providers/reporters or tuple options. Run each config separately with unique coverage destinations.",
98+
);
99+
return coverageFiles[name]!;
100+
})
101+
: [];
102+
this.capture = {
103+
pid: process.pid,
104+
command: [process.execPath, ...process.execArgv, ...process.argv.slice(1)],
105+
root: ctx.config.root,
106+
projects,
107+
modules: [],
108+
coverageDirectory: ctx.config.coverage.enabled ? ctx.config.coverage.reportsDirectory : null,
109+
coverageFiles: expectedCoverage,
110+
coverageOnFailure: coverage.reportOnFailure,
111+
processTimedOut: false,
112+
passWithNoTests: ctx.config.passWithNoTests,
113+
ignoreUnhandledErrors: ctx.config.dangerouslyIgnoreUnhandledErrors,
114+
};
115+
if (this.expected.length) {
116+
const expectedProjects = [
117+
...new Set(this.expected.flatMap((capture) => sorted(capture.projects))),
118+
].toSorted();
119+
assert.deepEqual(sorted(projects), expectedProjects, "Native merge project identity changed");
120+
}
121+
this.writeCapture();
122+
}
123+
124+
onTestRunStart(specs: readonly TestSpecification[]) {
125+
if (this.expected.length) {
126+
assert.deepEqual(
127+
sorted(specs.map(moduleIdentity)),
128+
sorted(this.expected.flatMap((capture) => capture.modules)),
129+
"Native merge module/project/root/pool attribution changed",
130+
);
131+
}
132+
}
133+
134+
onTestRunEnd(modules: readonly TestModule[], errors: readonly unknown[], reason: string) {
135+
this.capture.modules = modules.map((module) => moduleIdentity(module.toTestSpecification()));
136+
this.capture.ended = {
137+
reason,
138+
unhandledErrors: errors.length,
139+
failedModules: modules.filter((module) => !module.ok()).length,
140+
};
141+
this.writeCapture();
142+
}
143+
144+
onProcessTimeout() {
145+
this.capture.processTimedOut = true;
146+
this.writeCapture();
147+
}
148+
149+
private writeCapture() {
150+
fs.mkdirSync(path.dirname(this.output), { recursive: true });
151+
fs.writeFileSync(this.output, JSON.stringify(this.capture));
152+
}
153+
}

0 commit comments

Comments
 (0)