feat(research): run stateful TypeScript strategies on canonical replay

This commit is contained in:
Boki 2026-10-23 13:08:24 -04:00
parent 0870b55830
commit 2bcadbd117
14 changed files with 1864 additions and 33 deletions

View file

@ -25,6 +25,7 @@ import {
type ReplayResult,
type ReplayResultFormat,
type ReplayStep,
type ReplaySubmissionOutcome,
type ReplayTraceRequest,
} from '../contracts/native-replay';
import { validateDatasetV2 } from '../data/historical-dataset-v2';
@ -246,12 +247,21 @@ type Decide = (
context: DecisionContext,
observations: readonly PublishedObservation[]
) => FinancialStrategyIntent;
interface ReplayOptions {
export interface ReplayOptions {
eventBudget?: number;
reverseCallbacks?: boolean;
onProgress?: (step: ReplayStep) => void;
resultFormat?: ReplayResultFormat;
}
/** Internal trusted-host seam. All due decisions are staged before one native
* submission. A controller never receives the native handle. */
export interface ReplayController {
stage(
context: DecisionContext,
observations: readonly PublishedObservation[]
): FinancialStrategyDecision[];
committed?(outcome: ReplaySubmissionOutcome): void;
}
/* eslint-disable no-redeclare -- TypeScript overloads preserve the existing trace result type. */
export function runReplayConformance(
session: NativeReplaySession,
@ -281,6 +291,44 @@ export function runReplayConformance(
options: ReplayOptions = {}
) {
/* eslint-enable no-redeclare */
let sequence = 0;
return runReplaySession(
session,
{
stage(context, observations) {
const owners = [...context.barrier.owner_ids];
if (options.reverseCallbacks) {
owners.reverse();
}
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, observations),
})
);
sequence++;
return decisions;
},
},
options
);
}
/** One pull loop for conformance and stateful programs. Always disposes the
* attempt, including ambiguous submissions or failures in host callbacks. */
export function runReplaySession(
session: NativeReplaySession,
controller: ReplayController,
options: ReplayOptions = {}
) {
const metrics: ReplayMetrics = {
advanceCalls: 0,
submitCalls: 0,
@ -298,7 +346,6 @@ export function runReplayConformance(
disposeMs: 0,
};
let observations: PublishedObservation[] = [];
let sequence = 0;
try {
for (;;) {
const start = performance.now(),
@ -335,30 +382,12 @@ export function runReplayConformance(
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),
})
);
const decisions = controller.stage(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;
@ -366,6 +395,11 @@ export function runReplayConformance(
if (typeof outcome.status === 'object') {
throw new Error(outcome.status.Failed.diagnostic);
}
if (controller.committed) {
const commitStart = performance.now();
controller.committed(outcome);
metrics.decisionMs += performance.now() - commitStart;
}
break;
}
}

View file

@ -0,0 +1,415 @@
/** Trusted synchronous programs on the canonical financial engine. Fresh
* attempts recompute from original inputs; diagnostics are not resume tokens. */
import { types } from 'node:util';
import { z } from 'zod';
import { parseFinancialStrategyDecision, type FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyAdmissionFeedback,
StrategyDiagnostic,
StrategyDiagnosticSnapshot,
StrategyProgram,
} from '../contracts/canonical-strategy';
import {
nativeAdmissionOrders,
replayConfigSchema,
replayIdentitySchema,
type DecisionContext,
type PublishedObservation,
type ReplayIdentity,
type ReplayOutput,
type ReplayProjectionResult,
type ReplayReportResult,
type ReplayResult,
type ReplaySubmissionOutcome,
} from '../contracts/native-replay';
import {
NativeReplaySession,
runReplaySession,
type prepareReplayLoad,
type ReplayController,
type ReplayMetrics,
type ReplayOptions,
} from './native-replay';
export type { StrategyProgram } from '../contracts/canonical-strategy';
export type StrategyReplayOptions = Omit<ReplayOptions, 'reverseCallbacks'>;
type StrategyRun<Result extends ReplayOutput> = {
result: Result;
/** decisionMs includes state staging, validation and admission feedback. */
metrics: ReplayMetrics;
diagnostics: DeepReadonly<StrategyDiagnosticSnapshot>;
};
export class StrategyReplayError extends Error {
constructor(
cause: unknown,
readonly diagnostics: DeepReadonly<StrategyDiagnosticSnapshot>
) {
super(cause instanceof Error ? cause.message : String(cause), { cause });
this.name = 'StrategyReplayError';
}
}
function freeze<T>(value: T): DeepReadonly<T> {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
for (const child of Object.values(value)) {
freeze(child);
}
Object.freeze(value);
}
return value as DeepReadonly<T>;
}
/** Check descriptors before reading values: JSON.stringify would silently lose
* symbols/custom array keys, invoke accessors, or rewrite non-JSON objects. */
function stateCopy(input: unknown, ancestors = new Set<object>()): unknown {
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
return input;
}
if (typeof input === 'number' && Number.isFinite(input)) {
if (Object.is(input, -0)) {
throw new Error('Strategy state cannot contain negative zero');
}
return input;
}
const invalid = () => new Error('Strategy state requires finite plain JSON data properties');
if (!input || typeof input !== 'object' || ancestors.has(input)) {
throw invalid();
}
const array = Array.isArray(input);
if (Object.getPrototypeOf(input) !== (array ? Array.prototype : Object.prototype)) {
throw invalid();
}
const descriptors = Object.getOwnPropertyDescriptors(input);
const keys = Reflect.ownKeys(input);
if (keys.some(key => typeof key !== 'string')) {
throw invalid();
}
ancestors.add(input);
try {
const data = (key: string): unknown => {
const descriptor = descriptors[key];
if (!descriptor?.enumerable || !('value' in descriptor)) {
throw invalid();
}
return stateCopy(descriptor.value, ancestors);
};
if (array) {
if (keys.length !== input.length + 1) {
throw invalid();
}
return Array.from({ length: input.length }, (_, index) => data(String(index)));
}
// fromEntries preserves an own '__proto__' key without changing prototype.
return Object.fromEntries((keys as string[]).sort().map(key => [key, data(key)]));
} finally {
ancestors.delete(input);
}
}
const id = z
.string()
.min(1)
.refine(value =>
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
);
const metadataSchema = z
.object({
ownerId: id,
strategyId: id,
strategyVersion: id,
mode: z.enum(['target', 'orders']),
seed: z.number().int().min(0).max(0xffff_ffff),
})
.strict();
type Metadata = z.infer<typeof metadataSchema>;
interface Slot {
program: Metadata & { decide: StrategyProgram['decide'] };
diagnostic: DeepReadonly<StrategyDiagnostic>;
pendingObservations: PublishedObservation[];
}
function increment(value: number, amount = 1): number {
const next = value + amount;
if (!Number.isSafeInteger(next) || next < 0) {
throw new Error('Strategy counter exhausted');
}
return next;
}
class StrategyController implements ReplayController {
private slots: Map<string, Slot>;
private committedBarriers = 0;
private lastBarrierId: string | null = null;
private observed = 0;
private staged: {
barrierId: string;
expectedRevision: number;
owners: {
ownerId: string;
diagnostic: StrategyDiagnostic;
decision: FinancialStrategyDecision;
}[];
} | null = null;
constructor(
private readonly identity: ReplayIdentity,
programs: readonly StrategyProgram[],
config: ReturnType<typeof replayConfigSchema.parse>
) {
this.slots = new Map(
programs.map(program => {
const { ownerId, strategyId, strategyVersion, mode, seed } = program;
const metadata = metadataSchema.parse({ ownerId, strategyId, strategyVersion, mode, seed });
const decide = program.decide;
if (typeof decide !== 'function') {
throw new Error('Strategy decide must be synchronous callable code');
}
const diagnostic = freeze({
ownerId,
strategyId,
strategyVersion,
nextDecisionSequence: 0,
state: stateCopy(program.initialState),
rng: { algorithm: 'lcg32-v1' as const, seed, state: seed, draws: 0 },
observationCount: 0,
previousAdmission: null,
});
return [ownerId, { program: { ...metadata, decide }, diagnostic, pendingObservations: [] }];
})
);
const owners = config.matching.owners;
if (
this.slots.size !== programs.length ||
this.slots.size !== owners.length ||
owners.some(owner => this.slots.get(owner.ownerId)?.program.mode !== owner.mode.toLowerCase())
) {
throw new Error('Programs must exactly match configured owners and modes');
}
}
snapshot(): DeepReadonly<StrategyDiagnosticSnapshot> {
return freeze({
version: 1,
identity: this.identity,
committedBarriers: this.committedBarriers,
lastBarrierId: this.lastBarrierId,
strategies: [...this.slots.values()]
.sort((a, b) =>
a.program.ownerId < b.program.ownerId ? -1 : a.program.ownerId > b.program.ownerId ? 1 : 0
)
.map(slot => slot.diagnostic),
});
}
stage(context: DecisionContext, observations: readonly PublishedObservation[]) {
if (this.staged) {
throw new Error('Previous strategy barrier has not committed');
}
this.observed = increment(this.observed, observations.length);
const due = new Set(context.barrier.owner_ids);
if (
this.observed !== context.barrier.observation_count ||
due.size !== context.barrier.owner_ids.length ||
[...due].some(owner => !this.slots.has(owner)) ||
observations.some(observation => observation.available_at > context.barrier.at)
) {
throw new Error('Strategy barrier observation or owner mismatch');
}
const staged: NonNullable<StrategyController['staged']> = {
barrierId: context.barrier.barrier_id,
expectedRevision: increment(context.barrier.revision),
owners: [],
};
for (const slot of this.slots.values()) {
// Other owners may have slower cadence. Do not discard their warmup/prefix.
for (const observation of observations) {
slot.pendingObservations.push(observation);
}
if (!due.has(slot.program.ownerId)) {
continue;
}
const { program, diagnostic } = slot;
let active = true,
rngState = diagnostic.rng.state,
draws = diagnostic.rng.draws;
const random = () => {
if (!active) {
throw new Error('Strategy random is only valid during its decision');
}
draws = increment(draws);
rngState = (Math.imul(rngState, 1664525) + 1013904223) >>> 0;
return rngState / 4294967296;
};
let output: ReturnType<StrategyProgram['decide']>;
try {
const decide = program.decide;
output = decide(
Object.freeze({
ownerId: program.ownerId,
strategyId: program.strategyId,
strategyVersion: program.strategyVersion,
decisionSequence: diagnostic.nextDecisionSequence,
now: context.barrier.at,
barrier: context.barrier,
portfolio: context.view,
positions: Object.freeze(
context.view.portfolio.positions.filter(
position => position.ownerId === program.ownerId
)
),
observations: Object.freeze([...slot.pendingObservations]),
previousAdmission: diagnostic.previousAdmission,
state: diagnostic.state,
random,
})
);
} finally {
active = false;
}
if (types.isPromise(output)) {
// Reject async strategies synchronously, but observe their actual
// Promise rejection so failed attempts cannot leak unhandled errors.
// Do not await it or call arbitrary thenable methods.
Promise.prototype.then.call(output, undefined, () => {});
throw new Error('Strategy decide must synchronously return nextState and intent');
}
if (!output || typeof output !== 'object' || 'then' in output) {
throw new Error('Strategy decide must synchronously return nextState and intent');
}
const state = freeze(stateCopy(output.nextState));
const decision = parseFinancialStrategyDecision({
version: 1,
sessionId: this.identity.sessionId,
barrierId: context.barrier.barrier_id,
revision: context.barrier.revision,
decision: {
ownerId: program.ownerId,
decisionId: JSON.stringify([
'strategy',
program.ownerId,
program.strategyId,
program.strategyVersion,
diagnostic.nextDecisionSequence,
]),
sequence: diagnostic.nextDecisionSequence,
},
intent: output.intent,
});
if (decision.intent.mode !== program.mode) {
throw new Error('Strategy intent mode differs from its configured mode');
}
staged.owners.push({
ownerId: program.ownerId,
decision,
diagnostic: {
ownerId: program.ownerId,
strategyId: program.strategyId,
strategyVersion: program.strategyVersion,
state,
nextDecisionSequence: increment(diagnostic.nextDecisionSequence),
rng: { algorithm: 'lcg32-v1', seed: program.seed, state: rngState, draws },
observationCount: increment(diagnostic.observationCount, slot.pendingObservations.length),
previousAdmission: null,
},
});
}
this.staged = staged;
return staged.owners.map(owner => owner.decision);
}
committed(outcome: ReplaySubmissionOutcome): void {
const staged = this.staged;
if (
!staged ||
outcome.replayed ||
outcome.status !== 'Running' ||
outcome.revision !== staged.expectedRevision
) {
throw new Error('Unexpected strategy admission acknowledgement');
}
const orders = nativeAdmissionOrders(outcome.effects);
if (
orders.some(
order => !staged.owners.some(owner => owner.ownerId === order.order.decision.ownerId)
)
) {
throw new Error('Admission feedback belongs to an owner outside the barrier');
}
const nextCount = increment(this.committedBarriers);
const next = new Map(this.slots);
// Parse/detach ALL feedback before swapping any committed slot. Even an
// ambiguous/malformed acknowledgement leaves diagnostics at the old barrier.
for (const owner of staged.owners) {
const slot = this.slots.get(owner.ownerId);
if (!slot) {
throw new Error('Staged strategy owner is missing');
}
const previousAdmission: StrategyAdmissionFeedback = {
decision: owner.decision.decision,
revision: outcome.revision,
orders: orders
.filter(order => order.order.decision.ownerId === owner.ownerId)
.map(order => ({
orderId: order.order.orderId,
instrumentId: order.order.instrumentId,
decision: order.order.decision,
status: order.status,
})),
};
next.set(owner.ownerId, {
program: slot.program,
diagnostic: freeze({ ...owner.diagnostic, previousAdmission }),
pendingObservations: [],
});
}
this.slots = next;
this.committedBarriers = nextCount;
this.lastBarrierId = staged.barrierId;
this.staged = null;
}
}
/* eslint-disable no-redeclare -- Keep selected native result formats precise. */
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],
options: StrategyReplayOptions & { resultFormat: 'report' }
): StrategyRun<ReplayReportResult>;
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],
options: StrategyReplayOptions & { resultFormat: 'projection' }
): StrategyRun<ReplayProjectionResult>;
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],
options?: StrategyReplayOptions & { resultFormat?: 'trace' }
): StrategyRun<ReplayResult>;
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],
options: StrategyReplayOptions
): StrategyRun<ReplayOutput>;
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],
options: StrategyReplayOptions = {}
): StrategyRun<ReplayOutput> {
/* eslint-enable no-redeclare */
const identity = freeze(replayIdentitySchema.parse(load.identity));
const config = replayConfigSchema.parse(load.config);
const controller = new StrategyController(identity, programs, config);
try {
// Native construction synchronously detaches prepared data/config into Rust.
// Caller mutations during later callbacks cannot rewrite that loaded input.
const output = runReplaySession(
new NativeReplaySession({ ...load, identity, config }),
controller,
{ ...options }
);
return { ...output, diagnostics: controller.snapshot() };
} catch (cause) {
throw new StrategyReplayError(cause, controller.snapshot());
}
}

View file

@ -0,0 +1,78 @@
/** Trusted synchronous strategy author contract. No execution or native capabilities. */
import type { DecisionIdentity, FinancialStrategyIntent } from '@stock-bot/types';
import type {
DecisionContext,
NativeOrderStatus,
PublishedObservation,
ReplayIdentity,
} from './native-replay';
export type DeepReadonly<T> = T extends string | number | boolean | null | undefined
? T
: T extends object
? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }
: T;
/** Copied native admission outcomes, not a later fill-event stream. */
export interface StrategyAdmissionFeedback {
decision: DecisionIdentity;
revision: number;
orders: {
orderId: string;
instrumentId: string;
decision: DecisionIdentity;
status: NativeOrderStatus;
}[];
}
export interface StrategyContext<State = unknown> {
readonly ownerId: string;
readonly strategyId: string;
readonly strategyVersion: string;
readonly decisionSequence: number;
readonly now: number;
readonly barrier: DeepReadonly<DecisionContext['barrier']>;
/** The exact same read-only account view is shared by all due callbacks. */
readonly portfolio: DeepReadonly<DecisionContext['view']>;
readonly positions: DeepReadonly<DecisionContext['view']['portfolio']['positions']>;
readonly observations: readonly DeepReadonly<PublishedObservation>[];
readonly previousAdmission: DeepReadonly<StrategyAdmissionFeedback> | null;
readonly state: DeepReadonly<State>;
/** Valid only during this synchronous callback; never use Math.random for decisions. */
readonly random: () => number;
}
export interface StrategyProgram<State = unknown> {
readonly ownerId: string;
readonly strategyId: string;
readonly strategyVersion: string;
readonly mode: 'target' | 'orders';
readonly seed: number;
/** Finite plain JSON, checked and detached before the native attempt starts. */
readonly initialState: State;
decide(context: StrategyContext<State>): {
nextState: State;
intent: FinancialStrategyIntent;
};
}
export interface StrategyDiagnostic {
ownerId: string;
strategyId: string;
strategyVersion: string;
nextDecisionSequence: number;
state: unknown;
rng: { algorithm: 'lcg32-v1'; seed: number; state: number; draws: number };
observationCount: number;
previousAdmission: StrategyAdmissionFeedback | null;
}
/** Last confirmed strategy transitions only. This cannot restore financial state.
* Retry always starts a fresh native session and recomputes from original inputs. */
export interface StrategyDiagnosticSnapshot {
version: 1;
identity: ReplayIdentity;
committedBarriers: number;
lastBarrierId: string | null;
strategies: StrategyDiagnostic[];
}

View file

@ -162,6 +162,7 @@ const outcomeSchema = z
export const submissionSchema = z
.object({ identity: replayIdentitySchema, outcome: outcomeSchema })
.strict();
export type ReplaySubmissionOutcome = z.infer<typeof outcomeSchema>;
const resultSchema = z
.object({
identity: replayIdentitySchema,
@ -178,6 +179,70 @@ export type ReplayStep = z.infer<typeof stepSchema>;
export type ReplayResult = z.infer<typeof resultSchema>;
const nonnegative = decimal.refine(value => !value.startsWith('-'));
const positive = nonnegative.refine(value => value !== '0.00000000');
const nativeOrderStatusSchema = z.union([
z.enum(['Open', 'Filled', 'Cancelled', 'Expired']),
z
.object({
Rejected: z.enum([
'OrderSize',
'PositionSize',
'SymbolExposure',
'GrossExposure',
'InsufficientCash',
'InsufficientInventory',
'MissingMark',
'StaleMark',
'DailyLoss',
'Drawdown',
'InactiveOrder',
]),
})
.strict(),
]);
export type NativeOrderStatus = z.infer<typeof nativeOrderStatusSchema>;
const managedOrderSchema = z
.object({
order: z
.object({
orderId: id,
decision: z.object({ ownerId: id, decisionId: id, sequence: counter }).strict(),
instrumentId: id,
side: z.enum(['buy', 'sell']),
quantity: positive,
limitPrice: positive.nullable(),
origin: z.enum(['Explicit', 'Target']),
})
.strict(),
timeInForce: z.enum(['DAY', 'GTC', 'IOC', 'FOK']),
submittedAt: z
.object({
at: time,
phase: z.enum(['Observation', 'Decision', 'Execution', 'SessionClose']),
instrumentId: id,
sourceSequence: counter,
})
.strict(),
readyAt: time,
venueSession: id.nullable(),
remaining: nonnegative,
filled: nonnegative,
status: nativeOrderStatusSchema,
admissionSequence: counter,
})
.strict();
const admissionEffectSchema = z.union([
z.object({ Order: managedOrderSchema }).strict(),
z.object({ Risk: z.record(z.unknown()) }).strict(),
z.object({ Operator: z.record(z.unknown()) }).strict(),
]);
/** Decode only the existing native facts needed for strategy admission feedback.
* Other nested risk/ledger diagnostics are never interpreted as TS accounting. */
export function nativeAdmissionOrders(effects: ReplaySubmissionOutcome['effects']) {
return effects.flatMap(effect => {
const parsed = admissionEffectSchema.parse(effect);
return 'Order' in parsed ? [parsed.Order] : [];
});
}
const ownerValuationSchema = z
.object({
ownerId: id,