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;
|
||||
});
|
||||
}
|
||||
}
|
||||
520
apps/stock/orchestrator/src/paper/feed.ts
Normal file
520
apps/stock/orchestrator/src/paper/feed.ts
Normal file
|
|
@ -0,0 +1,520 @@
|
|||
/** Pure trusted-feed validation and deterministic command planning. Rust alone
|
||||
* matches orders and accounts for money; no feed clock or price is repaired here. */
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { ZodError } from 'zod';
|
||||
import {
|
||||
matchingCommandSchema,
|
||||
type CanonicalMatchingCommand,
|
||||
} from '../contracts/canonical-execution';
|
||||
import {
|
||||
paperConfigurationSchema,
|
||||
paperFrameSchema,
|
||||
PaperRuntimeError,
|
||||
type PaperConfiguration,
|
||||
type PaperConfigurationInput,
|
||||
type PaperFrame,
|
||||
type PaperFrameInput,
|
||||
} from '../contracts/paper-runtime';
|
||||
import type { CanonicalAccount, CanonicalPaperInput } from '../execution/canonical-paper';
|
||||
|
||||
type Observation = PaperFrame['observations'][number];
|
||||
type Quote = PaperFrame['quotes'][number];
|
||||
type Session = PaperConfiguration['policy']['calendars'][number]['sessions'][number];
|
||||
type Key = CanonicalMatchingCommand['key'];
|
||||
|
||||
function invalid(message: string): never {
|
||||
throw new PaperRuntimeError('invalid-input', message);
|
||||
}
|
||||
// Decimal wire transforms throw ordinary Errors. Classify only this synchronous
|
||||
// input parsing boundary, never arbitrary storage/native errors, as bad input.
|
||||
function parseInput<T>(schema: { parse(input: unknown): T }, input: unknown): T {
|
||||
try {
|
||||
return schema.parse(input);
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
throw error;
|
||||
}
|
||||
invalid(error instanceof Error ? error.message : 'Malformed paper input');
|
||||
}
|
||||
}
|
||||
// UTF-8 ordering agrees with Rust Id/String ordering, including supplementary characters.
|
||||
const compareText = (a: string, b: string) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
||||
const units = (value: string) => BigInt(value.replace('.', ''));
|
||||
function unique(values: readonly string[], label: string): void {
|
||||
if (new Set(values).size !== values.length) {
|
||||
invalid(`Duplicate paper ${label}`);
|
||||
}
|
||||
}
|
||||
function keyCompare(a: Key, b: Key): number {
|
||||
const phase = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 };
|
||||
return (
|
||||
a.at - b.at ||
|
||||
phase[a.phase] - phase[b.phase] ||
|
||||
compareText(a.instrumentId, b.instrumentId) ||
|
||||
a.sourceSequence - b.sourceSequence
|
||||
);
|
||||
}
|
||||
const observationId = (row: Observation) =>
|
||||
JSON.stringify([row.series_id, row.event_time, row.source_sequence]);
|
||||
const physicalQuote = (instrumentId: string, observedAt: number, sourceSequence: number) =>
|
||||
JSON.stringify([instrumentId, observedAt, sourceSequence]);
|
||||
const quoteId = (quote: Quote) =>
|
||||
physicalQuote(quote.instrumentId, quote.observedAt, quote.sourceSequence);
|
||||
const quoteKey = (frame: PaperFrame, quote: Quote): Key => ({
|
||||
at: frame.availableAt,
|
||||
phase: 'Execution',
|
||||
instrumentId: quote.instrumentId,
|
||||
sourceSequence: quote.sourceSequence,
|
||||
});
|
||||
function sessions(config: PaperConfiguration, instrumentId: string): Session[] {
|
||||
const calendar = config.policy.calendars.find(item => item.instrumentId === instrumentId);
|
||||
if (!calendar) {
|
||||
invalid('Paper instrument has no declared calendar');
|
||||
}
|
||||
return calendar.sessions;
|
||||
}
|
||||
function activeSession(config: PaperConfiguration, instrumentId: string, at: number): Session {
|
||||
const session = sessions(config, instrumentId).find(
|
||||
item => item.opensAt <= at && at < item.closesAt
|
||||
);
|
||||
if (!session) {
|
||||
invalid('Paper quote is outside declared session coverage');
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
export function validatePaperConfiguration(input: PaperConfigurationInput): PaperConfiguration {
|
||||
const config = parseInput(paperConfigurationSchema, input);
|
||||
const { matching, policy, strategies } = config;
|
||||
if (!matching.series.length || matching.series.some(series => series.mode !== 'Quote')) {
|
||||
invalid('Canonical paper feed supports Quote execution only');
|
||||
}
|
||||
unique(
|
||||
matching.series.map(item => item.instrumentId),
|
||||
'execution instrument'
|
||||
);
|
||||
unique(
|
||||
matching.series.map(item => item.seriesId),
|
||||
'execution series'
|
||||
);
|
||||
unique(
|
||||
matching.owners.map(item => item.ownerId),
|
||||
'owner'
|
||||
);
|
||||
unique(matching.risk.ledger.ownerIds, 'ledger owner');
|
||||
unique(
|
||||
strategies.map(item => item.ownerId),
|
||||
'strategy owner'
|
||||
);
|
||||
unique(
|
||||
policy.observations.map(item => item.seriesId),
|
||||
'observation series'
|
||||
);
|
||||
unique(
|
||||
policy.cadence.map(item => item.ownerId),
|
||||
'cadence owner'
|
||||
);
|
||||
unique(
|
||||
policy.calendars.map(item => item.instrumentId),
|
||||
'calendar instrument'
|
||||
);
|
||||
const owners = matching.owners.map(item => item.ownerId).sort(compareText);
|
||||
if (
|
||||
matching.owners.some(item => item.mode !== 'Target') ||
|
||||
!isDeepStrictEqual(owners, [...matching.risk.ledger.ownerIds].sort(compareText)) ||
|
||||
!isDeepStrictEqual(owners, strategies.map(item => item.ownerId).sort(compareText)) ||
|
||||
!isDeepStrictEqual(owners, policy.cadence.map(item => item.ownerId).sort(compareText))
|
||||
) {
|
||||
invalid('Paper built-ins must exactly match the target owner and cadence cohort');
|
||||
}
|
||||
const instruments = matching.series.map(item => item.instrumentId).sort(compareText);
|
||||
if (
|
||||
!isDeepStrictEqual(
|
||||
instruments,
|
||||
policy.calendars.map(item => item.instrumentId).sort(compareText)
|
||||
)
|
||||
) {
|
||||
invalid('Paper calendars must exactly cover execution instruments');
|
||||
}
|
||||
for (const observation of policy.observations) {
|
||||
if (!instruments.includes(observation.instrumentId)) {
|
||||
invalid('Paper observation references an unknown instrument');
|
||||
}
|
||||
}
|
||||
for (const cadence of policy.cadence) {
|
||||
unique(cadence.seriesIds, 'cadence series');
|
||||
if (cadence.seriesIds.some(id => !policy.observations.some(item => item.seriesId === id))) {
|
||||
invalid('Paper cadence references an unknown observation series');
|
||||
}
|
||||
cadence.seriesIds.sort(compareText);
|
||||
}
|
||||
for (const strategy of strategies) {
|
||||
const series = policy.observations.find(item => item.seriesId === strategy.seriesId);
|
||||
if (
|
||||
series?.instrumentId !== strategy.instrumentId ||
|
||||
!policy.cadence
|
||||
.find(item => item.ownerId === strategy.ownerId)
|
||||
?.seriesIds.includes(strategy.seriesId)
|
||||
) {
|
||||
invalid('Paper strategy requires its bound instrument/observation series in its cadence');
|
||||
}
|
||||
}
|
||||
const initial = matching.risk.ledger.riskSession;
|
||||
for (const calendar of policy.calendars) {
|
||||
unique(
|
||||
calendar.sessions.map(item => item.sessionId),
|
||||
'venue session'
|
||||
);
|
||||
calendar.sessions.sort((a, b) => a.opensAt - b.opensAt);
|
||||
let previousClose = initial.startsAt;
|
||||
for (const session of calendar.sessions) {
|
||||
if (session.opensAt < previousClose || session.opensAt >= session.closesAt) {
|
||||
invalid('Paper venue sessions overlap, are invalid, or precede the initial risk clock');
|
||||
}
|
||||
previousClose = session.closesAt;
|
||||
}
|
||||
}
|
||||
unique([initial.sessionId, ...policy.riskBoundaries.map(item => item.sessionId)], 'risk session');
|
||||
policy.riskBoundaries.sort((a, b) => a.startsAt - b.startsAt);
|
||||
let previousRisk = initial.startsAt;
|
||||
for (const boundary of policy.riskBoundaries) {
|
||||
if (
|
||||
boundary.calendarId !== initial.calendarId ||
|
||||
boundary.calendarRevision !== initial.calendarRevision ||
|
||||
boundary.startsAt <= previousRisk
|
||||
) {
|
||||
invalid('Paper risk boundaries must advance the declared account calendar revision');
|
||||
}
|
||||
previousRisk = boundary.startsAt;
|
||||
}
|
||||
matching.owners.sort((a, b) => compareText(a.ownerId, b.ownerId));
|
||||
matching.series.sort((a, b) => compareText(a.instrumentId, b.instrumentId));
|
||||
matching.risk.ledger.ownerIds.sort(compareText);
|
||||
strategies.sort((a, b) => compareText(a.ownerId, b.ownerId));
|
||||
policy.observations.sort((a, b) => compareText(a.seriesId, b.seriesId));
|
||||
policy.cadence.sort((a, b) => compareText(a.ownerId, b.ownerId));
|
||||
policy.calendars.sort((a, b) => compareText(a.instrumentId, b.instrumentId));
|
||||
return config;
|
||||
}
|
||||
|
||||
export function validatePaperFrame(
|
||||
config: PaperConfiguration,
|
||||
input: PaperFrameInput,
|
||||
now: number
|
||||
): PaperFrame {
|
||||
const frame = parseInput(paperFrameSchema, input);
|
||||
if (
|
||||
!Number.isSafeInteger(now) ||
|
||||
frame.sourceId !== config.policy.sourceId ||
|
||||
frame.availableAt > now
|
||||
) {
|
||||
invalid('Paper frame source or availability time is invalid');
|
||||
}
|
||||
unique(frame.quotes.map(quoteId), 'physical quote');
|
||||
unique(
|
||||
frame.quotes.map(quote => JSON.stringify([quote.instrumentId, quote.sourceSequence])),
|
||||
'quote event key'
|
||||
);
|
||||
for (const quote of frame.quotes) {
|
||||
const series = config.matching.series.find(item => item.instrumentId === quote.instrumentId);
|
||||
const session = activeSession(config, quote.instrumentId, frame.availableAt);
|
||||
if (
|
||||
series?.seriesId !== quote.seriesId ||
|
||||
quote.observedAt > frame.availableAt ||
|
||||
quote.observedAt < session.opensAt ||
|
||||
units(quote.bid) <= 0n ||
|
||||
units(quote.ask) <= 0n ||
|
||||
units(quote.bid) > units(quote.ask) ||
|
||||
units(quote.bidSize) < 0n ||
|
||||
units(quote.askSize) < 0n
|
||||
) {
|
||||
invalid('Paper quote identity, time, price or size is invalid');
|
||||
}
|
||||
}
|
||||
frame.quotes.sort((a, b) => keyCompare(quoteKey(frame, a), quoteKey(frame, b)));
|
||||
for (let index = 1; index < frame.quotes.length; index++) {
|
||||
const prior = frame.quotes[index - 1];
|
||||
const current = frame.quotes[index];
|
||||
if (
|
||||
prior &&
|
||||
current &&
|
||||
prior.instrumentId === current.instrumentId &&
|
||||
prior.observedAt > current.observedAt
|
||||
) {
|
||||
invalid('Paper quote sequence reverses physical event time within a frame');
|
||||
}
|
||||
}
|
||||
const observations = new Map<string, Observation>();
|
||||
for (const row of frame.observations) {
|
||||
const series = config.policy.observations.find(item => item.seriesId === row.series_id);
|
||||
if (!series || series.instrumentId !== row.instrument_id) {
|
||||
invalid('Paper observation is outside the declared series manifest');
|
||||
}
|
||||
const session = sessions(config, row.instrument_id).find(
|
||||
item => item.opensAt <= row.interval_start && row.interval_start < item.closesAt
|
||||
);
|
||||
const intervalEnd = BigInt(row.interval_start) + BigInt(series.intervalMs);
|
||||
// Intervals start on a session-open grid and the final complete bar may be
|
||||
// clipped at a half-day/session close. No synthetic partial prices or volume.
|
||||
if (
|
||||
!session ||
|
||||
row.interval_end <= row.interval_start ||
|
||||
(BigInt(row.interval_start) - BigInt(session.opensAt)) % BigInt(series.intervalMs) !== 0n ||
|
||||
BigInt(row.interval_end) !==
|
||||
(intervalEnd < BigInt(session.closesAt) ? intervalEnd : BigInt(session.closesAt)) ||
|
||||
row.event_time !== row.interval_end ||
|
||||
row.interval_end > row.available_at ||
|
||||
row.available_at > frame.availableAt ||
|
||||
units(row.open) <= 0n ||
|
||||
units(row.close) <= 0n ||
|
||||
units(row.low) <= 0n ||
|
||||
units(row.high) < units(row.low) ||
|
||||
units(row.high) < units(row.open) ||
|
||||
units(row.high) < units(row.close) ||
|
||||
units(row.low) > units(row.open) ||
|
||||
units(row.low) > units(row.close) ||
|
||||
units(row.volume) < 0n
|
||||
) {
|
||||
invalid('Paper observation is incomplete, unaligned, unavailable or has invalid OHLCV');
|
||||
}
|
||||
const prior = observations.get(observationId(row));
|
||||
if (prior && !isDeepStrictEqual(prior, row)) {
|
||||
invalid('Conflicting physical paper observation');
|
||||
}
|
||||
observations.set(observationId(row), row);
|
||||
}
|
||||
frame.observations = [...observations.values()];
|
||||
return frame;
|
||||
}
|
||||
|
||||
/** Caller atomically enqueues this complete plan under the same account lock.
|
||||
* The runtime owns cross-frame observation fingerprints; this pure helper also
|
||||
* deduplicates against the known latest observation while retaining delayed older bars. */
|
||||
export function planPaperFrame(
|
||||
config: PaperConfiguration,
|
||||
frame: PaperFrame,
|
||||
account: Pick<CanonicalAccount, 'checkpoint' | 'latestObservations' | 'observed'>
|
||||
): CanonicalPaperInput[] {
|
||||
const { checkpoint } = account;
|
||||
if (checkpoint.status !== 'Running' || !isDeepStrictEqual(checkpoint.config, config.matching)) {
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
'Paper financial snapshot is incompatible or terminal'
|
||||
);
|
||||
}
|
||||
const retained = new Set<string>();
|
||||
const physicalTime = new Map<string, number>();
|
||||
for (const receipt of checkpoint.receipts) {
|
||||
const input = receipt.input;
|
||||
if (!input || typeof input !== 'object' || !('source' in input) || input.source !== 'Engine') {
|
||||
continue;
|
||||
}
|
||||
const parsed = matchingCommandSchema.safeParse('command' in input ? input.command : undefined);
|
||||
if (!parsed.success) {
|
||||
invalid('Malformed retained paper execution receipt');
|
||||
}
|
||||
const command = parsed.data;
|
||||
const observedAt =
|
||||
command.body.kind === 'mark'
|
||||
? command.body.observedAt
|
||||
: command.body.kind === 'execute' && command.body.observation.kind === 'quote'
|
||||
? command.body.observation.observedAt
|
||||
: undefined;
|
||||
if (observedAt !== undefined) {
|
||||
physicalTime.set(
|
||||
command.key.instrumentId,
|
||||
Math.max(physicalTime.get(command.key.instrumentId) ?? observedAt, observedAt)
|
||||
);
|
||||
}
|
||||
if (command.body.kind === 'execute' && command.body.observation.kind === 'quote') {
|
||||
retained.add(
|
||||
physicalQuote(
|
||||
command.key.instrumentId,
|
||||
command.body.observation.observedAt,
|
||||
command.key.sourceSequence
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
if (frame.quotes.some(quote => retained.has(quoteId(quote)))) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper frame reuses retained physical quote liquidity');
|
||||
}
|
||||
if (
|
||||
frame.quotes.some(
|
||||
quote => quote.observedAt < (physicalTime.get(quote.instrumentId) ?? quote.observedAt)
|
||||
)
|
||||
) {
|
||||
invalid('Paper quote regresses the retained physical event time');
|
||||
}
|
||||
const commands: CanonicalMatchingCommand[] = [];
|
||||
const add = (command: CanonicalMatchingCommand) => {
|
||||
if (
|
||||
command.key.at <= frame.availableAt &&
|
||||
(!checkpoint.cursor || keyCompare(command.key, checkpoint.cursor) > 0)
|
||||
) {
|
||||
commands.push(command);
|
||||
}
|
||||
};
|
||||
for (const calendar of config.policy.calendars) {
|
||||
for (const session of calendar.sessions) {
|
||||
const identity = [
|
||||
frame.sourceId,
|
||||
calendar.instrumentId,
|
||||
calendar.calendarId,
|
||||
calendar.revision,
|
||||
session.sessionId,
|
||||
];
|
||||
add({
|
||||
commandId: JSON.stringify(['paper-session-open', ...identity]),
|
||||
key: {
|
||||
at: session.opensAt,
|
||||
phase: 'Observation',
|
||||
instrumentId: calendar.instrumentId,
|
||||
sourceSequence: 2,
|
||||
},
|
||||
body: { kind: 'openSession', session },
|
||||
});
|
||||
add({
|
||||
commandId: JSON.stringify(['paper-session-close', ...identity]),
|
||||
key: {
|
||||
at: session.closesAt,
|
||||
phase: 'Observation',
|
||||
instrumentId: calendar.instrumentId,
|
||||
sourceSequence: 0,
|
||||
},
|
||||
body: { kind: 'closeSession', sessionId: session.sessionId },
|
||||
});
|
||||
}
|
||||
}
|
||||
const firstSeries = config.matching.series[0];
|
||||
if (!firstSeries) {
|
||||
invalid('Paper configuration has no execution series');
|
||||
}
|
||||
for (const boundary of config.policy.riskBoundaries) {
|
||||
add({
|
||||
commandId: JSON.stringify([
|
||||
'paper-risk-boundary',
|
||||
frame.sourceId,
|
||||
boundary.calendarId,
|
||||
boundary.calendarRevision,
|
||||
boundary.sessionId,
|
||||
]),
|
||||
key: {
|
||||
at: boundary.startsAt,
|
||||
phase: 'Observation',
|
||||
instrumentId: firstSeries.instrumentId,
|
||||
sourceSequence: 1,
|
||||
},
|
||||
body: { kind: 'riskSessionBoundary', riskSession: boundary },
|
||||
});
|
||||
}
|
||||
const active = new Map(checkpoint.sessions);
|
||||
commands.sort((a, b) => keyCompare(a.key, b.key));
|
||||
for (const command of commands) {
|
||||
if (command.body.kind === 'openSession') {
|
||||
if (active.has(command.key.instrumentId)) {
|
||||
invalid('Paper venue session is already open at its declared boundary');
|
||||
}
|
||||
active.set(command.key.instrumentId, command.body.session);
|
||||
} else if (command.body.kind === 'closeSession') {
|
||||
if (active.get(command.key.instrumentId)?.sessionId !== command.body.sessionId) {
|
||||
invalid('Paper venue close does not match the retained open session');
|
||||
}
|
||||
active.delete(command.key.instrumentId);
|
||||
}
|
||||
}
|
||||
const quotes = [...frame.quotes].sort((a, b) =>
|
||||
keyCompare(quoteKey(frame, a), quoteKey(frame, b))
|
||||
);
|
||||
for (const quote of quotes) {
|
||||
const key = quoteKey(frame, quote);
|
||||
if (
|
||||
(checkpoint.cursor && keyCompare(key, checkpoint.cursor) <= 0) ||
|
||||
!isDeepStrictEqual(
|
||||
active.get(quote.instrumentId),
|
||||
activeSession(config, quote.instrumentId, frame.availableAt)
|
||||
)
|
||||
) {
|
||||
invalid('Paper quote cannot advance the retained event cursor/session');
|
||||
}
|
||||
commands.push({
|
||||
commandId: JSON.stringify([
|
||||
'paper-quote',
|
||||
frame.sourceId,
|
||||
quote.instrumentId,
|
||||
quote.seriesId,
|
||||
quote.observedAt,
|
||||
quote.sourceSequence,
|
||||
]),
|
||||
key,
|
||||
body: {
|
||||
kind: 'execute',
|
||||
seriesId: quote.seriesId,
|
||||
observation: {
|
||||
kind: 'quote',
|
||||
observedAt: quote.observedAt,
|
||||
bid: quote.bid,
|
||||
ask: quote.ask,
|
||||
bidSize: quote.bidSize,
|
||||
askSize: quote.askSize,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const observations = frame.observations.filter(row => {
|
||||
const latest = account.latestObservations.find(
|
||||
item => observationId(item) === observationId(row)
|
||||
);
|
||||
if (latest && !isDeepStrictEqual(latest, row)) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
'Paper observation conflicts with its retained identity'
|
||||
);
|
||||
}
|
||||
return !latest;
|
||||
});
|
||||
const latest = new Map(account.latestObservations.map(row => [row.series_id, row]));
|
||||
for (const row of observations) {
|
||||
const old = latest.get(row.series_id);
|
||||
if (
|
||||
!old ||
|
||||
row.event_time > old.event_time ||
|
||||
(row.event_time === old.event_time && row.source_sequence > old.source_sequence)
|
||||
) {
|
||||
latest.set(row.series_id, row);
|
||||
}
|
||||
}
|
||||
const ownerIds = config.policy.cadence
|
||||
.filter(cadence => observations.some(row => cadence.seriesIds.includes(row.series_id)))
|
||||
.map(cadence => cadence.ownerId)
|
||||
.sort(compareText);
|
||||
const result: CanonicalPaperInput[] = commands.map(command => ({ command, observations: [] }));
|
||||
const final = result.at(-1);
|
||||
if (!final || final.command.body.kind !== 'execute') {
|
||||
invalid('Paper frame requires a final execution quote');
|
||||
}
|
||||
final.observations = observations;
|
||||
if (ownerIds.length) {
|
||||
const identity = [frame.sourceId, frame.id, frame.sequence];
|
||||
final.decision = {
|
||||
commandId: JSON.stringify(['paper-decision', ...identity]),
|
||||
key: { ...final.command.key },
|
||||
barrierId: JSON.stringify(['paper-barrier', ...identity]),
|
||||
ownerIds,
|
||||
inputs: config.policy.observations.map(series => {
|
||||
const row = latest.get(series.seriesId);
|
||||
const timing = row && { event_time: row.event_time, available_at: row.available_at };
|
||||
return {
|
||||
series_id: series.seriesId,
|
||||
availability:
|
||||
!row || !timing
|
||||
? 'Missing'
|
||||
: frame.availableAt - row.event_time > series.staleAfterMs
|
||||
? { Stale: timing }
|
||||
: { Fresh: timing },
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue