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;