refactor(paper): separate safety enforcement from readiness projection (CL32)

This commit is contained in:
Boki 2026-10-28 14:01:18 -04:00
parent 366a6054bf
commit 2165a2efa8
9 changed files with 324 additions and 90 deletions

View file

@ -66,6 +66,7 @@ export function createPaperRoutes(
services.logger.error('Canonical paper request failed', { error });
return c.json({ error: 'Canonical paper runtime unavailable' }, 503);
});
// The status transaction may revoke expired activation; it never activates or recovers.
app.get('/readiness', async c => {
if (options.deploymentHost) {
return c.json(await options.deploymentHost.readiness());

View file

@ -33,6 +33,83 @@ function hostState(account: CanonicalAccount): CanonicalPaperHost {
return account.host;
}
function paperHealthReasons(account: CanonicalAccount, now: number): string[] {
const host = hostState(account);
const { policy, matching } = host.configuration;
const reasons: string[] = [];
if (!host.connection) {
reasons.push('feed-disconnected');
}
if (
host.lastReceivedAt === null ||
host.lastAvailableAt === null ||
now < host.lastReceivedAt ||
now < host.lastAvailableAt ||
now - host.lastReceivedAt > policy.maxFeedAgeMs ||
now - host.lastAvailableAt > policy.maxFeedAgeMs
) {
reasons.push('feed-stale');
}
for (const series of matching.series) {
const quote = host.quotes.find(item => item.instrumentId === series.instrumentId);
if (!quote || now < quote.observedAt || now - quote.observedAt > matching.risk.maxMarkAgeMs) {
reasons.push(`quote-stale:${series.instrumentId}`);
}
const calendar = policy.calendars.find(item => item.instrumentId === series.instrumentId);
if (!calendar?.sessions.some(session => session.opensAt <= now && now < session.closesAt)) {
reasons.push(`calendar-uncovered:${series.instrumentId}`);
}
}
if (account.checkpoint.status !== 'Running') {
reasons.push('native-not-running');
}
return reasons;
}
/** Pure diagnostic projection. It never changes activation or persists safety latches. */
export function projectPaperReadiness(
account: CanonicalAccount,
pending: Pick<PaperReadiness, 'pendingInput' | 'pendingBatch'>,
now: number
): PaperReadiness {
const { pendingInput, pendingBatch } = pending;
const host = hostState(account);
const reasons = paperHealthReasons(account, now);
if (host.operatorHalted) {
reasons.push('operator-halted');
}
if (host.diagnostic) {
reasons.push(host.diagnostic);
}
const pendingDecisionSequence = account.pendingDecisionSequence;
const requiresHistoricalRecovery =
pendingInput !== null || pendingBatch !== null || pendingDecisionSequence !== null;
if (requiresHistoricalRecovery) {
reasons.push('historical-recovery-required');
}
return {
configured: true,
accountId: account.identity.accountId,
sourceId: host.configuration.policy.sourceId,
active: host.active,
ready: reasons.length === 0,
operatorHalted: host.operatorHalted,
connected: host.connection !== null,
reasons,
lastReceivedAt: host.lastReceivedAt,
lastAvailableAt: host.lastAvailableAt,
requiresHistoricalRecovery,
pendingInput,
pendingBatch,
pendingDecisionSequence,
nativeStatus: account.checkpoint.status,
risk: {
dailyHalted: account.view.risk.dailyHalted,
drawdownHalted: account.view.risk.drawdownHalted,
},
};
}
/** An operational gate around durable custody, never a second financial simulator.
* Each transaction releases the account lock so a halt can stop the next step. */
export class CanonicalPaperRuntime implements PaperRuntime {
@ -55,7 +132,10 @@ export class CanonicalPaperRuntime implements PaperRuntime {
repository: options.repository,
programs: options.programs,
publish: options.publish,
control: { generation: this.generation, guard: account => this.guard(account) },
control: {
generation: this.generation,
guard: account => this.enforceReadinessExpiry(account),
},
});
}
@ -138,42 +218,10 @@ export class CanonicalPaperRuntime implements PaperRuntime {
);
}
private health(account: CanonicalAccount, now: number): string[] {
/** Mutates the transaction-owned safety latch; fresh data never reactivates it. */
private enforceReadinessExpiry(account: CanonicalAccount): boolean {
const host = hostState(account);
const { policy, matching } = host.configuration;
const reasons: string[] = [];
if (!host.connection) {
reasons.push('feed-disconnected');
}
if (
host.lastReceivedAt === null ||
host.lastAvailableAt === null ||
now < host.lastReceivedAt ||
now < host.lastAvailableAt ||
now - host.lastReceivedAt > policy.maxFeedAgeMs ||
now - host.lastAvailableAt > policy.maxFeedAgeMs
) {
reasons.push('feed-stale');
}
for (const series of matching.series) {
const quote = host.quotes.find(item => item.instrumentId === series.instrumentId);
if (!quote || now < quote.observedAt || now - quote.observedAt > matching.risk.maxMarkAgeMs) {
reasons.push(`quote-stale:${series.instrumentId}`);
}
const calendar = policy.calendars.find(item => item.instrumentId === series.instrumentId);
if (!calendar?.sessions.some(session => session.opensAt <= now && now < session.closesAt)) {
reasons.push(`calendar-uncovered:${series.instrumentId}`);
}
}
if (account.checkpoint.status !== 'Running') {
reasons.push('native-not-running');
}
return reasons;
}
private guard(account: CanonicalAccount): boolean {
const host = hostState(account);
if (this.health(account, this.now()).length && host.active) {
if (paperHealthReasons(account, this.now()).length && host.active) {
host.active = false;
host.diagnostic =
'Operational readiness expired; fresh feed and operator activation required';
@ -181,45 +229,11 @@ export class CanonicalPaperRuntime implements PaperRuntime {
return host.active && !host.operatorHalted;
}
private async readiness(tx: CanonicalTransaction): Promise<PaperReadiness> {
this.guard(tx.account);
const host = hostState(tx.account);
const reasons = this.health(tx.account, this.now());
if (host.operatorHalted) {
reasons.push('operator-halted');
}
if (host.diagnostic) {
reasons.push(host.diagnostic);
}
private async readReadiness(tx: CanonicalTransaction): Promise<PaperReadiness> {
const now = this.now();
const pendingInput = (await tx.nextInput())?.id ?? null;
const pendingBatch = (await tx.nextBatch())?.id ?? null;
const pendingDecisionSequence = tx.account.pendingDecisionSequence;
const requiresHistoricalRecovery =
pendingInput !== null || pendingBatch !== null || pendingDecisionSequence !== null;
if (requiresHistoricalRecovery) {
reasons.push('historical-recovery-required');
}
return {
configured: true,
accountId: tx.account.identity.accountId,
sourceId: host.configuration.policy.sourceId,
active: host.active,
ready: reasons.length === 0,
operatorHalted: host.operatorHalted,
connected: host.connection !== null,
reasons,
lastReceivedAt: host.lastReceivedAt,
lastAvailableAt: host.lastAvailableAt,
requiresHistoricalRecovery,
pendingInput,
pendingBatch,
pendingDecisionSequence,
nativeStatus: tx.account.checkpoint.status,
risk: {
dailyHalted: tx.account.view.risk.dailyHalted,
drawdownHalted: tx.account.view.risk.drawdownHalted,
},
};
return projectPaperReadiness(tx.account, { pendingInput, pendingBatch }, now);
}
/** A rejected request rolls back its admission transaction. Persist ONLY the
@ -230,7 +244,7 @@ export class CanonicalPaperRuntime implements PaperRuntime {
} catch (error) {
try {
await this.transaction(async tx => {
this.guard(tx.account);
this.enforceReadinessExpiry(tx.account);
});
} catch {
// A replacement generation or unavailable repository must not mask the original error.
@ -248,7 +262,7 @@ export class CanonicalPaperRuntime implements PaperRuntime {
'Paper source does not match its configured provider'
);
}
this.guard(tx.account);
this.enforceReadinessExpiry(tx.account);
if (canonicalJson(connection) !== canonicalJson(host.connection)) {
host.connection = connection;
host.active = false;
@ -256,7 +270,8 @@ export class CanonicalPaperRuntime implements PaperRuntime {
host.lastSequence = null;
host.quotes = [];
}
return this.readiness(tx);
this.enforceReadinessExpiry(tx.account);
return this.readReadiness(tx);
});
}
@ -267,7 +282,8 @@ export class CanonicalPaperRuntime implements PaperRuntime {
host.active = false;
host.connection = null;
}
return this.readiness(tx);
this.enforceReadinessExpiry(tx.account);
return this.readReadiness(tx);
});
}
@ -285,7 +301,7 @@ export class CanonicalPaperRuntime implements PaperRuntime {
if (old.fingerprint !== digest) {
throw new PaperRuntimeError('conflict', 'Paper frame ID has conflicting content');
}
this.guard(tx.account);
this.enforceReadinessExpiry(tx.account);
return { duplicate: true, disposition: old.disposition };
}
if (
@ -305,7 +321,7 @@ export class CanonicalPaperRuntime implements PaperRuntime {
);
}
// Compare the OLD health deadline before this fresh frame can change it.
this.guard(tx.account);
this.enforceReadinessExpiry(tx.account);
if (
host.active &&
((await tx.nextInput()) ||
@ -439,8 +455,8 @@ export class CanonicalPaperRuntime implements PaperRuntime {
return this.withFreshnessLatch(async () => {
const { recoverPending } = paperActivationSchema.parse(input);
await this.transaction(async (tx, host) => {
this.guard(tx.account);
const reasons = this.health(tx.account, this.now());
this.enforceReadinessExpiry(tx.account);
const reasons = paperHealthReasons(tx.account, this.now());
if (reasons.length) {
throw new PaperRuntimeError(
'not-ready',
@ -484,12 +500,17 @@ export class CanonicalPaperRuntime implements PaperRuntime {
host.active = false;
host.operatorHalted = true;
host.haltReason = parsed.reason;
return this.readiness(tx);
this.enforceReadinessExpiry(tx.account);
return this.readReadiness(tx);
});
}
/** A status poll commits expired activation before returning its diagnostic projection. */
status(): Promise<PaperReadiness> {
return this.transaction(tx => this.readiness(tx));
return this.transaction(async tx => {
this.enforceReadinessExpiry(tx.account);
return this.readReadiness(tx);
});
}
async shutdown(): Promise<void> {

View file

@ -40,7 +40,8 @@ export function createRoutes(
});
});
// Read-only evidence. No child is launched and no paper recovery/activation occurs.
// Diagnostics never launch children or recover/activate paper execution. Reading
// paper status can persist an expired-activation safety latch in its transaction.
app.get('/api/diagnostics', async c => {
const runtime = services.custom?.CanonicalPaperRuntime;
const host = services.custom?.PaperDeploymentHost;

View file

@ -19,3 +19,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone
- **CL34:** Independent provider normalization suite: 6 passed, 10 assertions. Disposable PostgreSQL pipeline safety: 8 passed, 28 assertions, including verified mapping preservation, unverified update and replay identity. Scoped lint/format passed; active QM session manager preserved.
- **CL25:** Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards.
- **CL32:** Independent pure projection/runtime suite 4 passed, 22 assertions; disposable PostgreSQL paper-runtime suite 22 passed, 143 assertions. Verified atomic expiry latch, rollback on storage failure, no implicit reactivation, stale generation and restart recovery. Scoped lint/format passed.

View file

@ -1,6 +1,6 @@
# Canonical development backlog
**Active: E13 architecture cleanup, CL22–CL35 (6/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
**Active: E13 architecture cleanup, CL22–CL35 (7/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
**Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md).

View file

@ -3817,7 +3817,7 @@
"complexity": "M",
"assignment": null,
"write_locks": ["CL25"],
"completed_commit": null,
"completed_commit": "366a6054bf831df7bff02207bccccb9b82912dc7",
"blocker": null,
"release_gates": [],
"completion_evidence": "architecture-cleanup-execution.md",
@ -3940,7 +3940,7 @@
"epic": "E13",
"priority": "P2",
"severity": "Medium",
"status": "ready",
"status": "done",
"dependencies": [],
"decision_dependencies": [],
"task_file": "backlog/tasks/CL32.md",
@ -3950,7 +3950,9 @@
"completed_commit": null,
"blocker": null,
"release_gates": [],
"completion_evidence": "architecture-cleanup-execution.md"
"completion_evidence": "architecture-cleanup-execution.md",
"integration_state": "accepted",
"validation": "Independent pure projection/runtime suite 4 passed, 22 assertions; disposable PostgreSQL paper-runtime suite 22 passed, 143 assertions. Verified atomic expiry latch, rollback on storage failure, no implicit reactivation, stale generation and restart recovery. Scoped lint/format passed."
},
{
"id": "CL33",
@ -10393,7 +10395,7 @@
],
"work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.",
"first_wave": ["CL22", "CL23", "CL24"],
"completed": 6,
"last_verification": "Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards."
"completed": 7,
"last_verification": "Independent pure projection/runtime suite 4 passed, 22 assertions; disposable PostgreSQL paper-runtime suite 22 passed, 143 assertions. Verified atomic expiry latch, rollback on storage failure, no implicit reactivation, stale generation and restart recovery. Scoped lint/format passed."
}
}

View file

@ -18,3 +18,7 @@ Stale active/fresh inactive, storage failure/rollback, stale execution refusal;
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Independent pure projection/runtime suite 4 passed, 22 assertions; disposable PostgreSQL paper-runtime suite 22 passed, 143 assertions. Verified atomic expiry latch, rollback on storage failure, no implicit reactivation, stale generation and restart recovery. Scoped lint/format passed.

View file

@ -0,0 +1,171 @@
import { expect, test } from 'bun:test';
import type {
CanonicalAccount,
CanonicalExecutionRepository,
CanonicalTransaction,
} from '../../apps/stock/orchestrator/src/execution/canonical-paper';
import type { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution';
import {
CanonicalPaperRuntime,
projectPaperReadiness,
} from '../../apps/stock/orchestrator/src/paper/CanonicalPaperRuntime';
import { counterProgram } from '../fixtures/canonical-paper';
import { paperFeedConfiguration, paperFeedFrame } from '../fixtures/paper-feed';
// Native initialization supplies a real financial checkpoint. The repository fake
// clones transactions and commits only on success; financial writes are forbidden.
async function fixture() {
let stored: CanonicalAccount;
let now = 1000;
let failRead = false;
let pendingReads = 0;
const unexpected = async (): Promise<never> => {
throw new Error('Unexpected financial write in readiness-only fixture');
};
const repository: CanonicalExecutionRepository = {
async initialize(account) {
stored = structuredClone(account);
},
async transact(_id, work) {
const account = structuredClone(stored);
const tx: CanonicalTransaction = {
account,
owners: unexpected,
putOwner: unexpected,
getInput: unexpected,
async nextInput() {
pendingReads++;
if (failRead) {
throw new Error('fixture storage unavailable');
}
return undefined;
},
putInput: unexpected,
async nextBatch() {
pendingReads++;
return undefined;
},
putBatch: unexpected,
appendJournal: unexpected,
journal: unexpected,
};
const value = await work(tx);
stored = account;
return value;
},
};
const config = paperFeedConfiguration();
config.matching.risk.maxMarkAgeMs = 100;
const runtime = new CanonicalPaperRuntime({
repository,
programs: [
{
...counterProgram('owner-X'),
strategyId: 'sma_crossover',
strategyVersion: 'sma-crossover-long-only/v1',
},
],
now: () => now,
});
await runtime.initialize(config);
await runtime.connect({ sourceId: 'trusted-fixture', connectionId: 'connection-1' });
await runtime.ingest(paperFeedFrame());
await runtime.activate({ recoverPending: false });
return {
runtime,
snapshot: () => structuredClone(stored),
clock(value: number) {
now = value;
},
failRead(value: boolean) {
failRead = value;
},
pendingReads: () => pendingReads,
};
}
test('pure readiness projection reports stale and pending evidence repeatedly without changing account state', async () => {
const f = await fixture();
const account = f.snapshot();
const before = structuredClone(account);
const pending = Object.freeze({ pendingInput: 'input-1', pendingBatch: 'batch-1' });
const first = projectPaperReadiness(account, pending, 1200);
const second = projectPaperReadiness(account, pending, 1200);
expect(first).toEqual(second);
expect(first).toMatchObject({
active: true,
ready: false,
requiresHistoricalRecovery: true,
pendingInput: 'input-1',
pendingBatch: 'batch-1',
reasons: ['feed-stale', 'quote-stale:X', 'historical-recovery-required'],
});
expect(account).toEqual(before);
expect(f.snapshot()).toEqual(before);
expect(
projectPaperReadiness(account, { pendingInput: null, pendingBatch: null }, 1000)
).toMatchObject({
active: true,
ready: true,
reasons: [],
});
const inactive = structuredClone(account);
inactive.host!.active = false;
const inactiveBefore = structuredClone(inactive);
expect(
projectPaperReadiness(inactive, { pendingInput: null, pendingBatch: null }, 1000)
).toMatchObject({ active: false, ready: true });
expect(inactive).toEqual(inactiveBefore);
});
test('status commits expired activation and repeated fresh evidence cannot automatically resume it', async () => {
const f = await fixture();
const checkpoint = f.snapshot().checkpoint;
f.clock(1200);
const expired = await f.runtime.status();
expect(expired).toMatchObject({ active: false, ready: false, operatorHalted: false });
expect(expired.reasons).toContain(
'Operational readiness expired; fresh feed and operator activation required'
);
expect(f.snapshot().host?.active).toBe(false);
expect(await f.runtime.status()).toEqual(expired);
f.clock(2000);
expect(await f.runtime.ingest(paperFeedFrame(2000))).toMatchObject({
disposition: 'health-only',
readiness: { active: false, ready: false },
});
expect(f.snapshot().checkpoint).toEqual(checkpoint);
expect(await f.runtime.activate({ recoverPending: false })).toMatchObject({
active: true,
ready: true,
});
});
test('storage failure rolls back status enforcement and returns failure instead of invented readiness', async () => {
const f = await fixture();
f.clock(1200);
const before = f.snapshot();
f.failRead(true);
await expect(f.runtime.status()).rejects.toThrow('fixture storage unavailable');
expect(f.snapshot()).toEqual(before);
f.failRead(false);
expect(await f.runtime.status()).toMatchObject({ active: false, ready: false });
expect(f.snapshot().host?.active).toBe(false);
});
test('execution independently enforces expiry before reading pending financial work without a status poll', async () => {
const f = await fixture();
const before = f.snapshot();
const reads = f.pendingReads();
f.clock(1200);
const execution = Reflect.get(f.runtime, 'execution') as CanonicalPaperExecution;
await execution.drain();
expect(f.pendingReads()).toBe(reads);
expect(f.snapshot().host?.active).toBe(false);
expect(f.snapshot().checkpoint).toEqual(before.checkpoint);
f.clock(2000);
expect(await f.runtime.ingest(paperFeedFrame(2000))).toMatchObject({
disposition: 'health-only',
readiness: { active: false },
});
});

View file

@ -120,6 +120,38 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
expect((await f.runtime.status()).active).toBe(true);
});
test('status expiry commits atomically, rolls back on storage failure and never resumes from fresh evidence alone', async () => {
const f = await fixture();
await start(f);
const before = await f.snapshot();
f.clock(200);
f.wrap(tx => ({
...tx,
async nextInput() {
throw new Error('readiness storage failure');
},
}));
await expect(f.runtime.status()).rejects.toThrow('readiness storage failure');
expect((await f.snapshot()).account).toEqual(before.account);
f.wrap(tx => tx);
const expired = await f.runtime.status();
expect(expired).toMatchObject({ active: false, ready: false });
expect(expired.reasons).toContain(
'Operational readiness expired; fresh feed and operator activation required'
);
expect((await f.snapshot()).account.host?.active).toBe(false);
expect(await f.runtime.status()).toEqual(expired);
expect(await f.runtime.ingest(paperFrame(2, 200))).toMatchObject({
disposition: 'health-only',
readiness: { active: false, ready: false },
});
expect((await f.snapshot()).account.checkpoint).toEqual(before.account.checkpoint);
expect(await f.runtime.activate({ recoverPending: false })).toMatchObject({
active: true,
ready: true,
});
});
test('frame inputs, health and receipts commit atomically and conflicting retries cannot alter them', async () => {
const f = await fixture();
await start(f);