Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
11 changes: 11 additions & 0 deletions docs/BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
63 changes: 63 additions & 0 deletions docs/POLICY_REGISTRY.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 10 additions & 0 deletions examples/react-policy-optimization/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
142 changes: 142 additions & 0 deletions examples/react-policy-optimization/src/registry.ts
Original file line number Diff line number Diff line change
@@ -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,
});
}
2 changes: 2 additions & 0 deletions packages/rl/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
2 changes: 1 addition & 1 deletion packages/rl/src/linear-q-learning.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number>(2)]) {
const invalid = new LinearQLearningPolicy({
...options,
encoder: { ...encoder, encode: () => features },
Expand Down
5 changes: 4 additions & 1 deletion packages/rl/src/linear-q-learning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Loading
Loading