feat(engine): expose canonical replay sessions through native workers
This commit is contained in:
parent
417a7bd21e
commit
e3635f23cf
26 changed files with 2693 additions and 33 deletions
|
|
@ -1,5 +1,10 @@
|
|||
import { fork, type ChildProcess } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
replayIdentitySchema,
|
||||
} from '../contracts/native-replay';
|
||||
import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol';
|
||||
import { BacktestConflictError } from './run-repository';
|
||||
|
||||
|
|
@ -23,6 +28,19 @@ export class NativeBacktestWorker {
|
|||
if (this.active) {
|
||||
throw new BacktestConflictError('A native backtest worker is already running');
|
||||
}
|
||||
// Capture expected identity/policy before asynchronous execution. A caller
|
||||
// mutating its request cannot change which completed child result is valid.
|
||||
const expectedReplay =
|
||||
request.type === 'runReplayTrace'
|
||||
? {
|
||||
identity: replayIdentitySchema.parse({
|
||||
version: 1,
|
||||
sessionId: request.config.matching.risk.ledger.sessionId,
|
||||
datasetHash: (request.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash,
|
||||
}),
|
||||
policy: replayConfigSchema.parse(request.config),
|
||||
}
|
||||
: undefined;
|
||||
const child = fork(fileURLToPath(this.workerUrl), [], {
|
||||
execPath: process.execPath,
|
||||
execArgv: [],
|
||||
|
|
@ -61,6 +79,14 @@ export class NativeBacktestWorker {
|
|||
if (message.type === 'error') {
|
||||
terminate(new Error(message.message));
|
||||
} else if (message.type === 'result') {
|
||||
if (expectedReplay) {
|
||||
try {
|
||||
parseReplayResult(message.result, expectedReplay.identity, expectedReplay.policy);
|
||||
} catch (error) {
|
||||
terminate(error instanceof Error ? error : new Error(String(error)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
result = message.result;
|
||||
} else {
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -111,11 +111,11 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
config: BacktestConfig,
|
||||
signal: AbortSignal,
|
||||
resolver?: DatasetResolver
|
||||
): Promise<NativeWorkerRequest['data']> {
|
||||
): Promise<Extract<NativeWorkerRequest, { type: 'run' }>['data']> {
|
||||
signal.throwIfAborted();
|
||||
const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal);
|
||||
signal.throwIfAborted();
|
||||
const data: NativeWorkerRequest['data'] = [];
|
||||
const data: Extract<NativeWorkerRequest, { type: 'run' }>['data'] = [];
|
||||
for (const bar of dataset.bars) {
|
||||
data.push({ ...bar, type: 'bar' });
|
||||
if (data.length % PREPARATION_BATCH_SIZE === 0) {
|
||||
|
|
|
|||
333
apps/stock/orchestrator/src/backtest/native-replay.ts
Normal file
333
apps/stock/orchestrator/src/backtest/native-replay.ts
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
/** Additive trusted-host F07 boundary, not an active runner or S01 strategy runtime. */
|
||||
import { FinancialReplaySession } from '@stock-bot/engine';
|
||||
import {
|
||||
parseFinancialDecimal,
|
||||
parseFinancialStrategyDecision,
|
||||
type FinancialStrategyDecision,
|
||||
type FinancialStrategyIntent,
|
||||
} from '@stock-bot/types';
|
||||
import {
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
replayTraceSchema,
|
||||
sameIdentity,
|
||||
stepSchema,
|
||||
submissionSchema,
|
||||
type DecisionContext,
|
||||
type PublishedObservation,
|
||||
type ReplayConfig,
|
||||
type ReplayIdentity,
|
||||
type ReplayResult,
|
||||
type ReplayStep,
|
||||
type ReplayTraceRequest,
|
||||
} from '../contracts/native-replay';
|
||||
import { validateDatasetV2 } from '../data/historical-dataset-v2';
|
||||
|
||||
export type {
|
||||
ReplayConfig,
|
||||
ReplayIdentity,
|
||||
ReplayStep,
|
||||
ReplayResult,
|
||||
DecisionContext,
|
||||
PublishedObservation,
|
||||
ReplayTraceRequest,
|
||||
} from '../contracts/native-replay';
|
||||
|
||||
/** Expand Number's exact shortest lexical representation, never round toFixed.
|
||||
* D01 already owns numeric data precision; >8 decimals cannot enter the ledger. */
|
||||
export function marketDecimal(value: number): string {
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new Error('Non-finite market decimal');
|
||||
}
|
||||
const source = String(value);
|
||||
if (!/[eE]/.test(source)) {
|
||||
return parseFinancialDecimal(source);
|
||||
}
|
||||
const [mantissa = '', exponent = ''] = source.toLowerCase().split('e');
|
||||
const negative = mantissa.startsWith('-');
|
||||
const [whole = '', fractional = ''] = (negative ? mantissa.slice(1) : mantissa).split('.');
|
||||
const digits = whole + fractional,
|
||||
point = whole.length + Number(exponent);
|
||||
const plain =
|
||||
point <= 0
|
||||
? `0.${'0'.repeat(-point)}${digits}`
|
||||
: point >= digits.length
|
||||
? digits + '0'.repeat(point - digits.length)
|
||||
: `${digits.slice(0, point)}.${digits.slice(point)}`;
|
||||
return parseFinancialDecimal(`${negative ? '-' : ''}${plain}`);
|
||||
}
|
||||
|
||||
/** Verify the actual payload in the worker, not an upstream supplied hash label. */
|
||||
export function prepareReplayLoad(datasetInput: unknown, configInput: ReplayConfig) {
|
||||
const dataset = validateDatasetV2(datasetInput),
|
||||
manifest = dataset.manifest;
|
||||
const config = replayConfigSchema.parse(configInput);
|
||||
const actual = config.matching.series.map(s => [s.instrumentId, s.seriesId]).sort();
|
||||
const expected = manifest.executionSeries.map(s => [s.instrumentId, s.seriesId]).sort();
|
||||
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
|
||||
throw new Error('Execution series must exactly match the verified dataset');
|
||||
}
|
||||
const identity: ReplayIdentity = {
|
||||
version: 1,
|
||||
sessionId: config.matching.risk.ledger.sessionId,
|
||||
datasetHash: manifest.hash,
|
||||
};
|
||||
return {
|
||||
identity,
|
||||
config,
|
||||
manifest,
|
||||
prepared: {
|
||||
dataset_id: manifest.hash,
|
||||
eligibility: { eligible: 'Eligible', exploratory: 'Exploratory', ineligible: 'Ineligible' }[
|
||||
manifest.eligibility
|
||||
],
|
||||
limitations: manifest.limitations,
|
||||
bounds: {
|
||||
warmup_start: manifest.bounds.warmupStart,
|
||||
trade_start: manifest.bounds.tradeStart,
|
||||
trade_end: manifest.bounds.tradeEnd,
|
||||
},
|
||||
series: manifest.series.map(series => {
|
||||
const calendar = manifest.calendars.find(c => c.id === series.calendarId);
|
||||
if (!calendar) {
|
||||
throw new Error('Missing retained calendar');
|
||||
}
|
||||
return {
|
||||
series_id: series.id,
|
||||
instrument_id: series.instrumentId,
|
||||
adjustment: series.adjustment === 'raw' ? 'Raw' : 'ProviderAdjusted',
|
||||
sessions: calendar.sessions
|
||||
.filter(
|
||||
session =>
|
||||
session.close > manifest.bounds.warmupStart &&
|
||||
session.open < manifest.bounds.tradeEnd
|
||||
)
|
||||
.map(session => ({
|
||||
sessionId: JSON.stringify([calendar.id, calendar.revision, session.date]),
|
||||
opensAt: session.open,
|
||||
closesAt: session.close,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
bars: dataset.bars.map(bar => ({
|
||||
series_id: bar.seriesId,
|
||||
instrument_id: bar.instrumentId,
|
||||
interval_start: bar.intervalStart,
|
||||
interval_end: bar.intervalEnd,
|
||||
event_time: bar.eventTime,
|
||||
available_at: bar.availableAt,
|
||||
source_sequence: bar.sourceSequence,
|
||||
open: marketDecimal(bar.open),
|
||||
high: marketDecimal(bar.high),
|
||||
low: marketDecimal(bar.low),
|
||||
close: marketDecimal(bar.close),
|
||||
volume: marketDecimal(bar.volume),
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function freeze<T>(value: T): T {
|
||||
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
||||
Object.values(value).forEach(freeze);
|
||||
Object.freeze(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
/** JSON transport is intentionally explicit and measured. No history/checkpoint API. */
|
||||
export class NativeReplaySession {
|
||||
readonly identity: ReplayIdentity;
|
||||
private readonly native: FinancialReplaySession;
|
||||
readonly transport = {
|
||||
advanceResponseBytes: 0,
|
||||
submitRequestBytes: 0,
|
||||
submitResponseBytes: 0,
|
||||
resultBytes: 0,
|
||||
};
|
||||
constructor(load: ReturnType<typeof prepareReplayLoad>) {
|
||||
this.identity = freeze({ ...load.identity });
|
||||
this.native = new FinancialReplaySession(JSON.stringify(load));
|
||||
}
|
||||
advance(eventBudget: number): ReplayStep {
|
||||
const raw = this.native.advance(JSON.stringify({ identity: this.identity, eventBudget }));
|
||||
this.transport.advanceResponseBytes += Buffer.byteLength(raw);
|
||||
const result = stepSchema.parse(JSON.parse(raw));
|
||||
sameIdentity(result.identity, this.identity);
|
||||
if (
|
||||
result.step.type === 'decisionBatch' &&
|
||||
(result.step.view.admissionRevision !== result.step.barrier.revision ||
|
||||
result.step.view.portfolio.sessionId !== this.identity.sessionId)
|
||||
) {
|
||||
throw new Error('Native barrier view mismatch');
|
||||
}
|
||||
return freeze(result);
|
||||
}
|
||||
submit(barrierId: string, decisions: FinancialStrategyDecision[]) {
|
||||
const request = JSON.stringify({
|
||||
identity: this.identity,
|
||||
barrierId,
|
||||
decisions: decisions.map(parseFinancialStrategyDecision),
|
||||
});
|
||||
this.transport.submitRequestBytes += Buffer.byteLength(request);
|
||||
const raw = this.native.submit(request);
|
||||
this.transport.submitResponseBytes += Buffer.byteLength(raw);
|
||||
const result = submissionSchema.parse(JSON.parse(raw));
|
||||
sameIdentity(result.identity, this.identity);
|
||||
return freeze(result.outcome);
|
||||
}
|
||||
finalize(): ReplayResult {
|
||||
const raw = this.native.finalize(JSON.stringify(this.identity));
|
||||
this.transport.resultBytes += Buffer.byteLength(raw);
|
||||
return parseReplayResult(raw, this.identity);
|
||||
}
|
||||
dispose(): void {
|
||||
this.native.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReplayMetrics {
|
||||
advanceCalls: number;
|
||||
submitCalls: number;
|
||||
contextBytes: number;
|
||||
submissionBytes: number;
|
||||
outcomeBytes: number;
|
||||
resultBytes: number;
|
||||
advanceMs: number;
|
||||
submitMs: number;
|
||||
decisionMs: number;
|
||||
finalizeMs: number;
|
||||
}
|
||||
/** Conformance driver only. No persisted strategy states/RNG, dynamic code, or
|
||||
* production strategy framework. Shared view is frozen before any fixture runs. */
|
||||
export function runReplayConformance(
|
||||
session: NativeReplaySession,
|
||||
decide: (
|
||||
ownerId: string,
|
||||
context: DecisionContext,
|
||||
observations: readonly PublishedObservation[]
|
||||
) => FinancialStrategyIntent,
|
||||
options: {
|
||||
eventBudget?: number;
|
||||
reverseCallbacks?: boolean;
|
||||
onProgress?: (step: ReplayStep) => void;
|
||||
} = {}
|
||||
) {
|
||||
const metrics: ReplayMetrics = {
|
||||
advanceCalls: 0,
|
||||
submitCalls: 0,
|
||||
contextBytes: 0,
|
||||
submissionBytes: 0,
|
||||
outcomeBytes: 0,
|
||||
resultBytes: 0,
|
||||
advanceMs: 0,
|
||||
submitMs: 0,
|
||||
decisionMs: 0,
|
||||
finalizeMs: 0,
|
||||
};
|
||||
let observations: PublishedObservation[] = [];
|
||||
let sequence = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const start = performance.now(),
|
||||
step = session.advance(options.eventBudget ?? 256);
|
||||
metrics.advanceMs += performance.now() - start;
|
||||
metrics.advanceCalls++;
|
||||
for (const observation of step.observations) {
|
||||
observations.push(observation);
|
||||
}
|
||||
options.onProgress?.(step);
|
||||
switch (step.step.type) {
|
||||
case 'progress':
|
||||
break;
|
||||
case 'failed':
|
||||
throw new Error(step.step.diagnostic);
|
||||
case 'complete': {
|
||||
const start = performance.now(),
|
||||
result = session.finalize();
|
||||
metrics.finalizeMs = performance.now() - start;
|
||||
metrics.contextBytes = session.transport.advanceResponseBytes;
|
||||
metrics.submissionBytes = session.transport.submitRequestBytes;
|
||||
metrics.outcomeBytes = session.transport.submitResponseBytes;
|
||||
metrics.resultBytes = session.transport.resultBytes;
|
||||
return { result, metrics };
|
||||
}
|
||||
case 'decisionBatch': {
|
||||
const context = step.step,
|
||||
start = performance.now();
|
||||
const owners = [...context.barrier.owner_ids];
|
||||
if (options.reverseCallbacks) {
|
||||
owners.reverse();
|
||||
}
|
||||
const publishedDelta = Object.freeze(observations);
|
||||
observations = [];
|
||||
// Stage all decisions before one admission. A thrown fixture disposes
|
||||
// the attempt; it cannot publish a partial barrier or successful run.
|
||||
const decisions = owners.map(ownerId =>
|
||||
parseFinancialStrategyDecision({
|
||||
version: 1,
|
||||
sessionId: session.identity.sessionId,
|
||||
barrierId: context.barrier.barrier_id,
|
||||
revision: context.barrier.revision,
|
||||
decision: {
|
||||
ownerId,
|
||||
decisionId: JSON.stringify(['trace', sequence, ownerId]),
|
||||
sequence,
|
||||
},
|
||||
intent: decide(ownerId, context, publishedDelta),
|
||||
})
|
||||
);
|
||||
metrics.decisionMs += performance.now() - start;
|
||||
sequence++;
|
||||
const submitStart = performance.now(),
|
||||
outcome = session.submit(context.barrier.barrier_id, decisions);
|
||||
metrics.submitMs += performance.now() - submitStart;
|
||||
metrics.submitCalls++;
|
||||
if (typeof outcome.status === 'object') {
|
||||
throw new Error(outcome.status.Failed.diagnostic);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
session.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/** Bounded fixed intent trace for conformance/debug, not a declarative strategy DSL. */
|
||||
export function executeReplayTrace(
|
||||
input: ReplayTraceRequest,
|
||||
onProgress: (step: ReplayStep) => void = () => {}
|
||||
) {
|
||||
const request = replayTraceSchema.parse(input),
|
||||
load = prepareReplayLoad(request.dataset, request.config);
|
||||
const trace = new Map<string, FinancialStrategyIntent>();
|
||||
for (const entry of request.trace) {
|
||||
const key = JSON.stringify([entry.at, entry.ownerId]);
|
||||
if (trace.has(key)) {
|
||||
throw new Error('Duplicate trace decision');
|
||||
}
|
||||
trace.set(key, entry.intent);
|
||||
}
|
||||
return runReplayConformance(
|
||||
new NativeReplaySession(load),
|
||||
(ownerId, context) => {
|
||||
const key = JSON.stringify([context.barrier.at, ownerId]),
|
||||
intent = trace.get(key);
|
||||
if (!intent) {
|
||||
throw new Error('Missing trace decision for due owner');
|
||||
}
|
||||
trace.delete(key);
|
||||
return intent;
|
||||
},
|
||||
{
|
||||
eventBudget: request.eventBudget,
|
||||
onProgress: step => {
|
||||
if (step.step.type === 'complete' && trace.size) {
|
||||
throw new Error('Unused trace decisions');
|
||||
}
|
||||
onProgress(step);
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import { z } from 'zod';
|
||||
import { replayTraceSchema } from '../contracts/native-replay';
|
||||
import { BacktestConfigSchema } from '../types';
|
||||
|
||||
const finite = z.number().finite();
|
||||
export const nativeWorkerRequestSchema = z.object({
|
||||
const legacyRequestSchema = z.object({
|
||||
type: z.literal('run'),
|
||||
config: BacktestConfigSchema,
|
||||
data: z.array(
|
||||
|
|
@ -20,6 +21,8 @@ export const nativeWorkerRequestSchema = z.object({
|
|||
),
|
||||
});
|
||||
|
||||
export const nativeWorkerRequestSchema = z.union([legacyRequestSchema, replayTraceSchema]);
|
||||
|
||||
export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('progress'), progress: finite.min(0).max(100), message: z.string() }),
|
||||
z.object({ type: z.literal('result'), result: z.string() }),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { BacktestEngine } from '@stock-bot/engine';
|
||||
import { executeReplayTrace } from './native-replay';
|
||||
import { resolveNativeStrategies } from './native-strategies';
|
||||
import { nativeWorkerRequestSchema, type NativeWorkerMessage } from './native-worker-protocol';
|
||||
|
||||
|
|
@ -15,7 +16,16 @@ function send(message: NativeWorkerMessage): Promise<void> {
|
|||
|
||||
process.once('message', async (input: unknown) => {
|
||||
try {
|
||||
const { config, data } = nativeWorkerRequestSchema.parse(input);
|
||||
const request = nativeWorkerRequestSchema.parse(input);
|
||||
if (request.type === 'runReplayTrace') {
|
||||
await send({ type: 'progress', progress: 0, message: 'Canonical replay trace started' });
|
||||
// One load and a local pull loop; no per-observation IPC. The supervisor
|
||||
// can still SIGKILL native work, exactly as for the legacy one-shot path.
|
||||
const { result } = executeReplayTrace(request);
|
||||
await send({ type: 'result', result: JSON.stringify(result) });
|
||||
return;
|
||||
}
|
||||
const { config, data } = request;
|
||||
const engine = new BacktestEngine({
|
||||
name: config.name ?? 'Backtest',
|
||||
strategy: config.strategy,
|
||||
|
|
@ -27,7 +37,9 @@ process.once('message', async (input: unknown) => {
|
|||
slippage: config.slippage ?? 0.0001,
|
||||
dataFrequency: config.dataFrequency,
|
||||
});
|
||||
if (config.riskLimits) {engine.updateRiskLimits(config.riskLimits);}
|
||||
if (config.riskLimits) {
|
||||
engine.updateRiskLimits(config.riskLimits);
|
||||
}
|
||||
for (const { strategy, name, id, parameters } of resolveNativeStrategies(config)) {
|
||||
engine.addNativeStrategy(strategy, name, id, parameters);
|
||||
}
|
||||
|
|
|
|||
244
apps/stock/orchestrator/src/contracts/native-replay.ts
Normal file
244
apps/stock/orchestrator/src/contracts/native-replay.ts
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
/** Schema-only native session protocol. No runtime, storage or native imports. */
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
parseFinancialDecimal,
|
||||
parseFinancialSnapshot,
|
||||
parseFinancialStrategyDecision,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
const id = z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(value =>
|
||||
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
|
||||
);
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
|
||||
const decimal = z.string().transform(value => parseFinancialDecimal(value));
|
||||
const riskSession = z
|
||||
.object({ calendarId: id, calendarRevision: id, sessionId: id, startsAt: time })
|
||||
.strict();
|
||||
export const replayIdentitySchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
sessionId: id,
|
||||
datasetHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
})
|
||||
.strict();
|
||||
export const replayConfigSchema = z
|
||||
.object({
|
||||
matching: z
|
||||
.object({
|
||||
risk: z
|
||||
.object({
|
||||
ledger: z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
sessionId: id,
|
||||
accountId: id,
|
||||
baseCurrency: id,
|
||||
reserveOwnerId: id,
|
||||
ownerIds: z.array(id),
|
||||
initialCapital: decimal,
|
||||
riskSession,
|
||||
})
|
||||
.strict(),
|
||||
feeRate: decimal,
|
||||
maxOrderQuantity: decimal,
|
||||
maxPositionQuantity: decimal,
|
||||
maxSymbolExposure: decimal,
|
||||
maxGrossExposure: decimal,
|
||||
maxDailyLoss: decimal,
|
||||
maxDrawdownAmount: decimal,
|
||||
maxMarkAgeMs: counter,
|
||||
})
|
||||
.strict(),
|
||||
owners: z.array(z.object({ ownerId: id, mode: z.enum(['Target', 'Orders']) }).strict()),
|
||||
series: z.array(
|
||||
z.object({ instrumentId: id, seriesId: id, mode: z.literal('Open') }).strict()
|
||||
),
|
||||
halfSpreadRate: decimal,
|
||||
slippageRate: decimal,
|
||||
latencyMs: counter,
|
||||
})
|
||||
.strict(),
|
||||
participation_rate: decimal,
|
||||
cadence: z.array(z.object({ owner_id: id, series_ids: z.array(id) }).strict()),
|
||||
allow_exploratory: z.boolean(),
|
||||
risk_boundaries: z.array(riskSession),
|
||||
})
|
||||
.strict();
|
||||
export type ReplayConfig = z.input<typeof replayConfigSchema>;
|
||||
export type ReplayIdentity = z.infer<typeof replayIdentitySchema>;
|
||||
|
||||
const observationSchema = z
|
||||
.object({
|
||||
series_id: id,
|
||||
instrument_id: id,
|
||||
interval_start: time,
|
||||
interval_end: time,
|
||||
event_time: time,
|
||||
available_at: time,
|
||||
source_sequence: counter,
|
||||
open: decimal,
|
||||
high: decimal,
|
||||
low: decimal,
|
||||
close: decimal,
|
||||
volume: decimal,
|
||||
})
|
||||
.strict();
|
||||
const barrierSchema = z
|
||||
.object({
|
||||
barrier_id: id,
|
||||
at: time,
|
||||
revision: counter,
|
||||
owner_ids: z.array(id),
|
||||
observation_count: counter,
|
||||
inputs: z.array(
|
||||
z
|
||||
.object({
|
||||
series_id: id,
|
||||
availability: z.union([
|
||||
z.literal('Missing'),
|
||||
z
|
||||
.object({ Fresh: z.object({ event_time: time, available_at: time }).strict() })
|
||||
.strict(),
|
||||
z
|
||||
.object({ Stale: z.object({ event_time: time, available_at: time }).strict() })
|
||||
.strict(),
|
||||
]),
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
const viewSchema = z
|
||||
.object({
|
||||
admissionRevision: counter,
|
||||
portfolio: z.unknown().transform(value => parseFinancialSnapshot(value)),
|
||||
equity: decimal,
|
||||
availableCash: decimal,
|
||||
// These are read-only native diagnostic projections, not a second admission API.
|
||||
orders: z.array(z.record(z.unknown())),
|
||||
reservations: z.array(z.record(z.unknown())),
|
||||
risk: z
|
||||
.object({
|
||||
dailyBaseline: decimal,
|
||||
peakEquity: decimal,
|
||||
dailyHalted: z.boolean(),
|
||||
drawdownHalted: z.boolean(),
|
||||
riskSession,
|
||||
lastEventTime: time,
|
||||
})
|
||||
.strict(),
|
||||
})
|
||||
.strict();
|
||||
export const stepSchema = z
|
||||
.object({
|
||||
identity: replayIdentitySchema,
|
||||
observations: z.array(observationSchema),
|
||||
step: z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('progress'), processed: counter }).strict(),
|
||||
z
|
||||
.object({ type: z.literal('decisionBatch'), barrier: barrierSchema, view: viewSchema })
|
||||
.strict(),
|
||||
z.object({ type: z.literal('complete') }).strict(),
|
||||
z.object({ type: z.literal('failed'), diagnostic: z.string() }).strict(),
|
||||
]),
|
||||
})
|
||||
.strict();
|
||||
const outcomeSchema = z
|
||||
.object({
|
||||
replayed: z.boolean(),
|
||||
revision: counter,
|
||||
status: z.union([
|
||||
z.literal('Running'),
|
||||
z.literal('Complete'),
|
||||
z.object({ Failed: z.object({ diagnostic: z.string() }).strict() }).strict(),
|
||||
]),
|
||||
effects: z.array(z.record(z.unknown())),
|
||||
})
|
||||
.strict();
|
||||
export const submissionSchema = z
|
||||
.object({ identity: replayIdentitySchema, outcome: outcomeSchema })
|
||||
.strict();
|
||||
const resultSchema = z
|
||||
.object({
|
||||
identity: replayIdentitySchema,
|
||||
status: z.literal('complete'),
|
||||
manifest: z.record(z.unknown()),
|
||||
policy: replayConfigSchema,
|
||||
view: viewSchema,
|
||||
receipts: z.array(z.object({ input: z.unknown(), outcome: outcomeSchema }).strict()),
|
||||
limitations: z.array(z.string()),
|
||||
modelLimitations: z.array(z.string()),
|
||||
})
|
||||
.strict();
|
||||
export type ReplayStep = z.infer<typeof stepSchema>;
|
||||
export type ReplayResult = z.infer<typeof resultSchema>;
|
||||
export type DecisionContext = Extract<ReplayStep['step'], { type: 'decisionBatch' }>;
|
||||
export type PublishedObservation = z.infer<typeof observationSchema>;
|
||||
|
||||
export function sameIdentity(actual: ReplayIdentity, expected: ReplayIdentity): void {
|
||||
if (
|
||||
actual.version !== expected.version ||
|
||||
actual.sessionId !== expected.sessionId ||
|
||||
actual.datasetHash !== expected.datasetHash
|
||||
) {
|
||||
throw new Error('Native replay identity mismatch');
|
||||
}
|
||||
}
|
||||
export function parseReplayResult(
|
||||
input: string,
|
||||
identity: ReplayIdentity,
|
||||
expectedPolicy?: ReplayConfig
|
||||
): ReplayResult {
|
||||
const result = resultSchema.parse(JSON.parse(input));
|
||||
sameIdentity(result.identity, identity);
|
||||
const ledger = result.policy.matching.risk.ledger,
|
||||
portfolio = result.view.portfolio;
|
||||
if (
|
||||
result.manifest.version !== 2 ||
|
||||
result.manifest.hash !== identity.datasetHash ||
|
||||
ledger.sessionId !== identity.sessionId ||
|
||||
portfolio.sessionId !== identity.sessionId ||
|
||||
portfolio.accountId !== ledger.accountId ||
|
||||
portfolio.baseCurrency !== ledger.baseCurrency ||
|
||||
portfolio.reserveOwnerId !== ledger.reserveOwnerId ||
|
||||
(expectedPolicy &&
|
||||
JSON.stringify(result.policy) !== JSON.stringify(replayConfigSchema.parse(expectedPolicy)))
|
||||
) {
|
||||
throw new Error('Native replay result identity mismatch');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export const replayTraceSchema = z
|
||||
.object({
|
||||
type: z.literal('runReplayTrace'),
|
||||
version: z.literal(1),
|
||||
dataset: z.unknown(),
|
||||
config: replayConfigSchema,
|
||||
eventBudget: counter.positive(),
|
||||
trace: z.array(
|
||||
z
|
||||
.object({
|
||||
at: time,
|
||||
ownerId: id,
|
||||
intent: z.unknown().transform(
|
||||
intent =>
|
||||
parseFinancialStrategyDecision({
|
||||
version: 1,
|
||||
sessionId: 'trace',
|
||||
barrierId: 'trace',
|
||||
revision: 0,
|
||||
decision: { ownerId: 'trace', decisionId: 'trace', sequence: 0 },
|
||||
intent,
|
||||
}).intent
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
export type ReplayTraceRequest = z.input<typeof replayTraceSchema>;
|
||||
Loading…
Add table
Add a link
Reference in a new issue