Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: retry a native Vitest worker crash once and name it when CI can't read the failing step

[._.]/ Adam Eivy7a3e6b92b4c3
diff --git a/scripts/cancel-current-ci-run.js b/scripts/cancel-current-ci-run.js
index 9c6a416e42..64d747d37b 100644
--- a/scripts/cancel-current-ci-run.js
+++ b/scripts/cancel-current-ci-run.js
@@ -68,9 +68,17 @@ async function reportFailureBeforeCancel({ env, fetchImpl, logger, writeSummary,
...target,
timeoutMs: DIAGNOSTIC_TIMEOUT_MS,
});
+ // `scripts/run-ci-tests.js` sets this via $GITHUB_ENV when a Vitest worker
+ // crashed natively (a Windows fail-fast abort, not an assertion) and the
+ // crash reproduced on a same-file retry — the API lookup above can't see
+ // this because it names FAILED STEPS, and the crash killed the step before
+ // any per-test output named the file (issue 8152).
+ const crashedFile = safeWorkflowText(env.CI_CRASHED_TEST_FILE);
const lines = found?.length
? found.map(formatFailedJob)
- : [`${label} — the failing step could not be read from the Actions API; open this job's log`];
+ : [crashedFile
+ ? `${label} — the failing step could not be read from the Actions API; the Vitest worker crashed natively on ${crashedFile} (see this job's log)`
+ : `${label} — the failing step could not be read from the Actions API; open this job's log`];
try {
for (const line of lines) logger.log?.(formatErrorAnnotation(`CI failed: ${label}`, line));
diff --git a/scripts/cancel-current-ci-run.test.js b/scripts/cancel-current-ci-run.test.js
index 0542b1f7fd..76267e2757 100644
--- a/scripts/cancel-current-ci-run.test.js
+++ b/scripts/cancel-current-ci-run.test.js
@@ -192,6 +192,27 @@ describe('reportFailureBeforeCancel', () => {
expect(annotation).toContain('windows-server (shard 3)');
});
+ it('names the crashed test file in the fallback when a native Vitest worker crash killed the step (issue 8152)', async () => {
+ // `run-ci-tests.js` writes CI_CRASHED_TEST_FILE via $GITHUB_ENV when a
+ // worker crash reproduces on retry — the failing-step lookup can't see
+ // this itself because the crash killed the step before Actions recorded
+ // a per-step failure the jobs API can read back.
+ const { fetchImpl, logger } = setup();
+ fetchImpl.mockImplementation((url) => (
+ url === JOBS_URL ? Promise.reject(new Error('network unavailable')) : Promise.resolve(response(202))
+ ));
+
+ await cancelCurrentCiRun({
+ env: { ...ANNOTATION_ENV, CI_CRASHED_TEST_FILE: 'server/services/sprites/importer.test.js' },
+ fetchImpl,
+ logger,
+ });
+
+ const annotation = logger.log.mock.calls.map(([line]) => line).find((line) => line.startsWith('::error'));
+ expect(annotation).toContain('server/services/sprites/importer.test.js');
+ expect(annotation).not.toContain('open this job\'s log');
+ });
+
it('annotates even when the environment cannot authorize a cancel', async () => {
const { fetchImpl, logger } = setup();
diff --git a/scripts/run-ci-tests.js b/scripts/run-ci-tests.js
index 025d9ced15..8d76725f0f 100644
--- a/scripts/run-ci-tests.js
+++ b/scripts/run-ci-tests.js
@@ -1,14 +1,66 @@
#!/usr/bin/env node
-import { spawnSync } from 'child_process';
+import { spawn } from 'child_process';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';
import { isDirectlyInvoked } from './lib/directInvocation.js';
-import { writeStepSummary } from './lib/githubOutput.js';
+import { writeStepEnv, writeStepSummary } from './lib/githubOutput.js';
const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
+/**
+ * Vitest's own signature for a worker that never returned control at all — a
+ * native process abort (Windows `STATUS_*` fail-fast codes such as
+ * `0xC0000409`, exit code 3221226505) rather than an assertion failure. That
+ * distinction matters: the crashed file printed no test-level output, so a
+ * single-file retry tells us whether the crash reproduces or was a one-off
+ * runner fault (issue 8152).
+ */
+const WORKER_CRASH_PATTERN = /Worker exited unexpectedly with exit code \d+.*?while running test file (\S+)/s;
+
+/**
+ * Retained tail of the child's combined output, bounded so a full-suite run
+ * (thousands of one-line "✓ file.test.js" rows) can't grow this without limit.
+ * The crash signature always lands in Vitest's end-of-run "Unhandled Errors"
+ * section, so only the tail is ever needed.
+ */
+const MAX_CAPTURED_OUTPUT = 200_000;
+
+export function extractCrashedTestFile(output) {
+ const match = WORKER_CRASH_PATTERN.exec(String(output || ''));
+ return match ? match[1].trim() : null;
+}
+
+/**
+ * Turn the absolute path Vitest prints (e.g.
+ * `D:/a/PortOS/PortOS/server/services/sprites/importer.test.js` on the
+ * Windows runner) into the repo-relative `<workspace>/...` path the rest of
+ * this script works in, or `null` when it can't be matched to a workspace
+ * this runner knows about.
+ */
+export function repoRelativeFromCrashPath(crashedPath) {
+ const normalized = String(crashedPath || '').replace(/\\/g, '/');
+ const match = /\/(server|client)\/(.+)$/.exec(normalized);
+ return match ? `${match[1]}/${match[2]}` : null;
+}
+
+/**
+ * Decide what a nonzero exit from `runNpm` means and, when it's a native
+ * Vitest worker crash, what a single-file retry should run — pulled out as a
+ * pure function so the crash/retry decision has a real input matrix under
+ * test without spawning a process (issue 8152).
+ *
+ * @returns {{retry: false}|{retry: true, relPath: string, selector: string}}
+ */
+export function planCrashRetry(scope, output) {
+ const crashedPath = extractCrashedTestFile(output);
+ if (!crashedPath) return { retry: false };
+ const relPath = repoRelativeFromCrashPath(crashedPath);
+ if (!relPath || !relPath.startsWith(`${scope}/`)) return { retry: false, crashedPath };
+ return { retry: true, relPath, selector: toRunnerPath(scope, relPath) };
+}
+
export function requiresSourceFiles(mode, repoSources) {
return mode === 'related' && repoSources.length === 0;
}
@@ -44,29 +96,71 @@ export function recordVitestDuration(scope, label, startedAt) {
writeStepSummary(line);
}
-function spawnNpm(scope, script, extraArgs, label) {
+/**
+ * Run `npm run <script> --prefix <scope> [-- extraArgs]`, streaming stdout and
+ * stderr live (so a long CI job keeps showing progress) while also retaining
+ * a bounded tail of the combined output for post-run crash detection.
+ *
+ * @returns {Promise<{status: number, output: string, error?: Error}>}
+ */
+function runNpm(scope, script, extraArgs) {
const args = ['run', script, '--prefix', scope];
if (extraArgs.length > 0) args.push('--', ...extraArgs);
- console.log(`Running ${scope} ${label}${extraArgs.length ? ` (${extraArgs.length} selector argument(s))` : ''}.`);
// Wrapped, not a bare `npm.cmd`: Node refuses to spawn a `.cmd` under
// `shell:false` and throws EINVAL, so this script could never run on a
// Windows checkout. See server/lib/bufferedSpawn.js.
const { command, args: spawnArgs } = prepareCliSpawn('npm', args);
- const startedAt = Date.now();
- const result = spawnSync(command, spawnArgs, {
- stdio: 'inherit',
- env: process.env,
- cwd: repoRoot,
+ return new Promise((resolve) => {
+ const child = spawn(command, spawnArgs, { env: process.env, cwd: repoRoot });
+ let output = '';
+ const tee = (stream, chunk) => {
+ stream.write(chunk);
+ output = (output + chunk).slice(-MAX_CAPTURED_OUTPUT);
+ };
+ child.stdout.on('data', (chunk) => tee(process.stdout, chunk));
+ child.stderr.on('data', (chunk) => tee(process.stderr, chunk));
+ child.on('error', (error) => resolve({ status: 1, output, error }));
+ child.on('close', (code) => resolve({ status: code ?? 1, output }));
});
+}
+
+async function spawnNpm(scope, script, extraArgs, label) {
+ console.log(`Running ${scope} ${label}${extraArgs.length ? ` (${extraArgs.length} selector argument(s))` : ''}.`);
+ const startedAt = Date.now();
+ const result = await runNpm(scope, script, extraArgs);
recordVitestDuration(scope, label, startedAt);
if (result.error) {
console.error(result.error.message);
return 1;
}
- return result.status ?? 1;
+ if (result.status === 0) return 0;
+
+ const plan = planCrashRetry(scope, result.output);
+ if (!plan.retry) {
+ if (plan.crashedPath) writeStepEnv('CI_CRASHED_TEST_FILE', plan.crashedPath);
+ return result.status;
+ }
+ const { relPath, selector } = plan;
+
+ // A native fail-fast abort, not an assertion — every other file in this run
+ // already passed (Vitest's own summary counts it separately from a real
+ // failure), so one retry of just the crashed file tells us whether this
+ // reproduces or was a one-off runner fault.
+ console.warn(`⚠️ Vitest worker crashed natively on ${relPath} — retrying that file once`);
+ const retryStartedAt = Date.now();
+ const retry = await runNpm(scope, script, [selector]);
+ recordVitestDuration(scope, `crash retry: ${relPath}`, retryStartedAt);
+ if (!retry.error && retry.status === 0) {
+ console.log(`✅ ${relPath} passed on retry — treating the original worker crash as a runner fault, not a regression`);
+ return 0;
+ }
+
+ console.error(`❌ ${relPath} crashed again on retry — this reproduces, not a runner fluke`);
+ writeStepEnv('CI_CRASHED_TEST_FILE', relPath);
+ return retry.status || result.status;
}
-function main() {
+async function main() {
const scope = process.argv[2];
if (!['server', 'client'].includes(scope)) {
console.error('Usage: node scripts/run-ci-tests.js <server|client>');
@@ -92,7 +186,7 @@ function main() {
if (mode === 'full') {
const shard = shardArgs(process.env.CI_SHARD);
const label = shard.length ? `full suite shard ${process.env.CI_SHARD}` : 'full suite';
- process.exit(spawnNpm(scope, 'test:ci', shard, label));
+ process.exit(await spawnNpm(scope, 'test:ci', shard, label));
}
if (mode === 'files') {
@@ -100,7 +194,7 @@ function main() {
console.log(`No ${scope} tests selected.`);
process.exit(0);
}
- process.exit(spawnNpm(scope, 'test:ci', selectedFiles, 'selected tests'));
+ process.exit(await spawnNpm(scope, 'test:ci', selectedFiles, 'selected tests'));
}
// Feed Vitest the actual changed source files instead of asking `list
@@ -113,7 +207,7 @@ function main() {
// Running them in a second exact-file process repeated any changed test that
// already imported the source; on PR #5299 that rebuilt the atlas twice and
// added 27.5 seconds after the related run had already passed it.
- process.exit(spawnNpm(
+ process.exit(await spawnNpm(
scope,
'test:ci:related',
relatedInputs(sourceFiles, selectedFiles),
@@ -121,4 +215,4 @@ function main() {
));
}
-if (isDirectlyInvoked(import.meta.url)) main();
+if (isDirectlyInvoked(import.meta.url)) await main();
diff --git a/scripts/run-ci-tests.test.js b/scripts/run-ci-tests.test.js
index ff4dd4c205..dc84f7204d 100644
--- a/scripts/run-ci-tests.test.js
+++ b/scripts/run-ci-tests.test.js
@@ -4,8 +4,11 @@ import { join } from 'path';
import { afterEach, describe, expect, it } from 'vitest';
import {
+ extractCrashedTestFile,
+ planCrashRetry,
recordVitestDuration,
relatedInputs,
+ repoRelativeFromCrashPath,
requiresSourceFiles,
shardArgs,
toRunnerPath,
@@ -117,6 +120,71 @@ describe('requiresSourceFiles', () => {
});
});
+describe('extractCrashedTestFile', () => {
+ // Verbatim shape of Vitest's own message for a forked worker that aborted
+ // natively (issue 8152 — a Windows 0xC0000409 fail-fast), trimmed to the
+ // two lines the regex actually needs.
+ const CRASH_OUTPUT = [
+ '⎯⎯⎯⎯⎯⎯ Unhandled Errors ⎯⎯⎯⎯⎯⎯',
+ 'Error: [vitest-pool]: Worker forks emitted error.',
+ 'Caused by: Error: Worker exited unexpectedly with exit code 3221226505 during started state while running test file D:/a/PortOS/PortOS/server/services/sprites/importer.test.js',
+ ' Test Files 798 passed | 2 skipped (801)',
+ ].join('\n');
+
+ it('pulls the crashed file out of a native worker-crash error', () => {
+ expect(extractCrashedTestFile(CRASH_OUTPUT)).toBe(
+ 'D:/a/PortOS/PortOS/server/services/sprites/importer.test.js',
+ );
+ });
+
+ it('finds nothing in an ordinary assertion failure or empty output', () => {
+ expect(extractCrashedTestFile('FAIL server/lib/foo.test.js > bar\nExpected 1 to be 2')).toBeNull();
+ expect(extractCrashedTestFile('')).toBeNull();
+ expect(extractCrashedTestFile(undefined)).toBeNull();
+ });
+});
+
+describe('repoRelativeFromCrashPath', () => {
+ it('maps an absolute Windows or POSIX runner path onto its workspace', () => {
+ expect(repoRelativeFromCrashPath('D:/a/PortOS/PortOS/server/services/sprites/importer.test.js'))
+ .toBe('server/services/sprites/importer.test.js');
+ expect(repoRelativeFromCrashPath('/home/runner/work/PortOS/PortOS/client/src/lib/foo.test.js'))
+ .toBe('client/src/lib/foo.test.js');
+ });
+
+ it('returns null when the path names neither workspace', () => {
+ expect(repoRelativeFromCrashPath('D:/a/PortOS/PortOS/scripts/foo.test.js')).toBeNull();
+ expect(repoRelativeFromCrashPath('')).toBeNull();
+ });
+});
+
+describe('planCrashRetry', () => {
+ const CRASH_OUTPUT = 'Caused by: Error: Worker exited unexpectedly with exit code 3221226505 '
+ + 'during started state while running test file D:/a/PortOS/PortOS/server/services/sprites/importer.test.js';
+
+ it('plans a same-workspace single-file retry for a matching crash', () => {
+ expect(planCrashRetry('server', CRASH_OUTPUT)).toEqual({
+ retry: true,
+ relPath: 'server/services/sprites/importer.test.js',
+ selector: './services/sprites/importer.test.js',
+ });
+ });
+
+ it('declines to retry a crash reported in the other workspace', () => {
+ // A server-shard crash never gets replayed as a client-scoped selector.
+ expect(planCrashRetry('client', CRASH_OUTPUT)).toEqual({
+ retry: false,
+ crashedPath: 'D:/a/PortOS/PortOS/server/services/sprites/importer.test.js',
+ });
+ });
+
+ it('declines to retry an ordinary test failure', () => {
+ expect(planCrashRetry('server', 'FAIL server/lib/foo.test.js\nExpected true to be false')).toEqual({
+ retry: false,
+ });
+ });
+});
+
describe('relatedInputs', () => {
it('runs source-related tests and explicit guards in one deduplicated invocation', () => {
expect(relatedInputs(