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

Record memo entries only from clean runs, slice shards in the runner, verify keys after the run

[._.]/ Adam Eivy58409601ad34
diff --git a/scripts/lib/testMemoRunner.js b/scripts/lib/testMemoRunner.js
index 870c1a1a92..cc98e19da9 100644
--- a/scripts/lib/testMemoRunner.js
+++ b/scripts/lib/testMemoRunner.js
@@ -14,15 +14,24 @@
* modules each test actually loaded. A passed file gets a memo record (that
* list) and an entry under its recorded key, plus an entry under its floor
* key when the static closure is fully resolvable — so the next run can hit
- * either.
+ * either. Entries come only from a run whose process exited 0 and whose
+ * run-level report shows no unhandled error, and only when the inputs hash
+ * the same after the run as before it.
+ *
+ * Sharding: a matrix shard takes its slice of the FULL selected list with
+ * Vitest's own algorithm (`vitestShardSlice`) before the memo subtracts
+ * anything, so every file lands in exactly one shard whatever each shard's
+ * store holds. Vitest itself is never given `--shard`.
*/
import { spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
import * as nodeFs from 'node:fs';
-import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import * as nodePath from 'node:path';
-import { join, relative, sep } from 'node:path';
+import { join, posix, relative, sep } from 'node:path';
import { WORKSPACE_BASE_INPUTS, createDiskFs, createTestMemoAnalyzer, relatedTests } from './testMemo.js';
import { readMemoEntry, readMemoRecord, writeMemoEntry, writeMemoRecord } from './testMemoStore.js';
import { listWorkspaceTests, toRepoPath, toWorkspacePath } from './workspaceTests.js';
@@ -42,12 +51,23 @@ const VIRTUAL_MODULE = /(?:^|\/)@vite\/|^\0|^virtual:/;
* @returns {{ selected: string[], run: string[], skipped: Array<{test: string, via: 'recorded'|'floor'}>,
* reasons: Map<string, string>, analyze: (test: string, recorded: string[]) => object, verdicts: Map }}
*/
-export function planTestMemo({ scope, mode, repoFiles, repoSources, memoDir, repoRoot, env = process.env, platform, arch, nodeMajor, listTests = listWorkspaceTests, readRecord = readMemoRecord, readEntry = readMemoEntry }) {
+export function planTestMemo({ scope, mode, repoFiles, repoSources, memoDir, repoRoot, shard = null, env = process.env, platform, arch, nodeVersion, toolVersion = () => null, listTests = listWorkspaceTests, readRecord = readMemoRecord, readEntry = readMemoEntry }) {
const workspaceTests = listTests(scope, { repoRoot, platform, env }).map((rel) => toRepoPath(scope, rel));
const candidates = mode === 'files' ? uniqueSorted(repoFiles) : uniqueSorted([...workspaceTests, ...repoFiles]);
- const analyzer = createTestMemoAnalyzer({ fs: createDiskFs(repoRoot, nodeFs, nodePath), workspaceRel: scope, env, platform, arch, nodeMajor });
+ const options = { fs: createDiskFs(repoRoot, nodeFs, nodePath), workspaceRel: scope, env, platform, arch, nodeVersion, toolVersion };
+ const analyzer = createTestMemoAnalyzer(options);
const baseClosure = analyzer.workspaceBase(WORKSPACE_BASE_INPUTS[scope]);
const analyze = (test, recorded) => analyzer.analyzeTest(test, { baseClosure, recorded });
+ // A second analyzer with empty caches re-reads every input after the run,
+ // so an entry is written only for inputs that did not change meanwhile.
+ let fresh = null;
+ const freshAnalyze = (test, recorded) => {
+ if (!fresh) {
+ const again = createTestMemoAnalyzer(options);
+ fresh = { analyzer: again, baseClosure: again.workspaceBase(WORKSPACE_BASE_INPUTS[scope]) };
+ }
+ return fresh.analyzer.analyzeTest(test, { baseClosure: fresh.baseClosure, recorded });
+ };
const verdicts = new Map();
for (const test of candidates) verdicts.set(test, analyze(test, memoDir ? readRecord(memoDir, scope, test) : null));
@@ -55,11 +75,12 @@ export function planTestMemo({ scope, mode, repoFiles, repoSources, memoDir, rep
const selected = mode === 'related'
? uniqueSorted([...relatedTests(verdicts, repoSources), ...repoFiles])
: candidates;
+ const slice = shard ? vitestShardSlice(selected, { repoRoot, scope, ...shard }) : selected;
const skipped = [];
const reasons = new Map();
const run = [];
- for (const test of selected) {
+ for (const test of slice) {
const info = verdicts.get(test);
const via = !memoDir ? null
: info.recorded?.memoizable && readEntry(memoDir, info.recorded.key, { test, workspace: scope }) ? 'recorded'
@@ -69,11 +90,41 @@ export function planTestMemo({ scope, mode, repoFiles, repoSources, memoDir, rep
run.push(test);
if (!info.floor.memoizable) reasons.set(test, info.recorded?.memoizable ? 'no green entry yet (recorded key)' : info.recorded?.reason ?? info.floor.reason);
}
- return { selected, run, skipped, reasons, analyze, verdicts };
+ return { selected, slice, run, skipped, reasons, analyze, freshAnalyze, verdicts };
}
export function memoSummaryLine(plan) {
- return `🧠 Test memo: skipped ${plan.skipped.length} of ${plan.selected.length} selected files (closure unchanged); running ${plan.run.length}.`;
+ return `🧠 Test memo: skipped ${plan.skipped.length} of ${plan.slice.length} selected files (closure unchanged); running ${plan.run.length}.`;
+}
+
+/** Vitest's `BaseSequencer.calculateShardRange`: the [start, end) slice of `count` hash-sorted files for shard `index` of `total`. */
+export function vitestShardRange(count, index, total) {
+ const base = Math.floor(count / total);
+ const remainder = count % total;
+ if (remainder >= index) {
+ const size = base + 1;
+ return [size * (index - 1), size * index];
+ }
+ const start = remainder * (base + 1) + (index - remainder - 1) * base;
+ return [start, start + base];
+}
+
+/**
+ * The files shard `index` of `count` runs, mirroring Vitest's
+ * `BaseSequencer.shard`: sort by the sha1 of each file's path relative to
+ * the Vitest root (the absolute path with the root prefix sliced off, so a
+ * file outside the workspace hashes its remaining absolute tail), then take
+ * the range. Pinned against a real `vitest run --shard` in the tests.
+ */
+export function vitestShardSlice(files, { repoRoot, scope, index, count }) {
+ const repoPosix = repoRoot.split(sep).join('/');
+ const rootPosix = posix.join(repoPosix, scope);
+ const hashed = files.map((rel) => ({
+ rel,
+ hash: createHash('sha1').update(posix.join(repoPosix, rel).slice(rootPosix.length)).digest('hex'),
+ })).sort((a, b) => (a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0));
+ const [start, end] = vitestShardRange(hashed.length, index, count);
+ return hashed.slice(start, end).map(({ rel }) => rel);
}
/**
@@ -109,12 +160,17 @@ export function fileResultsFromReport(reportPath) {
}
/**
- * Files a run proved green: status passed, at least one passed case, no
- * failed case, and no skipped case unless a name pattern deliberately skips
- * cases (a browser profile). A capability-gated skip is otherwise invisible
- * to the key, so a file that skipped anything is not recorded.
+ * Files a run proved green: the Vitest process exited 0 and its run-level
+ * report (`scripts/vitestRunDiagnostics.js`) ended `passed` with no
+ * unhandled error — a late rejection after the last test still marks every
+ * file `passed` in the JSON report — then per file: status passed, at least
+ * one passed case, no failed case, and no skipped case unless a name pattern
+ * deliberately skips cases (a browser profile). A capability-gated skip is
+ * otherwise invisible to the key, so a file that skipped anything is not
+ * recorded.
*/
-export function passedTestFiles(fileResults, { repoRoot, namePattern = false }) {
+export function passedTestFiles(fileResults, { repoRoot, namePattern = false, status, runReport }) {
+ if (status !== 0 || !runReport || runReport.reason !== 'passed' || runReport.errorCount !== 0) return [];
const out = [];
for (const result of fileResults) {
if (result.status !== 'passed' || result.passed < 1 || result.failed > 0) continue;
@@ -127,8 +183,9 @@ export function passedTestFiles(fileResults, { repoRoot, namePattern = false })
}
/**
- * Vitest's recorded depfile (`<workspace>/.cache/vitest/dependencies.json`):
- * test -> modules it loaded, both repo-relative. Null when absent or unreadable.
+ * Vitest's recorded depfile: test -> modules it loaded, both repo-relative.
+ * A test recorded by several projects gets the union, so a stale project
+ * entry can only widen a record. Null when absent or unreadable.
*/
export function readVitestDependencies(path, scope) {
try {
@@ -141,8 +198,10 @@ export function readVitestDependencies(path, scope) {
if (!Array.isArray(indexes)) continue;
// Vite's own virtual modules (`/@vite/client` under happy-dom) are not files.
const modules = indexes.map((index) => project.modules[index])
- .filter((module) => typeof module === 'string' && !VIRTUAL_MODULE.test(module));
- out.set(toRepoPath(scope, test), modules.map((module) => toRepoPath(scope, module)));
+ .filter((module) => typeof module === 'string' && !VIRTUAL_MODULE.test(module))
+ .map((module) => toRepoPath(scope, module));
+ const key = toRepoPath(scope, test);
+ out.set(key, uniqueSorted([...(out.get(key) ?? []), ...modules]));
}
}
return out;
@@ -151,6 +210,48 @@ export function readVitestDependencies(path, scope) {
}
}
+/**
+ * Remove every depfile under the workspace's Vitest cache before a run, so
+ * the records read afterwards come from this run alone: Vitest merges the
+ * file across runs, and CI restores it through a near-miss cache key.
+ */
+export function clearVitestDependencies(repoRoot, scope) {
+ for (;;) {
+ const path = findVitestDependenciesFile(repoRoot, scope);
+ if (!path) return;
+ rmSync(path, { force: true });
+ }
+}
+
+/**
+ * Version strings for `TEST_MEMO_TOOLS`, resolved once per process the way
+ * the suites find the programs: `PORTOS_TEST_PYTHON` or `python3`, `ffmpeg`
+ * on PATH, and Chrome through `CHROME_PATH` or playwright-core's bundled
+ * Chromium. Null (keyed as `absent`) when the program cannot be run.
+ */
+export function createToolVersionResolver({ repoRoot, env = process.env } = {}) {
+ const cache = new Map();
+ const firstLine = (command, args) => {
+ if (!command) return null;
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 15_000 });
+ if (result.error || result.status !== 0) return null;
+ return `${result.stdout}${result.stderr}`.trim().split('\n')[0] || null;
+ };
+ const chromeBinary = () => {
+ if (env.CHROME_PATH) return env.CHROME_PATH;
+ try { return createRequire(join(repoRoot, 'server', 'package.json'))('playwright-core').chromium.executablePath(); } catch { return null; }
+ };
+ return (tool) => {
+ if (cache.has(tool)) return cache.get(tool);
+ const version = tool === 'python' ? firstLine(env.PORTOS_TEST_PYTHON || 'python3', ['--version'])
+ : tool === 'ffmpeg' ? firstLine('ffmpeg', ['-version'])
+ : tool === 'chrome' ? firstLine(chromeBinary(), ['--version'])
+ : null;
+ cache.set(tool, version);
+ return version;
+ };
+}
+
/** Best-effort commit identity for the entry; never a reason to fail the run. */
export function currentCommit(repoRoot, env = process.env) {
if (env.GITHUB_SHA) return env.GITHUB_SHA;
@@ -160,7 +261,10 @@ export function currentCommit(repoRoot, env = process.env) {
/**
* Record green results: a memo record and entries for every passed file the
- * plan knows. Returns how many entries were written.
+ * plan knows. Each key is recomputed from the tree as it is after the run
+ * and written only when it still equals the key computed before (floor) or
+ * from the pre-run hashes (recorded): a file edited while Vitest ran is not
+ * attributed to the verdict. Returns how many entries were written.
*/
export function recordTestMemo({ scope, repoRoot, memoDir, plan, passed, dependencies, source, commit, writeEntry = writeMemoEntry, writeRecord = writeMemoRecord }) {
let written = 0;
@@ -168,11 +272,12 @@ export function recordTestMemo({ scope, repoRoot, memoDir, plan, passed, depende
const info = plan.verdicts.get(test);
if (!info) continue;
const meta = { test, workspace: scope, source, commit };
- if (info.floor.memoizable) { writeEntry(memoDir, info.floor.key, meta); written += 1; }
- const modules = dependencies?.get(test);
+ const modules = dependencies?.get(test) ?? null;
+ const after = plan.freshAnalyze(test, modules);
+ if (info.floor.memoizable && after.floor.key === info.floor.key) { writeEntry(memoDir, info.floor.key, meta); written += 1; }
if (!modules) continue;
const recorded = plan.analyze(test, modules).recorded;
- if (!recorded?.memoizable) continue;
+ if (!recorded?.memoizable || after.recorded?.key !== recorded.key) continue;
writeRecord(memoDir, scope, test, modules);
writeEntry(memoDir, recorded.key, meta);
written += 1;
diff --git a/scripts/lib/testMemoRunner.test.js b/scripts/lib/testMemoRunner.test.js
index 63bc6860a8..32c92aad67 100644
--- a/scripts/lib/testMemoRunner.test.js
+++ b/scripts/lib/testMemoRunner.test.js
@@ -4,13 +4,14 @@
* entries are written only for files a run reported green.
*/
+import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import {
- fileResultsFromReport, findVitestDependenciesFile, passedTestFiles, planTestMemo, readVitestDependencies, recordTestMemo,
- writeSelectionFile,
+ clearVitestDependencies, fileResultsFromReport, findVitestDependenciesFile, passedTestFiles, planTestMemo, readVitestDependencies,
+ recordTestMemo, vitestShardRange, vitestShardSlice, writeSelectionFile,
} from './testMemoRunner.js';
import { readMemoEntry, readMemoRecord, writeMemoEntry } from './testMemoStore.js';
@@ -44,7 +45,7 @@ describe('planTestMemo and recordTestMemo', () => {
const plan = (overrides = {}) => planTestMemo({
scope: 'server', mode: 'files', repoFiles: TESTS.map((t) => `server/${t}`), repoSources: [], memoDir, repoRoot: root,
- env: { NODE_ENV: 'test' }, platform: 'linux', arch: 'x64', nodeMajor: 24, listTests: () => TESTS, ...overrides,
+ env: { NODE_ENV: 'test' }, platform: 'linux', arch: 'x64', nodeVersion: '24.1.0', listTests: () => TESTS, ...overrides,
});
it('subtracts memoized files, selects related files from the closure, and records only passed files', () => {
@@ -66,9 +67,14 @@ describe('planTestMemo and recordTestMemo', () => {
};
const reportPath = join(root, 'report.json');
writeFileSync(reportPath, JSON.stringify(passedReport));
- const passed = passedTestFiles(fileResultsFromReport(reportPath), { repoRoot: root });
+ const clean = { repoRoot: root, status: 0, runReport: { reason: 'passed', errorCount: 0 } };
+ const passed = passedTestFiles(fileResultsFromReport(reportPath), clean);
expect(passed).toEqual(['server/lib/a.test.js']);
- expect(passedTestFiles(fileResultsFromReport(reportPath), { repoRoot: root, namePattern: true })).toEqual(['server/lib/a.test.js', 'server/lib/c.test.js']);
+ expect(passedTestFiles(fileResultsFromReport(reportPath), { ...clean, namePattern: true })).toEqual(['server/lib/a.test.js', 'server/lib/c.test.js']);
+ // A red process, a late unhandled error, or a missing run report proves nothing for any file.
+ expect(passedTestFiles(fileResultsFromReport(reportPath), { ...clean, status: 1 })).toEqual([]);
+ expect(passedTestFiles(fileResultsFromReport(reportPath), { ...clean, runReport: { reason: 'passed', errorCount: 1 } })).toEqual([]);
+ expect(passedTestFiles(fileResultsFromReport(reportPath), { ...clean, runReport: null })).toEqual([]);
expect(findVitestDependenciesFile(root, 'server')).toBeNull();
const dependenciesPath = join(root, 'server', '.cache', 'vitest', 'vitest', 'confighash', 'dependencies.json');
@@ -80,7 +86,14 @@ describe('planTestMemo and recordTestMemo', () => {
expect(findVitestDependenciesFile(root, 'server')).toBe(dependenciesPath);
const dependencies = readVitestDependencies(dependenciesPath, 'server');
expect(readVitestDependencies(null, 'server')).toBeNull();
- expect(dependencies.get('server/lib/a.test.js')).toEqual(['server/lib/a.test.js', 'server/lib/a.js']);
+ // Two projects recording one file (a stale entry from the other group) union rather than overwrite.
+ const twice = join(root, 'twice.json');
+ writeFileSync(twice, JSON.stringify({ version: 1, projects: {
+ capture: { modules: ['lib/x.test.js', 'lib/x.js', 'lib/newDep.js'], files: { 'lib/x.test.js': [0, 1, 2] } },
+ parallel: { modules: ['lib/x.test.js', 'lib/x.js'], files: { 'lib/x.test.js': [0, 1] } },
+ } }));
+ expect(readVitestDependencies(twice, 'server').get('server/lib/x.test.js')).toEqual(['server/lib/newDep.js', 'server/lib/x.js', 'server/lib/x.test.js']);
+ expect(dependencies.get('server/lib/a.test.js')).toEqual(['server/lib/a.js', 'server/lib/a.test.js']);
const written = recordTestMemo({ scope: 'server', repoRoot: root, memoDir, plan: cold, passed, dependencies, source: 'local', commit: 'abc' });
expect(written).toBe(2);
@@ -93,6 +106,22 @@ describe('planTestMemo and recordTestMemo', () => {
expect(warm.skipped).toEqual([{ test: 'server/lib/a.test.js', via: 'recorded' }]);
expect(warm.run).toEqual(['server/lib/b.test.js', 'server/lib/c.test.js']);
+ // A file edited while the run was in flight is not attributed to its verdict.
+ const midRun = plan();
+ writeFileSync(join(root, 'server/lib/b.js'), "export const load = () => import('./lazy.js'); // edited mid-run\n");
+ const bPassed = { testResults: [{ name: join(root, 'server/lib/b.test.js'), status: 'passed', assertionResults: [{ status: 'passed' }] }] };
+ writeFileSync(reportPath, JSON.stringify(bPassed));
+ expect(recordTestMemo({ scope: 'server', repoRoot: root, memoDir, plan: midRun, passed: passedTestFiles(fileResultsFromReport(reportPath), clean), dependencies, source: 'local', commit: 'abc' })).toBe(0);
+ expect(readMemoRecord(memoDir, 'server', 'server/lib/b.test.js')).toBeNull();
+ clearVitestDependencies(root, 'server');
+ expect(findVitestDependenciesFile(root, 'server')).toBeNull();
+
+ // A shard takes its slice of the full selection before the memo subtracts anything.
+ const shards = [1, 2].map((index) => plan({ shard: { index, count: 2 } }));
+ expect(shards.flatMap((s) => s.slice).sort()).toEqual(TESTS.map((t) => `server/${t}`));
+ expect(shards.every((s) => s.selected.length === 3)).toBe(true);
+ expect(shards.flatMap((s) => [...s.run, ...s.skipped.map((x) => x.test)]).sort()).toEqual(TESTS.map((t) => `server/${t}`));
+
// The recorded key survives a change to a module the green run never loaded.
writeFileSync(join(root, 'server/lib/lazy.js'), 'export const lazy = 2;\n');
expect(plan().skipped).toEqual([{ test: 'server/lib/a.test.js', via: 'recorded' }]);
@@ -111,6 +140,30 @@ describe('planTestMemo and recordTestMemo', () => {
expect(plan({ memoDir: null }).skipped).toEqual([]);
});
+ it('slices shards exactly like Vitest\'s sequencer', () => {
+ expect([1, 2, 3].map((index) => vitestShardRange(7, index, 3))).toEqual([[0, 3], [3, 5], [5, 7]]);
+ expect([1, 2].map((index) => vitestShardRange(1, index, 2))).toEqual([[0, 1], [1, 1]]);
+ const fixture = mkdtempSync(join(tmpdir(), 'portos-shard-parity-'));
+ try {
+ const host = join(fixture, 'host');
+ mkdirSync(host);
+ const files = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta'].map((name) => `${name}.test.js`);
+ for (const file of files) writeFileSync(join(fixture, file), "import { it } from 'vitest';\nit('x', () => {});\n");
+ writeFileSync(join(fixture, 'vitest.config.mjs'), 'export default { test: { include: ["*.test.js"], maxWorkers: 1 } };');
+ const vitest = join(import.meta.dirname, '..', '..', 'server', 'node_modules', '.bin', 'vitest');
+ const env = { ...process.env, NODE_ENV: 'test', TMPDIR: host, TMP: host, TEMP: host, NODE_DISABLE_COMPILE_CACHE: '1', PORTOS_CI_TEST_SELECTION: '' };
+ delete env.PORTOS_TEST_TEMP_ROOT;
+ for (const index of [1, 2, 3]) {
+ const report = join(fixture, `shard${index}.json`);
+ execFileSync(vitest, ['run', `--shard=${index}/3`, '--config', join(fixture, 'vitest.config.mjs'), '--root', fixture, '--reporter=json', `--outputFile=${report}`], { cwd: fixture, env, encoding: 'utf8', timeout: 60_000 });
+ const ran = JSON.parse(readFileSync(report, 'utf8')).testResults.map((suite) => suite.name.replace(/\\/g, '/').split('/').pop()).sort();
+ expect(ran, `shard ${index}`).toEqual(vitestShardSlice(files, { repoRoot: fixture, scope: '.', index, count: 3 }).sort());
+ }
+ } finally {
+ rmSync(fixture, { recursive: true, force: true });
+ }
+ }, 120_000);
+
it('writes the selection Vitest reads as workspace-relative paths', () => {
const selection = writeSelectionFile({ scope: 'server', include: ['server/lib/a.test.js', 'scripts/x.test.js'], exclude: [] });
try {
diff --git a/scripts/lib/testMemoStore.js b/scripts/lib/testMemoStore.js
index c322bffe68..fe0e32e8de 100644
--- a/scripts/lib/testMemoStore.js
+++ b/scripts/lib/testMemoStore.js
@@ -26,6 +26,9 @@ import { join } from 'node:path';
const KEY_PATTERN = /^[0-9a-f]{64}$/;
+/** An entry older than this is a miss, so the nightly re-verifies what it keeps skipping. */
+export const MAX_ENTRY_AGE_MS = 14 * 24 * 60 * 60 * 1000;
+
/** Where the store lives for `env`, or null when the memo is disabled. */
export function resolveMemoDir(env = process.env, home = homedir()) {
if (env.PORTOS_TEST_MEMO === 'off') return null;
@@ -53,11 +56,13 @@ function writeJsonAtomic(path, value) {
}
}
-/** The green entry for `key` when it names `test` in `workspace`; null on any miss or corruption. */
-export function readMemoEntry(dir, key, { test, workspace }) {
+/** The green entry for `key` when it names `test` in `workspace` and is young enough; null on any miss or corruption. */
+export function readMemoEntry(dir, key, { test, workspace, now = Date.now() }) {
if (!dir || !KEY_PATTERN.test(String(key))) return null;
const entry = readJson(entryPath(dir, key));
if (!entry || entry.test !== test || entry.workspace !== workspace || typeof entry.verifiedAt !== 'string') return null;
+ const age = now - Date.parse(entry.verifiedAt);
+ if (!Number.isFinite(age) || age < 0 || age > MAX_ENTRY_AGE_MS) return null;
return entry;
}
diff --git a/scripts/lib/testMemoStore.test.js b/scripts/lib/testMemoStore.test.js
index 159e96d40c..0b2c449e76 100644
--- a/scripts/lib/testMemoStore.test.js
+++ b/scripts/lib/testMemoStore.test.js
@@ -2,7 +2,7 @@ import { mkdtempSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
-import { readMemoEntry, readMemoRecord, resolveMemoDir, writeMemoEntry, writeMemoRecord } from './testMemoStore.js';
+import { MAX_ENTRY_AGE_MS, readMemoEntry, readMemoRecord, resolveMemoDir, writeMemoEntry, writeMemoRecord } from './testMemoStore.js';
const KEY = 'a'.repeat(64);
const META = { test: 'server/lib/a.test.js', workspace: 'server', source: 'local', commit: 'abc' };
@@ -26,6 +26,9 @@ describe('test memo store', () => {
expect(readMemoEntry(dir, KEY, META)).toMatchObject({ ...META, verifiedAt: expect.any(String) });
expect(readMemoEntry(dir, KEY, { ...META, test: 'server/lib/other.test.js' })).toBeNull();
expect(readMemoEntry(dir, 'not-a-key', META)).toBeNull();
+ // An entry ages out so a nightly re-verifies what it keeps skipping.
+ expect(readMemoEntry(dir, KEY, { ...META, now: Date.now() + MAX_ENTRY_AGE_MS + 1 })).toBeNull();
+ expect(readMemoEntry(dir, KEY, { ...META, now: Date.now() + MAX_ENTRY_AGE_MS - 60_000 })).not.toBeNull();
expect(readdirSync(join(dir, 'entries', 'aa')).filter((name) => name.endsWith('.tmp'))).toEqual([]);
writeFileSync(join(dir, 'entries', 'aa', `${KEY}.json`), '{ corrupt');
diff --git a/scripts/run-ci-tests.js b/scripts/run-ci-tests.js
index 9cca0d2c50..6e66733f26 100644
--- a/scripts/run-ci-tests.js
+++ b/scripts/run-ci-tests.js
@@ -14,8 +14,8 @@ import { reportWindowsCrashDiagnostics } from './ci-windows-crash-diagnostics.js
import { diagnosticTestFile, persistTestDiagnostic } from './ci-test-diagnostics.js';
import { browserTestProfileArgs, browserTestProfileFiles, assertBrowserProfileExecuted, BROWSER_FIDELITY_ONLY_FILES } from './lib/browserTestProfiles.js';
import {
- currentCommit, fileResultsFromReport, findVitestDependenciesFile, memoSummaryLine, passedTestFiles, planTestMemo,
- readVitestDependencies, recordTestMemo, writeSelectionFile,
+ clearVitestDependencies, createToolVersionResolver, currentCommit, fileResultsFromReport, findVitestDependenciesFile,
+ memoSummaryLine, passedTestFiles, planTestMemo, readVitestDependencies, recordTestMemo, writeSelectionFile,
} from './lib/testMemoRunner.js';
import { resolveMemoDir } from './lib/testMemoStore.js';
@@ -116,15 +116,28 @@ export function toRunnerPath(scope, path) {
}
/**
- * Vitest selector flags for this runner's slice of the selected suite. `CI_SHARD` is
- * `<index>/<count>` from the job matrix (ci.yml). A single shard passes nothing,
- * so the one-runner invocation stays identical to a local `npm run test:ci`.
+ * This runner's slice of the job matrix. `CI_SHARD` is `<index>/<count>`
+ * (ci.yml); a single shard is no shard, so the one-runner invocation stays
+ * identical to a local `npm run test:ci`. The slice is taken by the runner
+ * itself (scripts/lib/testMemoRunner.js vitestShardSlice), never by Vitest:
+ * each shard subtracts a different memo state, and a `--shard` applied after
+ * that subtraction could leave a file to no shard at all.
*/
-export function shardArgs(shard) {
- if (!shard) return [];
+export function parseShard(shard) {
+ if (!shard) return null;
const match = /^(\d+)\/(\d+)$/.exec(shard);
if (!match) throw new Error(`CI_SHARD must look like <index>/<count>, got "${shard}"`);
- return match[2] === '1' ? [] : [`--shard=${shard}`];
+ return match[2] === '1' ? null : { index: Number(match[1]), count: Number(match[2]) };
+}
+
+/** The run-level report `scripts/vitestRunDiagnostics.js` wrote: `{ reason, errorCount }`, or null. */
+function readRunReport(runReportPath) {
+ try {
+ const run = JSON.parse(readFileSync(runReportPath, 'utf8'));
+ return typeof run?.reason === 'string' && Number.isInteger(run.errorCount) ? { reason: run.reason, errorCount: run.errorCount } : null;
+ } catch {
+ return null;
+ }
}
export function recordVitestDuration(scope, label, startedAt) {
@@ -216,8 +229,12 @@ export async function runNpm(scope, script, extraArgs, { env = process.env, sign
console.error(`Test launcher cleanup unverified; diagnostics retained at ${reportDir}`);
return { ...launched, diagnosticsPath: reportDir };
}
- // Per-file outcomes feed the test memo; an interrupted run proves nothing.
- const result = { ...launched, fileResults: launched.interrupted ? [] : fileResultsFromReport(reportPath) };
+ // Per-file outcomes and the run-level verdict feed the test memo; an interrupted run proves nothing.
+ const result = {
+ ...launched,
+ fileResults: launched.interrupted ? [] : fileResultsFromReport(reportPath),
+ runReport: launched.interrupted ? null : readRunReport(join(reportDir, 'run.json')),
+ };
const profile = env.PORTOS_BROWSER_TEST_PROFILE;
if (profile !== undefined && result.status === 0) {
try {
@@ -362,7 +379,8 @@ export async function spawnNpm(scope, script, extraArgs, label, {
// 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 run(scope, script, [selector, ...profileArgs]);
+ // The retry keeps the run's flags (recording, pass-with-no-tests); only the selectors shrink to the crashed file.
+ const retry = await run(scope, script, [selector, ...profileArgs, ...extraArgs.filter(arg => arg.startsWith('--'))]);
recordVitestDuration(scope, `crash retry: ${relPath}`, retryStartedAt);
onResult(retry);
if (!retry.error && retry.status === 0) {
@@ -422,8 +440,8 @@ async function main() {
return;
}
- const shard = shardArgs(process.env.CI_SHARD);
- const label = mode === 'full' ? (shard.length ? `full suite shard ${process.env.CI_SHARD}` : 'full suite')
+ const shard = parseShard(process.env.CI_SHARD);
+ const label = mode === 'full' ? (shard ? `full suite shard ${process.env.CI_SHARD}` : 'full suite')
: mode === 'files' ? 'selected tests' : 'related and contract tests';
// process.exitCode, not process.exit(): the runner streams the child's
// output through this process's own stdout/stderr, and process.exit() can
@@ -431,8 +449,8 @@ async function main() {
// finish flushing. Setting exitCode lets Node drain normally once main()
// returns.
const memoDir = resolveMemoDir();
- if (mode === 'full' && !memoDir) {
- process.exitCode = await spawnNpm(scope, 'test:ci', shard, label);
+ if (mode === 'full' && !memoDir && !shard) {
+ process.exitCode = await spawnNpm(scope, 'test:ci', [], label);
return;
}
@@ -443,7 +461,8 @@ async function main() {
// the set here is what lets the memo subtract the files a trusted green
// run already verified, and the list reaches Vitest as a file because a
// related set can exceed the Windows command-line limit.
- const plan = planTestMemo({ scope, mode, repoFiles, repoSources, memoDir, repoRoot });
+ if (memoDir) clearVitestDependencies(repoRoot, scope);
+ const plan = planTestMemo({ scope, mode, repoFiles, repoSources, memoDir, repoRoot, shard, toolVersion: createToolVersionResolver({ repoRoot }) });
if (memoDir) {
console.log(memoSummaryLine(plan));
if (process.env.PORTOS_TEST_MEMO_VERBOSE === '1') {
@@ -451,21 +470,18 @@ async function main() {
}
}
if (plan.run.length === 0) {
- console.log(`No ${scope} tests left to run.`);
+ console.log(`No ${scope} tests left to run${shard ? ' in this shard' : ''}.`);
process.exitCode = 0;
return;
}
- const skipped = plan.skipped.map(({ test }) => test);
- const selection = writeSelectionFile({ scope, include: mode === 'full' ? null : plan.run, exclude: mode === 'full' ? skipped : [] });
+ const selection = writeSelectionFile({ scope, include: plan.run, exclude: [] });
process.env.PORTOS_CI_TEST_SELECTION = selection.path;
- // A memo-trimmed selection can leave one shard of the matrix empty, which
- // Vitest otherwise reports as a failure.
- const extraArgs = [...shard, ...(skipped.length ? ['--passWithNoTests'] : []), ...(memoDir ? ['--experimental.recordDependencies'] : [])];
+ const extraArgs = memoDir ? ['--experimental.recordDependencies'] : [];
const passed = [];
try {
process.exitCode = await spawnNpm(scope, 'test:ci', extraArgs, label, {
onResult: (result) => passed.push(...passedTestFiles(result.fileResults ?? [], {
- repoRoot, namePattern: process.env.PORTOS_BROWSER_TEST_PROFILE !== undefined,
+ repoRoot, namePattern: process.env.PORTOS_BROWSER_TEST_PROFILE !== undefined, status: result.status, runReport: result.runReport,
})),
});
} finally {
diff --git a/scripts/run-ci-tests.test.js b/scripts/run-ci-tests.test.js
index cf2d73c7c0..cf6fed1604 100644
--- a/scripts/run-ci-tests.test.js
+++ b/scripts/run-ci-tests.test.js
@@ -14,8 +14,8 @@ import {
planCrashRetry,
recordVitestDuration,
repoRelativeFromCrashPath,
+ parseShard,
requiresSourceFiles,
- shardArgs,
spawnNpm,
toRunnerPath,
} from './run-ci-tests.js';
@@ -23,6 +23,8 @@ import { killProcessTree } from '../server/lib/bufferedSpawn.js';
import * as nodeFs from 'node:fs';
import * as nodePath from 'node:path';
import { computeTestMemoKeys, createDiskFs, relatedTests } from './lib/testMemo.js';
+import { vitestShardSlice } from './lib/testMemoRunner.js';
+import { toWorkspacePath } from './lib/workspaceTests.js';
import { OWNER_FILE, STALE_ROOT_AGE_MS } from './lib/vitestStaleRunRoots.js';
import { workflowJobs } from './lib/workflowJobs.js';
@@ -47,13 +49,13 @@ const FIXTURE_CONFIG = `
const WORKFLOW = readFileSync(join(import.meta.dirname, '..', '.github', 'workflows', 'ci.yml'), 'utf8');
-describe('shardArgs', () => {
- it('passes a slice selector only when the matrix actually split the suite', () => {
- expect(shardArgs(undefined)).toEqual([]);
- expect(shardArgs('')).toEqual([]);
- expect(shardArgs('1/1')).toEqual([]);
- expect(shardArgs('2/3')).toEqual(['--shard=2/3']);
- expect(() => shardArgs('2')).toThrow(/<index>\/<count>/);
+describe('parseShard', () => {
+ it('reads a slice only when the matrix actually split the suite', () => {
+ expect(parseShard(undefined)).toBeNull();
+ expect(parseShard('')).toBeNull();
+ expect(parseShard('1/1')).toBeNull();
+ expect(parseShard('2/3')).toEqual({ index: 2, count: 3 });
+ expect(() => parseShard('2')).toThrow(/<index>\/<count>/);
});
});
@@ -68,7 +70,7 @@ function installFakeNpm(fixture, body) {
const REPORTING_NPM = 'process.stdout.write(JSON.stringify({ args: process.argv.slice(2), '
+ 'selection: JSON.parse(require("fs").readFileSync(process.env.PORTOS_CI_TEST_SELECTION, "utf8")) }) + "\\n");';
-it('forwards the scoped matrix slice as an argument and the selection as a file through the real launcher', () => {
+it('hands Vitest the selection as a file, sliced by the runner for the matrix shard, never as --shard', () => {
const fixture = mkdtempSync(join(tmpdir(), 'portos-related-shard-'));
try {
installFakeNpm(fixture, REPORTING_NPM);
@@ -76,26 +78,30 @@ it('forwards the scoped matrix slice as an argument and the selection as a file
// each must hand Vitest its slice rather than run the whole selection twice.
// Related selection is closure-based: this runner imports
// scripts/lib/directInvocation.js, so the runner's own test is related to it.
- for (const [mode, sources, expected] of [
- ['related', ['scripts/lib/directInvocation.js'], ['../scripts/run-ci-tests.test.js']],
- ['files', [], []],
+ const files = ['server/lib/example.test.js', 'scripts/example.test.js'];
+ for (const [mode, shard, sources, expected] of [
+ ['related', '', ['scripts/lib/directInvocation.js'], ['../scripts/run-ci-tests.test.js', 'lib/example.test.js', '../scripts/example.test.js']],
+ ['files', '', [], ['lib/example.test.js', '../scripts/example.test.js']],
+ // Two explicit files split three ways: shard 2 of 3 gets exactly one of them.
+ ['files', '2/3', [], [vitestShardSlice(files, { repoRoot: join(import.meta.dirname, '..'), scope: 'server', index: 2, count: 3 })].flat().map((rel) => toWorkspacePath('server', rel))],
]) {
const result = spawnSync(process.execPath, [join(import.meta.dirname, 'run-ci-tests.js'), 'server'], {
encoding: 'utf8', timeout: 120000,
env: { ...process.env, PATH: `${fixture}${delimiter}${process.env.PATH}`,
- CI_TEST_MODE: mode, CI_SHARD: '2/3', PORTOS_TEST_MEMO: 'off',
+ CI_TEST_MODE: mode, CI_SHARD: shard, PORTOS_TEST_MEMO: 'off',
CI_TEST_SOURCES: JSON.stringify(sources),
- CI_TEST_FILES: JSON.stringify(['server/lib/example.test.js', 'scripts/example.test.js']),
+ CI_TEST_FILES: JSON.stringify(files),
GITHUB_ENV: '', GITHUB_STEP_SUMMARY: '' },
});
expect(result.error).toBeUndefined();
expect(result.status, result.stderr).toBe(0);
const { args, selection } = JSON.parse(result.stdout.split('\n').find(line => line.startsWith('{"args"')));
- expect(args.slice(0, 6), mode).toEqual(['run', 'test:ci', '--prefix', 'server', '--', '--shard=2/3']);
+ expect(args.slice(0, 5), mode).toEqual(['run', 'test:ci', '--prefix', 'server', '--']);
+ expect(args.some(arg => arg.startsWith('--shard')), mode).toBe(false);
expect(args, mode).not.toContain('--experimental.recordDependencies');
expect(selection.exclude, mode).toEqual([]);
- expect(selection.include, mode).toEqual(expect.arrayContaining([...expected, 'lib/example.test.js', '../scripts/example.test.js']));
- if (mode === 'files') expect(selection.include).toHaveLength(2);
+ expect(selection.include, `${mode} ${shard}`).toEqual(expect.arrayContaining(expected));
+ if (mode === 'files') expect(selection.include, shard).toHaveLength(expected.length);
}
} finally {
rmSync(fixture, { recursive: true, force: true });
@@ -116,6 +122,8 @@ describe('test memo through the real runner', () => {
`const repo = ${JSON.stringify(join(import.meta.dirname, '..'))};`,
'const testResults = selection.include.map(rel => ({ name: require("path").resolve(repo, "server", rel), status: "passed", assertionResults: [{ status: "passed" }] }));',
'fs.writeFileSync(out, JSON.stringify({ testResults }));',
+ // The run-level report scripts/vitestRunDiagnostics.js would write; PORTOS_FAKE_LATE_ERROR simulates a rejection after the last test.
+ 'fs.writeFileSync(process.env.PORTOS_CI_DIAGNOSTICS_PATH, JSON.stringify({ reason: "passed", errorCount: process.env.PORTOS_FAKE_LATE_ERROR ? 1 : 0, errors: [] }));',
'process.stdout.write("RAN " + JSON.stringify(selection.include) + "\\n");',
].join('\n'));
const test = 'scripts/lib/releaseTitle.test.js';
@@ -125,6 +133,12 @@ describe('test memo through the real runner', () => {
CI_TEST_MODE: 'files', CI_TEST_FILES: JSON.stringify([test]), CI_TEST_SOURCES: '[]',
PORTOS_TEST_MEMO_DIR: memoDir, PORTOS_TEST_MEMO_VERBOSE: '1', GITHUB_ENV: '', GITHUB_STEP_SUMMARY: '', ...extraEnv },
});
+ // A green-looking report with a run-level error records nothing.
+ const tainted = run({ PORTOS_FAKE_LATE_ERROR: '1' });
+ expect(tainted.status, tainted.stderr).toBe(0);
+ expect(tainted.stdout).toContain('RAN ');
+ expect(tainted.stdout).not.toContain('recorded');
+
const first = run();
expect(first.status, first.stderr).toBe(0);
expect(first.stdout).toContain('🧠 Test memo: skipped 0 of 1 selected files (closure unchanged); running 1.');
@@ -445,9 +459,10 @@ describe('native crash diagnostics before retry/cancellation (#8152)', () => {
return { status: 1, output };
});
const diagnose = vi.fn(async () => { order.push('diagnose'); });
- expect(await spawnNpm('server', 'test:ci', ['--shard=3/3'], 'fixture', { run, diagnose })).toBe(1);
+ expect(await spawnNpm('server', 'test:ci', ['--experimental.recordDependencies'], 'fixture', { run, diagnose })).toBe(1);
expect(order).toEqual(['run', 'diagnose', 'run', 'diagnose']);
- expect(run.mock.calls[1]).toEqual(['server', 'test:ci', ['./services/sprites/walk.test.js']]);
+ // The retry narrows the selectors to the crashed file but keeps the run's flags, so its record is taken too.
+ expect(run.mock.calls[1]).toEqual(['server', 'test:ci', ['./services/sprites/walk.test.js', '--experimental.recordDependencies']]);
});
it('refuses an explicitly empty browser profile before invoking tests', async () => {
@@ -520,12 +535,19 @@ describe('structured failure diagnostics', () => {
delete env.PORTOS_TEST_TEMP_ROOT;
const result = spawnSync(process.execPath, ['--input-type=module', '-e',
`import { runNpm } from ${JSON.stringify(runnerUrl)};
+ import { passedTestFiles } from ${JSON.stringify(new URL('./lib/testMemoRunner.js', import.meta.url).href)};
const result = await runNpm('server', 'test:ci', ${JSON.stringify(args)});
+ console.log('MEMO ' + JSON.stringify({ status: result.status, runReport: result.runReport, files: result.fileResults.map(f => f.status),
+ passed: passedTestFiles(result.fileResults, { repoRoot: ${JSON.stringify(fixture)}, status: result.status, runReport: result.runReport }) }));
process.exitCode = result.status;`,
], { encoding: 'utf8', timeout: 30_000, env });
expect(result.error).toBeUndefined();
expect(result.status).toBe(1);
expect(stripVTControlCharacters(result.stdout)).toMatch(/Test Files\s+1 passed/);
+ // The JSON report calls the file passed; the process and run-level report say otherwise, and the memo believes them.
+ const memo = JSON.parse(result.stdout.split('\n').find(line => line.startsWith('MEMO ')).slice(5));
+ expect(memo).toMatchObject({ status: 1, files: ['passed'], passed: [] });
+ expect(memo.runReport.errorCount).toBe(1);
const diagnostic = result.stderr.slice(result.stderr.indexOf('Test launcher exited:'));
expect(diagnostic).toContain('code=1, signal=none');
expect(diagnostic).toContain('unhandledErrors=1');