- 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
311 lines
12 KiB
TypeScript
311 lines
12 KiB
TypeScript
import type { ChildProcess } from 'node:child_process';
|
|
import { describe, expect, test } from 'bun:test';
|
|
import { FinancialReplaySession } from '@stock-bot/engine';
|
|
import { parseFinancialDecimal } from '@stock-bot/types';
|
|
import {
|
|
executeReplayTrace,
|
|
NativeReplaySession,
|
|
prepareReplayLoad,
|
|
runReplayConformance,
|
|
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
|
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
|
import {
|
|
parseReplayProjectionResult,
|
|
parseReplayReportResult,
|
|
parseReplayResult,
|
|
replayConfigSchema,
|
|
} from '@stock-bot/stock-config/canonical-replay';
|
|
import { nativeReplayFixture } from '../fixtures/native-replay';
|
|
|
|
const hold = () => ({ mode: 'target' as const, targets: [] });
|
|
const buy = () => ({
|
|
mode: 'target' as const,
|
|
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }],
|
|
});
|
|
function request(twoSessions = false) {
|
|
const f = nativeReplayFixture();
|
|
if (twoSessions) {
|
|
f.config.risk_boundaries = [2, 3].map(n => ({
|
|
...f.config.matching.risk.ledger.riskSession,
|
|
sessionId: `risk-${n}`,
|
|
startsAt: f.start + n * f.minute,
|
|
}));
|
|
}
|
|
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: buy() },
|
|
{ at: f.start + 2 * f.minute, ownerId: 'A', intent: hold() },
|
|
],
|
|
};
|
|
}
|
|
|
|
describe('authoritative replay reporting', () => {
|
|
test('two_session_marks and occupancy preserve compact financial facts and earlier reset', () => {
|
|
const input = request(true),
|
|
f = nativeReplayFixture();
|
|
const projected = executeReplayTrace({ ...input, resultFormat: 'projection' }).result;
|
|
let reset: string | undefined;
|
|
const output = runReplayConformance(
|
|
new NativeReplaySession(prepareReplayLoad(input.dataset, input.config)),
|
|
(_owner, context) => (context.barrier.at === f.start + f.minute ? buy() : hold()),
|
|
{
|
|
resultFormat: 'report',
|
|
eventBudget: 1,
|
|
onProgress: step => {
|
|
if (
|
|
step.step.type === 'decisionBatch' &&
|
|
step.step.barrier.at === f.start + 2 * f.minute
|
|
) {
|
|
reset = step.step.view.risk.dailyBaseline;
|
|
}
|
|
},
|
|
}
|
|
).result;
|
|
expect(output.projection).toEqual(projected.projection);
|
|
expect(output.view).toEqual(projected.view);
|
|
expect(output.policy).toEqual(projected.policy);
|
|
expect(output.modelLimitations).toEqual(projected.modelLimitations);
|
|
expect(reset).toBe('9999.76000000');
|
|
expect(output.reporting).toEqual({
|
|
calendarId: 'account',
|
|
calendarRevision: '1',
|
|
tradeStart: f.start + f.minute,
|
|
tradeEnd: f.start + 3 * f.minute,
|
|
initialEquity: parseFinancialDecimal('10000.00000000'),
|
|
sampling: 'account-boundary-after-observations-v1',
|
|
exposureBasis: 'elapsed-calendar-time',
|
|
sessions: [
|
|
{
|
|
session: input.config.matching.risk.ledger.riskSession,
|
|
periodStart: f.start + f.minute,
|
|
periodEnd: f.start + 2 * f.minute,
|
|
partialStart: true,
|
|
partialEnd: false,
|
|
equity: parseFinancialDecimal('10001.76000000'),
|
|
},
|
|
{
|
|
session: input.config.risk_boundaries[0]!,
|
|
periodStart: f.start + 2 * f.minute,
|
|
periodEnd: f.start + 3 * f.minute,
|
|
partialStart: false,
|
|
partialEnd: false,
|
|
equity: parseFinancialDecimal('10005.76000000'),
|
|
},
|
|
],
|
|
occupiedIntervals: [{ start: f.start + f.minute, end: f.start + 3 * f.minute }],
|
|
occupiedMs: '120000',
|
|
elapsedMs: '120000',
|
|
});
|
|
expect(output).not.toHaveProperty('receipts');
|
|
expect(executeReplayTrace({ ...input, resultFormat: 'report' }).result).toEqual(output);
|
|
});
|
|
|
|
test('native report is read-only and rejects incomplete, failed, wrong identity and disposed states', () => {
|
|
const f = nativeReplayFixture(),
|
|
load = prepareReplayLoad(f.dataset, f.config);
|
|
const native = new FinancialReplaySession(JSON.stringify(load)),
|
|
identity = JSON.stringify(load.identity);
|
|
expect(() => native.report(identity)).toThrow('complete');
|
|
expect(() => native.report(JSON.stringify({ ...load.identity, version: 2 }))).toThrow();
|
|
expect(() => native.report(JSON.stringify({ ...load.identity, sessionId: 'wrong' }))).toThrow(
|
|
'identity'
|
|
);
|
|
let sequence = 0;
|
|
try {
|
|
for (;;) {
|
|
const step = JSON.parse(
|
|
native.advance(JSON.stringify({ identity: load.identity, eventBudget: 1 }))
|
|
).step;
|
|
if (step.type === 'complete') {
|
|
break;
|
|
}
|
|
if (step.type === 'failed') {
|
|
throw new Error(step.diagnostic);
|
|
}
|
|
if (step.type === 'decisionBatch') {
|
|
native.submit(
|
|
JSON.stringify({
|
|
identity: load.identity,
|
|
barrierId: step.barrier.barrier_id,
|
|
decisions: [
|
|
{
|
|
version: 1,
|
|
sessionId: load.identity.sessionId,
|
|
barrierId: step.barrier.barrier_id,
|
|
revision: step.barrier.revision,
|
|
decision: {
|
|
ownerId: 'A',
|
|
decisionId: `direct-${sequence}`,
|
|
sequence: sequence++,
|
|
},
|
|
intent: hold(),
|
|
},
|
|
],
|
|
})
|
|
);
|
|
}
|
|
}
|
|
const trace = native.finalize(identity),
|
|
projection = native.project(identity),
|
|
report = native.report(identity);
|
|
expect(native.report(identity)).toBe(report);
|
|
expect(native.finalize(identity)).toBe(trace);
|
|
expect(native.project(identity)).toBe(projection);
|
|
const parsed = parseReplayReportResult(report, load.identity);
|
|
expect(parsed.reporting.occupiedMs).toBe('0');
|
|
expect(parsed.reporting.sessions).toHaveLength(1);
|
|
expect(parsed.reporting.sessions[0]?.partialEnd).toBe(true);
|
|
} finally {
|
|
native.dispose();
|
|
}
|
|
expect(() => native.report(identity)).toThrow('disposed');
|
|
load.prepared.bars[0]!.high = '792281625142643375935.43950335';
|
|
load.prepared.bars[0]!.close = '792281625142643375935.43950335';
|
|
const failed = new FinancialReplaySession(JSON.stringify(load));
|
|
try {
|
|
const step = JSON.parse(
|
|
failed.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 }))
|
|
).step;
|
|
const submission = JSON.parse(
|
|
failed.submit(
|
|
JSON.stringify({
|
|
identity: load.identity,
|
|
barrierId: step.barrier.barrier_id,
|
|
decisions: [
|
|
{
|
|
version: 1,
|
|
sessionId: load.identity.sessionId,
|
|
barrierId: step.barrier.barrier_id,
|
|
revision: step.barrier.revision,
|
|
decision: { ownerId: 'A', decisionId: 'overflow', sequence: 0 },
|
|
intent: buy(),
|
|
},
|
|
],
|
|
})
|
|
)
|
|
);
|
|
expect(submission.outcome.status).toHaveProperty('Failed');
|
|
expect(() => failed.report(identity)).toThrow('complete');
|
|
} finally {
|
|
failed.dispose();
|
|
}
|
|
});
|
|
|
|
test('strict reporting format, identity, calendar, partition, terminal and union validation', () => {
|
|
const input = request(true),
|
|
result = executeReplayTrace({ ...input, resultFormat: 'report' }).result;
|
|
expect(() => parseReplayProjectionResult(JSON.stringify(result), result.identity)).toThrow();
|
|
expect(() => parseReplayResult(JSON.stringify(result), result.identity)).toThrow();
|
|
for (const mutate of [
|
|
(r: any) => (r.format = 'projection'),
|
|
(r: any) => (r.reportingVersion = 2),
|
|
(r: any) => (r.projectionVersion = 2),
|
|
(r: any) => (r.financialVersion = 2),
|
|
(r: any) => (r.receipts = []),
|
|
(r: any) => (r.identity.sessionId = 'wrong'),
|
|
(r: any) => (r.reporting.calendarId = 'wrong'),
|
|
(r: any) => (r.reporting.calendarRevision = 'wrong'),
|
|
(r: any) => r.reporting.tradeStart++,
|
|
(r: any) => (r.reporting.initialEquity = '9999'),
|
|
(r: any) => (r.reporting.sessions.at(-1).equity = '1'),
|
|
(r: any) => r.reporting.sessions[0].periodEnd++,
|
|
(r: any) => (r.reporting.sessions[0].partialStart = false),
|
|
(r: any) => (r.reporting.sessions.at(-1).partialEnd = true),
|
|
(r: any) => r.reporting.sessions.push(r.reporting.sessions[0]),
|
|
(r: any) => (r.reporting.occupiedMs = '0120000'),
|
|
(r: any) => (r.reporting.occupiedMs = '120001'),
|
|
(r: any) => (r.reporting.elapsedMs = '120001'),
|
|
(r: any) => r.reporting.occupiedIntervals[0].start--,
|
|
(r: any) => r.reporting.occupiedIntervals.push(r.reporting.occupiedIntervals[0]),
|
|
(r: any) => (r.policy.matching.risk.feeRate = '0.5'),
|
|
]) {
|
|
const changed = structuredClone(result);
|
|
mutate(changed);
|
|
expect(() =>
|
|
parseReplayReportResult(JSON.stringify(changed), result.identity, input.config)
|
|
).toThrow();
|
|
}
|
|
const projection = executeReplayTrace({ ...input, resultFormat: 'projection' }).result;
|
|
expect(() => parseReplayReportResult(JSON.stringify(projection), result.identity)).toThrow();
|
|
});
|
|
|
|
test('report duration validation uses exact integers before subtracting timestamps', () => {
|
|
const input = request();
|
|
input.trace = input.trace.map(row => ({ ...row, intent: hold() }));
|
|
const result = executeReplayTrace({ ...input, resultFormat: 'report' }).result;
|
|
const start = -Number.MAX_SAFE_INTEGER,
|
|
end = Number.MAX_SAFE_INTEGER - 1;
|
|
const session = { ...result.policy.matching.risk.ledger.riskSession, startsAt: start };
|
|
result.policy.matching.risk.ledger.riskSession = session;
|
|
Object.assign(result.manifest.bounds as object, { tradeStart: start, tradeEnd: end });
|
|
Object.assign(result.reporting, {
|
|
tradeStart: start,
|
|
tradeEnd: end,
|
|
elapsedMs: '18014398509481981',
|
|
sessions: [
|
|
{
|
|
session,
|
|
periodStart: start,
|
|
periodEnd: end,
|
|
partialStart: false,
|
|
partialEnd: true,
|
|
equity: result.view.equity,
|
|
},
|
|
],
|
|
});
|
|
expect(
|
|
parseReplayReportResult(JSON.stringify(result), result.identity).reporting.elapsedMs
|
|
).toBe('18014398509481981');
|
|
result.reporting.elapsedMs = String(end - start);
|
|
expect(() => parseReplayReportResult(JSON.stringify(result), result.identity)).toThrow(
|
|
'duration'
|
|
);
|
|
});
|
|
|
|
test('worker captures report format and preserves failure and post-result cancellation guards', async () => {
|
|
const input = { ...request(), resultFormat: 'report' as const },
|
|
worker = new NativeBacktestWorker();
|
|
const expected = executeReplayTrace(input).result;
|
|
const mutable = { ...input };
|
|
const raw = await worker.execute(mutable, new AbortController().signal, () => {
|
|
(mutable as { resultFormat: string }).resultFormat = 'projection';
|
|
});
|
|
expect(parseReplayReportResult(raw, expected.identity, input.config)).toEqual(expected);
|
|
const fixture = new NativeBacktestWorker(
|
|
new URL('../fixtures/native-replay-worker.ts', import.meta.url)
|
|
);
|
|
for (const mode of [
|
|
'wrong-format',
|
|
'wrong-policy',
|
|
'wrong-account',
|
|
'wrong-session',
|
|
'crash',
|
|
]) {
|
|
const bad = { ...request(), resultFormat: 'report' as const };
|
|
bad.config.matching.risk.ledger.accountId = mode;
|
|
await expect(fixture.execute(bad, new AbortController().signal, () => {})).rejects.toThrow();
|
|
}
|
|
const blocked = { ...request(), resultFormat: 'report' as const };
|
|
blocked.config.matching.risk.ledger.accountId = 'result-then-block';
|
|
const cancellation = new AbortController();
|
|
let observed = false;
|
|
const running = fixture.execute(blocked, cancellation.signal, () => {});
|
|
const child = (fixture as unknown as { active: ChildProcess }).active;
|
|
child.on('message', (message: any) => {
|
|
if (message.type === 'result') {
|
|
observed = true;
|
|
cancellation.abort(new Error('report cancelled'));
|
|
}
|
|
});
|
|
await expect(running).rejects.toThrow('report cancelled');
|
|
expect(observed).toBe(true);
|
|
expect(
|
|
JSON.parse(await fixture.execute(input, new AbortController().signal, () => {})).format
|
|
).toBe('report');
|
|
});
|
|
});
|