stock-bot/test/postgres/research-runtime-isolation.test.ts

146 lines
5.9 KiB
TypeScript

import { asValue } from 'awilix';
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { ServiceContainerBuilder } from '@stock-bot/di';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
import { logger } from '../fixtures/execution';
import { paperFixture, paperFrame } from '../fixtures/paper-runtime';
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture() {
const paper = await paperFixture();
cleanup.push(paper.close);
await paper.runtime.connect({ sourceId: 'fixture', connectionId: 'one' });
await paper.runtime.ingest(paperFrame(1));
await paper.runtime.activate({ recoverPending: false });
paper.clock(20);
await paper.runtime.ingest(paperFrame(2));
const admitted = await canonicalAdmissionFixture(paper.pool, paper.postgres);
const container = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
enableQueue: false,
enableMongoDB: false,
enablePostgres: false,
enableQuestDB: false,
enableBrowser: false,
enableProxy: false,
})
.build();
const services: OrchestratorServices = { logger, postgres: paper.postgres };
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container);
const runtime = services.custom!,
runner = runtime.BacktestRunner!;
cleanup.push(async () => {
await runner.shutdown();
await paper.runtime.shutdown();
await container.dispose();
});
return { paper, ...admitted, container, services, runtime, runner };
}
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
'canonical research isolation from durable paper custody',
() => {
test('default research composition cannot activate, reset or overlay the existing paper account', async () => {
const f = await fixture(),
before = await f.paper.snapshot();
for (const key of [
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'CanonicalPaperRuntime',
]) {
expect(f.runtime).not.toHaveProperty(key);
}
await expect(registerOrchestratorServices(f.container, { role: 'paper' })).rejects.toThrow(
'explicit canonicalPaper'
);
await expect(
registerOrchestratorServices(f.container, { useRustEngine: false })
).rejects.toThrow('Legacy financial execution is retired');
await expect(
registerOrchestratorServices(f.container, {
role: 'paper',
canonicalPaper: f.paper.configuration,
})
).rejects.toThrow('fresh runtime composition');
expect(await f.paper.snapshot()).toEqual(before);
expect((await f.paper.runtime.status()).active).toBe(true);
});
test('real native success, cancellation and failed durable research leave paper ledger/checkpoint/decisions unchanged', async () => {
const f = await fixture(),
before = await f.paper.snapshot();
const unchanged = async () => {
expect(await f.paper.snapshot()).toEqual(before);
expect((await f.paper.runtime.status()).active).toBe(true);
};
const accept = () => f.api.createRun({ backtestId: f.draft.id });
const completed = await accept();
expect((await f.runner.runQueued(completed.id)).status).toBe('completed');
await unchanged();
const result = await f.api.getRunResults(completed.id);
expect(result).not.toBeNull();
expect(result).toHaveProperty('kind', 'canonical-result/v1');
for (let index = 0; index < 2; index++) {
const run = await accept();
let stopped: Promise<void> | undefined;
const cancelOnProgress = () => {
f.runner.off('progress', cancelOnProgress);
stopped = f.runner.stopBacktest();
};
f.runner.on('progress', cancelOnProgress);
const cancelled = await f.runner.runQueued(run.id).catch(error => error);
await stopped;
expect(stopped).toBeDefined();
expect(cancelled).toBeInstanceOf(BacktestCancelledError);
await unchanged();
const failed = await accept();
// The pool deliberately keeps engines private; inject only at the adapter seam.
const failure = spyOn(RustBacktestAdapter.prototype, 'runCanonical').mockImplementationOnce(
async () => {
throw new Error('Injected canonical execution failure');
}
);
try {
await expect(f.runner.runQueued(failed.id)).rejects.toThrow(
'Injected canonical execution failure'
);
} finally {
failure.mockRestore();
}
await unchanged();
}
expect((await f.runner.runQueued((await accept()).id)).status).toBe('completed');
await unchanged();
expect(
(
await f.paper.pool.query(
'SELECT status,count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text'
)
).rows
).toEqual([
{ status: 'cancelled', count: 2 },
{ status: 'completed', count: 2 },
{ status: 'failed', count: 2 },
]);
f.paper.clock(30);
await f.paper.runtime.ingest(paperFrame(3));
const continued = await f.paper.snapshot();
expect(continued.owners[0]!.diagnostic.nextDecisionSequence).toBe(
before.owners[0]!.diagnostic.nextDecisionSequence + 1
);
expect(continued.account.view.portfolio.positions).toHaveLength(1);
}, 15000);
}
);