feat(research): run trusted SMA strategies through native workers
This commit is contained in:
parent
4f6e44a853
commit
ca5abdde0e
16 changed files with 1682 additions and 28 deletions
406
test/integration/canonical-sma.test.ts
Normal file
406
test/integration/canonical-sma.test.ts
Normal file
|
|
@ -0,0 +1,406 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import {
|
||||
runStrategyReplay,
|
||||
StrategyReplayError,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import {
|
||||
builtinStrategySelectionSchema,
|
||||
type BuiltinStrategySelection,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import type {
|
||||
StrategyContext,
|
||||
StrategyProgram,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type { PublishedObservation } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { strategyAliases } from '../../apps/stock/orchestrator/src/contracts/strategy-names';
|
||||
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
type SmaStrategyState,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
const d = parseFinancialDecimal;
|
||||
function selection(overrides: Partial<BuiltinStrategySelection> = {}) {
|
||||
return builtinStrategySelectionSchema.parse({
|
||||
...canonicalSmaFixture().selections[0],
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
function observation(
|
||||
close: string,
|
||||
sequence: number,
|
||||
overrides: Partial<PublishedObservation> = {}
|
||||
): PublishedObservation {
|
||||
return {
|
||||
series_id: 'X0.US:1m',
|
||||
instrument_id: 'X0.US',
|
||||
interval_start: sequence,
|
||||
interval_end: sequence + 1,
|
||||
event_time: sequence + 1,
|
||||
available_at: sequence + 1,
|
||||
source_sequence: sequence,
|
||||
open: d(close),
|
||||
high: d(close),
|
||||
low: d(close),
|
||||
close: d(close),
|
||||
volume: d('1000'),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
function context(
|
||||
state: SmaStrategyState,
|
||||
observations: PublishedObservation[],
|
||||
now = observations.at(-1)?.available_at ?? 0
|
||||
): StrategyContext<SmaStrategyState> {
|
||||
const last = observations.at(-1);
|
||||
const riskSession = { calendarId: 'test', calendarRevision: '1', sessionId: 'test', startsAt: 0 };
|
||||
return {
|
||||
ownerId: 'A',
|
||||
strategyId: 'sma_crossover',
|
||||
strategyVersion: 'sma-crossover-long-only/v1',
|
||||
decisionSequence: 0,
|
||||
now,
|
||||
barrier: {
|
||||
barrier_id: 'test',
|
||||
at: now,
|
||||
revision: 0,
|
||||
owner_ids: ['A'],
|
||||
observation_count: observations.length,
|
||||
inputs: [
|
||||
{
|
||||
series_id: 'X0.US:1m',
|
||||
availability: last
|
||||
? { Fresh: { event_time: last.event_time, available_at: last.available_at } }
|
||||
: 'Missing',
|
||||
},
|
||||
],
|
||||
},
|
||||
portfolio: {
|
||||
admissionRevision: 0,
|
||||
equity: d('10000'),
|
||||
availableCash: d('10000'),
|
||||
orders: [],
|
||||
reservations: [],
|
||||
portfolio: {
|
||||
version: 1,
|
||||
sessionId: 'test',
|
||||
accountId: 'test',
|
||||
revision: 0,
|
||||
baseCurrency: 'USD',
|
||||
reserveOwnerId: 'reserve',
|
||||
cash: d('10000'),
|
||||
positions: [],
|
||||
fees: [],
|
||||
riskSession,
|
||||
},
|
||||
risk: {
|
||||
dailyBaseline: d('10000'),
|
||||
peakEquity: d('10000'),
|
||||
dailyHalted: false,
|
||||
drawdownHalted: false,
|
||||
riskSession,
|
||||
lastEventTime: now,
|
||||
},
|
||||
},
|
||||
positions: [],
|
||||
observations,
|
||||
previousAdmission: null,
|
||||
state,
|
||||
random: () => {
|
||||
throw new Error('SMA must not consume random');
|
||||
},
|
||||
};
|
||||
}
|
||||
function decide(
|
||||
program: StrategyProgram<SmaStrategyState>,
|
||||
closes: string[],
|
||||
state = program.initialState,
|
||||
offset = 0
|
||||
) {
|
||||
return program.decide(
|
||||
context(
|
||||
state,
|
||||
closes.map((close, i) => observation(close, offset + i))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
test('sma_registry_alias selects only the explicit canonical version and leaves legacy factories available', () => {
|
||||
for (const strategyId of [...strategyAliases.sma_crossover, 'sma_crossover', ' SMA Crossover ']) {
|
||||
expect(builtinStrategySelectionSchema.parse({ ...selection(), strategyId }).strategyId).toBe(
|
||||
'sma_crossover'
|
||||
);
|
||||
}
|
||||
for (const patch of [
|
||||
{ strategyId: 'momentum' },
|
||||
{ strategyVersion: 'sma-crossover-fixed/v2' },
|
||||
{ source: 'code' },
|
||||
{ parameters: { fastPeriod: 2, slowPeriod: 3, quantity: 10 } },
|
||||
{ parameters: { fastPeriod: 3, slowPeriod: 3 } },
|
||||
{ ownerBudget: '0' },
|
||||
]) {
|
||||
expect(() => builtinStrategySelectionSchema.parse({ ...selection(), ...patch })).toThrow();
|
||||
}
|
||||
expect(typeof createBuiltinStrategyRegistry().create).toBe('function');
|
||||
});
|
||||
|
||||
test('binding validation rejects wrong owners, mode, cadence, instrument and unknown series before replay', () => {
|
||||
const fixture = canonicalSmaFixture();
|
||||
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
||||
expect(() => validateBuiltinStrategyBindings(fixture.selections, load)).not.toThrow();
|
||||
for (const changed of [
|
||||
selection({ ownerId: 'B' }),
|
||||
selection({ seriesId: 'missing' }),
|
||||
selection({ instrumentId: 'X1.US' }),
|
||||
]) {
|
||||
expect(() => validateBuiltinStrategyBindings([changed], load)).toThrow();
|
||||
}
|
||||
expect(() =>
|
||||
validateBuiltinStrategyBindings([...fixture.selections, ...fixture.selections], load)
|
||||
).toThrow();
|
||||
const wrongMode = structuredClone(load);
|
||||
wrongMode.config.matching.owners[0]!.mode = 'Orders';
|
||||
expect(() => validateBuiltinStrategyBindings(fixture.selections, wrongMode)).toThrow();
|
||||
const wrongCadence = structuredClone(load);
|
||||
wrongCadence.config.cadence[0]!.series_ids = [];
|
||||
expect(() => validateBuiltinStrategyBindings(fixture.selections, wrongCadence)).toThrow();
|
||||
});
|
||||
|
||||
test('owner_budget_sizing uses exact decimal whole shares, never account equity or a forced minimum', () => {
|
||||
for (const [budget, prices, expected] of [
|
||||
['0.3', ['0.2', '0.01', '0.1'], '3'],
|
||||
['0.09', ['0.2', '0.01', '0.1'], '0'],
|
||||
['9007199254740993', ['2', '0.5', '1'], '9007199254740993'],
|
||||
] as const) {
|
||||
const program = createBuiltinStrategy(
|
||||
selection({ ownerBudget: d(budget), parameters: { fastPeriod: 1, slowPeriod: 2 } })
|
||||
);
|
||||
const result = decide(program, [...prices]);
|
||||
expect(result.intent).toEqual({
|
||||
mode: 'target',
|
||||
targets: [{ instrumentId: 'X0.US', quantity: d(expected) }],
|
||||
});
|
||||
expect(JSON.stringify(result.nextState)).not.toContain('BigInt');
|
||||
}
|
||||
});
|
||||
|
||||
test('warmup requires a real crossover; target survives equality and a repeated golden cross until death', () => {
|
||||
const program = createBuiltinStrategy(
|
||||
selection({ parameters: { fastPeriod: 1, slowPeriod: 2 } })
|
||||
);
|
||||
expect(decide(program, ['1', '2']).intent).toEqual({ mode: 'target', targets: [] });
|
||||
expect(decide(program, ['1', '2', '3']).intent).toEqual({ mode: 'target', targets: [] });
|
||||
let result = decide(program, ['3', '1', '2']);
|
||||
expect(result.nextState.targetQuantity).toBe(d('20'));
|
||||
result = decide(program, ['2'], result.nextState, 3); // equality retains long
|
||||
expect(result.nextState.targetQuantity).toBe(d('20'));
|
||||
result = decide(program, ['4'], result.nextState, 4); // golden after equality must not resize to10
|
||||
expect(result.nextState.targetQuantity).toBe(d('20'));
|
||||
result = decide(program, ['1'], result.nextState, 5);
|
||||
expect(result.nextState.targetQuantity).toBe(d('0'));
|
||||
});
|
||||
|
||||
test('stale, missing, mismatched freshness and no-new inputs preserve GTC intent without new targets', () => {
|
||||
const program = createBuiltinStrategy(selection());
|
||||
const initial = decide(program, ['3', '2', '1', '4']);
|
||||
for (const availability of [
|
||||
'Missing',
|
||||
{ Stale: { event_time: 5, available_at: 5 } },
|
||||
{ Fresh: { event_time: 4, available_at: 4 } },
|
||||
] as const) {
|
||||
const input = context(initial.nextState, [observation('5', 4)]);
|
||||
const result = program.decide({
|
||||
...input,
|
||||
barrier: { ...input.barrier, inputs: [{ series_id: 'X0.US:1m', availability }] },
|
||||
});
|
||||
expect(result.intent).toEqual({ mode: 'target', targets: [] });
|
||||
expect(result.nextState.targetQuantity).toBe(d('10'));
|
||||
}
|
||||
expect(program.decide(context(initial.nextState, [])).intent).toEqual({
|
||||
mode: 'target',
|
||||
targets: [],
|
||||
});
|
||||
const delayed = observation('0.01', 1, { available_at: 10 });
|
||||
const input = context(initial.nextState, [delayed], 10);
|
||||
const result = program.decide({
|
||||
...input,
|
||||
barrier: {
|
||||
...input.barrier,
|
||||
inputs: [
|
||||
{ series_id: 'X0.US:1m', availability: { Fresh: { event_time: 4, available_at: 4 } } },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.nextState).toEqual(initial.nextState);
|
||||
expect(result.intent).toEqual({ mode: 'target', targets: [] });
|
||||
expect(() => program.decide(context(initial.nextState, [observation('5', 4)], 4))).toThrow(
|
||||
'availability'
|
||||
);
|
||||
});
|
||||
|
||||
test('sma_checkpoint_restore validates JSON state and reconstructs identical indicator decisions', () => {
|
||||
const selected = selection();
|
||||
const first = createBuiltinStrategy(selected);
|
||||
const before = decide(first, ['3', '2', '1', '4']);
|
||||
const restored = JSON.parse(JSON.stringify(before.nextState)) as SmaStrategyState;
|
||||
expect(decide(createBuiltinStrategy(selected), ['5', '1'], restored, 4)).toEqual(
|
||||
decide(first, ['5', '1'], before.nextState, 4)
|
||||
);
|
||||
expect(() => decide(first, ['5'], { ...restored, closes: [] }, 4)).toThrow();
|
||||
expect(() =>
|
||||
decide(createBuiltinStrategy(selection({ ownerId: 'B' })), ['5'], restored, 4)
|
||||
).toThrow();
|
||||
expect(() => decide(first, ['5'], { ...restored, targetQuantity: d('1.5') }, 4)).toThrow();
|
||||
});
|
||||
|
||||
test('sma_next_open_trace buys and closes at eligible next opens with authoritative fees and exact equity', () => {
|
||||
const fixture = canonicalSmaFixture();
|
||||
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
||||
validateBuiltinStrategyBindings(fixture.selections, load);
|
||||
const run = (eventBudget: number) =>
|
||||
runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), {
|
||||
resultFormat: 'report',
|
||||
eventBudget,
|
||||
});
|
||||
const first = run(1);
|
||||
expect(run(64)).toEqual({ ...first, metrics: expect.anything() });
|
||||
expect(first.result.projection.valuation.equity).toBe(d('9969.3'));
|
||||
expect(first.result.projection.valuation.fees).toBe(d('0.7'));
|
||||
expect(
|
||||
first.result.projection.fills.map(fill => ({
|
||||
price: fill.price,
|
||||
quantityDelta: fill.quantityDelta,
|
||||
}))
|
||||
).toEqual([
|
||||
{ price: d('5'), quantityDelta: d('10') },
|
||||
{ price: d('2'), quantityDelta: d('-10') },
|
||||
]);
|
||||
});
|
||||
|
||||
test('warmup crossover sizes once at the first eligible fresh trading close and cannot fill during warmup', () => {
|
||||
const fixture = canonicalSmaFixture(['A'], { tradeStartStep: 5 });
|
||||
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
||||
const run = runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), {
|
||||
resultFormat: 'report',
|
||||
});
|
||||
expect(run.result.projection.fills.map(fill => [fill.eventTime, fill.quantityDelta])).toEqual([
|
||||
[fixture.start + 5 * fixture.minute, d('8')],
|
||||
[fixture.start + 6 * fixture.minute, d('-8')],
|
||||
]);
|
||||
expect(run.result.projection.valuation.equity).toBe(d('9975.44'));
|
||||
});
|
||||
|
||||
test('canonical SMA cannot bypass native fee-inclusive funding or adverse-gap fill checks', () => {
|
||||
for (const capital of ['40', '45']) {
|
||||
const fixture = canonicalSmaFixture();
|
||||
fixture.config.matching.risk.ledger.initialCapital = capital;
|
||||
const run = runStrategyReplay(
|
||||
prepareReplayLoad(fixture.dataset, fixture.config),
|
||||
fixture.selections.map(createBuiltinStrategy),
|
||||
{ resultFormat: 'report' }
|
||||
);
|
||||
expect(run.result.projection.fills).toEqual([]);
|
||||
expect(run.result.projection.valuation.cash).toBe(d(capital));
|
||||
const trace = runStrategyReplay(
|
||||
prepareReplayLoad(fixture.dataset, fixture.config),
|
||||
fixture.selections.map(createBuiltinStrategy),
|
||||
{ resultFormat: 'trace' }
|
||||
);
|
||||
expect(JSON.stringify(trace.result.receipts)).toContain('InsufficientCash');
|
||||
expect(run.diagnostics.strategies[0]!.state).toMatchObject({
|
||||
lastCrossover: 'death',
|
||||
targetQuantity: d('0'),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('late older native observations cannot rewrite SMA history or alter its targets', () => {
|
||||
const run = (lateClose: number) => {
|
||||
const fixture = canonicalSmaFixture(['A'], {
|
||||
closes: [3, lateClose, 1, 4, 5, 1, 1],
|
||||
availabilitySteps: [1, 6, 3, 4, 5, 6, 7],
|
||||
});
|
||||
return runStrategyReplay(
|
||||
prepareReplayLoad(fixture.dataset, fixture.config),
|
||||
fixture.selections.map(createBuiltinStrategy),
|
||||
{ resultFormat: 'report', eventBudget: 1 }
|
||||
);
|
||||
};
|
||||
const first = run(2),
|
||||
changed = run(200);
|
||||
expect(changed.result.projection).toEqual(first.result.projection);
|
||||
expect(changed.diagnostics.strategies).toEqual(first.diagnostics.strategies);
|
||||
expect(first.result.projection.fills.map(fill => fill.quantityDelta)).toEqual([d('8'), d('-8')]);
|
||||
});
|
||||
|
||||
test('repeating the desired target preserves the partially filled native order before a death closes owned inventory', () => {
|
||||
const fixture = canonicalSmaFixture(['A'], { volume: 3 });
|
||||
const run = runStrategyReplay(
|
||||
prepareReplayLoad(fixture.dataset, fixture.config),
|
||||
fixture.selections.map(createBuiltinStrategy),
|
||||
{ resultFormat: 'report' }
|
||||
);
|
||||
const fills = run.result.projection.fills;
|
||||
expect(fills.map(fill => fill.quantityDelta)).toEqual([d('3'), d('3'), d('-3')]);
|
||||
expect(fills[0]!.orderId).toBe(fills[1]!.orderId);
|
||||
expect(run.result.view.portfolio.positions[0]!.quantity).toBe(d('3'));
|
||||
expect(run.result.projection.valuation.cash).toBe(d('9975.64'));
|
||||
expect(run.result.projection.valuation.equity).toBe(d('9978.64'));
|
||||
});
|
||||
|
||||
test('two owners sharing an asset keep independent targets, fills and P&L', () => {
|
||||
const fixture = canonicalSmaFixture(['B', 'A']);
|
||||
fixture.selections = fixture.selections.map(item =>
|
||||
selection({ ...item, ownerBudget: d(item.ownerId === 'A' ? '40' : '20') })
|
||||
);
|
||||
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
||||
validateBuiltinStrategyBindings(fixture.selections, load);
|
||||
const run = runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), {
|
||||
resultFormat: 'report',
|
||||
});
|
||||
expect(run.result.projection.fills.map(fill => [fill.ownerId, fill.quantityDelta])).toEqual([
|
||||
['A', d('10')],
|
||||
['B', d('5')],
|
||||
['A', d('-10')],
|
||||
['B', d('-5')],
|
||||
]);
|
||||
expect(
|
||||
run.result.projection.valuation.owners
|
||||
.filter(owner => owner.ownerId !== 'reserve')
|
||||
.map(owner => [owner.ownerId, owner.realizedGrossPnl, owner.fees])
|
||||
).toEqual([
|
||||
['A', d('-30'), d('0.7')],
|
||||
['B', d('-15'), d('0.35')],
|
||||
]);
|
||||
expect(run.result.projection.valuation.equity).toBe(d('9953.95'));
|
||||
});
|
||||
|
||||
test('sma_checkpoint_restore whole-attempt retry after strategy failure recomputes identical decisions and economics', () => {
|
||||
const fixture = canonicalSmaFixture();
|
||||
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
||||
const original = createBuiltinStrategy(fixture.selections[0]!);
|
||||
const failing: StrategyProgram<SmaStrategyState> = {
|
||||
...original,
|
||||
decide(input) {
|
||||
if (input.decisionSequence === 4) {
|
||||
throw new Error('injected strategy failure');
|
||||
}
|
||||
return original.decide(input);
|
||||
},
|
||||
};
|
||||
expect(() => runStrategyReplay(load, [failing], { resultFormat: 'report' })).toThrow(
|
||||
StrategyReplayError
|
||||
);
|
||||
const baseline = runStrategyReplay(load, [createBuiltinStrategy(fixture.selections[0]!)], {
|
||||
resultFormat: 'report',
|
||||
eventBudget: 1,
|
||||
});
|
||||
const retried = runStrategyReplay(load, [original], { resultFormat: 'report', eventBudget: 7 });
|
||||
expect(retried.result).toEqual(baseline.result);
|
||||
expect(retried.diagnostics).toEqual(baseline.diagnostics);
|
||||
expect(original.initialState.closes).toEqual([]);
|
||||
});
|
||||
238
test/integration/canonical-strategy-worker.test.ts
Normal file
238
test/integration/canonical-strategy-worker.test.ts
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
import type { ChildProcess } from 'node:child_process';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { nativeWorkerRequestSchema } from '../../apps/stock/orchestrator/src/backtest/native-worker-protocol';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import {
|
||||
replayIdentitySchema,
|
||||
type ReplayResultFormat,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import {
|
||||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
type StrategyReplayExpectation,
|
||||
type StrategyReplayRequest,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/strategy-replay';
|
||||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
function request(resultFormat: ReplayResultFormat = 'trace', owners = ['A']) {
|
||||
const { dataset, config } = nativeReplayFixture(24, 1, owners);
|
||||
return {
|
||||
type: 'runStrategyReplay' as const,
|
||||
version: 1 as const,
|
||||
dataset,
|
||||
config,
|
||||
eventBudget: 3,
|
||||
resultFormat,
|
||||
strategies: owners.map((ownerId, index) => ({
|
||||
ownerId,
|
||||
strategyId: 'SMA',
|
||||
strategyVersion: 'sma-crossover-long-only/v1' as const,
|
||||
seed: index + 7,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '100',
|
||||
parameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
})),
|
||||
} satisfies StrategyReplayRequest;
|
||||
}
|
||||
|
||||
function expected(input: StrategyReplayRequest): StrategyReplayExpectation {
|
||||
const normalized = strategyReplayRequestSchema.parse(input);
|
||||
return {
|
||||
strategies: normalized.strategies,
|
||||
identity: replayIdentitySchema.parse({
|
||||
version: 1,
|
||||
sessionId: normalized.config.matching.risk.ledger.sessionId,
|
||||
datasetHash: (normalized.dataset as { manifest: { hash: string } }).manifest.hash,
|
||||
}),
|
||||
policy: normalized.config,
|
||||
format: normalized.resultFormat ?? 'trace',
|
||||
};
|
||||
}
|
||||
|
||||
function direct(input: StrategyReplayRequest) {
|
||||
const normalized = strategyReplayRequestSchema.parse(input);
|
||||
const load = prepareReplayLoad(normalized.dataset, normalized.config);
|
||||
validateBuiltinStrategyBindings(normalized.strategies, load);
|
||||
return runStrategyReplay(load, normalized.strategies.map(createBuiltinStrategy), {
|
||||
eventBudget: normalized.eventBudget,
|
||||
resultFormat: normalized.resultFormat,
|
||||
}).result;
|
||||
}
|
||||
|
||||
describe('trusted built-in strategy worker', () => {
|
||||
test.each(['trace', 'projection', 'report'] as const)(
|
||||
'%s real child matches direct SMA replay and repeated frozen-input attempts',
|
||||
async resultFormat => {
|
||||
const input = request(resultFormat, ['B', 'A']);
|
||||
const captured = expected(input);
|
||||
const worker = new NativeBacktestWorker();
|
||||
const raw = await worker.execute(input, new AbortController().signal, () => {});
|
||||
const envelope = parseStrategyReplayResult(raw, captured);
|
||||
expect(envelope.result).toEqual(direct(input));
|
||||
expect(envelope.strategies).toEqual([...captured.strategies]);
|
||||
expect(envelope.strategies.map(selection => selection.strategyId)).toEqual([
|
||||
'sma_crossover',
|
||||
'sma_crossover',
|
||||
]);
|
||||
expect(envelope.result.view.portfolio.positions).toHaveLength(2);
|
||||
expect(Object.keys(envelope).sort()).toEqual(['result', 'strategies', 'type', 'version']);
|
||||
expect(await worker.execute(input, new AbortController().signal, () => {})).toBe(raw);
|
||||
}
|
||||
);
|
||||
|
||||
test('schema normalizes built-in aliases/defaults but rejects code and unsupported versions', () => {
|
||||
const defaults = request();
|
||||
const parsed = strategyReplayRequestSchema.parse({
|
||||
...defaults,
|
||||
strategies: [{ ...defaults.strategies[0], parameters: {} }],
|
||||
});
|
||||
expect(parsed.strategies[0]).toMatchObject({
|
||||
strategyId: 'sma_crossover',
|
||||
ownerBudget: '100.00000000',
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
});
|
||||
for (const extra of [
|
||||
{ source: 'return buy()' },
|
||||
{ module: './candidate.ts' },
|
||||
{ initialState: {} },
|
||||
{ decide: () => ({}) },
|
||||
]) {
|
||||
expect(() => nativeWorkerRequestSchema.parse({ ...request(), ...extra })).toThrow();
|
||||
const input = request();
|
||||
expect(() =>
|
||||
nativeWorkerRequestSchema.parse({
|
||||
...input,
|
||||
strategies: [{ ...input.strategies[0], ...extra }],
|
||||
})
|
||||
).toThrow();
|
||||
}
|
||||
for (const changes of [
|
||||
{ strategyId: 'momentum' },
|
||||
{ strategyVersion: 'legacy' },
|
||||
{ parameters: { fastPeriod: 1, slowPeriod: 2, quantity: 10 } },
|
||||
]) {
|
||||
const input = request();
|
||||
expect(() =>
|
||||
nativeWorkerRequestSchema.parse({
|
||||
...input,
|
||||
strategies: [{ ...input.strategies[0], ...changes }],
|
||||
})
|
||||
).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('captures the entire normalized request before caller mutation', async () => {
|
||||
const input = structuredClone(request('report'));
|
||||
const captured = expected(input);
|
||||
const reference = direct(structuredClone(input));
|
||||
const worker = new NativeBacktestWorker();
|
||||
const running = worker.execute(input, new AbortController().signal, () => {});
|
||||
input.strategies[0]!.seed = 999;
|
||||
input.strategies[0]!.parameters.slowPeriod = 20;
|
||||
input.strategies[0]!.ownerBudget = '5000';
|
||||
input.strategies[0]!.ownerId = 'mutated';
|
||||
input.config.matching.risk.ledger.sessionId = 'mutated';
|
||||
(input.dataset.manifest as { hash: string }).hash = '0'.repeat(64);
|
||||
(input.dataset.bars as unknown[]).length = 0;
|
||||
input.resultFormat = 'projection';
|
||||
input.eventBudget = 0;
|
||||
const envelope = parseStrategyReplayResult(await running, captured);
|
||||
expect(envelope.result).toEqual(reference);
|
||||
expect(envelope.strategies).toEqual([...captured.strategies]);
|
||||
});
|
||||
|
||||
test('actual child rejects invalid owner, cadence and series bindings', async () => {
|
||||
const worker = new NativeBacktestWorker();
|
||||
for (const change of ['owner', 'cadence', 'series', 'instrument'] as const) {
|
||||
const input = request();
|
||||
if (change === 'owner') {
|
||||
input.strategies[0]!.ownerId = 'unknown';
|
||||
}
|
||||
if (change === 'cadence') {
|
||||
input.config.cadence[0]!.series_ids = [];
|
||||
}
|
||||
if (change === 'series') {
|
||||
input.strategies[0]!.seriesId = 'X0.US:unknown';
|
||||
}
|
||||
if (change === 'instrument') {
|
||||
input.strategies[0]!.instrumentId = 'OTHER.US';
|
||||
}
|
||||
await expect(worker.execute(input, new AbortController().signal, () => {})).rejects.toThrow();
|
||||
}
|
||||
expect(
|
||||
JSON.parse(await worker.execute(request(), new AbortController().signal, () => {})).type
|
||||
).toBe('strategyReplayResult');
|
||||
});
|
||||
|
||||
test.each([
|
||||
'wrong-envelope-version',
|
||||
'wrong-envelope-type',
|
||||
'wrong-strategy',
|
||||
'wrong-version',
|
||||
'wrong-owner',
|
||||
'wrong-seed',
|
||||
'wrong-parameters',
|
||||
'wrong-budget',
|
||||
'wrong-series',
|
||||
'wrong-instrument',
|
||||
'reordered',
|
||||
'missing-selection',
|
||||
'wrong-session',
|
||||
'wrong-dataset',
|
||||
'wrong-policy',
|
||||
'wrong-format',
|
||||
'invalid-result',
|
||||
'malformed',
|
||||
'reported-error',
|
||||
'crash',
|
||||
'no-result',
|
||||
'duplicate',
|
||||
])('%s child cannot publish a successful result', async mode => {
|
||||
const worker = new NativeBacktestWorker(
|
||||
new URL('../fixtures/canonical-strategy-worker.ts', import.meta.url)
|
||||
);
|
||||
const input = request('trace', ['B', 'A']);
|
||||
input.config.matching.risk.ledger.accountId = mode;
|
||||
await expect(worker.execute(input, new AbortController().signal, () => {})).rejects.toThrow();
|
||||
expect(
|
||||
JSON.parse(await worker.execute(request(), new AbortController().signal, () => {})).type
|
||||
).toBe('strategyReplayResult');
|
||||
});
|
||||
|
||||
test('hard cancellation discards pending success and releases the worker', async () => {
|
||||
const actual = new NativeBacktestWorker();
|
||||
const beforeResult = new AbortController();
|
||||
await expect(
|
||||
actual.execute(request(), beforeResult.signal, () => {
|
||||
beforeResult.abort(new Error('cancel strategy work'));
|
||||
})
|
||||
).rejects.toThrow('cancel strategy work');
|
||||
const worker = new NativeBacktestWorker(
|
||||
new URL('../fixtures/canonical-strategy-worker.ts', import.meta.url)
|
||||
);
|
||||
const input = request();
|
||||
input.config.matching.risk.ledger.accountId = 'result-then-block';
|
||||
const afterResult = new AbortController();
|
||||
let observed = false;
|
||||
const running = worker.execute(input, afterResult.signal, () => {});
|
||||
const child = (worker as unknown as { active: ChildProcess }).active;
|
||||
child.on('message', (message: { type: string }) => {
|
||||
if (message.type === 'result') {
|
||||
observed = true;
|
||||
afterResult.abort(new Error('cancel pending strategy success'));
|
||||
}
|
||||
});
|
||||
await expect(running).rejects.toThrow('cancel pending strategy success');
|
||||
expect(observed).toBe(true);
|
||||
expect(
|
||||
JSON.parse(await worker.execute(request(), new AbortController().signal, () => {})).type
|
||||
).toBe('strategyReplayResult');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue