repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/overkill/__tests__/checker.test.ts
RawFile outline
- temporaryPaths line 16
- afterEach line 18
- fixture line 26
- checkerInput line 42
- checker serialization line 56
- uses canonical JSON, exact shape, byte-safe truncation, and recomputed retained calls line 57
- hashes exact source bytes and exactly four lexical suite files line 99
- checker subprocess line 129
- passes exactly one newline-delimited input and accepts only the output schema line 130
- rejects a checker result when any validated suite byte changes during use line 149
- waits for forced termination and turns stdin EPIPE into infrastructure failures line 164
- treats nonzero exits, stream caps, timeout, and cancellation as infrastructure failures line 227
import { createHash } from "node:crypto";
import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
buildCheckerInput,
CheckerInfrastructureError,
canonicalJson,
executeChecker,
fingerprintSource,
fingerprintSuite,
truncateUtf8,
} from "../lib/checker.ts";
const temporaryPaths: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryPaths
.splice(0)
.map((path) => rm(path, { force: true, recursive: true })),
);
});
async function fixture(
script: string,
): Promise<{ checkerPath: string; suitePath: string }> {
const root = await mkdtemp(join(tmpdir(), "overkill-checker-"));
temporaryPaths.push(root);
const suitePath = join(root, "suite");
await mkdir(join(suitePath, "train"), { recursive: true });
await mkdir(join(suitePath, "val"), { recursive: true });
await mkdir(join(suitePath, "test"), { recursive: true });
for (const split of ["train", "val", "test"])
await writeFile(join(suitePath, split, "items.json"), "[]");
const checkerPath = join(suitePath, "check.mjs");
await writeFile(checkerPath, script);
return { checkerPath, suitePath };
}
const checkerInput = buildCheckerInput({
item: { prompt: "task", id: "a" },
response: "final",
assistantTexts: ["before", "final"],
toolCalls: [
{
name: "read",
input: { b: 1, a: 2 },
outputText: "output",
isError: false,
},
],
});
describe("checker serialization", () => {
it("uses canonical JSON, exact shape, byte-safe truncation, and recomputed retained calls", () => {
expect(canonicalJson({ z: [3, { b: true, a: 1 }], a: "x" })).toBe(
'{"a":"x","z":[3,{"a":1,"b":true}]}',
);
expect(truncateUtf8("๐๐", 7)).toBe("โฆ[truncated]");
expect(JSON.parse(checkerInput)).toEqual({
item: { id: "a", prompt: "task" },
response: "final",
trajectory: {
assistantTexts: ["before", "final"],
toolCalls: [
{
name: "read",
inputJson: '{"a":2,"b":1}',
outputText: "output",
isError: false,
},
],
},
calledTools: ["read"],
});
const bounded = JSON.parse(
buildCheckerInput({
item: { id: "a", prompt: "task" },
response: "final",
assistantTexts: Array.from(
{ length: 80 },
(_, index) => `assistant-${index}`,
),
toolCalls: Array.from({ length: 80 }, (_, index) => ({
name: `tool-${index}`,
input: {},
outputText: "",
isError: false,
})),
}),
);
expect(bounded.trajectory.assistantTexts).toHaveLength(64);
expect(bounded.trajectory.toolCalls).toHaveLength(64);
expect(bounded.calledTools[0]).toBe("tool-16");
});
it("hashes exact source bytes and exactly four lexical suite files", async () => {
const { suitePath } = await fixture("// checker");
await writeFile(join(suitePath, "train", "items.json"), "train");
await writeFile(join(suitePath, "val", "items.json"), "val");
await writeFile(join(suitePath, "test", "items.json"), "test");
const expected = createHash("sha256")
.update("check.mjs")
.update(Buffer.from([0]))
.update("// checker")
.update(Buffer.from([0]))
.update("test/items.json")
.update(Buffer.from([0]))
.update("test")
.update(Buffer.from([0]))
.update("train/items.json")
.update(Buffer.from([0]))
.update("train")
.update(Buffer.from([0]))
.update("val/items.json")
.update(Buffer.from([0]))
.update("val")
.update(Buffer.from([0]))
.digest("hex");
expect(await fingerprintSuite(suitePath)).toBe(expected);
expect(fingerprintSource(Buffer.from("same\r\n"))).not.toBe(
fingerprintSource(Buffer.from("same\n")),
);
});
});
describe("checker subprocess", () => {
it("passes exactly one newline-delimited input and accepts only the output schema", async () => {
const { checkerPath, suitePath } = await fixture(
"let input = ''; process.stdin.on('data', chunk => input += chunk); process.stdin.on('end', () => { if (!input.endsWith('\\n')) process.exit(4); process.stdout.write(JSON.stringify({ score: 0.5, passed: false, feedback: 'ok' })); });",
);
await expect(
executeChecker({ checkerPath, suitePath, input: checkerInput }),
).resolves.toEqual({ score: 0.5, passed: false, feedback: "ok" });
const bad = await fixture(
"process.stdout.write(JSON.stringify({ score: 1, passed: true, extra: 1 }));",
);
await expect(
executeChecker({
checkerPath: bad.checkerPath,
suitePath: bad.suitePath,
input: checkerInput,
}),
).rejects.toThrow("unknown");
});
it("rejects a checker result when any validated suite byte changes during use", async () => {
const mutable = await fixture(
"import { writeFileSync } from 'node:fs'; writeFileSync(new URL('./val/items.json', import.meta.url), '[{\"id\":\"changed\"}]'); process.stdout.write(JSON.stringify({ score: 1, passed: true }));",
);
const expectedSuiteFingerprint = await fingerprintSuite(mutable.suitePath);
await expect(
executeChecker({
checkerPath: mutable.checkerPath,
suitePath: mutable.suitePath,
input: checkerInput,
expectedSuiteFingerprint,
}),
).rejects.toThrow("suite fingerprint changed");
});
it("waits for forced termination and turns stdin EPIPE into infrastructure failures", async () => {
const slow = await fixture(
"import { writeFileSync } from 'node:fs'; process.on('SIGTERM', () => {}); setTimeout(() => writeFileSync(process.env.OVERKILL_MARKER, 'late'), 500);",
);
const marker = join(slow.suitePath, "late-marker");
const environment = process.env.OVERKILL_MARKER;
process.env.OVERKILL_MARKER = marker;
try {
await expect(
executeChecker({
checkerPath: slow.checkerPath,
suitePath: slow.suitePath,
input: checkerInput,
timeoutMs: 250,
}),
).rejects.toThrow("timed out");
await new Promise((resolve) => setTimeout(resolve, 550));
await expect(access(marker)).rejects.toThrow();
} finally {
if (environment === undefined) delete process.env.OVERKILL_MARKER;
else process.env.OVERKILL_MARKER = environment;
}
const earlyExit = await fixture(
"process.stdin.destroy(); process.exit(0);",
);
await expect(
executeChecker({
checkerPath: earlyExit.checkerPath,
suitePath: earlyExit.suitePath,
input: "x".repeat(1024 * 1024),
}),
).rejects.toBeInstanceOf(CheckerInfrastructureError);
});
it.skipIf(process.platform === "win32")(
"kills POSIX checker descendants retaining inherited stdio without waiting for close",
async () => {
const slow = await fixture(
"import { spawn } from 'node:child_process'; import { writeFileSync } from 'node:fs'; spawn(process.execPath, ['-e', `setTimeout(() => require('node:fs').writeFileSync(process.env.OVERKILL_MARKER, 'late'), 1000)`], { stdio: 'inherit' }); process.on('SIGTERM', () => {}); setTimeout(() => {}, 5000);",
);
const marker = join(slow.suitePath, "descendant-marker");
const environment = process.env.OVERKILL_MARKER;
process.env.OVERKILL_MARKER = marker;
try {
const started = Date.now();
await expect(
executeChecker({
checkerPath: slow.checkerPath,
suitePath: slow.suitePath,
input: checkerInput,
timeoutMs: 30,
}),
).rejects.toThrow("timed out");
expect(Date.now() - started).toBeLessThan(500);
await new Promise((resolve) => setTimeout(resolve, 1_100));
await expect(access(marker)).rejects.toThrow();
} finally {
if (environment === undefined) delete process.env.OVERKILL_MARKER;
else process.env.OVERKILL_MARKER = environment;
}
},
);
it("treats nonzero exits, stream caps, timeout, and cancellation as infrastructure failures", async () => {
const nonzero = await fixture(
"process.stderr.write('no'); process.exit(2);",
);
await expect(
executeChecker({
checkerPath: nonzero.checkerPath,
suitePath: nonzero.suitePath,
input: checkerInput,
}),
).rejects.toThrow("exited");
const noisy = await fixture("process.stdout.write('x'.repeat(70 * 1024));");
await expect(
executeChecker({
checkerPath: noisy.checkerPath,
suitePath: noisy.suitePath,
input: checkerInput,
}),
).rejects.toThrow("cap");
const slow = await fixture("setTimeout(() => {}, 1_000);");
await expect(
executeChecker({
checkerPath: slow.checkerPath,
suitePath: slow.suitePath,
input: checkerInput,
timeoutMs: 20,
}),
).rejects.toThrow("timed out");
const controller = new AbortController();
controller.abort();
await expect(
executeChecker({
checkerPath: slow.checkerPath,
suitePath: slow.suitePath,
input: checkerInput,
signal: controller.signal,
}),
).rejects.toThrow("cancelled");
});
});