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

@ -0,0 +1,623 @@
import { expect, test } from 'bun:test';
import { parseFinancialDecimal, type FinancialStrategyDecision } from '@stock-bot/types';
import {
NativeReplaySession,
prepareReplayLoad,
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
import {
runStrategyReplay,
StrategyReplayError,
} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import type {
DeepReadonly,
StrategyContext,
StrategyDiagnosticSnapshot,
StrategyProgram,
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
import { nativeReplayFixture } from '../fixtures/native-replay';
const hold = () => ({ mode: 'target' as const, targets: [] });
const target = (quantity = '1') => ({
mode: 'target' as const,
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal(quantity) }],
});
type CountState = { count: number; samples: number[] };
const initial = (): CountState => ({ count: 0, samples: [] });
function fixture(owners = ['A'], bars = 6, assets = 1) {
const value = nativeReplayFixture(bars, assets, owners);
return { ...value, load: prepareReplayLoad(value.dataset, value.config) };
}
function program(
ownerId = 'A',
decide: StrategyProgram<CountState>['decide'] = context => ({
nextState: {
count: context.state.count + 1,
samples: [...context.state.samples, context.random()],
},
intent: target(),
}),
seed = 0
): StrategyProgram<CountState> {
return {
ownerId,
strategyId: 'test-counter',
strategyVersion: '1',
mode: 'target',
seed,
initialState: initial(),
decide,
};
}
function owner(snapshot: DeepReadonly<StrategyDiagnosticSnapshot>, ownerId = 'A') {
const value = snapshot.strategies.find(strategy => strategy.ownerId === ownerId);
if (!value) {
throw new Error(`Missing diagnostics for ${ownerId}`);
}
return value;
}
function captureFailure(run: () => unknown): StrategyReplayError {
try {
run();
} catch (error) {
expect(error).toBeInstanceOf(StrategyReplayError);
if (error instanceof StrategyReplayError) {
return error;
}
throw error;
}
throw new Error('Expected the attempted strategy replay to fail');
}
test('same seed, fresh retries, callback ordering and event budgets preserve all decisions and economics', () => {
const run = (reverse: boolean, eventBudget: number) => {
const f = fixture(['B', 'A']);
const programs = ['A', 'B'].map(id =>
program(
id,
context => {
const samples = [context.random()];
if (id === 'B') {
samples.push(context.random(), context.random());
}
return {
nextState: {
count: context.state.count + 1,
samples: [...context.state.samples, ...samples],
},
intent: target(samples[0]! < 0.5 ? '1' : '0'),
};
},
id === 'A' ? 0 : 42
)
);
if (reverse) {
programs.reverse();
}
const { result, diagnostics } = runStrategyReplay(f.load, programs, {
eventBudget,
resultFormat: 'trace',
});
return { result, diagnostics };
};
const baseline = run(false, 1);
expect(run(true, 64)).toEqual(baseline);
expect(run(false, 64)).toEqual(baseline);
expect(owner(baseline.diagnostics).rng.draws).toBe(5);
expect(owner(baseline.diagnostics, 'B').rng.draws).toBe(15);
expect(owner(baseline.diagnostics).rng.algorithm).toBe('lcg32-v1');
expect((owner(baseline.diagnostics).state as CountState).samples.slice(0, 2)).toEqual([
1013904223 / 4294967296,
1196435762 / 4294967296,
]);
expect(baseline.diagnostics.strategies.map(s => s.ownerId)).toEqual(['A', 'B']);
});
test('one owner consuming additional random draws cannot move another owner cursor', () => {
const run = (extra: boolean) => {
const f = fixture(['A', 'B']);
return runStrategyReplay(
f.load,
['A', 'B'].map(id =>
program(id, context => {
const draw = context.random();
if (id === 'B' && extra) {
context.random();
context.random();
}
return {
nextState: {
count: context.state.count + 1,
samples: [...context.state.samples, draw],
},
intent: hold(),
};
})
),
{ resultFormat: 'projection' }
);
};
expect(owner(run(true).diagnostics)).toEqual(owner(run(false).diagnostics));
});
test('mixed cadence retains each owner prefix and consumes warmup once', () => {
const f = fixture(['A', 'B'], 6, 2);
// Trusted prepared fixture: X1 publishes only at minutes 1, 4 and terminal 6.
f.load.prepared.bars = f.load.prepared.bars.filter(
bar => bar.instrument_id === 'X0.US' || [0, 3, 5].includes(bar.source_sequence)
);
f.load.config.cadence = [
{ owner_id: 'A', series_ids: ['X0.US:1m'] },
{ owner_id: 'B', series_ids: ['X1.US:1m'] },
];
const seen = new Map<string, { at: number; bars: string[] }[]>();
const programs = ['A', 'B'].map(id =>
program(id, context => {
const rows = seen.get(id) ?? [];
rows.push({
at: context.now,
bars: context.observations.map(bar => `${bar.instrument_id}:${bar.source_sequence}`),
});
seen.set(id, rows);
expect(context.observations.every(bar => bar.available_at <= context.now)).toBe(true);
return { nextState: { count: context.state.count + 1, samples: [] }, intent: hold() };
})
);
const { diagnostics } = runStrategyReplay(f.load, programs, { eventBudget: 1 });
expect(seen.get('A')?.map(row => row.bars.length)).toEqual([2, 1, 1, 2, 1]);
expect(seen.get('B')).toEqual([
{ at: f.start + f.minute, bars: ['X0.US:0', 'X1.US:0'] },
{ at: f.start + 4 * f.minute, bars: ['X0.US:1', 'X0.US:2', 'X0.US:3', 'X1.US:3'] },
]);
expect(owner(diagnostics).observationCount).toBe(7);
expect(owner(diagnostics, 'B').observationCount).toBe(6);
expect(owner(diagnostics).nextDecisionSequence).toBe(5);
expect(owner(diagnostics, 'B').nextDecisionSequence).toBe(2);
});
test('callbacks share one frozen native barrier view while state, positions and feedback remain owned', () => {
const f = fixture(['A', 'B']);
const views = new Map<number, StrategyContext<CountState>['portfolio']>();
const programs = ['B', 'A'].map(id =>
program(id, context => {
const previous = views.get(context.now);
if (previous) {
expect(context.portfolio).toBe(previous);
} else {
views.set(context.now, context.portfolio);
}
expect(context.barrier.revision).toBe(context.portfolio.admissionRevision);
expect(Object.isFrozen(context.portfolio.portfolio.positions)).toBe(true);
expect(Object.isFrozen(context.state.samples)).toBe(true);
expect(Object.isFrozen(context.observations)).toBe(true);
expect(context.positions.every(position => position.ownerId === id)).toBe(true);
expect(context.previousAdmission?.decision.ownerId ?? id).toBe(id);
expect(() => (context.state as CountState).samples.push(4)).toThrow();
expect(() => ((context.portfolio as unknown as { equity: string }).equity = '0')).toThrow();
return { nextState: { count: context.state.count + 1, samples: [] }, intent: target() };
})
);
const { result } = runStrategyReplay(f.load, programs, { resultFormat: 'report' });
expect(result.projection.fills.map(fill => fill.ownerId)).toEqual(['A', 'B']);
});
test('late callback exception discards the staged barrier; fresh retry reconstructs the committed prefix', () => {
const f = fixture(['A', 'B']);
const ordinary = [program('A'), program('B')];
const baseline = runStrategyReplay(f.load, ordinary, { resultFormat: 'report' });
const originalSubmit = NativeReplaySession.prototype.submit;
let submitted = 0;
let failedSession: NativeReplaySession | undefined;
NativeReplaySession.prototype.submit = function (...args) {
submitted++;
failedSession = this;
return originalSubmit.apply(this, args);
};
let failure: StrategyReplayError;
try {
const faulty = program('B', context => {
const output = ordinary[1]!.decide(context);
if (context.decisionSequence === 1) {
throw new Error('late callback failure');
}
return output;
});
failure = captureFailure(() => runStrategyReplay(f.load, [ordinary[0]!, faulty]));
} finally {
NativeReplaySession.prototype.submit = originalSubmit;
}
expect(submitted).toBe(1);
expect(failure.cause).toBeInstanceOf(Error);
expect(failure.diagnostics.committedBarriers).toBe(1);
for (const saved of failure.diagnostics.strategies) {
expect(saved.nextDecisionSequence).toBe(1);
expect(saved.rng.draws).toBe(1);
expect((saved.state as CountState).count).toBe(1);
}
expect(() => failedSession!.project()).toThrow('disposed');
expect(failure).not.toHaveProperty('result');
const retry = runStrategyReplay(f.load, ordinary, { resultFormat: 'report' });
expect(retry.result).toEqual(baseline.result);
expect(retry.diagnostics).toEqual(baseline.diagnostics);
});
test('post-native-submit failure never publishes unconfirmed strategy state or reuses the resident attempt', () => {
const f = fixture(['A', 'B']);
const programs = [program('A'), program('B')];
const baseline = runStrategyReplay(f.load, programs, { resultFormat: 'projection' });
const originalSubmit = NativeReplaySession.prototype.submit;
let submitted = 0;
let failedSession: NativeReplaySession | undefined;
NativeReplaySession.prototype.submit = function (...args) {
const output = originalSubmit.apply(this, args);
failedSession = this;
if (++submitted === 2) {
throw new Error('response lost after native admission');
}
return output;
};
let failure: StrategyReplayError;
try {
failure = captureFailure(() => runStrategyReplay(f.load, programs));
} finally {
NativeReplaySession.prototype.submit = originalSubmit;
}
expect(submitted).toBe(2);
expect(failure.diagnostics.committedBarriers).toBe(1);
expect(
failure.diagnostics.strategies.every(s => s.nextDecisionSequence === 1 && s.rng.draws === 1)
).toBe(true);
expect(() => failedSession!.project()).toThrow('disposed');
const retry = runStrategyReplay(f.load, programs, { resultFormat: 'projection' });
expect(retry.result).toEqual(baseline.result);
expect(retry.diagnostics).toEqual(baseline.diagnostics);
});
test('malformed second-owner feedback after real native admission cannot partially commit diagnostic state', () => {
const f = fixture(['A', 'B']);
const programs = ['A', 'B'].map(id =>
program(id, context => ({
nextState: {
count: context.state.count + 1,
samples: [...context.state.samples, context.random()],
},
intent: target(String(context.state.count + 1)),
}))
);
const originalSubmit = NativeReplaySession.prototype.submit;
let submissions = 0;
let failedSession: NativeReplaySession | undefined;
NativeReplaySession.prototype.submit = function (...args) {
const output = originalSubmit.apply(this, args);
failedSession = this;
if (++submissions !== 2) {
return output;
}
const malformed = structuredClone(output);
const secondOwner = malformed.effects.find(effect => {
const order = effect.Order as { order: { decision: { ownerId: string } } } | undefined;
return order?.order.decision.ownerId === 'B';
});
expect(secondOwner).toBeDefined();
(secondOwner!.Order as { status: unknown }).status = 'InventedStatus';
return malformed;
};
let failure: StrategyReplayError;
try {
failure = captureFailure(() => runStrategyReplay(f.load, programs));
} finally {
NativeReplaySession.prototype.submit = originalSubmit;
}
expect(submissions).toBe(2);
expect(failure.diagnostics.committedBarriers).toBe(1);
for (const saved of failure.diagnostics.strategies) {
expect(saved.nextDecisionSequence).toBe(1);
expect(saved.rng.draws).toBe(1);
expect((saved.state as CountState).count).toBe(1);
expect(saved.previousAdmission?.decision.sequence).toBe(0);
}
expect(() => failedSession!.project()).toThrow('disposed');
});
test('risk rejection commits state and cursors and returns the actual rejection at the next decision', () => {
const f = fixture();
f.load.config.matching.risk.maxOrderQuantity = parseFinancialDecimal('1');
const feedback: StrategyContext<CountState>['previousAdmission'][] = [];
const strategy = program('A', context => {
feedback.push(context.previousAdmission);
return {
nextState: {
count: context.state.count + 1,
samples: [...context.state.samples, context.random()],
},
intent: target('2'),
};
});
const { result, diagnostics } = runStrategyReplay(f.load, [strategy], { resultFormat: 'report' });
expect(feedback[0]).toBeNull();
expect(
feedback
.slice(1)
.every(
item =>
item?.orders[0]?.status &&
typeof item.orders[0].status === 'object' &&
item.orders[0].status.Rejected === 'OrderSize'
)
).toBe(true);
expect(owner(diagnostics).nextDecisionSequence).toBe(5);
expect(owner(diagnostics).rng.draws).toBe(5);
expect(owner(diagnostics).observationCount).toBe(5);
expect((owner(diagnostics).state as CountState).count).toBe(5);
expect(result.projection.fills).toHaveLength(0);
expect<string>(result.projection.valuation.equity).toBe('10000.00000000');
expect(owner(diagnostics).previousAdmission?.orders[0]?.status).toEqual({
Rejected: 'OrderSize',
});
});
test('repeated target preserves a partially filled order and charges each actual fill once', () => {
const f = fixture();
f.load.config.participation_rate = parseFinancialDecimal('0.001');
const quantities: string[] = [];
const { result } = runStrategyReplay(
f.load,
[
program('A', context => {
quantities.push(context.positions[0]?.quantity ?? '0.00000000');
return { nextState: { count: context.state.count + 1, samples: [] }, intent: target('3') };
}),
],
{ resultFormat: 'report' }
);
expect(quantities).toEqual([
'0.00000000',
'1.00000000',
'2.00000000',
'3.00000000',
'3.00000000',
]);
expect(result.projection.fills).toHaveLength(3);
expect(new Set(result.projection.fills.map(fill => fill.orderId)).size).toBe(1);
expect(result.projection.fills.map(fill => String(fill.price))).toEqual([
'12.00000000',
'14.00000000',
'16.00000000',
]);
expect<string>(result.projection.valuation.cash).toBe('9957.58000000');
expect<string>(result.projection.valuation.fees).toBe('0.42000000');
expect<string>(result.projection.valuation.equity).toBe('10020.58000000');
});
test('cancellation feedback remains with the owner and retains the cancelled original decision identity', () => {
const f = fixture(['A', 'B']);
f.load.config.matching.latencyMs = f.minute;
const feedback: StrategyContext<CountState>['previousAdmission'][] = [];
const a = program('A', context => {
feedback.push(context.previousAdmission);
return {
nextState: { count: context.state.count + 1, samples: [] },
intent: target(context.state.count === 0 ? '3' : '0'),
};
});
const { result } = runStrategyReplay(f.load, [a, program('B')], { resultFormat: 'report' });
const cancelled = feedback[2]!.orders;
expect(cancelled).toHaveLength(1);
expect(cancelled[0]?.status).toBe('Cancelled');
expect(cancelled[0]?.decision.ownerId).toBe('A');
expect(cancelled[0]?.decision.sequence).toBe(0);
expect(feedback[2]?.decision.sequence).toBe(1);
expect(result.projection.fills.every(fill => fill.ownerId === 'B')).toBe(true);
expect(result.projection.fills).toHaveLength(1);
});
test('unavailable future prices cannot alter earlier strategy state, random draws, observations or decisions', () => {
const run = (mutate: boolean) => {
const f = fixture();
if (mutate) {
f.load.prepared.bars[3]!.high = '999.00000000';
f.load.prepared.bars[3]!.close = '999.00000000';
}
const seen: unknown[] = [];
const strategy = program('A', context => {
const draw = context.random();
const intent = target(context.observations.some(bar => Number(bar.close) > 500) ? '2' : '1');
seen.push({
now: context.now,
state: context.state,
draw,
observations: context.observations,
portfolio: context.portfolio,
intent,
});
expect(JSON.stringify(context)).not.toMatch(/"(prepared|binding|checkpoint|manifest)"/);
return {
nextState: { count: context.state.count + 1, samples: [...context.state.samples, draw] },
intent,
};
});
const result = runStrategyReplay(f.load, [strategy], { resultFormat: 'projection' });
return { seen, result };
};
const before = run(false),
after = run(true);
expect(after.seen.slice(0, 3)).toEqual(before.seen.slice(0, 3));
expect(after.seen[3]).not.toEqual(before.seen[3]);
expect(after.result.result).not.toEqual(before.result.result);
});
test('caller and retained callback references cannot rewrite captured inputs or committed state and RNG', () => {
const f = fixture();
let retainedRandom: (() => number) | undefined;
let retainedState: CountState | undefined;
const strategy = program('A', context => {
retainedRandom = context.random;
const nextState = {
count: context.state.count + 1,
samples: [...context.state.samples, context.random()],
};
retainedState = nextState;
return { nextState, intent: target() };
});
let mutated = false;
const { result, diagnostics } = runStrategyReplay(f.load, [strategy], {
eventBudget: 1,
resultFormat: 'projection',
onProgress: () => {
if (!mutated) {
strategy.initialState.count = 900;
Object.assign(strategy, {
seed: 999,
ownerId: 'wrong',
strategyVersion: 'changed',
decide: () => {
throw new Error('caller replaced callback');
},
});
f.load.config.matching.risk.ledger.initialCapital = parseFinancialDecimal('1');
mutated = true;
}
if (retainedRandom) {
expect(() => retainedRandom!()).toThrow();
}
if (retainedState) {
// Returning an object does not transfer mutation authority to its author.
try {
retainedState.count = 900;
} catch {
/* Freezing the returned object is also safe. */
}
}
},
});
expect((owner(diagnostics).state as CountState).count).toBe(5);
expect(owner(diagnostics).rng.seed).toBe(0);
expect(owner(diagnostics).rng.draws).toBe(5);
expect(owner(diagnostics).strategyVersion).toBe('1');
expect(() => retainedRandom!()).toThrow();
expect<string>(result.projection.valuation.cash).toBe('9987.88000000');
});
test('lossy initial/next state, asynchronous output and incorrect intent mode never reach admission', () => {
const f = fixture();
const cyclic: { self?: unknown } = {};
cyclic.self = cyclic;
const withSymbol = { valid: 1, [Symbol('hidden')]: 2 };
const nonenumerable = Object.defineProperty({ valid: 1 }, 'hidden', { value: 2 });
const getter = Object.defineProperty({}, 'value', { enumerable: true, get: () => 1 });
const invalid = [
undefined,
NaN,
Infinity,
() => 1,
new Date(),
[undefined],
Array(1),
withSymbol,
nonenumerable,
getter,
cyclic,
];
const originalSubmit = NativeReplaySession.prototype.submit;
let submitted = 0;
NativeReplaySession.prototype.submit = function (...args) {
submitted++;
return originalSubmit.apply(this, args);
};
try {
for (const value of invalid) {
const badInitial = { ...program(), initialState: value } as StrategyProgram;
expect(() => runStrategyReplay(f.load, [badInitial])).toThrow();
const badNext = {
...program(),
decide: () => ({ nextState: value, intent: hold() }),
} as StrategyProgram;
const failure = captureFailure(() => runStrategyReplay(f.load, [badNext]));
expect(failure.diagnostics.committedBarriers).toBe(0);
}
const asynchronous = {
...program(),
decide: async () => ({ nextState: initial(), intent: hold() }),
} as unknown as StrategyProgram;
expect(() => runStrategyReplay(f.load, [asynchronous])).toThrow();
const wrongMode = {
...program(),
decide: () => ({ nextState: initial(), intent: { mode: 'orders', orders: [] } }),
} as StrategyProgram;
expect(() => runStrategyReplay(f.load, [wrongMode])).toThrow();
} finally {
NativeReplaySession.prototype.submit = originalSubmit;
}
expect(submitted).toBe(0);
});
test('invalid owner/mode/seed configuration is rejected before strategy code runs', () => {
const f = fixture();
let calls = 0;
const valid = program('A', context => {
calls++;
return { nextState: { ...context.state, samples: [] }, intent: hold() };
});
const cases = [
[],
[valid, valid],
[{ ...valid, ownerId: 'B' }],
[{ ...valid, mode: 'orders' as const }],
...[-1, 0.1, 4294967296, NaN].map(seed => [{ ...valid, seed }]),
];
for (const programs of cases) {
expect(() => runStrategyReplay(f.load, programs)).toThrow();
}
expect(calls).toBe(0);
});
test('explicit-order strategies use the same native ledger and retain engine-stamped decision identity', () => {
const f = fixture(['A'], 3);
f.load.config.matching.owners[0]!.mode = 'Orders';
const strategy: StrategyProgram<CountState> = {
...program(),
mode: 'orders',
decide: context => ({
nextState: { count: context.state.count + 1, samples: [] },
intent: {
mode: 'orders',
orders:
context.state.count === 0
? [
{
kind: 'market',
orderId: 'author-order',
instrumentId: 'X0.US',
side: 'buy',
quantity: parseFinancialDecimal('2'),
timeInForce: 'GTC',
},
]
: [],
},
}),
};
const captured: FinancialStrategyDecision[] = [];
const originalSubmit = NativeReplaySession.prototype.submit;
NativeReplaySession.prototype.submit = function (barrierId, decisions) {
captured.push(...structuredClone(decisions));
return originalSubmit.call(this, barrierId, decisions);
};
try {
const { result, diagnostics } = runStrategyReplay(f.load, [strategy], {
resultFormat: 'report',
});
expect<string>(result.projection.valuation.cash).toBe('9975.76000000');
expect<string>(result.projection.valuation.equity).toBe('10005.76000000');
expect(result.projection.fills[0]?.orderId).toBe('author-order');
expect(captured.map(decision => decision.decision.sequence)).toEqual([0, 1]);
expect(
captured.every(
decision =>
decision.decision.ownerId === 'A' && decision.sessionId === f.load.identity.sessionId
)
).toBe(true);
expect(owner(diagnostics).nextDecisionSequence).toBe(2);
} finally {
NativeReplaySession.prototype.submit = originalSubmit;
}
});