475 lines
19 KiB
TypeScript
475 lines
19 KiB
TypeScript
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') +
|
|
'\n' +
|
|
sql('18-backtest-strategy-versions.sql') +
|
|
'\n' +
|
|
sql('19-canonical-research.sql') +
|
|
'\n' +
|
|
sql('21-run-reproduction.sql') +
|
|
sql('22-experiments.sql') +
|
|
'\n' +
|
|
sql('23-experiment-retries.sql') +
|
|
'\n' +
|
|
sql('24-chronological-validation.sql') +
|
|
'\n' +
|
|
sql('25-walk-forward.sql') +
|
|
'\n' +
|
|
sql('26-cost-sensitivity.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() {
|
|
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',
|
|
'16-strategy-catalog.sql',
|
|
]) {
|
|
await pool.query(sql(name));
|
|
}
|
|
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();
|
|
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.dataset(run.id);
|
|
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,
|
|
]);
|
|
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);
|
|
});
|
|
});
|