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