feat(research): archive backtests and protect retained evidence
This commit is contained in:
parent
4a2e5ad362
commit
8cca0ee588
25 changed files with 1550 additions and 79 deletions
|
|
@ -69,6 +69,7 @@ async function fixture() {
|
|||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'17-research-retention.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -202,16 +203,24 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
|
|||
{ manifest: { ...manifest(), sources: [] }, bars: [{}] },
|
||||
{ manifest: { version: 2 }, bars: [] },
|
||||
];
|
||||
for (const payload of payloads) {
|
||||
await f.pool.query('DELETE FROM backtest_datasets');
|
||||
await f.insert(hash, payload);
|
||||
for (const [index, payload] of payloads.entries()) {
|
||||
const key = String(index + 1).repeat(64);
|
||||
const row = structuredClone(payload);
|
||||
// Preserve each malformed shape while matching the storage key except in the identity-mismatch case.
|
||||
if (index > 0 && 'hash' in row.manifest) {
|
||||
row.manifest.hash = key;
|
||||
}
|
||||
await f.insert(key, row);
|
||||
await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [
|
||||
saved.id,
|
||||
JSON.stringify(request().config),
|
||||
JSON.stringify({ ...request().config, datasetHash: key }),
|
||||
]);
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow();
|
||||
}
|
||||
await f.pool.query('DELETE FROM backtest_datasets');
|
||||
await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [
|
||||
saved.id,
|
||||
{ ...request().config, datasetHash: 'e'.repeat(64) },
|
||||
]);
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow('not found');
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
||||
|
|
@ -297,7 +306,7 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
|
|||
'UPDATE backtests SET symbols=\'["OTHER.TEST"]\',config=\'{"datasetHash":"bad"}\' WHERE id=$1',
|
||||
[saved.id]
|
||||
);
|
||||
await f.pool.query('DELETE FROM backtest_datasets');
|
||||
await expect(f.pool.query('DELETE FROM backtest_datasets')).rejects.toThrow();
|
||||
const retried = await f.api.createRun({ backtestId: saved.id }, submission);
|
||||
expect(retried.id).toBe(first.id);
|
||||
expect(retried.dataset).toEqual(first.dataset);
|
||||
|
|
@ -335,8 +344,12 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
|
|||
status: 'failed',
|
||||
dataset: { requestedHash: null, pinnedHash: hash, source: 'eod', state: 'pinned' },
|
||||
});
|
||||
await f.pool.query('UPDATE runs SET request_snapshot=NULL WHERE id=$1', [run.id]);
|
||||
expect((await f.api.getRun(run.id))!.dataset).toEqual({
|
||||
const legacyRunId = randomUUID();
|
||||
await f.pool.query(
|
||||
"INSERT INTO runs(id,backtest_id,run_number,status,dataset_hash) VALUES ($1,$2,2,'completed',$3)",
|
||||
[legacyRunId, saved.id, hash]
|
||||
);
|
||||
expect((await f.api.getRun(legacyRunId))!.dataset).toEqual({
|
||||
requestedHash: null,
|
||||
pinnedHash: hash,
|
||||
source: null,
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ async function fixture() {
|
|||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'17-research-retention.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
@ -558,12 +559,46 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const config = await f.snapshot(run.id);
|
||||
const claim = await f.repository.start(config);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
await f.repository.freezeDataset(run.id, claim.attemptId, dataset);
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_datasets SET payload = jsonb_set(payload, '{bars,0,volume}', '0'::jsonb) WHERE hash = $1",
|
||||
[dataset.manifest.hash]
|
||||
);
|
||||
// Model corrupt historical storage at initial insertion; retained evidence cannot be edited.
|
||||
const corrupt = structuredClone(dataset);
|
||||
corrupt.bars[0]!.volume = 0;
|
||||
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES ($1,$2)', [
|
||||
dataset.manifest.hash,
|
||||
corrupt,
|
||||
]);
|
||||
await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [
|
||||
run.id,
|
||||
dataset.manifest.hash,
|
||||
]);
|
||||
const reads = f.history.reads;
|
||||
f.history.unavailable = true;
|
||||
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
await expect(f.runner.runQueued(run.id)).rejects.toThrow('hash/content');
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('failed');
|
||||
expect(await f.api.getRunResults(run.id)).toBeNull();
|
||||
expect(f.history.reads).toBe(reads);
|
||||
});
|
||||
|
||||
test('a missing retained dataset fails a historical request without provider fallback', async () => {
|
||||
const f = await fixture();
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(
|
||||
{ ...f.definition, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
|
||||
{ runId, backtestId: f.definition.id }
|
||||
);
|
||||
// Imported history can reference unavailable storage; retain its request and report the loss.
|
||||
await f.pool.query(
|
||||
'INSERT INTO runs(id,backtest_id,run_number,request_snapshot) VALUES ($1,$2,1,$3)',
|
||||
[runId, f.definition.id, snapshot]
|
||||
);
|
||||
await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]);
|
||||
f.history.unavailable = true;
|
||||
await expect(f.runner.runQueued(runId)).rejects.toThrow('Frozen dataset not found');
|
||||
expect(f.history.reads).toBe(0);
|
||||
expect((await f.api.getRun(runId))?.status).toBe('failed');
|
||||
expect(await f.api.getRunResults(runId)).toBeNull();
|
||||
});
|
||||
|
||||
test('an explicit dataset replay rejects a different listing or date range', async () => {
|
||||
|
|
@ -880,8 +915,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
|
||||
test('invalid persisted snapshots become failed instead of remaining stranded pending', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.pool.query("UPDATE runs SET request_snapshot = '{}' WHERE id = $1", [run.id]);
|
||||
const run = { id: randomUUID() };
|
||||
// A legacy malformed snapshot is inserted as found, not fabricated by editing retained evidence.
|
||||
await f.pool.query(
|
||||
"INSERT INTO runs(id,backtest_id,run_number,request_snapshot) VALUES ($1,$2,1,'{}')",
|
||||
[run.id, f.definition.id]
|
||||
);
|
||||
await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [run.id]);
|
||||
await expect(f.runner.runQueued(run.id)).rejects.toThrow();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('failed');
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(0);
|
||||
|
|
@ -889,12 +929,14 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
|
||||
test('migration replay preserves leased owners, backfills legacy pending snapshots, and fails ownerless legacy runs', async () => {
|
||||
const f = await fixture();
|
||||
const pending = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const pending = { id: randomUUID() };
|
||||
await f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES ($1,$2,1)', [
|
||||
pending.id,
|
||||
f.definition.id,
|
||||
]);
|
||||
const active = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const oldActive = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(active.id));
|
||||
await f.pool.query('DELETE FROM backtest_dispatch WHERE run_id = $1', [pending.id]);
|
||||
await f.pool.query('UPDATE runs SET request_snapshot = NULL WHERE id = $1', [pending.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),
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ const migrations = [
|
|||
'14-backtest-submission.sql',
|
||||
'15-canonical-paper-intents.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
@ -134,7 +135,7 @@ async function fixture() {
|
|||
describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
||||
test('submission migration preserves legacy NULL-key runs and enforces complete key records', async () => {
|
||||
const f = await fixture();
|
||||
for (const filename of migrations.filter(name => name !== '14-backtest-submission.sql')) {
|
||||
for (const filename of migrations.filter(name => name < '14-backtest-submission.sql')) {
|
||||
await f.pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
);
|
||||
|
|
@ -160,7 +161,10 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
|||
null,
|
||||
]);
|
||||
await expect(
|
||||
f.pool.query("UPDATE runs SET submission_key = 'incomplete' WHERE id = $1", [runId])
|
||||
f.pool.query(
|
||||
"INSERT INTO runs(id,backtest_id,run_number,submission_key) VALUES ($1,$2,2,'incomplete')",
|
||||
[randomUUID(), backtestId]
|
||||
)
|
||||
).rejects.toThrow('runs_submission_complete');
|
||||
await f.startup().run();
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1);
|
||||
|
|
|
|||
460
test/postgres/research-retention.test.ts
Normal file
460
test/postgres/research-retention.test.ts
Normal file
|
|
@ -0,0 +1,460 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
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 { 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';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('research-retention-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
const sql = (name: string) =>
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8');
|
||||
const retention = sql('17-research-retention.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-01-05T00:00:00.000Z',
|
||||
initialCapital: 1000,
|
||||
config: { fastPeriod: 1, slowPeriod: 2, commission: 0, slippage: 0 },
|
||||
};
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(install = true) {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_retention_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
for (const name of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'08-create-runs-table.sql',
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
// The pre17 setup mode is only for constructing historical/corrupt imported rows.
|
||||
await pool.query('ALTER TABLE backtests ADD COLUMN archived_at timestamptz');
|
||||
if (install) {
|
||||
await pool.query(retention);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const api = new BacktestServiceV2({ postgres, logger }, async () => {
|
||||
throw new Error('No remote execution in retention tests');
|
||||
});
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const definition = await api.createBacktest(request, { autoStart: false });
|
||||
const snapshot = async (runId: string) =>
|
||||
parseBacktestRequest(
|
||||
(await pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
|
||||
.request_snapshot
|
||||
);
|
||||
const dataset = async (runId: string) =>
|
||||
loadDataset(
|
||||
{
|
||||
async getHistoricalBars() {
|
||||
return [0, 1, 2].map(day => ({
|
||||
symbol: 'FIXTURE.TEST',
|
||||
timestamp: new Date(Date.parse(request.startDate) + day * 86400000),
|
||||
source: 'eod' as const,
|
||||
open: 10,
|
||||
high: 11,
|
||||
low: 9,
|
||||
close: 10,
|
||||
volume: 100,
|
||||
}));
|
||||
},
|
||||
},
|
||||
await snapshot(runId)
|
||||
);
|
||||
const app = new Hono().route('/', createBacktestV2Routes({ postgres, logger }));
|
||||
return { pool, schema, postgres, api, repository, definition, snapshot, dataset, app };
|
||||
}
|
||||
// These fixed values exercise persistence only; no financial simulation is claimed.
|
||||
function result(runId: string, backtestId: string, dataset: HistoricalDataset): BacktestRunResult {
|
||||
return {
|
||||
runId,
|
||||
backtestId,
|
||||
engine: 'native',
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
config: {
|
||||
name: request.name,
|
||||
strategy: request.strategy,
|
||||
symbols: request.symbols,
|
||||
startDate: request.startDate,
|
||||
endDate: request.endDate,
|
||||
initialCapital: request.initialCapital,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
parameters: request.config,
|
||||
dataset: dataset.manifest,
|
||||
},
|
||||
metrics: {
|
||||
totalReturn: 0,
|
||||
sharpeRatio: null,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
totalTrades: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
},
|
||||
equity: [],
|
||||
ohlcData: {},
|
||||
trades: [],
|
||||
positions: [],
|
||||
analytics: { exposureTime: null },
|
||||
executionTime: 1,
|
||||
};
|
||||
}
|
||||
async function waitForBlocked(pool: Pool, schema: string) {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
const waiting = await pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
|
||||
[schema]
|
||||
);
|
||||
if (waiting.rows.length) {
|
||||
return;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
throw new Error('Expected concurrent operation to wait for the parent lock');
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
||||
test('retained_run_delete_restricted_postgres blocks raw cascades, mutations and truncation while preserving runless legacy deletion', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun(
|
||||
{ backtestId: f.definition.id },
|
||||
{ principal: 'operator', key: 'retained' }
|
||||
);
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.freezeDataset(
|
||||
run.id,
|
||||
claim.attemptId,
|
||||
await f.dataset(run.id)
|
||||
);
|
||||
await f.repository.complete(result(run.id, f.definition.id, frozen), claim.attemptId);
|
||||
await expect(f.api.deleteBacktest(f.definition.id)).rejects.toMatchObject({
|
||||
code: 'retained_runs',
|
||||
runCount: 1,
|
||||
});
|
||||
for (const statement of [
|
||||
'DELETE FROM backtests',
|
||||
'DELETE FROM runs',
|
||||
'DELETE FROM backtest_results',
|
||||
'DELETE FROM backtest_datasets',
|
||||
"UPDATE backtest_results SET metrics='{}'",
|
||||
"UPDATE backtest_datasets SET payload='{}'",
|
||||
'TRUNCATE backtests CASCADE',
|
||||
'TRUNCATE runs CASCADE',
|
||||
'TRUNCATE backtest_results',
|
||||
'TRUNCATE backtest_datasets CASCADE',
|
||||
]) {
|
||||
await expect(f.pool.query(statement)).rejects.toThrow();
|
||||
}
|
||||
const empty = await f.api.createBacktest(
|
||||
{ ...request, name: 'Unreferenced legacy definition' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
await f.api.deleteBacktest(empty.id);
|
||||
expect(await f.api.getBacktest(empty.id)).toBeNull();
|
||||
await f.api.deleteBacktest(empty.id);
|
||||
expect(await f.api.getRunResults(run.id)).not.toBeNull();
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
||||
1
|
||||
);
|
||||
});
|
||||
|
||||
test('archive_preserves_replay hides discovery only and rejects new admission or edits until restored', async () => {
|
||||
const f = await fixture();
|
||||
const receipt = { principal: 'operator' as const, key: 'archive-retry' };
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id }, receipt);
|
||||
const before = await f.snapshot(run.id);
|
||||
const archived = await f.api.archiveBacktest(f.definition.id, true);
|
||||
expect(archived?.archivedAt).toBeString();
|
||||
expect((await f.api.archiveBacktest(f.definition.id, true))?.archivedAt).toBe(
|
||||
archived?.archivedAt ?? null
|
||||
);
|
||||
expect(await f.api.listBacktests({ limit: 50, offset: 0 })).toEqual([]);
|
||||
expect(await f.api.listBacktests({ limit: 50, offset: 0, includeArchived: true })).toHaveLength(
|
||||
1
|
||||
);
|
||||
expect((await f.api.getBacktest(f.definition.id))?.archivedAt).toBe(
|
||||
archived?.archivedAt ?? null
|
||||
);
|
||||
expect(await f.api.listRuns(f.definition.id)).toHaveLength(1);
|
||||
expect((await f.api.createRun({ backtestId: f.definition.id }, receipt)).id).toBe(run.id);
|
||||
expect(await f.snapshot(run.id)).toEqual(before);
|
||||
await expect(
|
||||
f.api.createRun({ backtestId: f.definition.id }, { ...receipt, key: 'fresh' })
|
||||
).rejects.toMatchObject({ code: 'backtest_archived' });
|
||||
await expect(
|
||||
f.api.updateBacktest(f.definition.id, { name: 'Cannot edit' })
|
||||
).rejects.toMatchObject({ code: 'backtest_archived' });
|
||||
await expect(
|
||||
f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 5 }, receipt)
|
||||
).rejects.toThrow('submission key');
|
||||
expect((await f.api.archiveBacktest(f.definition.id, false))?.archivedAt).toBeNull();
|
||||
expect((await f.api.updateBacktest(f.definition.id, { name: 'Restored' }))?.name).toBe(
|
||||
'Restored'
|
||||
);
|
||||
expect((await f.api.createRun({ backtestId: f.definition.id })).runNumber).toBe(2);
|
||||
});
|
||||
|
||||
test('archive and admission use one parent lock, including direct repository inserts', async () => {
|
||||
const f = await fixture();
|
||||
const accepted = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.definition.id]);
|
||||
const pending = f.api.createRun({ backtestId: f.definition.id }).then(
|
||||
() => null,
|
||||
error => error
|
||||
);
|
||||
await waitForBlocked(f.pool, f.schema);
|
||||
await blocker.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.definition.id]);
|
||||
await blocker.query('COMMIT');
|
||||
blocker.release();
|
||||
expect(await pending).toMatchObject({ code: 'backtest_archived' });
|
||||
const direct = { ...(await f.snapshot(accepted.id)), runId: undefined };
|
||||
await expect(f.repository.start(direct)).rejects.toThrow('archived');
|
||||
await expect(
|
||||
f.pool.query("INSERT INTO runs(backtest_id,run_number,status) VALUES($1,99,'pending')", [
|
||||
f.definition.id,
|
||||
])
|
||||
).rejects.toThrow('archived');
|
||||
expect(await f.api.listRuns(f.definition.id)).toHaveLength(1);
|
||||
// Its pre-archive request remains accepted and can claim normally.
|
||||
expect((await f.repository.start(await f.snapshot(accepted.id))).runId).toBe(accepted.id);
|
||||
});
|
||||
|
||||
test('accepted archived work retains binding, lease recovery, controls, progress and terminal result writes', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.api.archiveBacktest(f.definition.id, true);
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.freezeDataset(
|
||||
run.id,
|
||||
claim.attemptId,
|
||||
await f.dataset(run.id)
|
||||
);
|
||||
await f.repository.freezeDataset(run.id, claim.attemptId, frozen);
|
||||
await f.repository.heartbeat(run.id, claim.attemptId);
|
||||
await f.repository.updateProgress(run.id, 25, request.startDate, claim.attemptId);
|
||||
await f.repository.updateControl(
|
||||
run.id,
|
||||
{ status: 'paused', speedMultiplier: 2 },
|
||||
claim.attemptId
|
||||
);
|
||||
await f.pool.query("UPDATE runs SET lease_expires_at=NOW()-INTERVAL '1 second' WHERE id=$1", [
|
||||
run.id,
|
||||
]);
|
||||
const delivered: unknown[] = [];
|
||||
const dispatcher = new BacktestDispatcher(
|
||||
f.postgres,
|
||||
{
|
||||
async add(...args) {
|
||||
delivered.push(args);
|
||||
return null as never;
|
||||
},
|
||||
},
|
||||
logger
|
||||
);
|
||||
await dispatcher.tick();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('pending');
|
||||
expect(delivered).toHaveLength(1);
|
||||
const retry = await f.repository.start(await f.snapshot(run.id));
|
||||
expect(retry.attemptId).not.toBe(claim.attemptId);
|
||||
await expect(f.repository.heartbeat(run.id, claim.attemptId)).rejects.toThrow('lease lost');
|
||||
expect(await f.repository.loadDataset(run.id, retry.attemptId)).toEqual(frozen);
|
||||
await f.api.updateRunProgress(run.id, { progress: 90, attemptId: retry.attemptId });
|
||||
await f.repository.complete(result(run.id, f.definition.id, frozen), retry.attemptId);
|
||||
const saved = await f.api.getRunResults(run.id);
|
||||
expect(saved?.config.dataset?.hash).toBe(frozen.manifest.hash);
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2);
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('completed');
|
||||
await f.pool.query(retention);
|
||||
expect(await f.api.getRunResults(run.id)).toEqual(saved);
|
||||
await dispatcher.shutdown();
|
||||
});
|
||||
|
||||
test('run identity and frozen inputs reject rewrites while legacy NULL snapshots can be populated once', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun(
|
||||
{ backtestId: f.definition.id },
|
||||
{ principal: 'service', key: 'immutable' }
|
||||
);
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
await f.repository.freezeDataset(run.id, claim.attemptId, await f.dataset(run.id));
|
||||
const other = await f.api.createBacktest(request, { autoStart: false });
|
||||
for (const [field, value] of [
|
||||
['id', randomUUID()],
|
||||
['backtest_id', other.id],
|
||||
['run_number', 99],
|
||||
['created_at', '2020-01-01'],
|
||||
['request_snapshot', '{}'],
|
||||
['request_snapshot', null],
|
||||
['submission_key', 'changed'],
|
||||
['submission_principal', 'operator'],
|
||||
['submission_hash', 'changed'],
|
||||
['dataset_hash', null],
|
||||
['dataset_hash', 'f'.repeat(64)],
|
||||
]) {
|
||||
await expect(
|
||||
f.pool.query(`UPDATE runs SET ${field}=$2 WHERE id=$1`, [run.id, value])
|
||||
).rejects.toThrow('immutable');
|
||||
}
|
||||
const legacy = randomUUID();
|
||||
await f.pool.query(
|
||||
"INSERT INTO runs(id,backtest_id,run_number,status) VALUES($1,$2,2,'pending')",
|
||||
[legacy, f.definition.id]
|
||||
);
|
||||
await f.api.archiveBacktest(f.definition.id, true);
|
||||
await f.pool.query(sql('10-durable-backtest-dispatch.sql'));
|
||||
const frozen = await f.snapshot(legacy);
|
||||
expect(frozen.runId).toBe(legacy);
|
||||
await f.pool.query(sql('10-durable-backtest-dispatch.sql'));
|
||||
expect(await f.snapshot(legacy)).toEqual(frozen);
|
||||
await expect(
|
||||
f.pool.query("UPDATE runs SET request_snapshot='{}' WHERE id=$1", [legacy])
|
||||
).rejects.toThrow('immutable');
|
||||
await f.api.archiveBacktest(f.definition.id, false);
|
||||
const terminalLegacy = randomUUID();
|
||||
await f.pool.query(
|
||||
"INSERT INTO runs(id,backtest_id,run_number,status) VALUES($1,$2,3,'completed')",
|
||||
[terminalLegacy, f.definition.id]
|
||||
);
|
||||
await expect(
|
||||
f.pool.query("UPDATE runs SET request_snapshot='{}' WHERE id=$1", [terminalLegacy])
|
||||
).rejects.toThrow('immutable');
|
||||
});
|
||||
|
||||
test('pending and running cancellation/failure still terminate accepted archived requests', async () => {
|
||||
const f = await fixture();
|
||||
const runs = await Promise.all(
|
||||
Array.from({ length: 4 }, () => f.api.createRun({ backtestId: f.definition.id }))
|
||||
);
|
||||
await f.api.archiveBacktest(f.definition.id, true);
|
||||
await f.api.cancelRun(runs[0]!.id);
|
||||
await f.api.cancelRun(runs[0]!.id);
|
||||
await f.repository.rejectPending(runs[1]!.id, 'Fixture validation failure');
|
||||
const active = await f.repository.start(await f.snapshot(runs[2]!.id));
|
||||
await f.api.cancelRun(active.runId);
|
||||
expect(await f.repository.heartbeat(active.runId, active.attemptId)).toEqual({
|
||||
cancelRequested: true,
|
||||
});
|
||||
await f.repository.cancel(active.runId, active.attemptId);
|
||||
const failed = await f.repository.start(await f.snapshot(runs[3]!.id));
|
||||
await f.repository.fail(failed.runId, 'Fixture execution failure', failed.attemptId);
|
||||
expect((await f.api.listRuns(f.definition.id)).map(run => run.status).sort()).toEqual([
|
||||
'cancelled',
|
||||
'cancelled',
|
||||
'failed',
|
||||
'failed',
|
||||
]);
|
||||
});
|
||||
|
||||
test('preexisting corrupted datasets remain immutable and fail checksum verification on retrieval', async () => {
|
||||
const f = await fixture(false);
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const dataset = await f.repository.freezeDataset(
|
||||
run.id,
|
||||
claim.attemptId,
|
||||
await f.dataset(run.id)
|
||||
);
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,volume}','0') WHERE hash=$1",
|
||||
[dataset.manifest.hash]
|
||||
);
|
||||
await f.pool.query(retention);
|
||||
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
|
||||
await expect(
|
||||
f.pool.query('UPDATE backtest_datasets SET payload=$2 WHERE hash=$1', [
|
||||
dataset.manifest.hash,
|
||||
JSON.stringify(dataset),
|
||||
])
|
||||
).rejects.toThrow('cannot be rewritten');
|
||||
});
|
||||
|
||||
test('HTTP archive/list/delete errors are actionable and direct saved resources remain accessible', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const archived = await f.app.request(`/api/v2/backtests/${f.definition.id}/archive`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ archived: true }),
|
||||
});
|
||||
expect(archived.status).toBe(200);
|
||||
expect((await archived.json()).archivedAt).toBeString();
|
||||
expect(await (await f.app.request('/api/v2/backtests')).json()).toEqual([]);
|
||||
expect(
|
||||
await (await f.app.request('/api/v2/backtests?includeArchived=true')).json()
|
||||
).toHaveLength(1);
|
||||
expect((await f.app.request(`/api/v2/runs/${run.id}`)).status).toBe(200);
|
||||
expect((await f.app.request(`/api/v2/backtests/${f.definition.id}`)).status).toBe(200);
|
||||
const deleted = await f.app.request(`/api/v2/backtests/${f.definition.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
expect(deleted.status).toBe(409);
|
||||
expect(await deleted.json()).toMatchObject({ code: 'retained_runs', runCount: 1 });
|
||||
const submit = await f.app.request(`/api/v2/backtests/${f.definition.id}/runs`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
});
|
||||
expect(submit.status).toBe(409);
|
||||
expect(await submit.json()).toMatchObject({ code: 'backtest_archived' });
|
||||
const edit = await f.app.request(`/api/v2/backtests/${f.definition.id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ name: 'Changed' }),
|
||||
});
|
||||
expect(edit.status).toBe(409);
|
||||
expect(await edit.json()).toMatchObject({ code: 'backtest_archived' });
|
||||
expect(
|
||||
(
|
||||
await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, {
|
||||
method: 'POST',
|
||||
body: '{"archived":true}',
|
||||
})
|
||||
).status
|
||||
).toBe(404);
|
||||
expect(
|
||||
(await f.app.request(`/api/v2/backtests/${randomUUID()}`, { method: 'DELETE' })).status
|
||||
).toBe(204);
|
||||
});
|
||||
});
|
||||
|
|
@ -64,6 +64,8 @@ async function fixture() {
|
|||
'11-simulation-execution-ledger.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'17-research-retention.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue