diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d9b340..cca5835 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ evaluation and measured step latency. Observed comparisons now require an explicit tool/control action registry. Actual IgnitionRAG runtime evidence remains unproven. +- Add strict tabular/linear policy artifacts, explicit baseline gates and a local + immutable registry with atomic promotion and rollback; synthetic lifecycle demo. + - Add a versioned, pseudonymized trajectory import and observed-policy evidence comparison contract. Real IgnitionRAG evidence remains unverified without an authorized export. diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index 0feaa4a..ddaac46 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -3278,3 +3278,14 @@ Return to this repository only to fix concrete issues discovered by real dogfood - #55: implemented and verified in draft PR #61; issue closed; merge pending. - #56: importer/evidence contract current on `feat/ignitionrag-trajectory-evidence`; actual real-export/gain criteria blocked by unavailable data access. Issue stays open. - Next: #55 rich observable features; #56 real IgnitionRAG trajectories; #57 policy artifacts/rollback; #58 algorithm decision. + +## Policy artifact lifecycle — issue #57 + +Implemented in a draft branch pending review and merge: +- strict versioned tabular/linear artifacts and compatibility-bound greedy loading; +- immutable local versions and gate reports, pinned baseline thresholds; +- explicit promotion, exclusive writer locking and atomic one-step rollback; +- synthetic held-out ReAct lifecycle report and process termination coverage. + +Real IgnitionRAG gain/adoption is still not proven (#56); this local registry does +not deploy policies or authenticate caller-supplied evaluation evidence. diff --git a/docs/POLICY_REGISTRY.md b/docs/POLICY_REGISTRY.md new file mode 100644 index 0000000..76f70fa --- /dev/null +++ b/docs/POLICY_REGISTRY.md @@ -0,0 +1,63 @@ +# Local policy artifacts and registry + +The experimental RL package exports `createPolicyArtifact`, `parsePolicyArtifact`, +`loadPolicyArtifact`, `comparePolicyBaseline`, and `LocalPolicyRegistry`. + +Artifacts use schema version 1 and identify tabular or linear Q-learning, learned +parameters, encoder id/version/parameters, complete action registry, training +hyperparameters, seeds, data provenance, reward configuration and evaluation +report reference. Their identity is the SHA-256 of canonical finite JSON. Unknown +fields, schema versions, duplicate table states/actions, non-finite values and +inconsistent linear dimensions are refused. The checksum detects corruption; +it does not authenticate data provenance or report authorship. + +Loading requires an explicitly registered runtime encoder with an exactly matching +descriptor and action registry. Pure encoder and action binder functions are +application code, never executable content embedded in an artifact. Include the +binder version in encoder parameters when argument binding is used. For linear +policies, include fitted normalization/category definitions in those parameters +and construct the compatible encoder from that public descriptor. No calibration +observations or private task content are needed. Callers own the truth of this +function-to-descriptor association; an artifact cannot validate arbitrary code. +The loaded policy is detached and greedy, with lexical tie-breaking and current +available-action masks, just as the original frozen policy. + +`register` writes an immutable content-addressed version. `initialize` explicitly +pins a baseline once; registration alone never changes active policy. `promote` +accepts observed aggregate metrics on a named independent corpus and an explicit +candidate evaluation report reference. It revalidates both artifacts, pins the +baseline to the current active identity, and requires compatible algorithm/encoder/actions, +reward configuration and evidence mode. Success, reward and tool thresholds are +mandatory; a cost threshold may be null when cost is not available. Requiring a +cost threshold with incomplete costs blocks promotion. Both failed and passed +gates preserve all thresholds and reasons in content-addressed local reports. +Metrics supplied by callers are not automatically authenticated; use the real +trajectory evidence protocol before considering a real deployment. + +An exclusive `.writer.lock` refuses concurrent pointer mutations. Promotion and +rollback write and fsync a temporary pointer, then atomically rename it within the +registry directory and fsync that directory. Before commit an interrupted writer +leaves the old pointer; after commit it leaves the new pointer. Rollback restores +the preceding active artifact and its baseline identity, then clears the one-step +rollback slot. A later promotion establishes another rollback slot. Immutability +means registering an existing damaged file fails rather than silently repairing +it. Readers validate active artifact checksums. This requires a local filesystem +with atomic same-directory rename and fsync support, not a cloud object store. + +After a killed process, a stale writer lock may remain. Readers still work; further +mutations fail closed. An operator must confirm no writer is alive before moving +the stale lock to Trash. Incomplete staging files are never read as active. +Initial registry creation must complete successfully before it is exposed to +readers. This provides a local recovery workflow, not a production rollout system. + +Run the executable lifecycle on a new directory: + +```sh +bun examples/react-policy-optimization/src/registry.ts /tmp/policy-lifecycle-new +``` + +It trains on six synthetic order tasks, reloads on 24 independent tasks, compares +against a pinned untrained baseline with explicit tool allowance, promotes +explicitly and rolls back. The report includes seeds, task ids, artifact ids, +thresholds and decision-preservation checks. It labels all evidence synthetic; +this demonstrates local lifecycle behavior and does not prove an IgnitionRAG gain. diff --git a/examples/react-policy-optimization/README.md b/examples/react-policy-optimization/README.md index 826e3bd..7a2fb60 100644 --- a/examples/react-policy-optimization/README.md +++ b/examples/react-policy-optimization/README.md @@ -137,3 +137,13 @@ selection and invalid offline inputs: ```bash bun test examples/react-policy-optimization/src/example.test.ts packages/rl/src/policy-optimization.test.ts ``` + +Local immutable artifacts, baseline gates and rollback are demonstrated with: + +```sh +bun src/registry.ts /tmp/policy-lifecycle-new +``` + +Use a new directory. The synthetic report proves reload/promotion/rollback behavior; +real IgnitionRAG adoption remains subject to the trajectory evidence protocol. +See [the registry contract](../../docs/POLICY_REGISTRY.md). diff --git a/examples/react-policy-optimization/src/registry.ts b/examples/react-policy-optimization/src/registry.ts new file mode 100644 index 0000000..672c75b --- /dev/null +++ b/examples/react-policy-optimization/src/registry.ts @@ -0,0 +1,142 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { pathToFileURL } from "node:url"; +import { + createPolicyArtifact, + LocalPolicyRegistry, + loadPolicyArtifact, + type PolicyGateInput, + type PolicyMetrics, +} from "@ignitionai/agent-trainer-rl"; +import { + bindOrderAction, + createOrderLearner, + encodeOrderState, + evaluateOrderPolicy, + evaluationTasks, + trainOrderPolicy, +} from "./learning"; + +export async function runPolicyRegistryExample(directory: string) { + const seed = 57; + const runtime = { + encoder: { + id: "order-observable", + version: 1, + parameters: { + stateFields: ["done", "quantity-is-one", "has-price", "has-total"], + binder: "order-answer-v1", + }, + }, + actions: ["answer", "lookup_price", "calculate_total"], + encodeState: encodeOrderState, + bindAction: bindOrderAction, + }; + const trained = await trainOrderPolicy(seed); + const metadata = { + schemaVersion: 1 as const, + algorithm: "tabular-q" as const, + encoder: runtime.encoder, + actions: runtime.actions, + hyperparameters: { alpha: 0.3, gamma: 1, epsilon: 0.3 }, + seeds: [seed], + provenance: { + reference: "synthetic-order-calibration-v1", + mode: "synthetic" as const, + fingerprint: "six-public-order-tasks-v1", + }, + rewardConfigId: "order-correctness-minus-tool-002-v1", + evaluationReportId: "registry-heldout-v1", + }; + const baseline = createPolicyArtifact({ + ...metadata, + parameters: createOrderLearner(seed).snapshot(), + }); + const candidate = createPolicyArtifact({ ...metadata, parameters: trained.learner.snapshot() }); + const registry = new LocalPolicyRegistry(`${directory}/registry`); + await registry.register(baseline); + await registry.register(candidate); + await registry.initialize(baseline.id); + const evaluatedBaseline = await evaluateOrderPolicy( + loadPolicyArtifact(baseline, runtime), + evaluationTasks, + baseline.id, + ); + const evaluatedCandidate = await evaluateOrderPolicy( + loadPolicyArtifact(candidate, runtime), + evaluationTasks, + candidate.id, + ); + const originalCandidate = await evaluateOrderPolicy( + trained.learner.freeze(), + evaluationTasks, + "original-frozen", + ); + const metrics = (result: typeof evaluatedBaseline): PolicyMetrics => ({ + successRate: result.successRate, + reward: result.averageReward, + tools: result.averageToolCalls, + costUsd: null, + }); + const gate: PolicyGateInput = { + baselineId: baseline.id, + candidateId: candidate.id, + corpusId: "24-disjoint-order-tasks-v1", + evaluationReportId: metadata.evaluationReportId, + mode: "synthetic", + baseline: metrics(evaluatedBaseline), + candidate: metrics(evaluatedCandidate), + // Untrained baseline spends no tools; allow up to 2 to solve the task. + thresholds: { + maxSuccessDrop: 0, + maxRewardDrop: 0, + maxToolIncrease: 2, + maxCostIncreaseUsd: null, + }, + }; + const promotion = await registry.promote(gate); + const activeAfterPromotion = await registry.active(); + const rollback = await registry.rollback(); + const restored = await evaluateOrderPolicy( + loadPolicyArtifact(await registry.readVersion(rollback.activeId), runtime), + evaluationTasks, + rollback.activeId, + ); + const report = { + schemaVersion: "ignition.policy-registry-example.v1", + evidenceMode: "synthetic", + productionAdoption: "NOT PROVEN; local lifecycle only", + seed, + baselineId: baseline.id, + candidateId: candidate.id, + evaluationTaskIds: evaluationTasks.map((task) => task.id), + reloadPreservesDecisions: + JSON.stringify(evaluatedCandidate.cases) === JSON.stringify(originalCandidate.cases), + promotion, + activeAfterPromotion, + rollback, + rollbackPreservesBaseline: + rollback.activeId === baseline.id && + rollback.baselineId === baseline.id && + JSON.stringify(restored.cases) === JSON.stringify(evaluatedBaseline.cases), + baseline: evaluatedBaseline.cases, + candidate: evaluatedCandidate.cases, + }; + if (!report.reloadPreservesDecisions || !report.rollbackPreservesBaseline || !promotion.passed) + throw new Error("Local lifecycle verification failed."); + await mkdir(directory, { recursive: true }); + await writeFile(`${directory}/policy-registry.json`, `${JSON.stringify(report, null, 2)}\n`); + return report; +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const directory = process.argv[2]; + if (!directory) + throw new Error( + "Supply a new output directory; existing active registry initialization is refused.", + ); + const report = await runPolicyRegistryExample(directory); + console.table({ + reloadPreservesDecisions: report.reloadPreservesDecisions, + promotionPassed: report.promotion.passed, + rollbackPreservesBaseline: report.rollbackPreservesBaseline, + }); +} diff --git a/packages/rl/src/index.ts b/packages/rl/src/index.ts index 634e2cd..bed546f 100644 --- a/packages/rl/src/index.ts +++ b/packages/rl/src/index.ts @@ -7,7 +7,9 @@ export * from "./learning-episode"; export * from "./linear-q-learning"; export * from "./offline-policy-evaluation"; export * from "./policy"; +export * from "./policy-artifact"; export * from "./policy-optimization"; +export * from "./policy-registry"; export * from "./ppo"; export * from "./q-learning"; export * from "./strategy-bandit"; diff --git a/packages/rl/src/linear-q-learning.test.ts b/packages/rl/src/linear-q-learning.test.ts index c1e0e4d..cb37c50 100644 --- a/packages/rl/src/linear-q-learning.test.ts +++ b/packages/rl/src/linear-q-learning.test.ts @@ -84,7 +84,7 @@ test("linear policy rejects malformed vectors, unavailable actions and invalid p for (const actions of [[], [{ name: "unknown" }], [{ name: "a" }, { name: "a" }]]) { await expect(policy.chooseAction(state(0), actions)).rejects.toThrow(); } - for (const features of [[1], [1, NaN]]) { + for (const features of [[1], [1, NaN], Array(2)]) { const invalid = new LinearQLearningPolicy({ ...options, encoder: { ...encoder, encode: () => features }, diff --git a/packages/rl/src/linear-q-learning.ts b/packages/rl/src/linear-q-learning.ts index e9b3988..9eda5ca 100644 --- a/packages/rl/src/linear-q-learning.ts +++ b/packages/rl/src/linear-q-learning.ts @@ -108,7 +108,10 @@ export class LinearQLearningPolicy implements LearningPolicy { private features(state: EnvironmentState): number[] { const features = this.options.encoder.encode(state); - if (features.length !== this.dimension || features.some((value) => !Number.isFinite(value))) + if ( + features.length !== this.dimension || + Array.from(features).some((value) => !Number.isFinite(value)) + ) throw new Error("Invalid linear feature vector."); return features; } diff --git a/packages/rl/src/policy-artifact.ts b/packages/rl/src/policy-artifact.ts new file mode 100644 index 0000000..89f8fa8 --- /dev/null +++ b/packages/rl/src/policy-artifact.ts @@ -0,0 +1,227 @@ +import { createHash } from "node:crypto"; +import type { + EnvironmentAction, + EnvironmentState, + Policy, +} from "@ignitionai/agent-trainer-environment"; +import type { QTableEntry } from "./q-learning"; + +export interface PolicyArtifactBody { + schemaVersion: 1; + algorithm: "tabular-q" | "linear-q"; + encoder: { id: string; version: number; parameters: Record }; + actions: string[]; + hyperparameters: { alpha: number; gamma: number; epsilon: number }; + seeds: number[]; + provenance: { reference: string; mode: "real" | "synthetic"; fingerprint: string }; + rewardConfigId: string; + evaluationReportId: string; + parameters: QTableEntry[] | Record; +} +export interface PolicyArtifact extends PolicyArtifactBody { + id: string; +} +export interface PolicyRuntime { + encoder: PolicyArtifactBody["encoder"]; + actions: readonly string[]; + encodeState(state: EnvironmentState): string | number[]; + bindAction?(state: EnvironmentState, action: EnvironmentAction): EnvironmentAction; +} + +/** Stable checksum, not an authenticity signature. Reject non-JSON values rather than dropping them. */ +export function canonicalPolicyJson(value: unknown): string { + if (value === null || typeof value === "boolean" || typeof value === "string") + return JSON.stringify(value); + if (typeof value === "number" && Number.isFinite(value)) return JSON.stringify(value); + if (Array.isArray(value)) return `[${Array.from(value, canonicalPolicyJson).join(",")}]`; + if ( + typeof value === "object" && + value !== null && + Object.getPrototypeOf(value) === Object.prototype + ) { + return `{${Object.entries(value) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([key, item]) => `${JSON.stringify(key)}:${canonicalPolicyJson(item)}`) + .join(",")}}`; + } + throw new Error("Artifact must contain only finite JSON values."); +} +function digest(body: unknown): string { + return createHash("sha256").update(canonicalPolicyJson(body)).digest("hex"); +} +function required(value: unknown): value is string { + return typeof value === "string" && value.trim().length > 0; +} +function record(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function exactKeys(value: Record, keys: string[]): void { + if (JSON.stringify(Object.keys(value).sort()) !== JSON.stringify([...keys].sort())) + throw new Error("Unknown or missing artifact fields."); +} + +export function createPolicyArtifact(body: PolicyArtifactBody): PolicyArtifact { + const artifact = { ...structuredClone(body), id: digest(body) }; + return parsePolicyArtifact(artifact); +} + +export function parsePolicyArtifact(input: unknown): PolicyArtifact { + if (!record(input)) throw new Error("Policy artifact must be an object."); + exactKeys(input, [ + "id", + "schemaVersion", + "algorithm", + "encoder", + "actions", + "hyperparameters", + "seeds", + "provenance", + "rewardConfigId", + "evaluationReportId", + "parameters", + ]); + if (input.schemaVersion !== 1 || !["tabular-q", "linear-q"].includes(String(input.algorithm))) + throw new Error("Unsupported policy schema or algorithm."); + if ( + !record(input.encoder) || + !required(input.encoder.id) || + !Number.isSafeInteger(input.encoder.version) || + Number(input.encoder.version) <= 0 || + !record(input.encoder.parameters) + ) + throw new Error("Invalid encoder descriptor."); + exactKeys(input.encoder, ["id", "version", "parameters"]); + if ( + !Array.isArray(input.actions) || + input.actions.length === 0 || + !input.actions.every(required) || + new Set(input.actions).size !== input.actions.length + ) + throw new Error("Invalid action registry."); + if (!record(input.hyperparameters)) throw new Error("Missing hyperparameters."); + exactKeys(input.hyperparameters, ["alpha", "gamma", "epsilon"]); + for (const name of ["alpha", "gamma", "epsilon"]) { + const value = input.hyperparameters[name]; + if ( + typeof value !== "number" || + !Number.isFinite(value) || + value < 0 || + value > 1 || + (name === "alpha" && value === 0) + ) + throw new Error("Invalid hyperparameters."); + } + if ( + !Array.isArray(input.seeds) || + input.seeds.length === 0 || + !input.seeds.every(Number.isSafeInteger) + ) + throw new Error("Invalid seeds."); + if ( + !record(input.provenance) || + !required(input.provenance.reference) || + !required(input.provenance.fingerprint) || + !["real", "synthetic"].includes(String(input.provenance.mode)) + ) + throw new Error("Invalid provenance."); + exactKeys(input.provenance, ["reference", "fingerprint", "mode"]); + if (!required(input.rewardConfigId) || !required(input.evaluationReportId)) + throw new Error("Missing reward or evaluation reference."); + validateParameters(input.parameters, input.algorithm, input.actions as string[]); + const { id, ...body } = input; + if (!required(id) || id !== digest(body)) throw new Error("Policy checksum mismatch."); + return structuredClone(input) as unknown as PolicyArtifact; +} + +function validateParameters(parameters: unknown, algorithm: unknown, actions: string[]): void { + if (algorithm === "tabular-q") { + if (!Array.isArray(parameters)) throw new Error("Invalid Q table."); + const states = new Set(); + for (const entry of parameters) { + if ( + !record(entry) || + !required(entry.state) || + states.has(entry.state) || + !record(entry.values) + ) + throw new Error("Invalid Q table state."); + exactKeys(entry, ["state", "values"]); + states.add(entry.state); + for (const [action, value] of Object.entries(entry.values)) + if (!actions.includes(action) || typeof value !== "number" || !Number.isFinite(value)) + throw new Error("Invalid Q table value."); + } + return; + } + if (!record(parameters)) throw new Error("Invalid linear weights."); + exactKeys(parameters, actions); + const vectors = Object.values(parameters); + const dimension = Array.isArray(vectors[0]) ? vectors[0].length : 0; + if ( + dimension === 0 || + vectors.some( + (vector) => + !Array.isArray(vector) || + vector.length !== dimension || + vector.some((value) => typeof value !== "number" || !Number.isFinite(value)), + ) + ) + throw new Error("Invalid linear dimensions or weights."); +} + +export function loadPolicyArtifact(input: unknown, runtime: PolicyRuntime): Policy { + const artifact = parsePolicyArtifact(input); + if ( + canonicalPolicyJson(artifact.encoder) !== canonicalPolicyJson(runtime.encoder) || + canonicalPolicyJson([...artifact.actions].sort()) !== + canonicalPolicyJson([...runtime.actions].sort()) + ) + throw new Error("Incompatible encoder or action registry."); + const table = + artifact.algorithm === "tabular-q" + ? new Map((artifact.parameters as QTableEntry[]).map((entry) => [entry.state, entry.values])) + : null; + const weights = artifact.parameters as Record; + return { + async chooseAction(state, actions) { + if ( + actions.length === 0 || + new Set(actions.map((action) => action.name)).size !== actions.length || + actions.some((action) => !artifact.actions.includes(action.name)) + ) + throw new Error("Invalid available action registry."); + const encoded = runtime.encodeState(state); + const score = (action: EnvironmentAction): number => { + if (table) { + if (!required(encoded)) throw new Error("Invalid encoded state."); + const values = table.get(encoded); + return values && Object.hasOwn(values, action.name) ? (values[action.name] ?? 0) : 0; + } + const vector = weights[action.name]; + if ( + !vector || + !Array.isArray(encoded) || + encoded.length !== vector.length || + Array.from(encoded).some((value) => !Number.isFinite(value)) + ) + throw new Error("Incompatible feature vector."); + const value = vector.reduce( + (sum, weight, index) => sum + weight * (encoded[index] ?? 0), + 0, + ); + if (!Number.isFinite(value)) throw new Error("Non-finite policy value."); + return value; + }; + const ranked = actions + .map((action) => ({ action, value: score(action) })) + .sort((a, b) => b.value - a.value || a.action.name.localeCompare(b.action.name)); + const selected = ranked[0]?.action; + if (!selected) throw new Error("No available action."); + const bound = runtime.bindAction + ? runtime.bindAction(state, { ...selected }) + : { ...selected }; + if (bound.name !== selected.name) throw new Error("Action binder changed selected action."); + return bound; + }, + }; +} diff --git a/packages/rl/src/policy-registry.test.ts b/packages/rl/src/policy-registry.test.ts new file mode 100644 index 0000000..cffe7ad --- /dev/null +++ b/packages/rl/src/policy-registry.test.ts @@ -0,0 +1,264 @@ +import { spawn } from "node:child_process"; +import { mkdtemp, readFile, unlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setTimeout } from "node:timers/promises"; +import type { EnvironmentState } from "@ignitionai/agent-trainer-environment"; +import { describe, expect, it } from "vitest"; +import { LinearQLearningPolicy } from "./linear-q-learning"; +import { + createPolicyArtifact, + loadPolicyArtifact, + type PolicyArtifactBody, + parsePolicyArtifact, +} from "./policy-artifact"; +import { LocalPolicyRegistry, type PolicyGateInput } from "./policy-registry"; +import { TabularQLearningPolicy } from "./q-learning"; + +const actions = [{ name: "lookup" }, { name: "answer" }]; +const state = (x: number): EnvironmentState => ({ + id: `heldout-${x}`, + observation: { x }, + done: false, +}); +const metadata = { + schemaVersion: 1 as const, + encoder: { id: "test-observable", version: 1, parameters: { fields: ["x"] } }, + actions: actions.map((action) => action.name), + hyperparameters: { alpha: 1, gamma: 0, epsilon: 0 }, + seeds: [57], + provenance: { + reference: "synthetic-calibration-v1", + mode: "synthetic" as const, + fingerprint: "calibration-sha256", + }, + rewardConfigId: "quality-tool-cost-v1", + evaluationReportId: "heldout-v1", +}; +function body( + parameters: PolicyArtifactBody["parameters"], + algorithm: PolicyArtifactBody["algorithm"] = "tabular-q", +): PolicyArtifactBody { + return { ...metadata, algorithm, parameters }; +} +function gate(baselineId: string, candidateId: string): PolicyGateInput { + return { + baselineId, + candidateId, + corpusId: "heldout-v1", + evaluationReportId: "heldout-v1", + mode: "synthetic", + baseline: { successRate: 1, reward: 0.9, tools: 2, costUsd: null }, + candidate: { successRate: 1, reward: 0.95, tools: 1, costUsd: null }, + thresholds: { + maxSuccessDrop: 0, + maxRewardDrop: 0, + maxToolIncrease: 0, + maxCostIncreaseUsd: null, + }, + }; +} + +describe("versioned policies and local registry", () => { + it("reloads both learned algorithms without calibration data on an independent corpus", async () => { + const encode = (value: EnvironmentState) => String(Number(value.observation.x) > 0); + const tabular = new TabularQLearningPolicy({ + ...metadata.hyperparameters, + seed: 57, + encodeState: encode, + }); + const encoder = { + descriptor: { + schema: { id: "test", version: 1, numeric: ["x"], categorical: {} }, + normalization: [], + featureNames: ["x"], + }, + encode: (value: EnvironmentState) => [Number(value.observation.x)], + }; + const linear = new LinearQLearningPolicy({ + ...metadata.hyperparameters, + seed: 57, + actionNames: metadata.actions, + encoder, + }); + for (const policy of [tabular, linear]) { + policy.update({ + state: state(1), + action: { name: "answer" }, + reward: 1, + nextState: state(1), + nextActions: [], + done: true, + }); + policy.update({ + state: state(-1), + action: { name: "lookup" }, + reward: 1, + nextState: state(-1), + nextActions: [], + done: true, + }); + } + const variants = [ + { + original: tabular.freeze(), + artifact: createPolicyArtifact(body(tabular.snapshot())), + encodeState: encode, + }, + { + original: linear.freeze(), + artifact: createPolicyArtifact(body(linear.snapshot(), "linear-q")), + encodeState: encoder.encode, + }, + ]; + for (const variant of variants) { + const loaded = loadPolicyArtifact(JSON.parse(JSON.stringify(variant.artifact)), { + encoder: metadata.encoder, + actions: metadata.actions, + encodeState: variant.encodeState, + }); + for (const x of [-10, -3, 0, 2, 100]) { + expect(await loaded.chooseAction(state(x), [...actions].reverse())).toEqual( + await variant.original.chooseAction(state(x), actions), + ); + } + } + }); + + it("rejects corruption, unknown versions and incompatible encoders at the loading boundary", async () => { + expect(() => + createPolicyArtifact({ ...body({ "a|b": [1] }, "linear-q"), actions: ["a", "b"] }), + ).toThrow("fields"); + expect(() => + createPolicyArtifact(body({ lookup: Array(2), answer: [0, 0] }, "linear-q")), + ).toThrow("finite JSON"); + const sparseRuntime = loadPolicyArtifact( + createPolicyArtifact(body({ lookup: [1, 0], answer: [0, 1] }, "linear-q")), + { encoder: metadata.encoder, actions: metadata.actions, encodeState: () => Array(2) }, + ); + await expect(sparseRuntime.chooseAction(state(1), actions)).rejects.toThrow("feature vector"); + const artifact = createPolicyArtifact(body([{ state: "true", values: { answer: 1 } }])); + for (const changed of [ + { ...artifact, schemaVersion: 2 }, + { ...artifact, parameters: [{ state: "true", values: { answer: 100 } }] }, + { ...artifact, extra: true }, + { ...artifact, hyperparameters: { ...artifact.hyperparameters, alpha: Number.NaN } }, + ]) + expect(() => parsePolicyArtifact(changed)).toThrow(); + expect(() => + loadPolicyArtifact(artifact, { + encoder: { ...metadata.encoder, version: 2 }, + actions: metadata.actions, + encodeState: () => "true", + }), + ).toThrow("Incompatible"); + expect(() => + loadPolicyArtifact(artifact, { + encoder: metadata.encoder, + actions: ["private"], + encodeState: () => "true", + }), + ).toThrow("Incompatible"); + }); + + it("blocks regressions, promotes explicitly, survives a precommit interruption and rolls back baseline choices", async () => { + const directory = await mkdtemp(join(tmpdir(), "policy-registry-")); + const registry = new LocalPolicyRegistry(directory); + const baseline = createPolicyArtifact(body([{ state: "true", values: { lookup: 1 } }])); + const candidate = createPolicyArtifact(body([{ state: "true", values: { answer: 1 } }])); + await registry.register(baseline); + await registry.register(candidate); + await registry.initialize(baseline.id); + expect((await registry.active()).activeId).toBe(baseline.id); + await writeFile(join(directory, ".writer.lock"), "another writer"); + await expect(registry.promote(gate(baseline.id, candidate.id))).rejects.toThrow(); + expect((await registry.active()).activeId).toBe(baseline.id); + await unlink(join(directory, ".writer.lock")); + const incomplete = gate(baseline.id, candidate.id); + delete (incomplete.thresholds as Partial).maxSuccessDrop; + await expect(registry.promote(incomplete)).rejects.toThrow("thresholds"); + expect((await registry.active()).activeId).toBe(baseline.id); + const regression = gate(baseline.id, candidate.id); + regression.candidate.successRate = 0; + const rejected = await registry.promote(regression); + expect(rejected.passed).toBe(false); + expect(rejected.reasons).toContain("success-regression"); + expect(rejected.thresholds.maxSuccessDrop).toBe(0); + expect((await registry.active()).activeId).toBe(baseline.id); + const costRequired = gate(baseline.id, candidate.id); + costRequired.thresholds.maxCostIncreaseUsd = 0; + expect((await registry.promote(costRequired)).reasons).toContain("cost-not-observed"); + await expect(registry.register({ ...candidate, parameters: [] })).rejects.toThrow("checksum"); + expect((await registry.active()).activeId).toBe(baseline.id); + // A terminated writer can leave only an incomplete staging file, never the published pointer. + await writeFile(join(directory, ".active-interrupted.tmp"), '{"activeId":'); + expect((await registry.active()).activeId).toBe(baseline.id); + expect((await registry.promote(gate(baseline.id, candidate.id))).passed).toBe(true); + const promoted = await registry.active(); + expect(promoted.activeId).toBe(candidate.id); + expect(promoted.baselineId).toBe(baseline.id); + const savedReport = JSON.parse( + await readFile(join(directory, "reports", `${promoted.gateReportId}.json`), "utf8"), + ); + expect(savedReport.candidateId).toBe(candidate.id); + expect(savedReport.baselineId).toBe(baseline.id); + await expect(registry.promote(gate(baseline.id, candidate.id))).rejects.toThrow("pinned"); + const restored = await registry.rollback(); + expect(restored.activeId).toBe(baseline.id); + expect(restored.baselineId).toBe(baseline.id); + const loaded = loadPolicyArtifact(await registry.readVersion(restored.activeId), { + encoder: metadata.encoder, + actions: metadata.actions, + encodeState: () => "true", + }); + expect((await loaded.chooseAction(state(8), actions)).name).toBe("lookup"); + await expect(registry.rollback()).rejects.toThrow("No previous"); + }); + it("keeps a checksummed active version when a real writer process is terminated", async () => { + const directory = await mkdtemp(join(tmpdir(), "policy-crash-")); + const registry = new LocalPolicyRegistry(directory); + const baseline = createPolicyArtifact(body([{ state: "true", values: { lookup: 1 } }])); + const candidate = createPolicyArtifact(body([{ state: "true", values: { answer: 1 } }])); + await registry.register(baseline); + await registry.register(candidate); + await registry.initialize(baseline.id); + const script = `import { LocalPolicyRegistry } from ${JSON.stringify(new URL("./policy-registry.ts", import.meta.url).pathname)}; + import { writeFile } from "node:fs/promises"; + const registry = new LocalPolicyRegistry(${JSON.stringify(directory)}); + const gate = ${JSON.stringify(gate(baseline.id, candidate.id))}; + await registry.promote(gate); await registry.rollback(); + await writeFile(${JSON.stringify(join(directory, "ready"))}, "ready"); + for (;;) { await registry.promote(gate); await registry.rollback(); }`; + const child = spawn("bun", ["--eval", script], { stdio: ["ignore", "ignore", "pipe"] }); + let childError = ""; + child.stderr.on("data", (chunk) => { + childError += String(chunk); + }); + const exited = new Promise((resolve) => { + child.once("exit", () => resolve()); + }); + try { + let ready = false; + for (let attempt = 0; attempt < 1000; attempt += 1) { + try { + await readFile(join(directory, "ready")); + ready = true; + break; + } catch { + await setTimeout(5); + } + if (child.exitCode !== null) + throw new Error(childError || "Writer exited before readiness."); + } + expect(ready).toBe(true); + child.kill("SIGKILL"); + await exited; + const pointer = await registry.active(); + expect([baseline.id, candidate.id]).toContain(pointer.activeId); + expect((await registry.readVersion(pointer.activeId)).id).toBe(pointer.activeId); + expect(pointer.baselineId).toBe(baseline.id); + } finally { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + } + }); +}); diff --git a/packages/rl/src/policy-registry.ts b/packages/rl/src/policy-registry.ts new file mode 100644 index 0000000..5e9a052 --- /dev/null +++ b/packages/rl/src/policy-registry.ts @@ -0,0 +1,279 @@ +import { createHash, randomUUID } from "node:crypto"; +import { mkdir, open, readFile, rename, unlink } from "node:fs/promises"; +import { join } from "node:path"; +import { canonicalPolicyJson, type PolicyArtifact, parsePolicyArtifact } from "./policy-artifact"; + +export interface PolicyMetrics { + successRate: number; + reward: number; + tools: number; + costUsd: number | null; +} +export interface PolicyGateInput { + baselineId: string; + candidateId: string; + corpusId: string; + evaluationReportId: string; + mode: "real" | "synthetic"; + baseline: PolicyMetrics; + candidate: PolicyMetrics; + thresholds: { + maxSuccessDrop: number; + maxRewardDrop: number; + maxToolIncrease: number; + maxCostIncreaseUsd: number | null; + }; +} +export interface PolicyGateReport extends PolicyGateInput { + passed: boolean; + reasons: string[]; +} +export function comparePolicyBaseline(input: PolicyGateInput): PolicyGateReport { + const reasons: string[] = []; + for (const id of [input.baselineId, input.candidateId, input.corpusId, input.evaluationReportId]) + if (!id.trim()) throw new Error("Gate identities are required."); + if (!["real", "synthetic"].includes(input.mode)) throw new Error("Unknown evidence mode."); + for (const metrics of [input.baseline, input.candidate]) { + if ( + !Number.isFinite(metrics.successRate) || + metrics.successRate < 0 || + metrics.successRate > 1 || + !Number.isFinite(metrics.reward) || + !Number.isFinite(metrics.tools) || + metrics.tools < 0 || + (metrics.costUsd !== null && (!Number.isFinite(metrics.costUsd) || metrics.costUsd < 0)) + ) + throw new Error("Invalid baseline metrics."); + } + if ( + JSON.stringify(Object.keys(input.thresholds).sort()) !== + JSON.stringify( + ["maxSuccessDrop", "maxRewardDrop", "maxToolIncrease", "maxCostIncreaseUsd"].sort(), + ) + ) + throw new Error("Missing or unknown gate thresholds."); + for (const [name, value] of Object.entries(input.thresholds)) { + if (value === null && name !== "maxCostIncreaseUsd") throw new Error("Missing gate threshold."); + } + for (const threshold of Object.values(input.thresholds)) + if (threshold !== null && (!Number.isFinite(threshold) || threshold < 0)) + throw new Error("Invalid gate thresholds."); + if (input.candidate.successRate < input.baseline.successRate - input.thresholds.maxSuccessDrop) + reasons.push("success-regression"); + if (input.candidate.reward < input.baseline.reward - input.thresholds.maxRewardDrop) + reasons.push("reward-regression"); + if (input.candidate.tools > input.baseline.tools + input.thresholds.maxToolIncrease) + reasons.push("tool-regression"); + if (input.thresholds.maxCostIncreaseUsd !== null) { + if (input.baseline.costUsd === null || input.candidate.costUsd === null) + reasons.push("cost-not-observed"); + else if (input.candidate.costUsd > input.baseline.costUsd + input.thresholds.maxCostIncreaseUsd) + reasons.push("cost-regression"); + } + return { ...structuredClone(input), passed: reasons.length === 0, reasons }; +} +export interface PolicyRegistryPointer { + schemaVersion: 1; + activeId: string; + previousId: string | null; + baselineId: string; + gateReportId: string | null; +} + +/** Local single-writer registry. Filesystem must support atomic same-directory rename. */ +export class LocalPolicyRegistry { + constructor(private readonly directory: string) {} + async register(input: unknown): Promise { + const artifact = parsePolicyArtifact(input); + await mkdir(join(this.directory, "versions"), { recursive: true }); + const path = this.versionPath(artifact.id); + try { + await writeExclusive(path, canonicalPolicyJson(artifact)); + } catch (error) { + if (!isExists(error)) throw error; + if ( + canonicalPolicyJson(await this.readVersion(artifact.id)) !== canonicalPolicyJson(artifact) + ) + throw new Error("Immutable version conflict."); + } + await syncDirectory(join(this.directory, "versions")); + return artifact.id; + } + async readVersion(id: string): Promise { + assertId(id); + const artifact = parsePolicyArtifact(JSON.parse(await readFile(this.versionPath(id), "utf8"))); + if (artifact.id !== id) throw new Error("Version identity mismatch."); + return artifact; + } + async active(): Promise { + const input: unknown = JSON.parse(await readFile(join(this.directory, "active.json"), "utf8")); + if (typeof input !== "object" || input === null) throw new Error("Invalid registry pointer."); + const pointer = input as PolicyRegistryPointer; + if ( + pointer.schemaVersion !== 1 || + JSON.stringify(Object.keys(pointer).sort()) !== + JSON.stringify( + ["schemaVersion", "activeId", "previousId", "baselineId", "gateReportId"].sort(), + ) + ) + throw new Error("Invalid pointer schema."); + assertId(pointer.activeId); + assertId(pointer.baselineId); + if (pointer.previousId !== null) assertId(pointer.previousId); + if (pointer.gateReportId !== null) assertId(pointer.gateReportId); + await this.readVersion(pointer.activeId); + await this.readVersion(pointer.baselineId); + if (pointer.gateReportId !== null) { + const report = await this.readReport(pointer.gateReportId); + if ( + !report.passed || + report.candidateId !== pointer.activeId || + report.baselineId !== pointer.baselineId || + pointer.previousId !== pointer.baselineId + ) + throw new Error("Inconsistent active gate report."); + } else if (pointer.previousId !== null || pointer.activeId !== pointer.baselineId) + throw new Error("Inconsistent baseline pointer."); + return pointer; + } + async initialize(baselineId: string): Promise { + await this.locked(async () => { + await this.readVersion(baselineId); + await writeExclusive( + join(this.directory, "active.json"), + canonicalPolicyJson({ + schemaVersion: 1, + activeId: baselineId, + previousId: null, + baselineId, + gateReportId: null, + }), + ); + }); + } + async promote(input: PolicyGateInput): Promise { + return this.locked(async () => { + const pointer = await this.active(); + if (input.baselineId !== pointer.activeId || input.candidateId === pointer.activeId) + throw new Error("Gate must compare candidate to pinned active baseline."); + const baseline = await this.readVersion(input.baselineId); + const candidate = await this.readVersion(input.candidateId); + if ( + baseline.algorithm !== candidate.algorithm || + canonicalPolicyJson(baseline.encoder) !== canonicalPolicyJson(candidate.encoder) || + canonicalPolicyJson([...baseline.actions].sort()) !== + canonicalPolicyJson([...candidate.actions].sort()) || + baseline.rewardConfigId !== candidate.rewardConfigId + ) + throw new Error("Incompatible promotion."); + if (candidate.provenance.mode !== input.mode || baseline.provenance.mode !== input.mode) + throw new Error("Evidence mode mismatch."); + if (input.evaluationReportId !== candidate.evaluationReportId) + throw new Error("Evaluation report does not match candidate artifact."); + const report = comparePolicyBaseline(input); + const reportId = await this.storeReport(report); + if (report.passed) + await this.replacePointer({ + schemaVersion: 1, + activeId: candidate.id, + previousId: pointer.activeId, + baselineId: pointer.activeId, + gateReportId: reportId, + }); + return report; + }); + } + async rollback(): Promise { + return this.locked(async () => { + const pointer = await this.active(); + if (pointer.previousId === null) throw new Error("No previous version to restore."); + await this.readVersion(pointer.previousId); + const restored: PolicyRegistryPointer = { + schemaVersion: 1, + activeId: pointer.previousId, + previousId: null, + baselineId: pointer.previousId, + gateReportId: null, + }; + await this.replacePointer(restored); + return restored; + }); + } + async readReport(id: string): Promise { + assertId(id); + const input: unknown = JSON.parse( + await readFile(join(this.directory, "reports", `${id}.json`), "utf8"), + ); + if (typeof input !== "object" || input === null) throw new Error("Invalid gate report."); + const report = input as PolicyGateReport; + if (createHash("sha256").update(canonicalPolicyJson(report)).digest("hex") !== id) + throw new Error("Gate report checksum mismatch."); + const verified = comparePolicyBaseline(report); + if ( + report.passed !== verified.passed || + canonicalPolicyJson(report.reasons) !== canonicalPolicyJson(verified.reasons) + ) + throw new Error("Invalid gate outcome."); + return report; + } + private versionPath(id: string): string { + assertId(id); + return join(this.directory, "versions", `${id}.json`); + } + private async storeReport(report: PolicyGateReport): Promise { + const json = canonicalPolicyJson(report); + const id = createHash("sha256").update(json).digest("hex"); + await mkdir(join(this.directory, "reports"), { recursive: true }); + try { + await writeExclusive(join(this.directory, "reports", `${id}.json`), json); + } catch (error) { + if (!isExists(error)) throw error; + if (canonicalPolicyJson(await this.readReport(id)) !== json) + throw new Error("Immutable report conflict."); + } + await syncDirectory(join(this.directory, "reports")); + return id; + } + private async replacePointer(pointer: PolicyRegistryPointer): Promise { + const temporary = join(this.directory, `.active-${randomUUID()}.tmp`); + await writeExclusive(temporary, canonicalPolicyJson(pointer)); + await rename(temporary, join(this.directory, "active.json")); + await syncDirectory(this.directory); + } + private async locked(operation: () => Promise): Promise { + await mkdir(this.directory, { recursive: true }); + const lockPath = join(this.directory, ".writer.lock"); + const lock = await open(lockPath, "wx"); + try { + return await operation(); + } finally { + await lock.close(); + await unlink(lockPath); + } + } +} +function assertId(id: unknown): asserts id is string { + if (typeof id !== "string" || !/^[a-f0-9]{64}$/.test(id)) + throw new Error("Invalid registry identity."); +} +function isExists(error: unknown): boolean { + return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST"; +} +async function writeExclusive(path: string, content: string): Promise { + const file = await open(path, "wx"); + try { + await file.writeFile(content, "utf8"); + await file.sync(); + } finally { + await file.close(); + } +} + +async function syncDirectory(path: string): Promise { + const directory = await open(path, "r"); + try { + await directory.sync(); + } finally { + await directory.close(); + } +}