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
9
test/fixtures/native-backtest-worker.ts
vendored
9
test/fixtures/native-backtest-worker.ts
vendored
|
|
@ -10,7 +10,11 @@ function send(message: NativeWorkerMessage | { invalid: boolean }): Promise<void
|
|||
}
|
||||
|
||||
process.once('message', async (input: unknown) => {
|
||||
const { config } = nativeWorkerRequestSchema.parse(input);
|
||||
const request = nativeWorkerRequestSchema.parse(input);
|
||||
if (request.type !== 'run') {
|
||||
throw new Error('Legacy fixture only');
|
||||
}
|
||||
const { config } = request;
|
||||
// Fixture controls are run labels, not unsupported production strategy parameters.
|
||||
const behavior = config.name?.startsWith('fixture:')
|
||||
? config.name.slice('fixture:'.length)
|
||||
|
|
@ -18,7 +22,7 @@ process.once('message', async (input: unknown) => {
|
|||
if (!behavior) {
|
||||
// The same adapter can recover and run the actual Rust engine after a failed worker.
|
||||
await import('../../apps/stock/orchestrator/src/backtest/native-worker');
|
||||
process.emit('message', input);
|
||||
process.emit('message', input, undefined);
|
||||
return;
|
||||
}
|
||||
await send({ type: 'progress', progress: 0, message: `Fixture worker ready:${process.pid}` });
|
||||
|
|
@ -43,6 +47,7 @@ process.once('message', async (input: unknown) => {
|
|||
break;
|
||||
case 'no-result':
|
||||
process.exit(0);
|
||||
return;
|
||||
case 'result-then-block':
|
||||
await send({ type: 'result', result: '{}' });
|
||||
while (true) {
|
||||
|
|
|
|||
212
test/fixtures/native-replay-load.json
vendored
Normal file
212
test/fixtures/native-replay-load.json
vendored
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
{
|
||||
"identity": {
|
||||
"version": 1,
|
||||
"sessionId": "f07-fixture",
|
||||
"datasetHash": "ad6300d751db8b65bc2e499b029bbd3e9882b57d74528b0b10b591ff55556101"
|
||||
},
|
||||
"config": {
|
||||
"matching": {
|
||||
"risk": {
|
||||
"ledger": {
|
||||
"version": 1,
|
||||
"sessionId": "f07-fixture",
|
||||
"accountId": "research-only",
|
||||
"baseCurrency": "USD",
|
||||
"reserveOwnerId": "reserve",
|
||||
"ownerIds": [
|
||||
"A"
|
||||
],
|
||||
"initialCapital": "10000.00000000",
|
||||
"riskSession": {
|
||||
"calendarId": "account",
|
||||
"calendarRevision": "1",
|
||||
"sessionId": "risk",
|
||||
"startsAt": 1704099600000
|
||||
}
|
||||
},
|
||||
"feeRate": "0.01000000",
|
||||
"maxOrderQuantity": "1000000.00000000",
|
||||
"maxPositionQuantity": "1000000.00000000",
|
||||
"maxSymbolExposure": "1000000.00000000",
|
||||
"maxGrossExposure": "1000000.00000000",
|
||||
"maxDailyLoss": "1000000.00000000",
|
||||
"maxDrawdownAmount": "1000000.00000000",
|
||||
"maxMarkAgeMs": 172800000
|
||||
},
|
||||
"owners": [
|
||||
{
|
||||
"ownerId": "A",
|
||||
"mode": "Target"
|
||||
}
|
||||
],
|
||||
"series": [
|
||||
{
|
||||
"instrumentId": "X0.US",
|
||||
"seriesId": "X0.US:1m",
|
||||
"mode": "Open"
|
||||
}
|
||||
],
|
||||
"halfSpreadRate": "0.00000000",
|
||||
"slippageRate": "0.00000000",
|
||||
"latencyMs": 0
|
||||
},
|
||||
"participation_rate": "1.00000000",
|
||||
"cadence": [
|
||||
{
|
||||
"owner_id": "A",
|
||||
"series_ids": [
|
||||
"X0.US:1m"
|
||||
]
|
||||
}
|
||||
],
|
||||
"allow_exploratory": false,
|
||||
"risk_boundaries": []
|
||||
},
|
||||
"manifest": {
|
||||
"calendars": [
|
||||
{
|
||||
"id": "fixture-calendar",
|
||||
"venue": "TEST",
|
||||
"timeZone": "UTC",
|
||||
"revision": "1",
|
||||
"source": "synthetic",
|
||||
"startDate": "2024-01-01",
|
||||
"endDate": "2024-01-02",
|
||||
"sessions": [
|
||||
{
|
||||
"date": "2024-01-01",
|
||||
"open": 1704099600000,
|
||||
"close": 1704135600000
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"series": [
|
||||
{
|
||||
"id": "X0.US:1m",
|
||||
"instrumentId": "X0.US",
|
||||
"interval": "1m",
|
||||
"calendarId": "fixture-calendar",
|
||||
"venue": "TEST",
|
||||
"source": {
|
||||
"provider": "synthetic",
|
||||
"revision": "f07-v1"
|
||||
},
|
||||
"timestamp": "interval-start",
|
||||
"availability": "explicit",
|
||||
"adjustment": "raw"
|
||||
}
|
||||
],
|
||||
"executionSeries": [
|
||||
{
|
||||
"instrumentId": "X0.US",
|
||||
"seriesId": "X0.US:1m"
|
||||
}
|
||||
],
|
||||
"bounds": {
|
||||
"warmupStart": 1704099600000,
|
||||
"tradeStart": 1704099660000,
|
||||
"tradeEnd": 1704099780000
|
||||
},
|
||||
"universe": {
|
||||
"selection": "point-in-time",
|
||||
"asOf": 1704099600000,
|
||||
"revision": "1",
|
||||
"instrumentIds": [
|
||||
"X0.US"
|
||||
]
|
||||
},
|
||||
"corporateActions": [
|
||||
{
|
||||
"instrumentId": "X0.US",
|
||||
"status": "action-free",
|
||||
"start": 1704099600000,
|
||||
"end": 1704099780000,
|
||||
"revision": "1",
|
||||
"actions": []
|
||||
}
|
||||
],
|
||||
"version": 2,
|
||||
"normalizationRevision": "historical-normalization-v2",
|
||||
"parentDatasetHash": null,
|
||||
"volumePolicy": "reported",
|
||||
"qualityPolicy": "reject-invalid-no-interpolation",
|
||||
"intradayPolicy": "full-duration-session-contained",
|
||||
"eligibility": "eligible",
|
||||
"limitations": [
|
||||
"Open liquidity must use previously available volume; intraday partial bars are unsupported"
|
||||
],
|
||||
"barCount": 3,
|
||||
"hash": "ad6300d751db8b65bc2e499b029bbd3e9882b57d74528b0b10b591ff55556101"
|
||||
},
|
||||
"prepared": {
|
||||
"dataset_id": "ad6300d751db8b65bc2e499b029bbd3e9882b57d74528b0b10b591ff55556101",
|
||||
"eligibility": "Eligible",
|
||||
"limitations": [
|
||||
"Open liquidity must use previously available volume; intraday partial bars are unsupported"
|
||||
],
|
||||
"bounds": {
|
||||
"warmup_start": 1704099600000,
|
||||
"trade_start": 1704099660000,
|
||||
"trade_end": 1704099780000
|
||||
},
|
||||
"series": [
|
||||
{
|
||||
"series_id": "X0.US:1m",
|
||||
"instrument_id": "X0.US",
|
||||
"adjustment": "Raw",
|
||||
"sessions": [
|
||||
{
|
||||
"sessionId": "[\"fixture-calendar\",\"1\",\"2024-01-01\"]",
|
||||
"opensAt": 1704099600000,
|
||||
"closesAt": 1704135600000
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"bars": [
|
||||
{
|
||||
"series_id": "X0.US:1m",
|
||||
"instrument_id": "X0.US",
|
||||
"interval_start": 1704099600000,
|
||||
"interval_end": 1704099660000,
|
||||
"event_time": 1704099660000,
|
||||
"available_at": 1704099660000,
|
||||
"source_sequence": 0,
|
||||
"open": "10.00000000",
|
||||
"high": "11.00000000",
|
||||
"low": "10.00000000",
|
||||
"close": "11.00000000",
|
||||
"volume": "1000.00000000"
|
||||
},
|
||||
{
|
||||
"series_id": "X0.US:1m",
|
||||
"instrument_id": "X0.US",
|
||||
"interval_start": 1704099660000,
|
||||
"interval_end": 1704099720000,
|
||||
"event_time": 1704099720000,
|
||||
"available_at": 1704099720000,
|
||||
"source_sequence": 1,
|
||||
"open": "12.00000000",
|
||||
"high": "13.00000000",
|
||||
"low": "12.00000000",
|
||||
"close": "13.00000000",
|
||||
"volume": "1000.00000000"
|
||||
},
|
||||
{
|
||||
"series_id": "X0.US:1m",
|
||||
"instrument_id": "X0.US",
|
||||
"interval_start": 1704099720000,
|
||||
"interval_end": 1704099780000,
|
||||
"event_time": 1704099780000,
|
||||
"available_at": 1704099780000,
|
||||
"source_sequence": 2,
|
||||
"open": "14.00000000",
|
||||
"high": "15.00000000",
|
||||
"low": "14.00000000",
|
||||
"close": "15.00000000",
|
||||
"volume": "1000.00000000"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
41
test/fixtures/native-replay-worker.ts
vendored
Normal file
41
test/fixtures/native-replay-worker.ts
vendored
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { replayTraceSchema } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
|
||||
function send(message: unknown): Promise<void> {
|
||||
return new Promise((resolve, reject) =>
|
||||
process.send!(message, (error: Error | null) => (error ? reject(error) : resolve()))
|
||||
);
|
||||
}
|
||||
process.once('message', async (input: unknown) => {
|
||||
const request = replayTraceSchema.parse(input),
|
||||
{ result } = executeReplayTrace(request);
|
||||
const mode = request.config.matching.risk.ledger.accountId;
|
||||
await send({ type: 'progress', progress: 0, message: 'Fixture ready' });
|
||||
switch (mode) {
|
||||
case 'wrong-version':
|
||||
result.manifest.version = 1;
|
||||
break;
|
||||
case 'wrong-account':
|
||||
result.view.portfolio.accountId = 'wrong';
|
||||
break;
|
||||
case 'wrong-policy':
|
||||
result.policy.matching.risk.feeRate = '0.5' as typeof result.policy.matching.risk.feeRate;
|
||||
break;
|
||||
case 'wrong-session':
|
||||
result.identity.sessionId = 'wrong';
|
||||
break;
|
||||
case 'wrong-dataset':
|
||||
result.identity.datasetHash = '0'.repeat(64);
|
||||
break;
|
||||
case 'crash':
|
||||
process.kill(process.pid, 'SIGKILL');
|
||||
return;
|
||||
}
|
||||
await send({ type: 'result', result: JSON.stringify(result) });
|
||||
if (mode === 'result-then-block') {
|
||||
while (true) {
|
||||
Math.sqrt(Math.random());
|
||||
}
|
||||
}
|
||||
process.disconnect?.();
|
||||
});
|
||||
117
test/fixtures/native-replay.ts
vendored
Normal file
117
test/fixtures/native-replay.ts
vendored
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import type { ReplayConfig } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
|
||||
/** Retained synthetic sessions, raw executable bars, explicit availability. */
|
||||
export function nativeReplayFixture(barsPerAsset = 3, assets = 1, owners = ['A']) {
|
||||
const start = Date.parse('2024-01-01T09:00:00Z'),
|
||||
minute = 60000,
|
||||
day = 86400000;
|
||||
const at = (step: number) => start + Math.floor(step / 600) * day + (step % 600) * minute;
|
||||
const end = at(barsPerAsset - 1) + minute;
|
||||
const instruments = Array.from({ length: assets }, (_, i) => `X${i}.US`);
|
||||
const calendar = {
|
||||
id: 'fixture-calendar',
|
||||
venue: 'TEST',
|
||||
timeZone: 'UTC',
|
||||
revision: '1',
|
||||
source: 'synthetic',
|
||||
startDate: '2024-01-01',
|
||||
endDate: new Date(end + day).toISOString().slice(0, 10),
|
||||
sessions: Array.from({ length: Math.ceil(barsPerAsset / 600) }, (_, i) => ({
|
||||
date: new Date(start + i * day).toISOString().slice(0, 10),
|
||||
open: start + i * day,
|
||||
close: start + i * day + 600 * minute,
|
||||
})),
|
||||
};
|
||||
const dataset = createDatasetV2({
|
||||
metadata: {
|
||||
calendars: [calendar],
|
||||
series: instruments.map(instrumentId => ({
|
||||
id: `${instrumentId}:1m`,
|
||||
instrumentId,
|
||||
interval: '1m',
|
||||
calendarId: calendar.id,
|
||||
venue: calendar.venue,
|
||||
source: { provider: 'synthetic', revision: 'f07-v1' },
|
||||
timestamp: 'interval-start',
|
||||
availability: 'explicit',
|
||||
adjustment: 'raw',
|
||||
})),
|
||||
executionSeries: instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
seriesId: `${instrumentId}:1m`,
|
||||
})),
|
||||
bounds: { warmupStart: start, tradeStart: start + minute, tradeEnd: end },
|
||||
universe: {
|
||||
selection: 'point-in-time',
|
||||
asOf: start,
|
||||
revision: '1',
|
||||
instrumentIds: instruments,
|
||||
},
|
||||
corporateActions: instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
status: 'action-free',
|
||||
start,
|
||||
end,
|
||||
revision: '1',
|
||||
actions: [],
|
||||
})),
|
||||
},
|
||||
bars: instruments.flatMap(instrumentId =>
|
||||
Array.from({ length: barsPerAsset }, (_, step) => ({
|
||||
seriesId: `${instrumentId}:1m`,
|
||||
timestamp: at(step),
|
||||
availableAt: at(step) + minute,
|
||||
sourceSequence: step,
|
||||
open: 10 + (step % 20) * 2,
|
||||
high: 11 + (step % 20) * 2,
|
||||
low: 10 + (step % 20) * 2,
|
||||
close: 11 + (step % 20) * 2,
|
||||
volume: 1000,
|
||||
}))
|
||||
),
|
||||
});
|
||||
const config: ReplayConfig = {
|
||||
matching: {
|
||||
risk: {
|
||||
ledger: {
|
||||
version: 1,
|
||||
sessionId: 'f07-fixture',
|
||||
accountId: 'research-only',
|
||||
baseCurrency: 'USD',
|
||||
reserveOwnerId: 'reserve',
|
||||
ownerIds: owners,
|
||||
initialCapital: '10000',
|
||||
riskSession: {
|
||||
calendarId: 'account',
|
||||
calendarRevision: '1',
|
||||
sessionId: 'risk',
|
||||
startsAt: start,
|
||||
},
|
||||
},
|
||||
feeRate: '0.01',
|
||||
maxOrderQuantity: '1000000',
|
||||
maxPositionQuantity: '1000000',
|
||||
maxSymbolExposure: '1000000',
|
||||
maxGrossExposure: '1000000',
|
||||
maxDailyLoss: '1000000',
|
||||
maxDrawdownAmount: '1000000',
|
||||
maxMarkAgeMs: day * 2,
|
||||
},
|
||||
owners: owners.map(ownerId => ({ ownerId, mode: 'Target' })),
|
||||
series: instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
seriesId: `${instrumentId}:1m`,
|
||||
mode: 'Open',
|
||||
})),
|
||||
halfSpreadRate: '0',
|
||||
slippageRate: '0',
|
||||
latencyMs: 0,
|
||||
},
|
||||
participation_rate: '1',
|
||||
cadence: owners.map(owner_id => ({ owner_id, series_ids: instruments.map(id => `${id}:1m`) })),
|
||||
allow_exploratory: false,
|
||||
risk_boundaries: [],
|
||||
};
|
||||
return { dataset, config, start, minute, instruments };
|
||||
}
|
||||
347
test/integration/native-replay.test.ts
Normal file
347
test/integration/native-replay.test.ts
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
import type { ChildProcess } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { FinancialReplaySession } from '@stock-bot/engine';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
executeReplayTrace,
|
||||
marketDecimal,
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplayConformance,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import {
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
import sharedLoad from '../fixtures/native-replay-load.json';
|
||||
|
||||
const target = (quantity = '2') => ({
|
||||
mode: 'target' as const,
|
||||
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal(quantity) }],
|
||||
});
|
||||
const hold = () => ({ mode: 'target' as const, targets: [] });
|
||||
function fixture(owners = ['A']) {
|
||||
const f = nativeReplayFixture(3, 1, owners);
|
||||
return { ...f, load: prepareReplayLoad(f.dataset, f.config) };
|
||||
}
|
||||
function traceRequest() {
|
||||
const f = fixture();
|
||||
return {
|
||||
type: 'runReplayTrace' as const,
|
||||
version: 1 as const,
|
||||
dataset: f.dataset,
|
||||
config: replayConfigSchema.parse(f.config),
|
||||
eventBudget: 1,
|
||||
trace: [
|
||||
{ at: f.start + f.minute, ownerId: 'A', intent: target() },
|
||||
{ at: f.start + 2 * f.minute, ownerId: 'A', intent: hold() },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe('canonical native replay session', () => {
|
||||
test('step_tagged_union: bounded progress, decision and complete; exact next-open terminal economics', () => {
|
||||
const f = fixture(),
|
||||
seen = new Set<string>();
|
||||
expect<unknown>(f.load).toEqual(sharedLoad); // Same input as Rust direct-Replay/transport receipt parity test.
|
||||
const { result, metrics } = runReplayConformance(
|
||||
new NativeReplaySession(f.load),
|
||||
(_owner, c) => (c.barrier.at === f.start + f.minute ? target() : hold()),
|
||||
{ eventBudget: 1, onProgress: s => seen.add(s.step.type) }
|
||||
);
|
||||
expect([...seen].sort()).toEqual(['complete', 'decisionBatch', 'progress']);
|
||||
expect<string>(result.view.portfolio.cash).toBe('9975.76000000');
|
||||
expect<string>(result.view.equity).toBe('10005.76000000');
|
||||
expect<unknown>(result.view.portfolio.fees).toEqual([{ ownerId: 'A', amount: '0.24000000' }]);
|
||||
expect(result.view.orders).toEqual([]);
|
||||
expect(metrics.submitCalls).toBe(2);
|
||||
expect(metrics.contextBytes).toBeGreaterThan(0);
|
||||
expect<unknown>(result.manifest).toEqual(f.dataset.manifest);
|
||||
expect(result.modelLimitations.some(s => s.includes('intermediate equity'))).toBe(true);
|
||||
});
|
||||
test('immutable_barrier_revision and reverse_callback_order: same shared frozen view, deterministic priority', () => {
|
||||
const run = (reverseCallbacks: boolean) => {
|
||||
const f = fixture(['B', 'A']),
|
||||
views = new Map<number, object>();
|
||||
return runReplayConformance(
|
||||
new NativeReplaySession(f.load),
|
||||
(_owner, c, observations) => {
|
||||
expect(c.barrier.revision).toBe(c.view.admissionRevision);
|
||||
expect(Object.isFrozen(c.view)).toBe(true);
|
||||
expect(Object.isFrozen(observations)).toBe(true);
|
||||
expect(observations.every(b => b.available_at <= c.barrier.at)).toBe(true);
|
||||
const previous = views.get(c.barrier.at);
|
||||
if (previous) {
|
||||
expect(previous).toBe(c.view);
|
||||
} else {
|
||||
views.set(c.barrier.at, c.view);
|
||||
}
|
||||
return c.barrier.at === f.start + f.minute ? target('1') : hold();
|
||||
},
|
||||
{ eventBudget: 1, reverseCallbacks }
|
||||
).result;
|
||||
};
|
||||
expect(run(true)).toEqual(run(false));
|
||||
});
|
||||
test('decision_exception_aborts_barrier: no partial submit and disposed attempt cannot finalize', () => {
|
||||
const f = fixture(['A', 'B']),
|
||||
session = new NativeReplaySession(f.load);
|
||||
let submissions = 0;
|
||||
const submit = session.submit.bind(session);
|
||||
session.submit = (...args) => {
|
||||
submissions++;
|
||||
return submit(...args);
|
||||
};
|
||||
expect(() =>
|
||||
runReplayConformance(session, owner => {
|
||||
if (owner === 'B') {
|
||||
throw new Error('fixture failure');
|
||||
}
|
||||
return target();
|
||||
})
|
||||
).toThrow('fixture failure');
|
||||
expect(submissions).toBe(0);
|
||||
expect(() => session.finalize()).toThrow('disposed');
|
||||
});
|
||||
test('rejected_intent_is_committed_outcome: risk rejection advances barrier without financial mutation', () => {
|
||||
const f = fixture();
|
||||
f.load.config.matching.risk.maxOrderQuantity = parseFinancialDecimal('1');
|
||||
const { result } = runReplayConformance(new NativeReplaySession(f.load), () => target());
|
||||
expect<string>(result.view.portfolio.cash).toBe('10000.00000000');
|
||||
expect(
|
||||
result.receipts.filter(r => JSON.stringify(r).includes('Rejected')).length
|
||||
).toBeGreaterThan(0);
|
||||
expect(
|
||||
result.receipts.filter(r => JSON.stringify(r).includes('"decisionId"')).length
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
test('strict native identity/version/precision/disposal and pending retry validation', () => {
|
||||
const f = fixture();
|
||||
for (const mutate of [
|
||||
(v: any) => (v.identity.version = 2),
|
||||
(v: any) => (v.identity.datasetHash = '0'.repeat(64)),
|
||||
(v: any) => (v.prepared.bars[0].future = true),
|
||||
(v: any) => (v.prepared.bars[0].open = '1.000000001'),
|
||||
(v: any) => (v.config.matching.risk.ledger.sessionId = 'wrong'),
|
||||
]) {
|
||||
const bad = structuredClone(f.load);
|
||||
mutate(bad);
|
||||
expect(() => new FinancialReplaySession(JSON.stringify(bad))).toThrow();
|
||||
}
|
||||
const native = new FinancialReplaySession(JSON.stringify(f.load)),
|
||||
request = { identity: f.load.identity, eventBudget: 100 };
|
||||
expect(() => native.finalize(JSON.stringify(f.load.identity))).toThrow('complete');
|
||||
expect(() => native.advance(JSON.stringify({ ...request, eventBudget: 0 }))).toThrow(
|
||||
'positive'
|
||||
);
|
||||
expect(() =>
|
||||
native.advance(
|
||||
JSON.stringify({ ...request, identity: { ...request.identity, sessionId: 'wrong' } })
|
||||
)
|
||||
).toThrow('identity');
|
||||
const first = JSON.parse(native.advance(JSON.stringify(request))),
|
||||
retry = JSON.parse(native.advance(JSON.stringify(request)));
|
||||
expect(first.step).toEqual(retry.step);
|
||||
expect(first.observations).toHaveLength(1);
|
||||
expect(retry.observations).toEqual([]);
|
||||
expect(() =>
|
||||
native.submit(
|
||||
JSON.stringify({
|
||||
identity: f.load.identity,
|
||||
barrierId: first.step.barrier.barrier_id,
|
||||
decisions: [],
|
||||
})
|
||||
)
|
||||
).toThrow('due owners');
|
||||
expect(JSON.parse(native.advance(JSON.stringify(request))).step).toEqual(first.step);
|
||||
native.dispose();
|
||||
native.dispose();
|
||||
expect(() => native.advance(JSON.stringify(request))).toThrow('disposed');
|
||||
expect(() => native.finalize(JSON.stringify(f.load.identity))).toThrow('disposed');
|
||||
expect(() =>
|
||||
native.submit(
|
||||
JSON.stringify({ identity: f.load.identity, barrierId: 'barrier', decisions: [] })
|
||||
)
|
||||
).toThrow('disposed');
|
||||
});
|
||||
test('failed_step_is_terminal_and_cannot_finalize: native numeric failure never yields successful result', () => {
|
||||
const f = fixture(),
|
||||
maximum = '792281625142643375935.43950335';
|
||||
f.load.prepared.bars[0]!.high = maximum;
|
||||
f.load.prepared.bars[0]!.close = maximum;
|
||||
const native = new FinancialReplaySession(JSON.stringify(f.load)),
|
||||
request = { identity: f.load.identity, eventBudget: 100 };
|
||||
const first = JSON.parse(native.advance(JSON.stringify(request)));
|
||||
const outcome = JSON.parse(
|
||||
native.submit(
|
||||
JSON.stringify({
|
||||
identity: f.load.identity,
|
||||
barrierId: first.step.barrier.barrier_id,
|
||||
decisions: [
|
||||
{
|
||||
version: 1,
|
||||
sessionId: f.load.identity.sessionId,
|
||||
barrierId: first.step.barrier.barrier_id,
|
||||
revision: first.step.barrier.revision,
|
||||
decision: { ownerId: 'A', decisionId: 'overflow', sequence: 0 },
|
||||
intent: target(),
|
||||
},
|
||||
],
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(outcome.outcome.status).toHaveProperty('Failed');
|
||||
expect(JSON.parse(native.advance(JSON.stringify(request))).step.type).toBe('failed');
|
||||
expect(() => native.finalize(JSON.stringify(f.load.identity))).toThrow('complete');
|
||||
native.dispose();
|
||||
});
|
||||
test('verified frozen loader preserves exact provenance and rejects forged datasets/precision/execution mapping', () => {
|
||||
const f = fixture();
|
||||
expect(f.load.prepared.bars[0]?.open).toBe('10.00000000');
|
||||
expect(f.load.prepared.series[0]?.sessions[0]?.opensAt).toBe(f.start);
|
||||
for (const mutate of [
|
||||
(v: any) => v.bars[0].close++,
|
||||
(v: any) => (v.manifest.hash = '0'.repeat(64)),
|
||||
(v: any) => (v.manifest.limitations = []),
|
||||
]) {
|
||||
const bad = structuredClone(f.dataset);
|
||||
mutate(bad);
|
||||
expect(() => prepareReplayLoad(bad, f.config)).toThrow();
|
||||
}
|
||||
const bad = structuredClone(f.config);
|
||||
bad.matching.series[0]!.seriesId = 'wrong';
|
||||
expect(() => prepareReplayLoad(f.dataset, bad)).toThrow('Execution series');
|
||||
expect(marketDecimal(1e-8)).toBe('0.00000001');
|
||||
expect(marketDecimal(1e20)).toBe('100000000000000000000.00000000');
|
||||
expect(() => marketDecimal(1e-9)).toThrow('8 fractional');
|
||||
expect(() => marketDecimal(NaN)).toThrow('Non-finite');
|
||||
});
|
||||
test('worker trace equals local callback trace; real cancellation cannot publish successful results', async () => {
|
||||
const request = traceRequest(),
|
||||
expected = executeReplayTrace(request).result,
|
||||
worker = new NativeBacktestWorker();
|
||||
const raw = await worker.execute(request, new AbortController().signal, () => {});
|
||||
expect(parseReplayResult(raw, expected.identity)).toEqual(expected);
|
||||
const cancel = new AbortController();
|
||||
await expect(
|
||||
worker.execute(request, cancel.signal, () => cancel.abort(new Error('cancel fixture')))
|
||||
).rejects.toThrow('cancel fixture');
|
||||
expect(
|
||||
JSON.parse(await worker.execute(request, new AbortController().signal, () => {})).status
|
||||
).toBe('complete');
|
||||
});
|
||||
test('worker captures expected policy/identity before caller mutation; malformed and stale successes reject', async () => {
|
||||
const request = structuredClone(traceRequest()),
|
||||
worker = new NativeBacktestWorker();
|
||||
const raw = await worker.execute(request, new AbortController().signal, () => {
|
||||
request.config.matching.risk.ledger.sessionId = 'mutated';
|
||||
request.config.matching.risk.feeRate = parseFinancialDecimal('0.5');
|
||||
(request.dataset.manifest as { hash: string }).hash = '0'.repeat(64);
|
||||
});
|
||||
expect(JSON.parse(raw).identity.sessionId).toBe('f07-fixture');
|
||||
const fixtureWorker = new NativeBacktestWorker(
|
||||
new URL('../fixtures/native-replay-worker.ts', import.meta.url)
|
||||
);
|
||||
for (const mode of [
|
||||
'wrong-version',
|
||||
'wrong-account',
|
||||
'wrong-policy',
|
||||
'wrong-session',
|
||||
'wrong-dataset',
|
||||
'crash',
|
||||
]) {
|
||||
const request = traceRequest();
|
||||
request.config.matching.risk.ledger.accountId = mode;
|
||||
await expect(
|
||||
fixtureWorker.execute(request, new AbortController().signal, () => {})
|
||||
).rejects.toThrow();
|
||||
}
|
||||
const block = traceRequest();
|
||||
block.config.matching.risk.ledger.accountId = 'result-then-block';
|
||||
const cancel = new AbortController();
|
||||
let observedResult = false;
|
||||
await expect(
|
||||
fixtureWorker.execute(block, cancel.signal, () => {
|
||||
// Test-only observation of the already-created child. Registered after
|
||||
// the supervisor listener, so abort happens after it stores the result.
|
||||
const child = (fixtureWorker as unknown as { active: ChildProcess }).active;
|
||||
child.on('message', (message: any) => {
|
||||
if (message.type === 'result') {
|
||||
observedResult = true;
|
||||
cancel.abort(new Error('pending success cancelled'));
|
||||
}
|
||||
});
|
||||
})
|
||||
).rejects.toThrow('pending success cancelled');
|
||||
expect(observedResult).toBe(true);
|
||||
});
|
||||
test('future suffix mutation cannot change published decision view, observations or intents', () => {
|
||||
const first = fixture(),
|
||||
second = fixture();
|
||||
second.load.prepared.bars[2]!.high = '999.00000000';
|
||||
second.load.prepared.bars[2]!.close = '999.00000000';
|
||||
const early = (load: typeof first.load) => {
|
||||
const session = new NativeReplaySession(load),
|
||||
observations: any[] = [];
|
||||
try {
|
||||
for (;;) {
|
||||
const step = session.advance(1);
|
||||
expect(JSON.stringify(step)).not.toMatch(/"(prepared|binding|checkpoint|manifest)"/);
|
||||
observations.push(...step.observations);
|
||||
if (step.step.type === 'decisionBatch') {
|
||||
return {
|
||||
context: step.step,
|
||||
observations,
|
||||
intent: observations[0]?.close === '11.00000000' ? target() : hold(),
|
||||
};
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
session.dispose();
|
||||
}
|
||||
};
|
||||
expect(early(second.load)).toEqual(early(first.load));
|
||||
});
|
||||
test('D01 eligibility, exact calendars, actual market precision and source sequences survive adaptation', () => {
|
||||
const input = structuredClone(datasetInput()) as any;
|
||||
const config = fixture().config;
|
||||
config.matching.series = [{ instrumentId: 'A.US', seriesId: 'A.US:daily:raw', mode: 'Open' }];
|
||||
config.cadence = [{ owner_id: 'A', series_ids: ['A.US:daily:raw'] }];
|
||||
config.matching.risk.ledger.riskSession.startsAt = input.metadata.bounds.warmupStart;
|
||||
const dataset = createDatasetV2(input),
|
||||
load = prepareReplayLoad(dataset, config);
|
||||
expect(load.prepared.series[0]!.sessions.map(s => [s.opensAt, s.closesAt])).toEqual(
|
||||
input.metadata.calendars[0].sessions.map((s: any) => [s.open, s.close])
|
||||
);
|
||||
input.bars[0].sourceSequence = 7;
|
||||
input.bars[1].sourceSequence = 3;
|
||||
input.bars[2].sourceSequence = 9;
|
||||
const sequenceLoad = prepareReplayLoad(createDatasetV2(input), config);
|
||||
expect(sequenceLoad.prepared.bars.map(b => b.source_sequence)).toEqual([7, 3, 9]);
|
||||
input.metadata.universe.selection = 'unknown';
|
||||
const exploratory = createDatasetV2(input);
|
||||
expect(() => new NativeReplaySession(prepareReplayLoad(exploratory, config))).toThrow(
|
||||
'eligibility'
|
||||
);
|
||||
const allowed = { ...config, allow_exploratory: true };
|
||||
new NativeReplaySession(prepareReplayLoad(exploratory, allowed)).dispose();
|
||||
const forged = structuredClone(exploratory) as any;
|
||||
forged.manifest.eligibility = 'eligible';
|
||||
const { hash: _hash, ...manifest } = forged.manifest;
|
||||
forged.manifest.hash = createHash('sha256')
|
||||
.update(JSON.stringify({ manifest, bars: forged.bars }))
|
||||
.digest('hex');
|
||||
expect(() => prepareReplayLoad(forged, allowed)).toThrow('derived policy');
|
||||
input.metadata.series[0].adjustment = 'provider-adjusted';
|
||||
const ineligible = createDatasetV2(input);
|
||||
expect(() => new NativeReplaySession(prepareReplayLoad(ineligible, allowed))).toThrow();
|
||||
input.metadata.series[0].adjustment = 'raw';
|
||||
input.bars[0].open = 100.000000001;
|
||||
expect(() => prepareReplayLoad(createDatasetV2(input), allowed)).toThrow('8 fractional');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue