512 lines
19 KiB
TypeScript
512 lines
19 KiB
TypeScript
/** 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 {
|
|
compareEventKeys,
|
|
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}`);
|
|
}
|
|
}
|
|
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) => compareEventKeys(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 || compareEventKeys(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) => compareEventKeys(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) =>
|
|
compareEventKeys(quoteKey(frame, a), quoteKey(frame, b))
|
|
);
|
|
for (const quote of quotes) {
|
|
const key = quoteKey(frame, quote);
|
|
if (
|
|
(checkpoint.cursor && compareEventKeys(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;
|
|
}
|