import { applyPatch, type EditReport, type Patch, type PatchEdit, } from "./patches.ts"; export type ItemScore = { id: string; score: number; passed: boolean; feedback?: string; trajectory?: unknown; }; type Split = "train" | "validation" | "test"; export type Rejection = { reason: string; delta: number; reports?: EditReport[]; edits?: PatchEdit[]; }; type Terminal = "perfect" | "all_pass" | "two_rejections" | "three_steps"; export type OptimizerProgress = { step: number; failure?: string; success?: string; merged?: string; }; export type OptimizerReflectionProgress = Omit; export type AttemptedPatch = { patch: Patch; reports: EditReport[]; validationScore?: number; }; export class TrainingCancelledError extends Error { constructor() { super("durable training cancelled"); } } function mean(scores: readonly ItemScore[]): number { if (scores.length === 0) throw new Error("full split evaluation returned no scores"); let total = 0; for (const entry of scores) { if (!Number.isFinite(entry.score) || entry.score < 0 || entry.score > 1) throw new Error("split evaluation returned an invalid score"); total += entry.score; } return total / scores.length; } function boundedRejections(rejections: readonly Rejection[]): Rejection[] { return rejections.slice(-8).map((rejection) => ({ reason: rejection.reason.slice(0, 1024), delta: rejection.delta, ...(rejection.reports === undefined ? {} : { reports: rejection.reports.slice(0, 4).map((report) => ({ index: report.index, status: report.status, ...(report.reason === undefined ? {} : { reason: report.reason.slice(0, 512) }), })), }), ...(rejection.edits === undefined ? {} : { edits: structuredClone(rejection.edits) }), })); } export type DurableTrainingState = { nextStep: number; body: string; bestBody: string; baselineScore: number; currentScore: number; bestScore: number; accepted: number; optimizerCalls: number; consecutiveRejections: number; rejections: Rejection[]; attempts: AttemptedPatch[]; pendingPatch?: { step: number; body: string; patch: Patch }; pendingOptimizer?: OptimizerProgress; terminal?: Terminal; finalTest?: { body: string; completedItemIds: string[]; total: number; score?: number; }; finalTestScore?: number; }; export function createTrainingState(options: { body: string; baseline: readonly ItemScore[]; }): DurableTrainingState { const baselineScore = mean(options.baseline); return { nextStep: 1, body: options.body, bestBody: options.body, baselineScore, currentScore: baselineScore, bestScore: baselineScore, accepted: 0, optimizerCalls: 0, consecutiveRejections: 0, rejections: [], attempts: [], ...(baselineScore === 1 ? { terminal: "perfect" as const } : {}), }; } function durableResult(state: DurableTrainingState): { bestBody: string; baselineScore: number; bestScore: number; testScore?: number; terminal: Terminal; accepted: number; steps: number; optimizerCalls: number; rejections: Rejection[]; attempts: AttemptedPatch[]; } { if (!state.terminal) throw new Error("durable training has not terminated"); return { bestBody: state.bestBody, baselineScore: state.baselineScore, bestScore: state.bestScore, ...(state.finalTestScore === undefined ? {} : { testScore: state.finalTestScore }), terminal: state.terminal, accepted: state.accepted, steps: state.nextStep - 1, optimizerCalls: state.optimizerCalls, rejections: state.rejections, attempts: state.attempts, }; } /** * Checkpoints every model-side boundary. * A persisted pending patch means its optimizer step completed and must never run again. */ export async function runDurableTrainingSchedule( initial: DurableTrainingState, seam: { evaluate: ( body: string, split: Split, onProgress?: (progress: { completed: number; total: number; }) => Promise, ) => Promise; optimize: ( input: { body: string; failures: readonly ItemScore[]; successes: readonly ItemScore[]; rejections: readonly Rejection[]; }, onCall?: () => Promise, onProgress?: (progress: OptimizerReflectionProgress) => Promise, ) => Promise<{ patch: Patch; calls: number }>; checkpoint: (state: DurableTrainingState) => Promise; testItemIds?: readonly string[] | (() => Promise); signal?: AbortSignal; }, ): Promise> { const state = structuredClone(initial) as DurableTrainingState; const ensureNotCancelled = () => { if (seam.signal?.aborted) throw new TrainingCancelledError(); }; const checkpoint = async () => { await seam.checkpoint(structuredClone(state)); ensureNotCancelled(); }; ensureNotCancelled(); if (state.nextStep < 1 || state.nextStep > 4) throw new Error("invalid durable training step position"); const finishTest = async () => { if (state.accepted === 0 || state.finalTestScore !== undefined) return; const testItemIds = typeof seam.testItemIds === "function" ? await seam.testItemIds() : (seam.testItemIds ?? []); ensureNotCancelled(); state.finalTest ??= { body: state.bestBody, completedItemIds: [], total: testItemIds.length, }; await checkpoint(); const scores = await seam.evaluate( state.bestBody, "test", async (progress) => { if (!state.finalTest) throw new Error("final test state is unavailable"); state.finalTest.completedItemIds = testItemIds.slice( 0, progress.completed, ); state.finalTest.total = progress.total; await checkpoint(); }, ); ensureNotCancelled(); state.finalTestScore = mean(scores); state.finalTest.score = state.finalTestScore; state.finalTest.completedItemIds = [...testItemIds]; await checkpoint(); }; if (state.terminal) { await finishTest(); return durableResult(state); } for (let step = state.nextStep; step <= 3; step += 1) { ensureNotCancelled(); let pending = state.pendingPatch; if (pending && pending.step !== step) throw new Error("pending optimizer patch has an invalid step position"); if (!pending) { const training = await seam.evaluate(state.body, "train"); ensureNotCancelled(); const failures = training.filter((entry) => !entry.passed); const successes = training.filter((entry) => entry.passed); if (failures.length === 0) { state.terminal = "all_pass"; await checkpoint(); break; } if (state.pendingOptimizer && state.pendingOptimizer.step !== step) throw new Error("pending optimizer state has an invalid step position"); let checkpointedCalls = 0; ensureNotCancelled(); const optimized = await seam.optimize( { body: state.body, failures, successes, rejections: boundedRejections(state.rejections), }, async () => { if (state.optimizerCalls >= 12) throw new Error("optimizer call maximum exceeded"); checkpointedCalls += 1; state.optimizerCalls += 1; await checkpoint(); }, async (progress) => { state.pendingOptimizer = { ...progress, step }; await checkpoint(); }, ); ensureNotCancelled(); state.optimizerCalls += Math.max(0, optimized.calls - checkpointedCalls); state.pendingOptimizer = undefined; pending = { step, body: state.body, patch: optimized.patch }; state.pendingPatch = pending; await checkpoint(); } const applied = applyPatch(pending.body, pending.patch); const attempt: AttemptedPatch = { patch: pending.patch, reports: applied.reports, }; state.attempts.push(attempt); state.pendingPatch = undefined; state.nextStep = step + 1; if (!applied.changed) { state.consecutiveRejections += 1; state.rejections.push({ reason: applied.reports[0]?.reason ?? "patch was rejected", delta: 0, reports: applied.reports, edits: pending.patch.edits, }); if (state.consecutiveRejections === 2) state.terminal = "two_rejections"; await checkpoint(); if (state.terminal) break; continue; } const validationScores = await seam.evaluate(applied.body, "validation"); ensureNotCancelled(); const validationScore = mean(validationScores); attempt.validationScore = validationScore; if (validationScore > state.currentScore) { state.body = applied.body; state.bestBody = applied.body; state.currentScore = validationScore; state.bestScore = validationScore; state.accepted += 1; state.consecutiveRejections = 0; if (validationScore === 1) state.terminal = "perfect"; } else { state.consecutiveRejections += 1; state.rejections.push({ reason: "validation score did not strictly improve", delta: validationScore - state.currentScore, reports: applied.reports, edits: pending.patch.edits, }); if (state.consecutiveRejections === 2) state.terminal = "two_rejections"; } await checkpoint(); if (state.terminal) break; } if (!state.terminal) { state.terminal = "three_steps"; await checkpoint(); } await finishTest(); return durableResult(state); } export async function runTrainingSchedule( options: { body: string; baseline: readonly ItemScore[] }, seam: { evaluate: (body: string, split: Split) => Promise; optimize: (input: { body: string; failures: readonly ItemScore[]; successes: readonly ItemScore[]; rejections: readonly Rejection[]; }) => Promise<{ patch: Patch; calls: number }>; }, ): Promise<{ bestBody: string; baselineScore: number; bestScore: number; testScore?: number; terminal: Terminal; accepted: number; steps: number; optimizerCalls: number; rejections: Rejection[]; attempts: AttemptedPatch[]; }> { const baselineScore = mean(options.baseline); let bestScore = baselineScore; let bestBody = options.body; let accepted = 0; let optimizerCalls = 0; let consecutiveRejections = 0; const rejections: Rejection[] = []; const attempts: AttemptedPatch[] = []; const finish = async (terminal: Terminal, steps: number) => ({ bestBody, baselineScore, bestScore, ...(accepted > 0 ? { testScore: mean(await seam.evaluate(bestBody, "test")) } : {}), terminal, accepted, steps, optimizerCalls, rejections, attempts, }); if (baselineScore === 1) return await finish("perfect", 0); for (let step = 1; step <= 3; step += 1) { const training = await seam.evaluate(bestBody, "train"); const failures = training.filter((entry) => !entry.passed); const successes = training.filter((entry) => entry.passed); if (failures.length === 0) return await finish("all_pass", step); const optimized = await seam.optimize({ body: bestBody, failures, successes, rejections: boundedRejections(rejections), }); optimizerCalls += optimized.calls; const applied = applyPatch(bestBody, optimized.patch); const attempt: AttemptedPatch = { patch: optimized.patch, reports: applied.reports, }; attempts.push(attempt); if (!applied.changed) { consecutiveRejections += 1; rejections.push({ reason: applied.reports[0]?.reason ?? "patch was rejected", delta: 0, reports: applied.reports, edits: optimized.patch.edits, }); if (consecutiveRejections === 2) return await finish("two_rejections", step); continue; } const validationScore = mean( await seam.evaluate(applied.body, "validation"), ); attempt.validationScore = validationScore; if (validationScore > bestScore) { bestBody = applied.body; bestScore = validationScore; accepted += 1; consecutiveRejections = 0; if (bestScore === 1) return await finish("perfect", step); continue; } consecutiveRejections += 1; rejections.push({ reason: "validation score did not strictly improve", delta: validationScore - bestScore, reports: applied.reports, edits: optimized.patch.edits, }); if (consecutiveRejections === 2) return await finish("two_rejections", step); } return await finish("three_steps", 3); }