diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 29a11ec5..f7abbbb7 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -56,7 +56,8 @@ export async function runMigrations(container: IServiceContainer): Promise 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(); diff --git a/apps/stock/web-api/src/routes/backtests-v2.routes.ts b/apps/stock/web-api/src/routes/backtests-v2.routes.ts index b0d1bbdc..ec07774c 100644 --- a/apps/stock/web-api/src/routes/backtests-v2.routes.ts +++ b/apps/stock/web-api/src/routes/backtests-v2.routes.ts @@ -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); } diff --git a/apps/stock/web-api/src/services/backtest-v2.service.ts b/apps/stock/web-api/src/services/backtest-v2.service.ts index cd2e0956..4ef68b40 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -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 }; 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 { + async listBacktests(params: { + limit: number; + offset: number; + includeArchived?: boolean; + }): Promise { 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 { - 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 { + 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, diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index 6c6d2aa9..9f58b55d 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -2,6 +2,7 @@ import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { useWebSocket } from '@/hooks/useWebSocket'; +import { ArchiveBacktestDialog } from './components/ArchiveBacktestDialog'; import { BacktestConfiguration } from './components/BacktestConfiguration'; import { BacktestPlayback } from './components/BacktestPlayback'; import { BacktestTrades } from './components/BacktestTrades'; @@ -26,6 +27,7 @@ export function BacktestDetailPageV2() { const navigate = useNavigate(); const [activeTab, setActiveTab] = useState('details'); const [showNewRun, setShowNewRun] = useState(false); + const [showArchiveDialog, setShowArchiveDialog] = useState(false); const navigationGeneration = useRef(0); const { @@ -40,12 +42,15 @@ export function BacktestDetailPageV2() { hasPendingSubmission, loadBacktest, updateBacktest, + setBacktestArchived, createRun, cancelRun, cancelRequested, selectRun, refreshRun, } = useBacktestV2(); + const archived = Boolean(backtest?.archivedAt); + const canSubmit = !archived || hasPendingSubmission; // Notifications invalidate the same persisted-state reader used by polling. useWebSocket({ @@ -63,6 +68,7 @@ export function BacktestDetailPageV2() { useEffect(() => { navigationGeneration.current++; setShowNewRun(false); + setShowArchiveDialog(false); return () => { navigationGeneration.current++; }; @@ -83,7 +89,7 @@ export function BacktestDetailPageV2() { // Handle configuration save const handleConfigSubmit = useCallback( async (config: BacktestConfig) => { - if (!id) { + if (!id || archived) { return; } @@ -112,7 +118,7 @@ export function BacktestDetailPageV2() { }, }); }, - [id, updateBacktest, backtest] + [id, updateBacktest, backtest, archived] ); // Handle new run creation @@ -233,6 +239,7 @@ export function BacktestDetailPageV2() {

Run History

- {showNewRun && ( + {showNewRun && canSubmit && (

Run current settings

@@ -252,7 +259,7 @@ export function BacktestDetailPageV2() { onClick={() => { void handleCreateRun(); }} - disabled={isSubmitting} + disabled={isSubmitting || !canSubmit} className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors" > {isSubmitting @@ -286,7 +293,7 @@ export function BacktestDetailPageV2() {

@@ -358,6 +365,9 @@ export function BacktestDetailPageV2() {

{backtest?.name || 'Loading...'} + {archived && ( + Archived + )} {currentRun && ( - Run #{currentRun.runNumber} @@ -392,6 +402,16 @@ export function BacktestDetailPageV2() {

{/* Run Controls */} + {backtest && ( + + )} {currentRun && (
)} @@ -409,6 +430,15 @@ export function BacktestDetailPageV2() { {/* Tab Content */}
+ {archived && ( +

+ This backtest is archived. Restore it to edit settings or start new runs. Saved history + remains available; accepted runs can finish, recover or be cancelled. +

+ )} {submissionError && (

@@ -416,7 +446,7 @@ export function BacktestDetailPageV2() {

{!showNewRun && (
+ {showArchiveDialog && backtest && ( + setShowArchiveDialog(false)} + onConfirm={() => setBacktestArchived(backtest.id, !archived)} + /> + )}
); } diff --git a/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx index 3b7e88f1..9e5e238b 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx @@ -1,9 +1,8 @@ import { PlusIcon } from '@heroicons/react/24/solid'; import type { ColumnDef } from '@tanstack/react-table'; -import { useEffect, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { DataTable } from '@/components/ui/DataTable/DataTable'; -import { browserLog } from '@/utils/browserLog'; import { CreateBacktestDialog } from './components/CreateBacktestDialog'; import { backtestApiV2, type Backtest } from './services/backtestApiV2'; @@ -13,31 +12,50 @@ export function BacktestListPageV2() { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [showCreateDialog, setShowCreateDialog] = useState(false); + const [includeArchived, setIncludeArchived] = useState(false); + const request = useRef(null); - const loadBacktests = async () => { + const loadBacktests = useCallback(async () => { + request.current?.abort(); + const controller = new AbortController(); + request.current = controller; setIsLoading(true); setError(null); + setBacktests([]); try { - const data = await backtestApiV2.listBacktests(); - setBacktests(data); + const data = await backtestApiV2.listBacktests(50, 0, includeArchived, controller.signal); + if (!controller.signal.aborted) { + setBacktests(data); + } } catch (err) { - setError('Failed to load backtests'); - browserLog.error(err); + if (!controller.signal.aborted) { + setError(err instanceof Error ? err.message : 'Failed to load backtests'); + } } finally { - setIsLoading(false); + if (!controller.signal.aborted) { + setIsLoading(false); + } } - }; + }, [includeArchived]); useEffect(() => { - loadBacktests(); - }, []); + void loadBacktests(); + return () => request.current?.abort(); + }, [loadBacktests]); const columns: ColumnDef[] = [ { accessorKey: 'name', header: 'Name', size: 200, - cell: ({ row }) =>
{row.original.name}
, + cell: ({ row }) => ( +
+ {row.original.name} + {row.original.archivedAt && ( + Archived + )} +
+ ), }, { accessorKey: 'strategy', @@ -104,12 +122,40 @@ export function BacktestListPageV2() {
+ + {isLoading && ( +

+ Loading backtests... +

+ )} {error && (
- {error} +

{error}

+
)} + {!isLoading && !error && backtests.length === 0 && ( +

+ {includeArchived + ? 'No backtests yet.' + : 'No active backtests. Create one or show archived backtests.'} +

+ )} +
Promise; + onClose: () => void; +}) { + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const pending = useRef(false); + const active = useRef(true); + const title = archived ? 'Archive backtest' : 'Restore backtest'; + useEffect(() => { + active.current = true; + return () => { + active.current = false; + }; + }, []); + const confirm = async () => { + if (pending.current) { + return; + } + pending.current = true; + setSaving(true); + setError(null); + try { + await onConfirm(); + if (active.current) { + onClose(); + } + } catch (failure) { + if (active.current) { + setError(failure instanceof Error ? failure.message : 'Could not change archive status'); + } + } finally { + pending.current = false; + if (active.current) { + setSaving(false); + } + } + }; + return ( + { + if (!open && !pending.current) { + onClose(); + } + }} + > + +
+ + {title} + +

{name}

+

+ {archived + ? 'Saved runs, results and dataset links remain available. Accepted runs can finish, recover or be cancelled. Restore the backtest to edit it or start new runs.' + : 'Restore this backtest to the active list and allow editing and new runs.'} +

+ {error && ( +

+ {error} +

+ )} + {saving && ( +

+ {archived ? 'Archiving...' : 'Restoring...'} +

+ )} +
+ + +
+
+
+
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx b/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx index fa80ebe1..f8634105 100644 --- a/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx +++ b/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx @@ -8,6 +8,7 @@ interface RunControlsCompactProps { onRerun: (speed: number | null) => void; isSubmitting?: boolean; hasPendingSubmission?: boolean; + archived?: boolean; } export function RunControlsCompact({ @@ -17,6 +18,7 @@ export function RunControlsCompact({ onRerun, isSubmitting = false, hasPendingSubmission = false, + archived = false, }: RunControlsCompactProps) { const active = ['pending', 'running', 'paused'].includes(run.status); const requested = active && (cancelRequested || run.cancelRequested); @@ -42,7 +44,7 @@ export function RunControlsCompact({ )}