Files
morluto 2bb554e8b0 feat(cli)!: keep over-budget CLI results recoverable by default (#14610)
* feat(cli)!: keep over-budget CLI results recoverable by default

An over-budget CLI result without --evidence_output now saves its
complete Evidence to a private retained-Evidence cache under the user
cache directory and returns the summary with the file's path, size and
digest, so it pages with inspect-analysis-view without a rerun.

Files are named by the complete record's Evidence ID, created
exclusively as 0600 by the Evidence bundle writer in a 0700 directory
the user owns, reused by repeat runs and never overwritten. Each
retention removes records unused for 7 days, then the least recently
used over delivery.cli_retained_evidence_bytes (REA_CLI_RETAINED_EVIDENCE_BYTES,
default 256 MiB). --no-retain or a 0 setting writes nothing; a record
that cannot be kept falls back to the rerun arguments with the reason.

Fixes #14594

BREAKING CHANGE: An over-budget CLI result without --evidence_output is
now saved to REA's private retained-Evidence cache and reported as
{summary, evidence_bundle, delivery} with delivery.retained cache-file,
instead of writing nothing. Pass --no-retain, or set
REA_CLI_RETAINED_EVIDENCE_BYTES=0, to write nothing as before.

* fix(cli): key retained Evidence by its content and keep its owner's facts

Review fixes for default CLI retention:

- Name files by the SHA-256 of the complete record's exact JSON, since
  the Evidence ID leaves out caller paths; report it as
  evidence_bundle.sha256.
- Remove a bundle that outgrows the cache after the write.
- Renew a record's age when inspect-analysis-view reads it.
- Re-check a record's use time before evicting it.
- Never use a cache whose path holds a value marked sensitive, and
  redact retention failure reasons.
- Report a save that committed but then failed with its receipt and
  cleanup owner, as --evidence_output does.
- Request source records whenever the cache may receive a bundle.
- Refresh the advertised-schema summaries for the new setting.

* fix(cli): withdraw the receipt of a bundle the cache discards

A bundle that outgrew the cache was removed after the writer had already
recorded its publication receipt, so output recovery could name a
missing file. Retention now withdraws that receipt whenever it keeps
nothing, unless the file committed and its failure is reported.

* fix(cli): retain publication receipt when removing an oversized retained bundle fails
2026-11-25 21:39:33 +00:00

247 lines
8.8 KiB
TypeScript

import { realpathSync } from "node:fs";
import { availableParallelism, tmpdir } from "node:os";
import { join } from "node:path";
import { defineConfig } from "vitest/config";
import { parseCLI } from "vitest/node";
import {
BUILT_TEST_PROJECTS,
SOURCE_TEST_PROJECTS,
} from "./scripts/lib/test-projects.mjs";
import { CiTestSequencer } from "./tests/ciTestSequencer.js";
import {
COVERAGE_DEADLINE_SCALE,
HOSTED_RUNNER_DEADLINE_SCALE,
LONG_RUNNING_DEADLINE_MS,
remainingTestDeadline,
TEST_DEADLINE_MS as BASE_TEST_DEADLINE_MS,
} from "./tests/support/testDeadlines.js";
// Playwright's registry does not derive a cache directory for Termux's
// `android` platform. Match the production CLI fallback before workers import
// browser modules.
if (
process.platform === "android" &&
process.env.PLAYWRIGHT_BROWSERS_PATH === undefined
) {
const cacheRoot =
process.env.XDG_CACHE_HOME ?? join(process.env.HOME ?? ".", ".cache");
process.env.PLAYWRIGHT_BROWSERS_PATH = join(cacheRoot, "ms-playwright");
}
const CANONICAL_TEMPORARY_DIRECTORY = realpathSync(tmpdir());
// Use Vitest's option parser so explicit false and spaced shard values retain
// their meaning. Unknown worker/embedding arguments are not Vitest options.
const { options: testOptions } = parseCLI(
["vitest", ...process.argv.slice(2)],
{ allowUnknownOptions: true },
);
const COVERAGE_ENABLED = testOptions.coverage?.enabled === true;
const COVERAGE_SHARD = testOptions.shard !== undefined;
// Bound concurrency by the runner rather than command locks. A hosted CI job
// owns its whole four-core runner, so it may use every core; other hosts stay
// at two workers because developers and agents share them with other checks.
const DEDICATED_CI_RUNNER = process.env.GITHUB_ACTIONS === "true";
const MAX_TEST_WORKERS = Math.min(
DEDICATED_CI_RUNNER ? 4 : 2,
availableParallelism(),
);
// A test deadline only turns a hang into a named failure; it is not a
// performance assertion. Projects own it so tests do not hard-code host speed.
// Built projects launch compiled CLI, MCP, and provider processes while other
// lanes share the runner, and coverage instrumentation slows every lane. Hosted
// CI runs a worker per core, so CPU-bound cases there share every core with
// other workers and their subprocesses.
const DEADLINE_SCALE =
(COVERAGE_ENABLED ? COVERAGE_DEADLINE_SCALE : 1) *
(DEDICATED_CI_RUNNER ? HOSTED_RUNNER_DEADLINE_SCALE : 1);
const TEST_DEADLINE_MS = {
source: BASE_TEST_DEADLINE_MS.source * DEADLINE_SCALE,
built: BASE_TEST_DEADLINE_MS.built * DEADLINE_SCALE,
} as const;
// Vitest's one-second `expect.poll` default is a host-speed guess. A poll the
// project owns waits as long as its test may run, less a reporting reserve, so
// a condition that never holds still fails with the poll's own diagnostics.
const pollPolicy = (deadlineMs: number) => {
const timeout = remainingTestDeadline(deadlineMs, 0);
return timeout === undefined ? {} : { timeout };
};
const TEST_PROJECTS = [...SOURCE_TEST_PROJECTS, ...BUILT_TEST_PROJECTS];
// Source projects that share a module graph still run in forked workers.
// Thread workers share one process, so the source lane's workers once grew
// one 3.8 GiB process; Linux CI then refused to fork test subprocesses from it
// (`spawnSync ... ENOMEM`). A forked worker keeps its own heap and main-thread
// stack, so the largest process stays near one worker's size.
const PROJECT_POLICIES = {
domain: {
pool: "forks" as const,
maxWorkers: MAX_TEST_WORKERS,
// Domain and contract modules are pure and own no process-global state, so
// per-file module isolation adds startup cost without protecting a seam.
},
services: {
pool: "forks" as const,
maxWorkers: MAX_TEST_WORKERS,
// Service tests use recording ports and own no process-global state. Share
// their module graph so file startup does not dominate the lane.
},
adapters: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS },
composition: {
pool: "forks" as const,
maxWorkers: MAX_TEST_WORKERS,
// Composition tests use provider-neutral sessions and test-scoped cleanup;
// sharing their immutable module graph avoids per-file startup work.
},
boundary: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS },
"cli-boundary": {
pool: "forks" as const,
maxWorkers: MAX_TEST_WORKERS,
// CLI tests create fresh command instances or subprocesses and own their
// cleanup. Reuse the immutable graph; module mocks belong in process-global.
// The shared source/contract graph also needs transient schema/help space.
// Ordinary CI exhausted 384 MiB after earlier files warmed that graph.
// Use the measured 512 MiB budget with the same bounded concurrency.
execArgv: ["--max-old-space-size=512"],
},
"process-boundary": {
pool: "forks" as const,
maxWorkers: 1,
// Process-tree observations share host sampling resources; keep this small
// lane serial while the independent projects run together.
fileParallelism: false,
sequence: { groupOrder: 1 },
},
"mcp-boundary": {
pool: "threads" as const,
maxWorkers: MAX_TEST_WORKERS,
// Each file creates and closes an explicit in-memory MCP session. Reuse the
// immutable server graph so module startup does not outweigh transport work.
},
acceptance: { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS },
"process-global": { pool: "forks" as const, maxWorkers: MAX_TEST_WORKERS },
conformance: {
pool: "forks" as const,
maxWorkers: MAX_TEST_WORKERS,
// Contract cases use recording providers and own no process-global state.
},
evaluation: {
pool: "forks" as const,
maxWorkers: MAX_TEST_WORKERS,
// Evaluator tests inspect deterministic inputs without mutating shared state.
},
};
const ZERO_COVERAGE_THRESHOLDS = {
statements: 0,
branches: 0,
functions: 0,
lines: 0,
"src/domain/**": {
statements: 0,
branches: 0,
functions: 0,
lines: 0,
},
"src/contracts/**": {
statements: 0,
branches: 0,
functions: 0,
lines: 0,
},
};
const projects = TEST_PROJECTS.map((project) => {
const policy =
PROJECT_POLICIES[project.name as keyof typeof PROJECT_POLICIES];
if (!policy)
throw new Error(`Missing test runner policy for ${project.name}`);
return {
extends: true as const,
test: {
name: project.name,
include: [...project.include],
...(project.exclude ? { exclude: [...project.exclude] } : {}),
isolate: project.isolate !== false,
testTimeout: TEST_DEADLINE_MS[project.group],
hookTimeout: TEST_DEADLINE_MS[project.group],
expect: { poll: pollPolicy(TEST_DEADLINE_MS[project.group]) },
...policy,
},
};
});
export default defineConfig({
test: {
env: {
TMPDIR: CANONICAL_TEMPORARY_DIRECTORY,
// Tests read analysis facts, so a CLI or server they spawn delivers
// complete Evidence, as the in-process harness default does. Delivery
// tests set their own budget; this is the largest accepted seed.
REA_AGENT_RESULT_BUDGET_BYTES: String(10 * 1024 * 1024),
// Nothing a test runs writes to the user's retained-Evidence cache;
// retention tests select a temporary cache and their own size.
REA_CLI_RETAINED_EVIDENCE_BYTES: "0",
},
maxWorkers: MAX_TEST_WORKERS,
projects,
...(process.env.REA_CI_TEST_HISTORY
? { sequence: { sequencer: CiTestSequencer } }
: {}),
retry: 0,
reporters: ["default"],
runner: "./tests/processOwnershipRunner.ts",
testTimeout: TEST_DEADLINE_MS.source,
hookTimeout: TEST_DEADLINE_MS.source,
expect: { poll: pollPolicy(TEST_DEADLINE_MS.source) },
// Deadline probes compare what Vitest applies with the configured policy.
provide: { testDeadlineScale: DEADLINE_SCALE },
tags: [
{
name: "long-running",
description:
"A bounded workload that needs more than its project's deadline",
timeout: LONG_RUNNING_DEADLINE_MS * DEADLINE_SCALE,
},
],
coverage: {
enabled: false,
provider: "v8",
reportsDirectory: join(
tmpdir(),
`rea-vitest-coverage-${String(process.pid)}`,
),
include: ["src/**"],
thresholds: COVERAGE_SHARD
? ZERO_COVERAGE_THRESHOLDS
: {
statements: 65,
branches: 60,
functions: 60,
lines: 68,
"src/domain/**": {
statements: 80,
branches: 75,
functions: 75,
lines: 80,
},
"src/contracts/**": {
statements: 85,
branches: 80,
functions: 80,
lines: 85,
},
},
reporter: ["text", "text-summary"],
},
},
});
declare module "vitest" {
export interface ProvidedContext {
readonly testDeadlineScale: number;
}
}