- 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
238 lines
9 KiB
TypeScript
238 lines
9 KiB
TypeScript
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 '@stock-bot/stock-config/canonical-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-builtins';
|
|
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');
|
|
});
|
|
});
|