- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
123 lines
4.6 KiB
TypeScript
123 lines
4.6 KiB
TypeScript
import { expect, test } from 'bun:test';
|
|
import { parseFinancialDecimal } from '@stock-bot/types';
|
|
import {
|
|
NativeReplaySession,
|
|
prepareReplayLoad,
|
|
runReplaySessionAsync,
|
|
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
|
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
|
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
|
import type { ReplayResultFormat } from '@stock-bot/stock-config/canonical-replay';
|
|
import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller';
|
|
import { nativeReplayFixture } from '../fixtures/native-replay';
|
|
|
|
function setup() {
|
|
const fixture = nativeReplayFixture(8, 1, ['A', 'B']);
|
|
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
|
const programs: StrategyProgram<number>[] = ['A', 'B'].map(ownerId => ({
|
|
ownerId,
|
|
strategyId: 'async-parity',
|
|
strategyVersion: '1',
|
|
mode: 'target',
|
|
seed: ownerId === 'A' ? 12 : 34,
|
|
initialState: 0,
|
|
decide(context) {
|
|
expect(context.observations.every(bar => bar.available_at <= context.now)).toBe(true);
|
|
expect(context.positions.every(position => position.ownerId === ownerId)).toBe(true);
|
|
expect(context.previousAdmission?.decision.ownerId ?? ownerId).toBe(ownerId);
|
|
return {
|
|
nextState: context.state + 1,
|
|
intent: {
|
|
mode: 'target',
|
|
targets: [
|
|
{
|
|
instrumentId: 'X0.US',
|
|
quantity: parseFinancialDecimal(context.random() > 0.5 ? '1' : '0'),
|
|
},
|
|
],
|
|
},
|
|
};
|
|
},
|
|
}));
|
|
const controller = new StrategyController(load.identity, programs, load.config);
|
|
return { load, programs, controller };
|
|
}
|
|
|
|
for (const resultFormat of ['trace', 'projection', 'report'] satisfies ReplayResultFormat[]) {
|
|
test(`async controller preserves synchronous ${resultFormat} economics, state and admission order`, async () => {
|
|
const { load, programs, controller } = setup();
|
|
const synchronous = runStrategyReplay(load, programs, { resultFormat, eventBudget: 1 });
|
|
const phases: string[] = [];
|
|
const asynchronous = await runReplaySessionAsync(
|
|
new NativeReplaySession(load),
|
|
{
|
|
async stage(context, observations) {
|
|
phases.push('stage');
|
|
await Promise.resolve();
|
|
expect(Object.isFrozen(context.view)).toBe(true);
|
|
expect(Object.isFrozen(observations)).toBe(true);
|
|
return controller.stage(context, observations);
|
|
},
|
|
async committed(outcome) {
|
|
phases.push('commit');
|
|
await Promise.resolve();
|
|
controller.committed(outcome);
|
|
},
|
|
},
|
|
{ resultFormat, eventBudget: 256 }
|
|
);
|
|
expect(asynchronous.result).toEqual(synchronous.result);
|
|
expect(controller.snapshot()).toEqual(synchronous.diagnostics);
|
|
expect(phases).toEqual(Array.from({ length: 7 }, () => ['stage', 'commit']).flat());
|
|
expect(asynchronous.metrics.submitCalls).toBe(synchronous.metrics.submitCalls);
|
|
});
|
|
}
|
|
|
|
for (const phase of ['stage', 'commit'] as const) {
|
|
test(`async ${phase} rejection disposes the native session and preserves only acknowledged diagnostics`, async () => {
|
|
const { load, controller } = setup();
|
|
const session = new NativeReplaySession(load);
|
|
const dispose = session.dispose.bind(session);
|
|
let disposals = 0;
|
|
session.dispose = () => {
|
|
disposals++;
|
|
dispose();
|
|
};
|
|
await expect(
|
|
runReplaySessionAsync(session, {
|
|
async stage(context, observations) {
|
|
await Promise.resolve();
|
|
if (phase === 'stage') {
|
|
throw new Error('isolated stage lost');
|
|
}
|
|
return controller.stage(context, observations);
|
|
},
|
|
async committed() {
|
|
await Promise.resolve();
|
|
throw new Error('isolated commit lost');
|
|
},
|
|
})
|
|
).rejects.toThrow(`isolated ${phase} lost`);
|
|
expect(disposals).toBe(1);
|
|
expect(controller.snapshot().committedBarriers).toBe(0);
|
|
expect(() => session.advance(1)).toThrow();
|
|
});
|
|
}
|
|
|
|
test('async malformed financial decisions fail before an acknowledgement and still dispose', async () => {
|
|
const { load } = setup();
|
|
const session = new NativeReplaySession(load);
|
|
let acknowledged = false;
|
|
await expect(
|
|
runReplaySessionAsync(session, {
|
|
async stage() {
|
|
return [{ intent: { mode: 'target', targets: [] } }] as never;
|
|
},
|
|
async committed() {
|
|
acknowledged = true;
|
|
},
|
|
})
|
|
).rejects.toThrow();
|
|
expect(acknowledged).toBe(false);
|
|
expect(() => session.advance(1)).toThrow();
|
|
});
|