repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/__tests__/training.test.ts

Raw
File outline
import { describe, expect, it } from "vitest";
import { parsePatch } from "../lib/patches.ts";
import {
	createTrainingState,
	runDurableTrainingSchedule,
	runTrainingSchedule,
	TrainingCancelledError,
} from "../lib/training.ts";

const score = (id: string, value: number, passed = value === 1) => ({
	id,
	score: value,
	passed,
});

describe("strict optimizer schedule", () => {
	it("uses full train and validation arithmetic scoring, accepts only strict improvements, then reports one test", async () => {
		const calls: Array<[string, string]> = [];
		const result = await runTrainingSchedule(
			{
				body: "base",
				baseline: [score("v1", 0.25, false), score("v2", 0.75, false)],
			},
			{
				async evaluate(body, split) {
					calls.push([body, split]);
					if (split === "train")
						return [score("t1", body === "base" ? 0 : 1, body !== "base")];
					if (split === "validation")
						return [
							score("v1", body === "base" ? 0.25 : 1),
							score("v2", body === "base" ? 0.75 : 1),
						];
					return [score("held-out", 0.5, false)];
				},
				async optimize() {
					return {
						patch: parsePatch({ edits: [{ op: "append", content: "better" }] }),
						calls: 4,
					};
				},
			},
		);
		expect(result).toMatchObject({
			bestBody: "base\nbetter",
			baselineScore: 0.5,
			bestScore: 1,
			testScore: 0.5,
			terminal: "perfect",
			accepted: 1,
		});
		expect(calls).toEqual([
			["base", "train"],
			["base\nbetter", "validation"],
			["base\nbetter", "test"],
		]);
	});

	it("rejects equal validation scores, records bounded rejection context, and stops after two rejections without reading test", async () => {
		let optimizerCalls = 0;
		const requested: string[] = [];
		const result = await runTrainingSchedule(
			{ body: "base", baseline: [score("v", 0.5, false)] },
			{
				async evaluate(body, split) {
					requested.push(`${body}:${split}`);
					return [score(split, split === "train" ? 0 : 0.5, false)];
				},
				async optimize(input) {
					optimizerCalls += 1;
					if (optimizerCalls === 2)
						expect(input.rejections).toMatchObject([
							{
								reason: "validation score did not strictly improve",
								delta: 0,
								edits: [{ op: "append", content: "try-1" }],
							},
						]);
					return {
						patch: parsePatch({
							edits: [{ op: "append", content: `try-${optimizerCalls}` }],
						}),
						calls: 3,
					};
				},
			},
		);
		expect(result).toMatchObject({ terminal: "two_rejections", accepted: 0 });
		expect(result.testScore).toBeUndefined();
		expect(optimizerCalls).toBe(2);
		expect(requested.some((value) => value.endsWith(":test"))).toBe(false);
	});

	it("reports the accepted candidate once when a later all-pass stop occurs", async () => {
		const calls: string[] = [];
		const result = await runTrainingSchedule(
			{ body: "base", baseline: [score("v", 0, false)] },
			{
				async evaluate(body, split) {
					calls.push(`${body}:${split}`);
					if (split === "train")
						return [score("t", body === "base" ? 0 : 1, body !== "base")];
					if (split === "validation") return [score("v", 0.5, false)];
					return [score("held-out", 0.5, false)];
				},
				async optimize() {
					return {
						patch: parsePatch({ edits: [{ op: "append", content: "better" }] }),
						calls: 1,
					};
				},
			},
		);
		expect(result).toMatchObject({ accepted: 1, testScore: 0.5 });
		expect(calls.filter((call) => call.endsWith(":test"))).toEqual([
			"base\nbetter:test",
		]);
	});

	it("resumes from a checkpointed optimizer patch without repeating its call, then records one final test", async () => {
		let optimizerCalls = 0;
		let testCalls = 0;
		let interrupted = false;
		let checkpoint = createTrainingState({
			body: "base",
			baseline: [score("v", 0, false)],
		});
		const seam = {
			async evaluate(body: string, split: "train" | "validation" | "test") {
				if (split === "test") {
					testCalls += 1;
					return [score("held-out", 0.5, false)];
				}
				if (split === "train")
					return [score("train", body === "base" ? 0 : 1, body !== "base")];
				return [score("val", body === "base" ? 0 : 0.5, false)];
			},
			async optimize() {
				optimizerCalls += 1;
				return {
					patch: parsePatch({ edits: [{ op: "append", content: "better" }] }),
					calls: 4,
				};
			},
			async checkpoint(next: typeof checkpoint) {
				checkpoint = structuredClone(next);
				if (!interrupted && checkpoint.pendingPatch) {
					interrupted = true;
					throw new Error("interrupt after optimizer output");
				}
			},
		};
		await expect(runDurableTrainingSchedule(checkpoint, seam)).rejects.toThrow(
			"interrupt after optimizer output",
		);
		expect({ optimizerCalls, testCalls }).toEqual({
			optimizerCalls: 1,
			testCalls: 0,
		});
		const result = await runDurableTrainingSchedule(checkpoint, seam);
		expect(result).toMatchObject({
			accepted: 1,
			bestBody: "base\nbetter",
			testScore: 0.5,
			terminal: "all_pass",
		});
		expect({ optimizerCalls, testCalls }).toEqual({
			optimizerCalls: 1,
			testCalls: 1,
		});
		expect(checkpoint).toMatchObject({
			nextStep: 2,
			accepted: 1,
			finalTestScore: 0.5,
			pendingPatch: undefined,
		});
	});

	it("preserves partial final-test IDs across resume checkpoints", async () => {
		const initial = {
			...createTrainingState({
				body: "base",
				baseline: [score("v", 0, false)],
			}),
			terminal: "perfect" as const,
			accepted: 1,
			bestBody: "better",
			finalTest: { body: "better", completedItemIds: ["held-1"], total: 2 },
		};
		const checkpoints: (typeof initial)[] = [];
		await runDurableTrainingSchedule(initial, {
			async evaluate(_body, split) {
				expect(split).toBe("test");
				return [score("held-1", 1, true), score("held-2", 0, false)];
			},
			async optimize() {
				throw new Error("optimizer must remain complete");
			},
			async checkpoint(state) {
				checkpoints.push(state);
			},
			testItemIds: ["held-1", "held-2"],
		});
		expect(checkpoints[0]?.finalTest?.completedItemIds).toEqual(["held-1"]);
	});

	it("checkpoints consumed optimizer reflection calls and completed phases before malformed later output", async () => {
		let checkpoint = createTrainingState({
			body: "base",
			baseline: [score("v", 0, false)],
		});
		await expect(
			runDurableTrainingSchedule(checkpoint, {
				async evaluate(_body, split) {
					if (split === "train") return [score("t", 0, false)];
					throw new Error("must not validate");
				},
				async optimize(_input, onCall, onProgress) {
					await onCall?.();
					await onProgress?.({ failure: "root cause" });
					await onCall?.();
					throw new Error("malformed ranking output");
				},
				async checkpoint(state) {
					checkpoint = structuredClone(state);
				},
			}),
		).rejects.toThrow("malformed ranking");
		expect(checkpoint).toMatchObject({
			optimizerCalls: 2,
			pendingOptimizer: { step: 1, failure: "root cause" },
		});
	});

	it("never resumes an optimizer prompt after the persisted attempt cap", async () => {
		let reachedPrompt = false;
		await expect(
			runDurableTrainingSchedule(
				{
					...createTrainingState({
						body: "base",
						baseline: [score("v", 0, false)],
					}),
					optimizerCalls: 12,
				},
				{
					async evaluate(_body, split) {
						if (split === "train") return [score("t", 0, false)];
						throw new Error("unexpected evaluation");
					},
					async optimize(_input, onCall) {
						await onCall?.();
						reachedPrompt = true;
						throw new Error("prompt must not run");
					},
					async checkpoint() {},
				},
			),
		).rejects.toThrow("optimizer call maximum exceeded");
		expect(reachedPrompt).toBe(false);
	});

	it("stops at a checkpoint cancellation before scheduling validation work", async () => {
		const controller = new AbortController();
		const evaluated: string[] = [];
		let optimized = 0;
		await expect(
			runDurableTrainingSchedule(
				createTrainingState({ body: "base", baseline: [score("v", 0, false)] }),
				{
					async evaluate(_body, split) {
						evaluated.push(split);
						return [score(split, 0, false)];
					},
					async optimize() {
						optimized += 1;
						return {
							patch: parsePatch({
								edits: [{ op: "append", content: "candidate" }],
							}),
							calls: 1,
						};
					},
					async checkpoint(state) {
						if (state.pendingPatch) controller.abort();
					},
					signal: controller.signal,
				},
			),
		).rejects.toBeInstanceOf(TrainingCancelledError);
		expect({ evaluated, optimized }).toEqual({
			evaluated: ["train"],
			optimized: 1,
		});
	});

	it("does not resolve held-out IDs until a candidate has been accepted", async () => {
		let heldOutResolved = false;
		await runDurableTrainingSchedule(
			createTrainingState({ body: "base", baseline: [score("v", 0.5, false)] }),
			{
				async evaluate(_body, split) {
					if (split === "train") return [score("t", 1, true)];
					throw new Error("validation and test must remain locked");
				},
				async optimize() {
					throw new Error("optimizer must remain locked");
				},
				async checkpoint() {},
				async testItemIds() {
					heldOutResolved = true;
					return ["held-out"];
				},
			},
		);
		expect(heldOutResolved).toBe(false);
	});

	it("stops before optimizer calls when every training rollout passes", async () => {
		let optimized = 0;
		const result = await runTrainingSchedule(
			{ body: "base", baseline: [score("v", 0.5, false)] },
			{
				async evaluate(_body, split) {
					if (split === "train") return [score("t", 1, true)];
					throw new Error("validation and test must remain locked");
				},
				async optimize() {
					optimized += 1;
					throw new Error("must not optimize all-pass training");
				},
			},
		);
		expect(result).toMatchObject({ terminal: "all_pass", accepted: 0 });
		expect(optimized).toBe(0);
	});
});