refactor(backtest): isolate legacy persistence capabilities (CL33)

This commit is contained in:
Boki 2026-10-28 14:45:12 -04:00
parent 24487d35da
commit ec582bd5e8
14 changed files with 413 additions and 311 deletions

View file

@ -17,6 +17,7 @@ import {
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
@ -181,6 +182,7 @@ async function fixture(historical = false) {
return { id: runId };
};
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
const legacyWriter = new LegacyBacktestRunWriter(postgres, 2_000);
const history = { reads: 0, unavailable: false };
const storage = {
async getHistoricalBars() {
@ -268,6 +270,7 @@ async function fixture(historical = false) {
definition,
definitionInput,
repository,
legacyWriter,
runner,
engine,
queue,
@ -517,7 +520,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
.query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
PERFORM pg_sleep(0.35); RETURN NEW; END $$;
CREATE TRIGGER delay_snapshot BEFORE INSERT ON backtest_datasets FOR EACH ROW EXECUTE FUNCTION delay_snapshot()`);
const short = new PostgresBacktestRunRepository(f.postgres, 250);
const short = new LegacyBacktestRunWriter(f.postgres, 250);
const claim = await short.start(config);
await expect(short.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toBeInstanceOf(
BacktestLeaseLostError
@ -562,13 +565,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const claim = await f.repository.start(config);
const claim = await f.legacyWriter.start(config);
const dataset = await loadDataset(f.storage, config);
await f.pool
.query(`CREATE FUNCTION reject_dataset_pointer() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
IF NEW.dataset_hash IS NOT NULL THEN RAISE EXCEPTION 'injected snapshot pointer failure'; END IF; RETURN NEW; END $$;
CREATE TRIGGER reject_dataset_pointer BEFORE UPDATE ON runs FOR EACH ROW EXECUTE FUNCTION reject_dataset_pointer()`);
await expect(f.repository.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toThrow(
await expect(f.legacyWriter.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toThrow(
'injected'
);
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0);
@ -577,16 +580,16 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
.dataset_hash
).toBeNull();
await f.pool.query('DROP TRIGGER reject_dataset_pointer ON runs');
await f.repository.freezeDataset(run.id, claim.attemptId, dataset);
await f.legacyWriter.freezeDataset(run.id, claim.attemptId, dataset);
const different = await loadDataset(f.storage, {
...config,
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
endDate: '2024-03-16T00:00:00.000Z',
});
await expect(f.repository.freezeDataset(run.id, claim.attemptId, different)).rejects.toThrow(
await expect(f.legacyWriter.freezeDataset(run.id, claim.attemptId, different)).rejects.toThrow(
'already frozen'
);
expect((await f.repository.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe(
expect((await f.legacyWriter.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe(
dataset.manifest.hash
);
});
@ -595,11 +598,11 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const claim = await f.repository.start(config);
const claim = await f.legacyWriter.start(config);
const dataset = await loadDataset(f.storage, config);
const controller = new AbortController();
const reason = new BacktestCancelledError();
const repository = new PostgresBacktestRunRepository({
const repository = new LegacyBacktestRunWriter({
transaction: work =>
f.postgres.transaction(client =>
work(
@ -637,7 +640,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const claim = await f.repository.start(config);
const claim = await f.legacyWriter.start(config);
const dataset = await loadDataset(f.storage, config);
// Model corrupt historical storage at initial insertion; retained evidence cannot be edited.
const corrupt = structuredClone(dataset);
@ -652,7 +655,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
]);
const reads = f.history.reads;
f.history.unavailable = true;
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
await expect(f.legacyWriter.loadDataset(run.id, claim.attemptId)).rejects.toThrow(
'hash/content'
);
await f.expire(run.id);
await f.dispatcher.tick();
expect((await f.runner.runQueued(run.id)).status).toBe('failed');
@ -797,7 +802,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
f.repository.updateProgress(run.id, 99, undefined, old.attemptId)
).rejects.toBeInstanceOf(BacktestLeaseLostError);
await expect(
f.repository.updateControl(run.id, { status: 'paused' }, old.attemptId)
f.legacyWriter.updateControl(run.id, { status: 'paused' }, old.attemptId)
).rejects.toBeInstanceOf(BacktestLeaseLostError);
await expect(f.repository.cancel(run.id, old.attemptId)).rejects.toBeInstanceOf(
BacktestLeaseLostError
@ -996,7 +1001,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
]);
const active = await f.historicalRun({ backtestId: f.definition.id });
const oldActive = await f.historicalRun({ backtestId: f.definition.id });
const claim = await f.repository.start(await f.legacySnapshot(active.id));
const claim = await f.legacyWriter.start(await f.legacySnapshot(active.id));
await f.pool.query("UPDATE runs SET status = 'running' WHERE id = $1", [oldActive.id]);
const migration = readFileSync(
new URL('../../database/postgres/init/10-durable-backtest-dispatch.sql', import.meta.url),