stock-bot/test/integration/retained-strategy-worker.test.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- 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
2026-11-27 00:11:50 -05:00

425 lines
16 KiB
TypeScript

import { fork } from 'node:child_process';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { beforeAll, describe, expect, test } from 'bun:test';
import {
canonicalRunRequestSchema,
type CanonicalRunRequest,
} from '@stock-bot/stock-config/canonical-research';
import { parseFinancialDecimal, type StrategyVersionPackage } from '@stock-bot/types';
import {
canonicalWorkerUrl,
readCanonicalBuildIdentity,
} from '@stock-bot/trading-runtime/canonical-build';
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import {
nativeWorkerRequestSchema,
parseRetainedStrategyResult,
} 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 { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { nativeReplayFixture } from '../fixtures/native-replay';
const runId = 'b96aae03-f6d6-43b5-a006-a160e37f012b';
const versionId = '212a7d31-893d-46c9-910b-2234566f20d6';
const ownerId = `strategy:${versionId}`;
const sha = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
let packages: StrategyVersionPackage[];
beforeAll(async () => {
packages = await packageBuiltinStrategies();
});
async function input(strategyId = 'sma_crossover') {
const { dataset, config } = nativeReplayFixture(24, 1, [ownerId]);
config.matching.risk.ledger.sessionId = runId;
config.matching.risk.ledger.accountId = `research:${runId}`;
const pkg = structuredClone(packages.find(item => item.program.strategyId === strategyId)!);
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId: '4ea6a0fa-7bab-416f-b99e-ef9456567f66',
name: 'Exact retained built-in',
strategy: {
familyId: '05c49df3-08a4-40c5-b78d-4ee3364ac7a9',
versionId,
origin: 'builtin',
reviewId: 'e06828fc-8b37-4631-bf32-828d6095fdb6',
package: pkg,
selection: {
strategyId,
strategyVersion: pkg.program.strategyVersion,
ownerId,
seed: 17,
instrumentId: 'X0.US',
seriesId: 'X0.US:1m',
ownerBudget: '100',
parameters:
strategyId === 'sma_crossover'
? { fastPeriod: 1, slowPeriod: 2 }
: {
lookbackPeriod: 2,
trendPeriod: 3,
momentumPeriod: 1,
volatilityPeriod: 2,
entryZScore: 1,
exitZScore: 0,
minTrendReturn: -0.9,
minMomentumReturn: -0.9,
maxVolatility: 1,
minNotionalVolume: '0',
regimeFilter: 'none',
},
},
},
datasetHash: dataset.manifest.hash,
policy: config,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
build: await readCanonicalBuildIdentity(),
modelArtifacts: [],
});
return { type: 'runRetainedStrategy' as const, request, dataset };
}
function retainedSource(request: CanonicalRunRequest, source: string) {
request.strategy.package.artifact.content = source;
request.strategy.package.artifact.sha256 = sha(source);
}
async function execute(value: Awaited<ReturnType<typeof input>>) {
const raw = await new NativeBacktestWorker().execute(
value,
new AbortController().signal,
() => {}
);
return { raw, result: parseRetainedStrategyResult(raw, value.request) };
}
describe('retained canonical strategy worker', () => {
test.each(['sma_crossover', 'mean_reversion'])(
'%s exact packaged bytes match the native report and repeat identically',
async strategyId => {
const value = await input(strategyId);
if (value.request.strategy.origin !== 'builtin') {
throw new Error('Expected a built-in fixture');
}
const load = prepareReplayLoad(value.dataset, value.request.policy);
const direct = runStrategyReplay(
load,
[createBuiltinStrategy(value.request.strategy.selection)],
{
resultFormat: 'report',
}
).result;
const expected = buildCanonicalBacktestReport(direct, value.request.analyticsPolicy);
const first = await execute(value);
expect(first.result.financial).toEqual(expected.financial);
expect(first.result.analytics).toEqual(expected.analytics);
expect(first.result.build).toEqual(value.request.build);
expect(first.result.artifactHash).toBe(value.request.strategy.package.artifact.sha256);
expect((await execute(value)).raw).toBe(first.raw);
expect(
await new NativeBacktestWorker().executeRetained(
value,
new AbortController().signal,
() => {}
)
).toEqual(first.result);
}
);
test('a retained version executes its own bytes when the current constructor differs', async () => {
const value = await input();
if (value.request.strategy.origin !== 'builtin') {
throw new Error('Expected a built-in fixture');
}
const current = runStrategyReplay(
prepareReplayLoad(value.dataset, value.request.policy),
[createBuiltinStrategy(value.request.strategy.selection)],
{ resultFormat: 'report' }
).result;
expect(current.projection.fills.length).toBeGreaterThan(0);
// An earlier retained implementation that holds cash, with the same author API.
retainedSource(
value.request,
`export function createSmaStrategy(selection) {
return { ownerId:selection.ownerId, strategyId:selection.strategyId,
strategyVersion:selection.strategyVersion, seed:selection.seed, mode:'target',
initialState:{draws:0}, decide(context) { context.random();
return {nextState:{draws:context.state.draws+1}, intent:{mode:'target',targets:[]}}; }
};
}`
);
const first = await execute(value);
expect(first.result.financial.projection.fills).toEqual([]);
expect(first.result.financial.projection.valuation.equity).toBe(parseFinancialDecimal('10000'));
expect(first.result.analytics.metrics.exposureTime).toBe(0);
expect(first.result.analytics.metrics.roundTripCount).toBeNull();
expect((await execute(value)).raw).toBe(first.raw);
});
test('build and retained hashes are checked before module or factory side effects', async () => {
for (const changed of [
'workerSha256',
'engineWrapperSha256',
'engineBinarySha256',
'dependencyLockSha256',
'runtimeVersion',
'platform',
'arch',
] as const) {
const value = await input();
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
value.request.build[changed] = changed.endsWith('Sha256') ? 'f'.repeat(64) : 'wrong-build';
await expect(execute(value)).rejects.toThrow('build identity mismatch');
}
for (const changed of ['artifact', 'dependencyLock'] as const) {
const value = await input();
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
value.request.strategy.package[changed].sha256 = 'f'.repeat(64);
await expect(execute(value)).rejects.toThrow('artifact or dependency lock hash mismatch');
}
const verified = await input();
retainedSource(verified.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
await expect(execute(verified)).rejects.toThrow('RETAINED_MODULE_EXECUTED');
});
test('eligible exact single-series data and ownership are required before bundle import', async () => {
const value = await input();
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
const corrupt = {
...value,
dataset: {
manifest: structuredClone(value.dataset.manifest),
bars: value.dataset.bars.map(bar => ({ ...bar })),
},
};
corrupt.dataset.bars[0]!.volume += 1;
await expect(execute(corrupt)).rejects.toThrow('Dataset v2');
const other = nativeReplayFixture(24, 2, [ownerId]).dataset;
value.request.datasetHash = other.manifest.hash;
await expect(
new NativeBacktestWorker().execute(
{ ...value, dataset: other },
new AbortController().signal,
() => {}
)
).rejects.toThrow('Execution series must exactly match');
const candidate = await input();
expect(() =>
nativeWorkerRequestSchema.parse({
...candidate,
request: {
...candidate.request,
strategy: { ...candidate.request.strategy, origin: 'candidate' },
},
})
).toThrow();
const owners = await input();
owners.request.policy.matching.risk.ledger.ownerIds.push('second-owner');
await expect(execute(owners)).rejects.toThrow('single-asset');
});
test('factory identity, missing exports, thrown decisions and no-result exits fail closed', async () => {
for (const [source, reason] of [
['export const somethingElse = 1;', 'factory export is missing'],
['export function createSmaStrategy() { return {}; }', 'factory identity or API mismatch'],
[
'export function createSmaStrategy(selection) { selection.seed = 99; return {}; }',
'readonly',
],
['process.exit(0);', 'exited without a result'],
[
'export function createSmaStrategy() { throw new Error("bad retained factory"); }',
'bad retained factory',
],
[
'export function createSmaStrategy(selection) { return { ...selection, mode:"target", initialState:null, decide() { throw new Error("bad retained decision"); } }; }',
'bad retained decision',
],
]) {
const value = await input();
retainedSource(value.request, source!);
await expect(execute(value)).rejects.toThrow(reason!);
}
});
test('capture detaches all admitted inputs before the caller can mutate them', async () => {
const value = structuredClone(await input());
const captured = structuredClone(value.request);
const running = new NativeBacktestWorker().executeRetained(
value,
new AbortController().signal,
() => {}
);
value.request.strategy.package.artifact.content = 'throw new Error("mutated");';
value.request.strategy.selection.seed = 222;
value.request.build.engineBinarySha256 = 'f'.repeat(64);
(value.dataset.bars as unknown[]).length = 0;
const result = await running;
expect(result.artifactHash).toBe(captured.strategy.package.artifact.sha256);
expect(result.financial.projection.fills.length).toBeGreaterThan(0);
});
test('result parser rejects false identity, policy and statistical claims', async () => {
const value = await input();
const { raw } = await execute(value);
for (const mutate of [
(result: ReturnType<typeof JSON.parse>) => {
result.type = 'strategyReplayResult';
},
(result: ReturnType<typeof JSON.parse>) => {
result.version = 2;
},
(result: ReturnType<typeof JSON.parse>) => {
result.artifactHash = 'f'.repeat(64);
},
(result: ReturnType<typeof JSON.parse>) => {
result.build.workerSha256 = 'f'.repeat(64);
},
(result: ReturnType<typeof JSON.parse>) => {
result.financial.identity.sessionId = 'wrong';
},
(result: ReturnType<typeof JSON.parse>) => {
result.financial.identity.datasetHash = 'f'.repeat(64);
},
(result: ReturnType<typeof JSON.parse>) => {
result.financial.policy.matching.risk.feeRate = '0';
},
(result: ReturnType<typeof JSON.parse>) => {
result.analytics.metrics.exposureTime = null;
},
(result: ReturnType<typeof JSON.parse>) => {
result.analytics.metrics.roundTripCount = 0;
},
(result: ReturnType<typeof JSON.parse>) => {
result.analytics.policy.periodsPerYear = 365;
},
]) {
const result = JSON.parse(raw);
mutate(result);
expect(() => parseRetainedStrategyResult(JSON.stringify(result), value.request)).toThrow();
}
});
test.each([
[
'result.artifactHash = "f".repeat(64)',
'Retained strategy result build/artifact identity mismatch',
],
[
'result.build.workerSha256 = "f".repeat(64)',
'Retained strategy result build/artifact identity mismatch',
],
[
'result.financial.policy.matching.risk.feeRate = "0"',
'Native replay result identity mismatch',
],
[
'result.analytics.metrics.exposureTime = null',
'Retained strategy result analytics do not match the frozen policy',
],
])('typed worker rejects a malformed completed envelope: %s', async (mutation, reason) => {
const value = await input();
// A trusted fixture artifact intercepts its own child's IPC result. The
// supervisor must still validate the envelope before returning typed data.
retainedSource(
value.request,
`${value.request.strategy.package.artifact.content}
const originalSend = process.send.bind(process);
process.send = (message, callback) => {
if (message.type === 'result') {
const result = JSON.parse(message.result);
${mutation};
message.result = JSON.stringify(result);
}
return originalSend(message, callback);
};`
);
await expect(
new NativeBacktestWorker().executeRetained(value, new AbortController().signal, () => {})
).rejects.toThrow(reason);
});
test('typed retained results wait for successful child exit', async () => {
const value = await input();
retainedSource(
value.request,
`${value.request.strategy.package.artifact.content}
const originalSend = process.send.bind(process);
process.send = (message, callback) => {
if (message.type === 'result') process.exitCode = 23;
return originalSend(message, callback);
};`
);
await expect(
new NativeBacktestWorker().executeRetained(value, new AbortController().signal, () => {})
).rejects.toThrow('code 23');
});
test('alternate and source workers cannot claim the bundled worker identity', async () => {
const value = await input();
const sourceUrl = new URL(
'../../apps/stock/orchestrator/src/backtest/native-worker.ts',
import.meta.url
);
await expect(
new NativeBacktestWorker(sourceUrl).executeRetained(
value,
new AbortController().signal,
() => {}
)
).rejects.toThrow('canonical bundled worker');
expect(
await new NativeBacktestWorker(canonicalWorkerUrl()).execute(
value,
new AbortController().signal,
() => {}
)
).toContain('retainedStrategyResult');
// Bypass the supervisor to test the source child's independent own-file check.
const messages = await new Promise<{ type: string; message?: string }[]>((resolve, reject) => {
const child = fork(fileURLToPath(sourceUrl), [], {
execPath: process.execPath,
execArgv: [],
serialization: 'json',
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
});
const received: { type: string; message?: string }[] = [];
const timer = setTimeout(() => {
child.kill('SIGKILL');
reject(new Error('Source worker timeout'));
}, 5000);
child.stderr?.resume();
child.on('message', message => received.push(message as { type: string; message?: string }));
child.on('error', reject);
child.on('close', () => {
clearTimeout(timer);
resolve(received);
});
child.send(value);
});
expect(messages).toEqual([
{
type: 'error',
message: 'Canonical research requires the bundled worker from this checkout',
},
]);
});
test('hard cancellation discards retained execution and the worker can be reused', async () => {
const value = await input();
const worker = new NativeBacktestWorker();
const abort = new AbortController();
await expect(
worker.executeRetained(value, abort.signal, () =>
abort.abort(new Error('cancel retained replay'))
)
).rejects.toThrow('cancel retained replay');
expect((await worker.executeRetained(value, new AbortController().signal, () => {})).type).toBe(
'retainedStrategyResult'
);
});
});