feat(paper): gate canonical execution on durable feed readiness
This commit is contained in:
parent
c01e96e4dd
commit
75abae2cfc
24 changed files with 3720 additions and 66 deletions
498
apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts
Normal file
498
apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts
Normal file
|
|
@ -0,0 +1,498 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import {
|
||||
paperActivationSchema,
|
||||
paperConnectionSchema,
|
||||
paperHaltSchema,
|
||||
PaperRuntimeError,
|
||||
type PaperConfiguration,
|
||||
type PaperConfigurationInput,
|
||||
type PaperConnection,
|
||||
type PaperFrameInput,
|
||||
type PaperReadiness,
|
||||
type PaperRuntime,
|
||||
} from '../contracts/paper-runtime';
|
||||
import type {
|
||||
CanonicalAccount,
|
||||
CanonicalExecutionRepository,
|
||||
CanonicalJournalEntry,
|
||||
CanonicalPaperHost,
|
||||
CanonicalTransaction,
|
||||
} from '../execution/canonical-paper';
|
||||
import { CanonicalPaperExecution } from '../execution/CanonicalPaperExecution';
|
||||
import { canonicalJson } from '../execution/strategy-recovery';
|
||||
import { planPaperFrame, validatePaperConfiguration, validatePaperFrame } from './feed';
|
||||
|
||||
const fingerprint = (value: unknown) =>
|
||||
createHash('sha256').update(canonicalJson(value)).digest('hex');
|
||||
function hostState(account: CanonicalAccount): CanonicalPaperHost {
|
||||
if (!account.host) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper account has no host policy');
|
||||
}
|
||||
return account.host;
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
private readonly generation = randomUUID();
|
||||
private readonly execution: CanonicalPaperExecution;
|
||||
private configuration?: PaperConfiguration;
|
||||
private readonly now: () => number;
|
||||
|
||||
constructor(
|
||||
private readonly options: {
|
||||
repository: CanonicalExecutionRepository;
|
||||
programs: readonly StrategyProgram[];
|
||||
now?: () => number;
|
||||
publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise<void>;
|
||||
}
|
||||
) {
|
||||
this.now = options.now ?? Date.now;
|
||||
this.execution = new CanonicalPaperExecution({
|
||||
repository: options.repository,
|
||||
programs: options.programs,
|
||||
publish: options.publish,
|
||||
control: { generation: this.generation, guard: account => this.guard(account) },
|
||||
});
|
||||
}
|
||||
|
||||
async initialize(input: PaperConfigurationInput): Promise<void> {
|
||||
if (this.configuration) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper runtime is already initialized');
|
||||
}
|
||||
const configuration = validatePaperConfiguration(input);
|
||||
if (
|
||||
configuration.strategies.length !== this.options.programs.length ||
|
||||
configuration.strategies.some(
|
||||
selection =>
|
||||
!this.options.programs.some(
|
||||
program =>
|
||||
program.ownerId === selection.ownerId &&
|
||||
program.strategyId === selection.strategyId &&
|
||||
program.strategyVersion === selection.strategyVersion &&
|
||||
program.seed === selection.seed &&
|
||||
program.mode === 'target'
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
'Paper programs must match immutable configured strategy selections'
|
||||
);
|
||||
}
|
||||
const host: CanonicalPaperHost = {
|
||||
version: 1,
|
||||
configuration,
|
||||
generation: this.generation,
|
||||
active: false,
|
||||
operatorHalted: true,
|
||||
haltReason: 'Initial operator activation required',
|
||||
diagnostic: null,
|
||||
connection: null,
|
||||
lastReceivedAt: null,
|
||||
lastAvailableAt: null,
|
||||
lastSequence: null,
|
||||
quotes: [],
|
||||
quoteHighWater: [],
|
||||
frames: {},
|
||||
observations: {},
|
||||
physicalQuotes: {},
|
||||
};
|
||||
await this.execution.initialize(configuration.matching, host);
|
||||
await this.options.repository.transact(
|
||||
configuration.matching.risk.ledger.accountId,
|
||||
async tx => {
|
||||
if (!tx.account.host) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper account has no host policy');
|
||||
}
|
||||
tx.account.host.generation = this.generation;
|
||||
tx.account.host.active = false;
|
||||
tx.account.host.connection = null;
|
||||
tx.account.host.lastReceivedAt = null;
|
||||
tx.account.host.lastSequence = null;
|
||||
tx.account.host.quotes = [];
|
||||
}
|
||||
);
|
||||
this.configuration = configuration;
|
||||
}
|
||||
|
||||
private transaction<T>(
|
||||
work: (tx: CanonicalTransaction, host: CanonicalPaperHost) => Promise<T>
|
||||
): Promise<T> {
|
||||
if (!this.configuration) {
|
||||
throw new PaperRuntimeError('not-ready', 'Paper runtime is not initialized');
|
||||
}
|
||||
return this.options.repository.transact(
|
||||
this.configuration.matching.risk.ledger.accountId,
|
||||
async tx => {
|
||||
const host = tx.account.host;
|
||||
if (!host || host.generation !== this.generation) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper runtime generation is obsolete');
|
||||
}
|
||||
return work(tx, host);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private health(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;
|
||||
}
|
||||
|
||||
private guard(account: CanonicalAccount): boolean {
|
||||
const host = hostState(account);
|
||||
if (this.health(account, this.now()).length && host.active) {
|
||||
host.active = false;
|
||||
host.diagnostic =
|
||||
'Operational readiness expired; fresh feed and operator activation required';
|
||||
}
|
||||
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);
|
||||
}
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A rejected request rolls back its admission transaction. Persist ONLY the
|
||||
* freshness latch separately, preserving the original failure if storage is down. */
|
||||
private async withFreshnessLatch<T>(work: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
try {
|
||||
await this.transaction(async tx => {
|
||||
this.guard(tx.account);
|
||||
});
|
||||
} catch {
|
||||
// A replacement generation or unavailable repository must not mask the original error.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
connect(input: PaperConnection): Promise<PaperReadiness> {
|
||||
const connection = paperConnectionSchema.parse(input);
|
||||
return this.transaction(async (tx, host) => {
|
||||
if (connection.sourceId !== host.configuration.policy.sourceId) {
|
||||
throw new PaperRuntimeError(
|
||||
'invalid-input',
|
||||
'Paper source does not match its configured provider'
|
||||
);
|
||||
}
|
||||
this.guard(tx.account);
|
||||
if (canonicalJson(connection) !== canonicalJson(host.connection)) {
|
||||
host.connection = connection;
|
||||
host.active = false;
|
||||
host.lastReceivedAt = null;
|
||||
host.lastSequence = null;
|
||||
host.quotes = [];
|
||||
}
|
||||
return this.readiness(tx);
|
||||
});
|
||||
}
|
||||
|
||||
disconnect(input: PaperConnection): Promise<PaperReadiness> {
|
||||
const connection = paperConnectionSchema.parse(input);
|
||||
return this.transaction(async (tx, host) => {
|
||||
if (canonicalJson(connection) === canonicalJson(host.connection)) {
|
||||
host.active = false;
|
||||
host.connection = null;
|
||||
}
|
||||
return this.readiness(tx);
|
||||
});
|
||||
}
|
||||
|
||||
async ingest(input: PaperFrameInput): ReturnType<PaperRuntime['ingest']> {
|
||||
return this.withFreshnessLatch(async () => {
|
||||
if (!this.configuration) {
|
||||
throw new PaperRuntimeError('not-ready', 'Paper runtime is not initialized');
|
||||
}
|
||||
const frame = validatePaperFrame(this.configuration, input, this.now());
|
||||
const digest = fingerprint(frame);
|
||||
const frameIdentity = fingerprint(frame.id);
|
||||
const receipt = await this.transaction(async (tx, host) => {
|
||||
const old = host.frames[frameIdentity];
|
||||
if (old) {
|
||||
if (old.fingerprint !== digest) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper frame ID has conflicting content');
|
||||
}
|
||||
this.guard(tx.account);
|
||||
return { duplicate: true, disposition: old.disposition };
|
||||
}
|
||||
if (
|
||||
!host.connection ||
|
||||
host.connection.sourceId !== frame.sourceId ||
|
||||
host.connection.connectionId !== frame.connectionId
|
||||
) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper frame belongs to an inactive connection');
|
||||
}
|
||||
if (
|
||||
(host.lastSequence !== null && frame.sequence <= host.lastSequence) ||
|
||||
(host.lastAvailableAt !== null && frame.availableAt <= host.lastAvailableAt)
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
'Distinct paper frames require increasing sequence and availability time'
|
||||
);
|
||||
}
|
||||
// Compare the OLD health deadline before this fresh frame can change it.
|
||||
this.guard(tx.account);
|
||||
if (
|
||||
host.active &&
|
||||
((await tx.nextInput()) ||
|
||||
(await tx.nextBatch()) ||
|
||||
tx.account.pendingDecisionSequence !== null)
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
'Previously admitted paper work requires completion before another frame'
|
||||
);
|
||||
}
|
||||
const observations = frame.observations.filter(observation => {
|
||||
const identity = fingerprint([
|
||||
observation.series_id,
|
||||
observation.event_time,
|
||||
observation.source_sequence,
|
||||
]);
|
||||
const value = fingerprint(observation);
|
||||
const known = host.observations[identity];
|
||||
if (known && known !== value) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
'Physical observation identity has conflicting content'
|
||||
);
|
||||
}
|
||||
return !known;
|
||||
});
|
||||
for (const quote of frame.quotes) {
|
||||
const latest = host.quoteHighWater.find(item => item.instrumentId === quote.instrumentId);
|
||||
if (
|
||||
latest &&
|
||||
(quote.observedAt < latest.observedAt ||
|
||||
(quote.observedAt === latest.observedAt &&
|
||||
quote.sourceSequence < latest.sourceSequence))
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'invalid-input',
|
||||
'Paper quote regresses the retained physical event time'
|
||||
);
|
||||
}
|
||||
if (
|
||||
host.active &&
|
||||
this.now() - quote.observedAt > host.configuration.matching.risk.maxMarkAgeMs
|
||||
) {
|
||||
throw new PaperRuntimeError('invalid-input', 'Admitted paper quote is stale');
|
||||
}
|
||||
const known =
|
||||
host.physicalQuotes[
|
||||
fingerprint([quote.instrumentId, quote.observedAt, quote.sourceSequence])
|
||||
];
|
||||
if (known) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
known === fingerprint(quote)
|
||||
? 'New paper frame reuses known physical quote liquidity'
|
||||
: 'Physical quote identity has conflicting content'
|
||||
);
|
||||
}
|
||||
}
|
||||
const disposition = host.active ? ('admitted' as const) : ('health-only' as const);
|
||||
host.lastReceivedAt = this.now();
|
||||
host.lastAvailableAt = frame.availableAt;
|
||||
host.lastSequence = frame.sequence;
|
||||
for (const quote of frame.quotes) {
|
||||
for (const clocks of [host.quotes, host.quoteHighWater]) {
|
||||
const oldQuote = clocks.find(item => item.instrumentId === quote.instrumentId);
|
||||
if (!oldQuote) {
|
||||
clocks.push({
|
||||
instrumentId: quote.instrumentId,
|
||||
observedAt: quote.observedAt,
|
||||
sourceSequence: quote.sourceSequence,
|
||||
});
|
||||
} else if (
|
||||
quote.observedAt > oldQuote.observedAt ||
|
||||
(quote.observedAt === oldQuote.observedAt &&
|
||||
quote.sourceSequence > oldQuote.sourceSequence)
|
||||
) {
|
||||
Object.assign(oldQuote, {
|
||||
observedAt: quote.observedAt,
|
||||
sourceSequence: quote.sourceSequence,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (disposition === 'admitted') {
|
||||
await this.execution.enqueueFrame(
|
||||
tx,
|
||||
planPaperFrame(host.configuration, { ...frame, observations }, tx.account)
|
||||
);
|
||||
}
|
||||
for (const observation of frame.observations) {
|
||||
host.observations[
|
||||
fingerprint([
|
||||
observation.series_id,
|
||||
observation.event_time,
|
||||
observation.source_sequence,
|
||||
])
|
||||
] = fingerprint(observation);
|
||||
}
|
||||
for (const quote of frame.quotes) {
|
||||
host.physicalQuotes[
|
||||
fingerprint([quote.instrumentId, quote.observedAt, quote.sourceSequence])
|
||||
] = fingerprint(quote);
|
||||
}
|
||||
host.frames[frameIdentity] = { fingerprint: digest, disposition };
|
||||
return { duplicate: false, disposition };
|
||||
});
|
||||
// A retry retains its first disposition and never replays an inactive probe.
|
||||
if (!receipt.duplicate && receipt.disposition === 'admitted') {
|
||||
await this.drain();
|
||||
}
|
||||
return { ...receipt, readiness: await this.status() };
|
||||
});
|
||||
}
|
||||
|
||||
private async drain(): Promise<void> {
|
||||
try {
|
||||
await this.execution.drain();
|
||||
} catch (error) {
|
||||
await this.transaction(async (_tx, host) => {
|
||||
host.active = false;
|
||||
host.diagnostic = error instanceof Error ? error.message : String(error);
|
||||
}).catch(() => {
|
||||
/* A replacement generation alone controls its account. */
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async activate(input: { recoverPending: boolean }): Promise<PaperReadiness> {
|
||||
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());
|
||||
if (reasons.length) {
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
`Paper activation unavailable: ${reasons.join(', ')}`
|
||||
);
|
||||
}
|
||||
if (
|
||||
!recoverPending &&
|
||||
((await tx.nextInput()) ||
|
||||
(await tx.nextBatch()) ||
|
||||
tx.account.pendingDecisionSequence !== null)
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
'Historical admitted work requires explicit recoverPending: true'
|
||||
);
|
||||
}
|
||||
host.active = true;
|
||||
host.operatorHalted = false;
|
||||
host.haltReason = null;
|
||||
host.diagnostic = null;
|
||||
});
|
||||
await this.drain();
|
||||
const result = await this.status();
|
||||
if (!result.active || !result.ready || result.requiresHistoricalRecovery) {
|
||||
await this.transaction(async (_tx, host) => {
|
||||
host.active = false;
|
||||
});
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
'Paper activation stopped before recovery and fresh readiness completed'
|
||||
);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
halt(reason: string): Promise<PaperReadiness> {
|
||||
const parsed = paperHaltSchema.parse({ reason });
|
||||
return this.transaction(async (tx, host) => {
|
||||
host.active = false;
|
||||
host.operatorHalted = true;
|
||||
host.haltReason = parsed.reason;
|
||||
return this.readiness(tx);
|
||||
});
|
||||
}
|
||||
|
||||
status(): Promise<PaperReadiness> {
|
||||
return this.transaction(tx => this.readiness(tx));
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
await this.transaction(async (_tx, host) => {
|
||||
host.active = false;
|
||||
host.connection = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue