mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
Merge reviewed master sleep diagnostics and recovery fixes
This commit is contained in:
commit
66c2ea4570
19 files changed
+513
-54
No files matched your search
@@ -0,0 +1,146 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
// A test file that stops making progress otherwise holds its CI job silently
|
||||
// until the job's time limit cancels it. Turbo prints a task's output only
|
||||
// when the task ends, so a cancelled job never names the stuck file (server
|
||||
// shard 2/12 on 2026-11-16: five cancellations at 20m16s, no file named).
|
||||
//
|
||||
// This reporter watches every running file. When one starts no test, hook or
|
||||
// result for the stall limit, it prints a GitHub error annotation naming the
|
||||
// file and the step it was in, then ends the run with a failure, so the job
|
||||
// fails minutes earlier with the file and step in its log.
|
||||
export const stallEnvName = "PAPERCLIP_VITEST_FILE_STALL_MS";
|
||||
// The slowest healthy server files ran about 5 minutes in total
|
||||
// (issue-recovery-live-run-agent-census, 235-300 s in PR shards), and no
|
||||
// single test or hook in a healthy run goes this long without progress.
|
||||
export const defaultStallMs = 8 * 60_000;
|
||||
// How long a cancelled run may take to stop before the process exits anyway.
|
||||
export const exitGraceMs = 30_000;
|
||||
const repoRoot = fileURLToPath(new URL("../../", import.meta.url));
|
||||
|
||||
export function stallLimitMs(env = process.env) {
|
||||
const configured = env[stallEnvName]?.trim();
|
||||
if (!configured) return defaultStallMs;
|
||||
const parsed = Number(configured);
|
||||
if (!Number.isInteger(parsed) || parsed <= 0) {
|
||||
throw new Error(`${stallEnvName} must be a positive integer of milliseconds. Received "${configured}".`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
// Watching is for CI, where a stuck file costs a whole job; a local run can be
|
||||
// stopped by hand. The variable turns it on anywhere, for example to reproduce.
|
||||
export function stalledFileReporterEnabled(env = process.env) {
|
||||
return env.GITHUB_ACTIONS === "true" || Boolean(env[stallEnvName]?.trim());
|
||||
}
|
||||
|
||||
function escapeData(value) {
|
||||
return String(value).replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
|
||||
}
|
||||
|
||||
function escapeProperty(value) {
|
||||
return escapeData(value).replaceAll(":", "%3A").replaceAll(",", "%2C");
|
||||
}
|
||||
|
||||
export function stallAnnotation(entry, now) {
|
||||
const minutes = ((now - entry.progressAt) / 60_000).toFixed(1);
|
||||
const properties = [`file=${escapeProperty(entry.file)}`, `title=${escapeProperty("Test file stopped making progress")}`];
|
||||
return `::error ${properties.join(",")}::${escapeData(
|
||||
`${entry.file} made no progress for ${minutes} min while in: ${entry.step}. `
|
||||
+ "The run was stopped so this job fails with the file's name instead of reaching its time limit.")}`;
|
||||
}
|
||||
|
||||
export default class StalledFileReporter {
|
||||
constructor(options = {}) {
|
||||
this.limitMs = options.limitMs ?? stallLimitMs();
|
||||
this.now = options.now ?? Date.now;
|
||||
this.exit = options.exit ?? (code => process.exit(code));
|
||||
this.write = options.write ?? (line => process.stderr.write(`${line}\n`));
|
||||
this.root = options.root ?? repoRoot;
|
||||
this.graceMs = options.graceMs ?? exitGraceMs;
|
||||
this.intervalMs = options.intervalMs ?? Math.min(15_000, Math.max(250, Math.floor(this.limitMs / 4)));
|
||||
this.files = new Map();
|
||||
this.timer = null;
|
||||
this.stopped = false;
|
||||
}
|
||||
|
||||
onInit(vitest) {
|
||||
this.vitest = vitest;
|
||||
}
|
||||
|
||||
onTestRunStart() {
|
||||
this.stopped = false;
|
||||
if (this.timer) return;
|
||||
// The reporter runs in the main Vitest process, whose timers tests never
|
||||
// fake. The interval must not keep a finished run alive.
|
||||
this.timer = setInterval(() => this.check(), this.intervalMs);
|
||||
this.timer.unref?.();
|
||||
}
|
||||
|
||||
progress(moduleId, step) {
|
||||
const entry = this.files.get(moduleId);
|
||||
if (!entry) return;
|
||||
entry.progressAt = this.now();
|
||||
entry.step = step;
|
||||
}
|
||||
|
||||
// Queued fires before the file is imported, so a file that never finishes
|
||||
// loading (a top-level await or a blocking setup import) is watched too.
|
||||
onTestModuleQueued(testModule) {
|
||||
const file = path.relative(this.root, testModule.moduleId).split(path.sep).join("/");
|
||||
this.files.set(testModule.moduleId, { file, progressAt: this.now(), step: "loading the file" });
|
||||
}
|
||||
|
||||
onTestModuleStart(testModule) {
|
||||
if (!this.files.has(testModule.moduleId)) this.onTestModuleQueued(testModule);
|
||||
this.progress(testModule.moduleId, "starting the file's tests");
|
||||
}
|
||||
|
||||
onHookStart(hook) {
|
||||
const moduleId = hook.entity?.module?.moduleId ?? hook.entity?.moduleId;
|
||||
const owner = hook.entity?.fullName ?? hook.entity?.name;
|
||||
this.progress(moduleId, owner ? `${hook.name} of ${owner}` : hook.name);
|
||||
}
|
||||
|
||||
onHookEnd(hook) {
|
||||
this.onHookStart({ ...hook, name: `after ${hook.name}` });
|
||||
}
|
||||
|
||||
onTestCaseReady(testCase) {
|
||||
this.progress(testCase.module.moduleId, `test "${testCase.fullName}"`);
|
||||
}
|
||||
|
||||
onTestCaseResult(testCase) {
|
||||
this.progress(testCase.module.moduleId, `after test "${testCase.fullName}"`);
|
||||
}
|
||||
|
||||
onTestModuleEnd(testModule) {
|
||||
this.files.delete(testModule.moduleId);
|
||||
}
|
||||
|
||||
onTestRunEnd() {
|
||||
this.files.clear();
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
// A cancelled run can report its finished files as passed. It still failed:
|
||||
// exit once the other reporters have printed their summaries.
|
||||
if (this.stopped) setTimeout(() => this.exit(1), 1000);
|
||||
}
|
||||
|
||||
check() {
|
||||
if (this.stopped) return;
|
||||
const now = this.now();
|
||||
const stalled = [...this.files.values()].filter(entry => now - entry.progressAt >= this.limitMs);
|
||||
if (stalled.length === 0) return;
|
||||
this.stopped = true;
|
||||
for (const entry of stalled) this.write(stallAnnotation(entry, now));
|
||||
const running = [...this.files.values()].map(entry => entry.file).sort();
|
||||
this.write(`[stalled-file-reporter] stopping the run; files still running: ${running.join(", ")}`);
|
||||
process.exitCode = 1;
|
||||
// A stalled worker may never answer a cancel, so exit after a grace period
|
||||
// either way. This timer is kept referenced on purpose.
|
||||
setTimeout(() => this.exit(1), this.graceMs);
|
||||
void Promise.resolve(this.vitest?.cancelCurrentRun("stalled-file")).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import test from "node:test";
|
||||
import StalledFileReporter, { defaultStallMs, stallAnnotation, stalledFileReporterEnabled, stallLimitMs }
|
||||
from "./stalled-file-reporter.mjs";
|
||||
|
||||
const root = fileURLToPath(new URL("../../", import.meta.url));
|
||||
const reporterPath = fileURLToPath(new URL("./stalled-file-reporter.mjs", import.meta.url));
|
||||
|
||||
test("the stall limit defaults to eight minutes and accepts a positive override", () => {
|
||||
assert.equal(stallLimitMs({}), defaultStallMs);
|
||||
assert.equal(defaultStallMs, 8 * 60_000);
|
||||
assert.equal(stallLimitMs({ PAPERCLIP_VITEST_FILE_STALL_MS: " 1500 " }), 1500);
|
||||
assert.equal(stallLimitMs({ PAPERCLIP_VITEST_FILE_STALL_MS: "" }), defaultStallMs);
|
||||
for (const value of ["0", "-5", "1.5", "soon"]) {
|
||||
assert.throws(() => stallLimitMs({ PAPERCLIP_VITEST_FILE_STALL_MS: value }), /positive integer/, value);
|
||||
}
|
||||
});
|
||||
|
||||
test("the reporter watches in GitHub Actions, or wherever the limit is set", () => {
|
||||
assert.equal(stalledFileReporterEnabled({}), false);
|
||||
assert.equal(stalledFileReporterEnabled({ GITHUB_ACTIONS: "true" }), true);
|
||||
assert.equal(stalledFileReporterEnabled({ PAPERCLIP_VITEST_FILE_STALL_MS: "1000" }), true);
|
||||
});
|
||||
|
||||
test("a file stops the run only once it makes no progress for the whole limit", () => {
|
||||
let now = 0;
|
||||
const lines = [], exits = [];
|
||||
const cancels = [];
|
||||
const reporter = new StalledFileReporter({ limitMs: 1000, now: () => now, write: line => lines.push(line),
|
||||
exit: code => exits.push(code), root: "/repo", graceMs: 0 });
|
||||
reporter.onInit({ cancelCurrentRun: reason => { cancels.push(reason); return Promise.resolve(); } });
|
||||
const moduleId = "/repo/server/src/stuck.test.ts";
|
||||
const testCase = { fullName: "suite > waits forever", module: { moduleId } };
|
||||
reporter.onTestModuleStart({ moduleId });
|
||||
reporter.onTestModuleStart({ moduleId: "/repo/server/src/healthy.test.ts" });
|
||||
now = 900; reporter.onTestCaseReady(testCase);
|
||||
now = 1800; reporter.onTestCaseResult({ fullName: "ok", module: { moduleId: "/repo/server/src/healthy.test.ts" } });
|
||||
reporter.check();
|
||||
assert.deepEqual(lines, [], "progress 900 ms ago is not a stall");
|
||||
now = 1900; reporter.check();
|
||||
assert.equal(lines.length, 2);
|
||||
assert.match(lines[0], /^::error file=server\/src\/stuck\.test\.ts,title=Test file stopped making progress::/);
|
||||
assert.match(lines[0], /while in: test "suite > waits forever"/);
|
||||
assert.equal(lines[1], "[stalled-file-reporter] stopping the run; files still running: server/src/healthy.test.ts, server/src/stuck.test.ts");
|
||||
assert.deepEqual(cancels, ["stalled-file"]);
|
||||
reporter.check();
|
||||
assert.equal(lines.length, 2, "a stopped run reports once");
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
test("finished files and hooks count as progress", () => {
|
||||
let now = 0;
|
||||
const lines = [];
|
||||
const reporter = new StalledFileReporter({ limitMs: 1000, now: () => now, write: line => lines.push(line), exit: () => {}, root: "/repo" });
|
||||
const moduleId = "/repo/a.test.ts";
|
||||
reporter.onTestModuleStart({ moduleId });
|
||||
now = 800; reporter.onHookStart({ name: "beforeAll", entity: { moduleId } });
|
||||
now = 1600; reporter.check();
|
||||
assert.deepEqual(lines, []);
|
||||
reporter.onTestModuleEnd({ moduleId });
|
||||
now = 10_000; reporter.check();
|
||||
assert.deepEqual(lines, []);
|
||||
assert.equal(stallAnnotation({ file: "a,b:c.test.ts", progressAt: 0, step: "x\ny" }, 90_000),
|
||||
"::error file=a%2Cb%3Ac.test.ts,title=Test file stopped making progress::a,b:c.test.ts made no progress for 1.5 min while in: x%0Ay."
|
||||
+ " The run was stopped so this job fails with the file's name instead of reaching its time limit.");
|
||||
});
|
||||
|
||||
test("a file that never finishes loading is named from the moment it is queued", () => {
|
||||
let now = 0;
|
||||
const lines = [];
|
||||
const reporter = new StalledFileReporter({ limitMs: 1000, now: () => now, write: line => lines.push(line), exit: () => {}, root: "/repo" });
|
||||
reporter.onTestModuleQueued({ moduleId: "/repo/server/src/top-level-await.test.ts" });
|
||||
now = 1000; reporter.check();
|
||||
assert.match(lines[0] ?? "", /^::error file=server\/src\/top-level-await\.test\.ts,.*while in: loading the file\./);
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
// The failure this guards: a test awaiting a promise that never settles, with
|
||||
// a test timeout longer than the CI job, holds Vitest until the job is
|
||||
// cancelled and never prints the file's name.
|
||||
for (const [label, body, step] of [
|
||||
["a test that never settles", 'import { test } from "vitest";\ntest("waits forever", () => new Promise(() => {}), 600_000);\n', 'test "waits forever"'],
|
||||
["a top-level await that never settles", 'import { test } from "vitest";\nawait new Promise(() => {});\ntest("never collected", () => {});\n', "loading the file"],
|
||||
]) test(`a real Vitest run with ${label} fails fast and names the file`, () => {
|
||||
const directory = realpathSync(mkdtempSync(path.join(tmpdir(), "stalled-file-reporter-")));
|
||||
try {
|
||||
writeFileSync(path.join(directory, "stuck.test.mjs"), body);
|
||||
writeFileSync(path.join(directory, "quick.test.mjs"), `import { test } from "vitest";
|
||||
test("passes", () => {});
|
||||
`);
|
||||
const configFile = path.join(directory, "vitest.config.mjs");
|
||||
writeFileSync(configFile, `export default ${JSON.stringify({ test: { include: ["*.test.mjs"],
|
||||
reporters: ["default", [reporterPath, { limitMs: 1500, graceMs: 5000, root: directory }]] } })};`);
|
||||
const started = Date.now();
|
||||
const result = spawnSync(process.execPath, [path.join(root, "node_modules/vitest/vitest.mjs"), "run",
|
||||
"--config", configFile, "--root", directory], {
|
||||
cwd: directory, encoding: "utf8", timeout: 60_000,
|
||||
env: { ...process.env, GITHUB_ACTIONS: "", PAPERCLIP_VITEST_FILE_STALL_MS: "" },
|
||||
});
|
||||
const output = `${result.stdout}\n${result.stderr}`;
|
||||
assert.equal(result.signal, null, `Vitest was still running after 60 s:\n${output}`);
|
||||
assert.notEqual(result.status, 0, output);
|
||||
assert.ok(Date.now() - started < 30_000, `took ${Date.now() - started} ms:\n${output}`);
|
||||
assert.match(output, /::error file=stuck\.test\.mjs,title=Test file stopped making progress::stuck\.test\.mjs made no progress/);
|
||||
assert.ok(output.includes(`while in: ${step}.`), output);
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user