feat(research): run stateful TypeScript strategies on canonical replay
This commit is contained in:
parent
0870b55830
commit
2bcadbd117
14 changed files with 1864 additions and 33 deletions
297
scripts/test/strategy-runtime.test.ts
Normal file
297
scripts/test/strategy-runtime.test.ts
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
import { describe, expect, spyOn, test } from 'bun:test';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import {
|
||||
runStrategyReplay,
|
||||
StrategyReplayError,
|
||||
type StrategyProgram,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import { nativeAdmissionOrders } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { nativeReplayFixture } from '../../test/fixtures/native-replay';
|
||||
|
||||
const hold = () => ({ mode: 'target' as const, targets: [] });
|
||||
function program(initialState: unknown): StrategyProgram {
|
||||
return {
|
||||
ownerId: 'A',
|
||||
strategyId: 'state-test',
|
||||
strategyVersion: '1',
|
||||
mode: 'target',
|
||||
seed: 1,
|
||||
initialState,
|
||||
decide: context => ({ nextState: context.state, intent: hold() }),
|
||||
};
|
||||
}
|
||||
function load(owners = ['A']) {
|
||||
const fixture = nativeReplayFixture(4, 1, owners);
|
||||
return prepareReplayLoad(fixture.dataset, fixture.config);
|
||||
}
|
||||
const managed = (status: unknown) => ({
|
||||
order: {
|
||||
orderId: 'order',
|
||||
decision: { ownerId: 'A', decisionId: 'old-decision', sequence: 0 },
|
||||
instrumentId: 'X0.US',
|
||||
side: 'buy',
|
||||
quantity: '1.00000000',
|
||||
limitPrice: null,
|
||||
origin: 'Target',
|
||||
},
|
||||
timeInForce: 'GTC',
|
||||
submittedAt: { at: 1, phase: 'Decision', instrumentId: 'X0.US', sourceSequence: 0 },
|
||||
readyAt: 1,
|
||||
venueSession: null,
|
||||
remaining: '1.00000000',
|
||||
filled: '0.00000000',
|
||||
status,
|
||||
admissionSequence: 1,
|
||||
});
|
||||
|
||||
describe('canonical strategy state and native admission boundary', () => {
|
||||
test('native status facts validate all supported risk reasons without reinterpreting them', () => {
|
||||
const reasons = [
|
||||
'OrderSize',
|
||||
'PositionSize',
|
||||
'SymbolExposure',
|
||||
'GrossExposure',
|
||||
'InsufficientCash',
|
||||
'InsufficientInventory',
|
||||
'MissingMark',
|
||||
'StaleMark',
|
||||
'DailyLoss',
|
||||
'Drawdown',
|
||||
'InactiveOrder',
|
||||
];
|
||||
for (const status of [
|
||||
'Open',
|
||||
'Filled',
|
||||
'Cancelled',
|
||||
'Expired',
|
||||
...reasons.map(Rejected => ({ Rejected })),
|
||||
]) {
|
||||
const order = managed(status);
|
||||
const parsed = nativeAdmissionOrders([{ Order: order }]);
|
||||
expect<unknown>(parsed[0]?.status).toEqual(status);
|
||||
expect(parsed[0]?.order.decision.decisionId).toBe('old-decision');
|
||||
}
|
||||
expect(nativeAdmissionOrders([{ Risk: {} }, { Operator: {} }])).toEqual([]);
|
||||
for (const effect of [
|
||||
{ Order: managed('Unknown') },
|
||||
{ Order: managed({ Rejected: 'Invented' }) },
|
||||
{ Order: { ...managed('Open'), extra: true } },
|
||||
{ Order: managed('Open'), extra: true },
|
||||
{ Unknown: {} },
|
||||
{},
|
||||
{ Risk: null },
|
||||
{ Risk: undefined },
|
||||
{ Risk: 1 },
|
||||
{ Operator: 'wrong' },
|
||||
]) {
|
||||
expect(() => nativeAdmissionOrders([effect])).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('plain __proto__ and constructor state keys survive without mutating the prototype', () => {
|
||||
const state = JSON.parse(
|
||||
'{"__proto__":{"value":7},"constructor":"own","nested":[true,null,1]}'
|
||||
);
|
||||
const output = runStrategyReplay(load(), [program(state)], { resultFormat: 'projection' });
|
||||
const saved = output.diagnostics.strategies[0]!.state;
|
||||
expect(saved).toEqual(state);
|
||||
expect(Object.getPrototypeOf(saved)).toBe(Object.prototype);
|
||||
expect(Object.hasOwn(saved as object, '__proto__')).toBe(true);
|
||||
expect(Object.isFrozen(saved)).toBe(true);
|
||||
expect(({} as { value?: number }).value).toBeUndefined();
|
||||
});
|
||||
|
||||
test('lossy initial states reject before any admission and do not invoke getters', () => {
|
||||
let getters = 0;
|
||||
const hidden = Object.defineProperty({}, 'hidden', { value: 1, enumerable: false });
|
||||
const accessor = Object.defineProperty({}, 'value', {
|
||||
get() {
|
||||
getters++;
|
||||
return 1;
|
||||
},
|
||||
enumerable: true,
|
||||
});
|
||||
const array = [1] as number[] & { extra?: number };
|
||||
array.extra = 2;
|
||||
const cyclic: Record<string, unknown> = {};
|
||||
cyclic.self = cyclic;
|
||||
const sparse = Array(2);
|
||||
sparse[1] = 1;
|
||||
const bad = [
|
||||
undefined,
|
||||
NaN,
|
||||
Infinity,
|
||||
-0,
|
||||
1n,
|
||||
() => 1,
|
||||
new Date(),
|
||||
Object.create(null),
|
||||
{ [Symbol('hidden')]: 1 },
|
||||
hidden,
|
||||
accessor,
|
||||
sparse,
|
||||
array,
|
||||
cyclic,
|
||||
];
|
||||
const submit = spyOn(NativeReplaySession.prototype, 'submit');
|
||||
try {
|
||||
for (const state of bad) {
|
||||
expect(() => runStrategyReplay(load(), [program(state)])).toThrow();
|
||||
}
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
expect(getters).toBe(0);
|
||||
} finally {
|
||||
submit.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test('malformed later-owner feedback keeps every owner at the prior committed barrier', () => {
|
||||
const programs = ['A', 'B'].map(
|
||||
ownerId =>
|
||||
({
|
||||
ownerId,
|
||||
strategyId: 'counter',
|
||||
strategyVersion: '1',
|
||||
mode: 'target' as const,
|
||||
seed: 2,
|
||||
initialState: { count: 0 },
|
||||
decide(context) {
|
||||
context.random();
|
||||
const count = context.state.count + 1;
|
||||
return {
|
||||
nextState: { count },
|
||||
intent: {
|
||||
mode: 'target' as const,
|
||||
targets: [
|
||||
{ instrumentId: 'X0.US', quantity: parseFinancialDecimal(String(count)) },
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
}) satisfies StrategyProgram<{ count: number }>
|
||||
);
|
||||
const original = NativeReplaySession.prototype.submit;
|
||||
let count = 0;
|
||||
const submit = spyOn(NativeReplaySession.prototype, 'submit').mockImplementation(function (
|
||||
this: NativeReplaySession,
|
||||
barrier,
|
||||
decisions
|
||||
) {
|
||||
const response = structuredClone(original.call(this, barrier, decisions));
|
||||
if (++count === 2) {
|
||||
const effect = response.effects.find(
|
||||
effect => (effect.Order as any)?.order.decision.ownerId === 'B'
|
||||
);
|
||||
expect(effect).toBeDefined();
|
||||
(effect!.Order as any).status = { Rejected: 'Invented' };
|
||||
}
|
||||
return response;
|
||||
});
|
||||
try {
|
||||
let failure: unknown;
|
||||
try {
|
||||
runStrategyReplay(load(['A', 'B']), programs);
|
||||
} catch (error) {
|
||||
failure = error;
|
||||
}
|
||||
expect(failure).toBeInstanceOf(StrategyReplayError);
|
||||
const diagnostics = (failure as StrategyReplayError).diagnostics;
|
||||
expect(diagnostics.committedBarriers).toBe(1);
|
||||
expect(diagnostics.strategies.map(owner => owner.state)).toEqual([
|
||||
{ count: 1 },
|
||||
{ count: 1 },
|
||||
]);
|
||||
expect(diagnostics.strategies.map(owner => owner.rng.draws)).toEqual([1, 1]);
|
||||
expect(diagnostics.strategies.map(owner => owner.nextDecisionSequence)).toEqual([1, 1]);
|
||||
} finally {
|
||||
submit.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test('replayed and mismatched acknowledgement revisions cannot commit strategy state', () => {
|
||||
for (const mismatch of ['replayed', 'revision']) {
|
||||
const original = NativeReplaySession.prototype.submit;
|
||||
const submit = spyOn(NativeReplaySession.prototype, 'submit').mockImplementation(function (
|
||||
this: NativeReplaySession,
|
||||
barrier,
|
||||
decisions
|
||||
) {
|
||||
const response = structuredClone(original.call(this, barrier, decisions));
|
||||
if (mismatch === 'replayed') {
|
||||
response.replayed = true;
|
||||
} else {
|
||||
response.revision++;
|
||||
}
|
||||
return response;
|
||||
});
|
||||
try {
|
||||
let failure: unknown;
|
||||
try {
|
||||
runStrategyReplay(load(), [program({ count: 0 })]);
|
||||
} catch (error) {
|
||||
failure = error;
|
||||
}
|
||||
expect(failure).toBeInstanceOf(StrategyReplayError);
|
||||
expect((failure as StrategyReplayError).diagnostics.committedBarriers).toBe(0);
|
||||
expect(
|
||||
(failure as StrategyReplayError).diagnostics.strategies[0]?.nextDecisionSequence
|
||||
).toBe(0);
|
||||
} finally {
|
||||
submit.mockRestore();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('rejected async outputs fail synchronously without unhandled rejections', async () => {
|
||||
const runtimePath = new URL(
|
||||
'../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts',
|
||||
import.meta.url
|
||||
).pathname;
|
||||
const replayPath = new URL(
|
||||
'../../apps/stock/orchestrator/src/backtest/native-replay.ts',
|
||||
import.meta.url
|
||||
).pathname;
|
||||
const fixturePath = new URL('../../test/fixtures/native-replay.ts', import.meta.url).pathname;
|
||||
for (const kind of ['immediate', 'after-await', 'foreign']) {
|
||||
const script = `
|
||||
import { runInNewContext } from 'node:vm';
|
||||
import { runStrategyReplay, StrategyReplayError } from ${JSON.stringify(runtimePath)};
|
||||
import { NativeReplaySession, prepareReplayLoad } from ${JSON.stringify(replayPath)};
|
||||
import { nativeReplayFixture } from ${JSON.stringify(fixturePath)};
|
||||
let admissions=0, disposals=0;
|
||||
const submit=NativeReplaySession.prototype.submit;
|
||||
NativeReplaySession.prototype.submit=function(...args){admissions++;return submit.apply(this,args);};
|
||||
const dispose=NativeReplaySession.prototype.dispose;
|
||||
NativeReplaySession.prototype.dispose=function(){disposals++;return dispose.call(this);};
|
||||
const fixture=nativeReplayFixture();
|
||||
let failure;
|
||||
try {
|
||||
runStrategyReplay(prepareReplayLoad(fixture.dataset,fixture.config), [{
|
||||
ownerId:'A',strategyId:'async-test',strategyVersion:'1',mode:'target',seed:1,initialState:null,
|
||||
decide: ${
|
||||
kind === 'foreign'
|
||||
? `()=>runInNewContext("Promise.reject(new Error('async-rejected'))")`
|
||||
: `async()=>{${kind === 'after-await' ? 'await Promise.resolve();' : ''}throw new Error('async-rejected');}`
|
||||
}
|
||||
}]);
|
||||
} catch(error) {failure=error;}
|
||||
if (!(failure instanceof StrategyReplayError) || failure.diagnostics.committedBarriers!==0) throw new Error('Missing synchronous strategy failure');
|
||||
await new Promise(resolve=>setTimeout(resolve,10));
|
||||
if(admissions!==0||disposals!==1)throw new Error('Async strategy was admitted or attempt leaked');
|
||||
process.stdout.write('async-contract-checked');
|
||||
`;
|
||||
const child = Bun.spawn([process.execPath, '-e', script], { stdout: 'pipe', stderr: 'pipe' });
|
||||
const [stdout, stderr, exitCode] = await Promise.all([
|
||||
new Response(child.stdout).text(),
|
||||
new Response(child.stderr).text(),
|
||||
child.exited,
|
||||
]);
|
||||
expect({ exitCode, stderr }).toEqual({ exitCode: 0, stderr: '' });
|
||||
expect(stdout).toBe('async-contract-checked');
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue