refactor(backtest): isolate legacy persistence capabilities (CL33)
This commit is contained in:
parent
24487d35da
commit
ec582bd5e8
14 changed files with 413 additions and 311 deletions
|
|
@ -3,7 +3,11 @@ import type {
|
|||
BacktestExecutionEngine,
|
||||
LegacyBacktestExecutionEngine,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import type { BacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import type { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import type {
|
||||
BacktestRunRepository,
|
||||
UnavailableBacktestRunRepository,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
|
||||
function canonicalDependencies(
|
||||
|
|
@ -34,3 +38,27 @@ function canonicalDependencies(
|
|||
}
|
||||
|
||||
void canonicalDependencies;
|
||||
|
||||
function canonicalRepositorySurface(
|
||||
repository: PostgresBacktestRunRepository,
|
||||
unavailable: UnavailableBacktestRunRepository
|
||||
) {
|
||||
// @ts-expect-error Legacy claim/create is an explicit compatibility-only capability.
|
||||
repository.start;
|
||||
// @ts-expect-error Production cannot perform legacy provider lookup/pinning.
|
||||
repository.loadDataset;
|
||||
// @ts-expect-error Admission already binds canonical datasets.
|
||||
repository.freezeDataset;
|
||||
// @ts-expect-error Production cannot persist an independent legacy financial result.
|
||||
repository.complete;
|
||||
// @ts-expect-error Playback controls are retained only by the compatibility writer.
|
||||
repository.updateControl;
|
||||
// @ts-expect-error Shared completion fences are not public writer capabilities.
|
||||
repository.markComplete;
|
||||
// @ts-expect-error Shared transaction locks are protected, not public.
|
||||
repository.ownedTransaction;
|
||||
// @ts-expect-error The unavailable production implementation has the same canonical surface.
|
||||
unavailable.start;
|
||||
}
|
||||
|
||||
void canonicalRepositorySurface;
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import {
|
|||
parseStrategyVersionPackage,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter';
|
||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||
|
||||
const definition = {
|
||||
|
|
@ -69,7 +69,7 @@ describe('catalog draft and execution contracts', () => {
|
|||
throw new Error('Unexpected write');
|
||||
}),
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(database);
|
||||
const repository = new LegacyBacktestRunWriter(database);
|
||||
for (const marker of [
|
||||
{ strategy: 'catalog' },
|
||||
{ strategyVersionId: null },
|
||||
|
|
|
|||
63
test/integration/run-repository-capabilities.test.ts
Normal file
63
test/integration/run-repository-capabilities.test.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { expect, mock, test } from 'bun:test';
|
||||
import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { UnavailableBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { runtimeImports } from '../../scripts/runtime-imports';
|
||||
|
||||
const legacyMethods = [
|
||||
'start',
|
||||
'loadDataset',
|
||||
'freezeDataset',
|
||||
'complete',
|
||||
'updateControl',
|
||||
] as const;
|
||||
|
||||
test('canonical concrete repositories cannot expose retired write capabilities', () => {
|
||||
const database = {
|
||||
transaction: mock(async () => {
|
||||
throw new Error('Unexpected database access');
|
||||
}),
|
||||
};
|
||||
const canonical = new PostgresBacktestRunRepository(database);
|
||||
const unavailable = new UnavailableBacktestRunRepository();
|
||||
const historical = new LegacyBacktestRunWriter(database);
|
||||
for (const method of legacyMethods) {
|
||||
expect(method in canonical).toBe(false);
|
||||
expect(method in unavailable).toBe(false);
|
||||
expect(typeof historical[method]).toBe('function');
|
||||
}
|
||||
// Compatibility does not copy or replace supported ownership/failure transitions.
|
||||
for (const method of [
|
||||
'startCanonical',
|
||||
'loadCanonicalDataset',
|
||||
'completeCanonical',
|
||||
'heartbeat',
|
||||
'updateProgress',
|
||||
'cancel',
|
||||
'fail',
|
||||
] as const) {
|
||||
expect(historical[method]).toBe(canonical[method]);
|
||||
}
|
||||
expect(database.transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('production modules do not import or re-export the compatibility writer', () => {
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const compatibility = resolve(
|
||||
root,
|
||||
'apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'
|
||||
);
|
||||
const files = new Bun.Glob('{apps,libs}/**/src/**/*.{ts,tsx}').scanSync({ cwd: root });
|
||||
for (const file of files) {
|
||||
const absolute = resolve(root, file);
|
||||
for (const specifier of runtimeImports(absolute)) {
|
||||
if (specifier.startsWith('.')) {
|
||||
expect(resolve(dirname(absolute), specifier).replace(/\.[cm]?[jt]sx?$/, '')).not.toBe(
|
||||
compatibility
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -12,6 +12,7 @@ import {
|
|||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { readCanonicalBuildIdentity } from '../../apps/stock/orchestrator/src/backtest/canonical-build';
|
||||
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';
|
||||
|
|
@ -183,6 +184,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
|
|||
return {
|
||||
pool,
|
||||
repository,
|
||||
legacyWriter: new LegacyBacktestRunWriter(postgres, 5000),
|
||||
engine,
|
||||
runner,
|
||||
dispatcher,
|
||||
|
|
@ -211,7 +213,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
|
|||
}),
|
||||
kind: 'canonical-research/v999',
|
||||
};
|
||||
await expect(f.repository.start(raw)).rejects.toThrow('Retained strategy versions');
|
||||
await expect(f.legacyWriter.start(raw)).rejects.toThrow('Retained strategy versions');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
await f.admit();
|
||||
await expect(f.repository.startCanonical({ ...f.request, name: 'different' })).rejects.toThrow(
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter';
|
||||
import { createBacktestRoutes } from '../../apps/stock/web-api/src/routes/backtest.routes';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import {
|
||||
|
|
@ -304,7 +304,7 @@ describe.skipIf(!url)('saved catalog backtest drafts on PostgreSQL', () => {
|
|||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toMatchObject({
|
||||
code: 'catalog_execution_unavailable',
|
||||
});
|
||||
const repository = new PostgresBacktestRunRepository(f.postgres);
|
||||
const repository = new LegacyBacktestRunWriter(f.postgres);
|
||||
const legacyConfig = parseBacktestRequest({
|
||||
...common,
|
||||
mode: 'backtest',
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter';
|
||||
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
|
|
@ -89,7 +89,7 @@ async function fixture() {
|
|||
const api = new BacktestServiceV2({ postgres, logger }, async () => {
|
||||
throw new Error('No remote execution in retention tests');
|
||||
});
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const repository = new LegacyBacktestRunWriter(postgres);
|
||||
const definition = await api.createBacktest(request, { autoStart: false });
|
||||
const snapshot = async (runId: string) =>
|
||||
parseBacktestRequest(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue