feat(research): archive backtests and protect retained evidence

This commit is contained in:
Boki 2026-10-23 20:18:58 -04:00
parent 4a2e5ad362
commit 8cca0ee588
25 changed files with 1550 additions and 79 deletions

View file

@ -56,7 +56,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
f === '13-strategy-recovery.sql' ||
f === '14-backtest-submission.sql' ||
f === '15-canonical-paper-intents.sql' ||
f === '16-strategy-catalog.sql')
f === '16-strategy-catalog.sql' ||
f === '17-research-retention.sql')
) // Explicit additive migration allowlist; never replay destructive init migrations
.sort();

View file

@ -1,4 +1,5 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { getVerifiedHttpPrincipal } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
@ -6,7 +7,11 @@ import {
isBacktestRequestError,
rejectCatalogVersionReferences,
} from '@stock-bot/stock-config/backtest';
import { BacktestServiceV2, RunSubmissionConflictError } from '../services/backtest-v2.service';
import {
BacktestRetentionError,
BacktestServiceV2,
RunSubmissionConflictError,
} from '../services/backtest-v2.service';
const logger = getLogger('backtests-v2-routes');
@ -19,8 +24,15 @@ export function createBacktestV2Routes(container: IServiceContainer) {
try {
const limit = parseInt(c.req.query('limit') || '50');
const offset = parseInt(c.req.query('offset') || '0');
const backtests = await backtestService.listBacktests({ limit, offset });
const archiveQuery = c.req.query('includeArchived');
if (archiveQuery !== undefined && archiveQuery !== 'true' && archiveQuery !== 'false') {
return c.json({ error: 'includeArchived must be true or false' }, 400);
}
const backtests = await backtestService.listBacktests({
limit,
offset,
includeArchived: archiveQuery === 'true',
});
return c.json(backtests);
} catch (error) {
logger.error('Failed to list backtests', error);
@ -69,6 +81,9 @@ export function createBacktestV2Routes(container: IServiceContainer) {
return c.json(backtest);
} catch (error) {
logger.error('Failed to update backtest', error);
if (error instanceof BacktestRetentionError) {
return c.json({ error: error.message, code: error.code }, 409);
}
if (isBacktestRequestError(error)) {
return c.json({ error: error.message }, 400);
}
@ -82,10 +97,30 @@ export function createBacktestV2Routes(container: IServiceContainer) {
return c.body(null, 204);
} catch (error) {
logger.error('Failed to delete backtest', error);
if (error instanceof BacktestRetentionError) {
return c.json({ error: error.message, code: error.code, runCount: error.runCount }, 409);
}
return c.json({ error: 'Failed to delete backtest' }, 500);
}
});
app.post('/api/v2/backtests/:id/archive', async c => {
try {
const body = z
.object({ archived: z.boolean() })
.strict()
.parse(await c.req.json());
const backtest = await backtestService.archiveBacktest(c.req.param('id'), body.archived);
return backtest ? c.json(backtest) : c.json({ error: 'Backtest not found' }, 404);
} catch (error) {
if (error instanceof z.ZodError || error instanceof SyntaxError) {
return c.json({ error: 'Archive request must contain only archived: boolean' }, 400);
}
logger.error('Failed to archive backtest', error);
return c.json({ error: 'Failed to archive backtest' }, 500);
}
});
// Run endpoints
app.get('/api/v2/backtests/:backtestId/runs', async c => {
try {
@ -120,6 +155,9 @@ export function createBacktestV2Routes(container: IServiceContainer) {
return c.json(run, 202);
} catch (error) {
logger.error('Failed to create run', error);
if (error instanceof BacktestRetentionError) {
return c.json({ error: error.message, code: error.code }, 409);
}
if (error instanceof RunSubmissionConflictError) {
return c.json({ error: error.message }, 409);
}

View file

@ -35,6 +35,7 @@ export interface BacktestRequest {
export interface Backtest {
id: string;
archivedAt: string | null;
name: string;
strategy: string;
symbols: string[];
@ -82,6 +83,19 @@ export class RunSubmissionConflictError extends Error {
}
}
export class BacktestRetentionError extends Error {
constructor(
public readonly code: 'backtest_archived' | 'retained_runs',
public readonly runCount?: number
) {
super(
code === 'backtest_archived'
? 'Backtest is archived; restore it before editing or submitting a new run'
: `Backtest has ${runCount} retained run(s); archive it to preserve results and reproducibility`
);
}
}
export class BacktestServiceV2 {
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
private wsHandler: WebSocketHandler | null = null;
@ -160,6 +174,9 @@ export class BacktestServiceV2 {
if (!locked.rows[0]) {
return null;
}
if (locked.rows[0].archived_at) {
throw new BacktestRetentionError('backtest_archived');
}
const existing = this.mapBacktest(locked.rows[0]);
const next = { ...existing, ...request };
await assertSelectedDatasetMatchesRequest(client, backtestRequestFromDefinition(next));
@ -217,19 +234,54 @@ export class BacktestServiceV2 {
});
}
async listBacktests(params: { limit: number; offset: number }): Promise<Backtest[]> {
async listBacktests(params: {
limit: number;
offset: number;
includeArchived?: boolean;
}): Promise<Backtest[]> {
const result = await this.container.postgres.query(
`SELECT * FROM backtests
WHERE ($3::boolean OR archived_at IS NULL)
ORDER BY created_at DESC
LIMIT $1 OFFSET $2`,
[params.limit, params.offset]
[params.limit, params.offset, params.includeArchived === true]
);
return result.rows.map(row => this.mapBacktest(row));
}
async deleteBacktest(id: string): Promise<void> {
await this.container.postgres.query('DELETE FROM backtests WHERE id = $1', [id]);
await this.container.postgres.transaction(async client => {
const parent = await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [id]);
if (!parent.rows[0]) {
return;
}
const retained = await client.query(
'SELECT count(*)::int AS count FROM runs WHERE backtest_id=$1',
[id]
);
const count = Number(retained.rows[0]?.count ?? 0);
if (count > 0) {
throw new BacktestRetentionError('retained_runs', count);
}
await client.query('DELETE FROM backtests WHERE id=$1', [id]);
});
}
async archiveBacktest(id: string, archived: boolean): Promise<Backtest | null> {
return this.container.postgres.transaction(async client => {
const parent = await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [id]);
if (!parent.rows[0]) {
return null;
}
const updated = await client.query(
`UPDATE backtests
SET archived_at=CASE WHEN $2::boolean THEN COALESCE(archived_at,NOW()) ELSE NULL END,
updated_at=NOW() WHERE id=$1 RETURNING *`,
[id, archived]
);
return this.mapBacktest(at(updated.rows, 0));
});
}
// Run operations
@ -281,6 +333,9 @@ export class BacktestServiceV2 {
if (concurrent) {
return concurrent;
}
if (at(parent.rows, 0).archived_at) {
throw new BacktestRetentionError('backtest_archived');
}
const definition = this.mapBacktest(at(parent.rows, 0));
const snapshot = backtestRequestFromDefinition(definition, {
runId,
@ -434,6 +489,7 @@ export class BacktestServiceV2 {
private mapBacktest(row: QueryResultRow): Backtest {
return {
id: row.id,
archivedAt: row.archived_at ? new Date(row.archived_at).toISOString() : null,
name: row.name,
strategy: row.strategy,
symbols: row.symbols,