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
|
|
@ -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();
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
<h3 className="text-lg font-medium text-text-primary">Run History</h3>
|
||||
<button
|
||||
onClick={() => setShowNewRun(true)}
|
||||
disabled={archived}
|
||||
className="inline-flex items-center px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
<PlusIcon className="w-4 h-4 mr-2" />
|
||||
|
|
@ -240,7 +247,7 @@ export function BacktestDetailPageV2() {
|
|||
</button>
|
||||
</div>
|
||||
|
||||
{showNewRun && (
|
||||
{showNewRun && canSubmit && (
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-4 space-y-4">
|
||||
<h4 className="text-base font-medium text-text-primary">Run current settings</h4>
|
||||
<p className="text-sm text-text-secondary">
|
||||
|
|
@ -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() {
|
|||
<div className="max-w-4xl mx-auto">
|
||||
<BacktestConfiguration
|
||||
onSubmit={handleConfigSubmit}
|
||||
disabled={false}
|
||||
disabled={archived || isLoading}
|
||||
initialConfig={backtestConfig}
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -358,6 +365,9 @@ export function BacktestDetailPageV2() {
|
|||
<div className="px-2">
|
||||
<h1 className="text-sm font-bold text-text-primary flex items-center gap-1">
|
||||
{backtest?.name || 'Loading...'}
|
||||
{archived && (
|
||||
<span className="text-xs font-normal text-text-secondary">Archived</span>
|
||||
)}
|
||||
{currentRun && (
|
||||
<span className="text-text-secondary font-normal">
|
||||
- Run #{currentRun.runNumber}
|
||||
|
|
@ -392,6 +402,16 @@ export function BacktestDetailPageV2() {
|
|||
</div>
|
||||
|
||||
{/* Run Controls */}
|
||||
{backtest && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isLoading}
|
||||
onClick={() => setShowArchiveDialog(true)}
|
||||
className="px-3 py-2 text-sm text-text-secondary border border-border rounded-md disabled:opacity-50"
|
||||
>
|
||||
{archived ? 'Restore backtest' : 'Archive backtest'}
|
||||
</button>
|
||||
)}
|
||||
{currentRun && (
|
||||
<div className="px-4">
|
||||
<RunControlsCompact
|
||||
|
|
@ -401,6 +421,7 @@ export function BacktestDetailPageV2() {
|
|||
onRerun={handleRerun}
|
||||
isSubmitting={isSubmitting}
|
||||
hasPendingSubmission={hasPendingSubmission}
|
||||
archived={archived}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -409,6 +430,15 @@ export function BacktestDetailPageV2() {
|
|||
|
||||
{/* Tab Content */}
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden py-4">
|
||||
{archived && (
|
||||
<p
|
||||
role="status"
|
||||
className="mb-4 p-3 border border-border rounded-lg text-sm text-text-secondary"
|
||||
>
|
||||
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.
|
||||
</p>
|
||||
)}
|
||||
{submissionError && (
|
||||
<div className="mb-4 p-4 bg-error/10 border border-error/20 rounded-lg">
|
||||
<p role="alert" className="text-sm text-error">
|
||||
|
|
@ -416,7 +446,7 @@ export function BacktestDetailPageV2() {
|
|||
</p>
|
||||
{!showNewRun && (
|
||||
<button
|
||||
disabled={isSubmitting}
|
||||
disabled={isSubmitting || !canSubmit}
|
||||
className="mt-2 text-primary-500"
|
||||
onClick={() => void handleCreateRun()}
|
||||
>
|
||||
|
|
@ -440,6 +470,15 @@ export function BacktestDetailPageV2() {
|
|||
{currentRun && <RunDataset dataset={currentRun.dataset} />}
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">{renderTabContent()}</div>
|
||||
</div>
|
||||
{showArchiveDialog && backtest && (
|
||||
<ArchiveBacktestDialog
|
||||
key={backtest.id}
|
||||
name={backtest.name}
|
||||
archived={!archived}
|
||||
onClose={() => setShowArchiveDialog(false)}
|
||||
onConfirm={() => setBacktestArchived(backtest.id, !archived)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<string | null>(null);
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(false);
|
||||
const [includeArchived, setIncludeArchived] = useState(false);
|
||||
const request = useRef<AbortController | null>(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<Backtest>[] = [
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: 'Name',
|
||||
size: 200,
|
||||
cell: ({ row }) => <div className="font-medium text-text-primary">{row.original.name}</div>,
|
||||
cell: ({ row }) => (
|
||||
<div className="font-medium text-text-primary">
|
||||
{row.original.name}
|
||||
{row.original.archivedAt && (
|
||||
<span className="ml-2 text-xs text-text-secondary">Archived</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'strategy',
|
||||
|
|
@ -104,12 +122,40 @@ export function BacktestListPageV2() {
|
|||
</button>
|
||||
</div>
|
||||
|
||||
<label className="flex items-center gap-2 text-sm text-text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeArchived}
|
||||
onChange={event => setIncludeArchived(event.target.checked)}
|
||||
/>
|
||||
Show archived backtests
|
||||
</label>
|
||||
{isLoading && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Loading backtests...
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<div className="bg-error/10 border border-error text-error px-4 py-3 rounded-lg text-sm">
|
||||
{error}
|
||||
<p role="alert">{error}</p>
|
||||
<button
|
||||
type="button"
|
||||
className="mt-2 text-primary-500"
|
||||
onClick={() => void loadBacktests()}
|
||||
>
|
||||
Retry backtests
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && backtests.length === 0 && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
{includeArchived
|
||||
? 'No backtests yet.'
|
||||
: 'No active backtests. Create one or show archived backtests.'}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex-1 min-h-0">
|
||||
<DataTable
|
||||
data={backtests}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,101 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/Dialog';
|
||||
|
||||
export function ArchiveBacktestDialog({
|
||||
name,
|
||||
archived,
|
||||
onConfirm,
|
||||
onClose,
|
||||
}: {
|
||||
name: string;
|
||||
archived: boolean;
|
||||
onConfirm: () => Promise<void>;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(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 (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={open => {
|
||||
if (!open && !pending.current) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-lg">
|
||||
<div role="dialog" aria-modal="true" aria-label={title} className="space-y-4">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-text-primary">{name}</p>
|
||||
<p className="text-sm text-text-secondary">
|
||||
{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.'}
|
||||
</p>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{saving && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
{archived ? 'Archiving...' : 'Restoring...'}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 border border-border rounded-md text-sm text-text-primary disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={() => void confirm()}
|
||||
className="px-4 py-2 bg-primary-500 rounded-md text-sm text-white disabled:opacity-50"
|
||||
>
|
||||
{archived ? 'Confirm archive' : 'Confirm restore'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -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({
|
|||
)}
|
||||
<button
|
||||
onClick={() => onRerun(null)}
|
||||
disabled={isSubmitting}
|
||||
disabled={isSubmitting || (archived && !hasPendingSubmission)}
|
||||
className="p-1 rounded hover:bg-surface-tertiary transition-colors disabled:opacity-50"
|
||||
title={hasPendingSubmission ? 'Retry submission' : 'Run current settings'}
|
||||
aria-label={hasPendingSubmission ? 'Retry submission' : 'Run current settings'}
|
||||
|
|
|
|||
|
|
@ -249,6 +249,9 @@ export function useBacktestV2() {
|
|||
|
||||
const updateBacktest = useCallback(
|
||||
async (id: string, updates: Partial<CreateBacktestRequest>) => {
|
||||
if (backtest?.id === id && backtest.archivedAt) {
|
||||
throw new Error('Restore this archived backtest before editing its settings.');
|
||||
}
|
||||
const generation = ++backtestGeneration.current;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
|
|
@ -268,7 +271,7 @@ export function useBacktestV2() {
|
|||
}
|
||||
}
|
||||
},
|
||||
[]
|
||||
[backtest]
|
||||
);
|
||||
|
||||
const deleteBacktest = useCallback(
|
||||
|
|
@ -301,11 +304,36 @@ export function useBacktestV2() {
|
|||
[selectRun]
|
||||
);
|
||||
|
||||
const setBacktestArchived = useCallback(async (id: string, archived: boolean) => {
|
||||
const generation = ++backtestGeneration.current;
|
||||
setIsBacktestLoading(true);
|
||||
try {
|
||||
const updated = await backtestApiV2.setBacktestArchived(id, archived);
|
||||
if (
|
||||
mounted.current &&
|
||||
generation === backtestGeneration.current &&
|
||||
loadedBacktestId.current === id
|
||||
) {
|
||||
// Archival changes only the template. Keep selected results, active run
|
||||
// monitoring and custody of any ambiguous submission key/body intact.
|
||||
setBacktest(updated);
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setIsBacktestLoading(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const createRun = useCallback(
|
||||
async (speedMultiplier: number | null = null) => {
|
||||
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
|
||||
return undefined;
|
||||
}
|
||||
if (backtest.archivedAt && !submission.current) {
|
||||
setSubmissionError('Restore this archived backtest before starting a new run.');
|
||||
return undefined;
|
||||
}
|
||||
const intent = (submission.current ??= {
|
||||
backtestId: backtest.id,
|
||||
key: crypto.randomUUID(),
|
||||
|
|
@ -399,6 +427,7 @@ export function useBacktestV2() {
|
|||
createBacktest,
|
||||
updateBacktest,
|
||||
deleteBacktest,
|
||||
setBacktestArchived,
|
||||
createRun,
|
||||
cancelRun,
|
||||
selectRun,
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ export interface Backtest {
|
|||
config: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
archivedAt: string | null;
|
||||
}
|
||||
|
||||
export interface Run {
|
||||
|
|
@ -125,13 +126,19 @@ export const backtestApiV2 = {
|
|||
return response.json();
|
||||
},
|
||||
|
||||
async listBacktests(limit = 50, offset = 0): Promise<Backtest[]> {
|
||||
async listBacktests(
|
||||
limit = 50,
|
||||
offset = 0,
|
||||
includeArchived = false,
|
||||
signal?: AbortSignal
|
||||
): Promise<Backtest[]> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}`
|
||||
`${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`,
|
||||
{ signal }
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to list backtests: ${response.statusText}`);
|
||||
throw await requestError(response, 'Failed to list backtests');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
|
|
@ -159,10 +166,22 @@ export const backtestApiV2 = {
|
|||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to delete backtest: ${response.statusText}`);
|
||||
throw await requestError(response, 'Failed to delete backtest');
|
||||
}
|
||||
},
|
||||
|
||||
async setBacktestArchived(id: string, archived: boolean): Promise<Backtest> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}/archive`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ archived }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Failed to change archive status');
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
|
||||
// Run operations
|
||||
async createRun(
|
||||
backtestId: string,
|
||||
|
|
@ -213,7 +232,7 @@ export const backtestApiV2 = {
|
|||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get run results: ${response.status} ${response.statusText}`);
|
||||
throw await requestError(response, 'Failed to get run results');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
|
|
|
|||
76
database/postgres/init/17-research-retention.sql
Normal file
76
database/postgres/init/17-research-retention.sql
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
-- Archiving affects future admissions and discovery, never accepted worker progress.
|
||||
ALTER TABLE backtests ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;
|
||||
|
||||
ALTER TABLE runs DROP CONSTRAINT IF EXISTS runs_backtest_id_fkey;
|
||||
ALTER TABLE runs ADD CONSTRAINT runs_backtest_id_fkey
|
||||
FOREIGN KEY (backtest_id) REFERENCES backtests(id) ON DELETE RESTRICT;
|
||||
ALTER TABLE backtest_results DROP CONSTRAINT IF EXISTS backtest_results_run_id_fkey;
|
||||
ALTER TABLE backtest_results ADD CONSTRAINT backtest_results_run_id_fkey
|
||||
FOREIGN KEY (run_id) REFERENCES runs(id) ON DELETE RESTRICT;
|
||||
ALTER TABLE backtest_dispatch DROP CONSTRAINT IF EXISTS backtest_dispatch_run_id_fkey;
|
||||
ALTER TABLE backtest_dispatch ADD CONSTRAINT backtest_dispatch_run_id_fkey
|
||||
FOREIGN KEY (run_id) REFERENCES runs(id) ON DELETE RESTRICT;
|
||||
|
||||
CREATE OR REPLACE FUNCTION reject_research_evidence_mutation() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$ BEGIN
|
||||
RAISE EXCEPTION 'Retained research evidence cannot be rewritten or deleted; archive its backtest instead'
|
||||
USING ERRCODE = '23514';
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS backtest_results_retained ON backtest_results;
|
||||
CREATE TRIGGER backtest_results_retained BEFORE UPDATE OR DELETE ON backtest_results
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
DROP TRIGGER IF EXISTS backtest_datasets_retained ON backtest_datasets;
|
||||
CREATE TRIGGER backtest_datasets_retained BEFORE UPDATE OR DELETE ON backtest_datasets
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
DROP TRIGGER IF EXISTS runs_retained ON runs;
|
||||
CREATE TRIGGER runs_retained BEFORE DELETE ON runs
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
DROP TRIGGER IF EXISTS backtest_results_no_truncate ON backtest_results;
|
||||
CREATE TRIGGER backtest_results_no_truncate BEFORE TRUNCATE ON backtest_results
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
DROP TRIGGER IF EXISTS backtest_datasets_no_truncate ON backtest_datasets;
|
||||
CREATE TRIGGER backtest_datasets_no_truncate BEFORE TRUNCATE ON backtest_datasets
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
DROP TRIGGER IF EXISTS runs_no_truncate ON runs;
|
||||
CREATE TRIGGER runs_no_truncate BEFORE TRUNCATE ON runs
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
|
||||
CREATE OR REPLACE FUNCTION protect_run_evidence_identity() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF NEW.id IS DISTINCT FROM OLD.id
|
||||
OR NEW.backtest_id IS DISTINCT FROM OLD.backtest_id
|
||||
OR NEW.run_number IS DISTINCT FROM OLD.run_number
|
||||
OR NEW.created_at IS DISTINCT FROM OLD.created_at
|
||||
OR NEW.submission_principal IS DISTINCT FROM OLD.submission_principal
|
||||
OR NEW.submission_key IS DISTINCT FROM OLD.submission_key
|
||||
OR NEW.submission_hash IS DISTINCT FROM OLD.submission_hash
|
||||
OR (OLD.request_snapshot IS NOT NULL AND NEW.request_snapshot IS DISTINCT FROM OLD.request_snapshot)
|
||||
OR (OLD.request_snapshot IS NULL AND NEW.request_snapshot IS NOT NULL AND OLD.status <> 'pending')
|
||||
OR (OLD.dataset_hash IS NOT NULL AND NEW.dataset_hash IS DISTINCT FROM OLD.dataset_hash) THEN
|
||||
RAISE EXCEPTION 'Retained run identity, submission receipt, snapshot and bound dataset are immutable'
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
-- Legacy NULL snapshots may be populated once by migration10. Workers may bind
|
||||
-- a dataset once; lease, status, progress and control updates remain mutable.
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS runs_evidence_identity ON runs;
|
||||
CREATE TRIGGER runs_evidence_identity BEFORE UPDATE ON runs
|
||||
FOR EACH ROW EXECUTE FUNCTION protect_run_evidence_identity();
|
||||
|
||||
CREATE OR REPLACE FUNCTION require_active_backtest_for_new_run() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE archived TIMESTAMPTZ;
|
||||
BEGIN
|
||||
-- Use the same parent lock as API submissions, edits, archive and deletion.
|
||||
-- This also covers direct repository creation; existing runs need no parent lock.
|
||||
SELECT archived_at INTO archived FROM backtests WHERE id = NEW.backtest_id FOR UPDATE;
|
||||
IF FOUND AND archived IS NOT NULL THEN
|
||||
RAISE EXCEPTION 'Backtest is archived; restore it before submitting a new run'
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS runs_active_parent ON runs;
|
||||
CREATE TRIGGER runs_active_parent BEFORE INSERT ON runs
|
||||
FOR EACH ROW EXECUTE FUNCTION require_active_backtest_for_new_run();
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
# Revised development roadmap
|
||||
|
||||
Baseline `b7aeca4` · execution 2026-10-23 · **F08 committed; S01 validated, uncommitted**
|
||||
Baseline `b7aeca4` · execution 2026-10-23 · **R01 committed; R10 validated, uncommitted**
|
||||
|
||||
Authorization update: the owner accepted F08 and requested “commit all of it and continue” after the handoff named S01 and linked ADR-005. F08 is committed as `3838295`; S01 is authorized under ADR-004/005. Other pending ADRs and the multi-asset mark policy are unchanged. New S01 implementation commits, pushes, PRs and trading/default-engine operations remain outside this continuation's scope.
|
||||
Authorization update: the owner requested “commit and continue with backlog”. R01 is committed as `4a2e5ad`; R10 is authorized under ADR-006. Performance work remains paused. New R10 implementation commits, pushes, PRs and trading/default-engine operations remain outside this continuation’s scope.
|
||||
|
||||
## Strategy and review outcome
|
||||
|
||||
|
|
@ -495,3 +495,16 @@ R01 deliberately exposes no version-based execution. R02 catalog/forms can proce
|
|||
Independent G1/G2/security review accepted the final implementation. Validation: build/source/contracts, 93 tooling, 43 utility, 44 calculation, 509 integration and 150 Rust tests (four manual ignored), plus lint. Full disposable PostgreSQL/Redis suite: **122 tests / 903 assertions**. Release-addon focused strategy/API suite: **65 tests / 377 assertions**, plus the final contract edge case. Browser regressions: **6 workflows / 66 assertions**. Strict new-test/script types and scoped lint/format/diff checks passed. Initial allowlist/lint/declaration errors were corrected; the browser contract boundary now builds from current type source after a combined-suite generated-file read failure. Exact commands and evidence are recorded in `manifest.json` → `twentieth_wave_validation` and `/tmp/stock-bot-wave20.XIW6lx/`.
|
||||
|
||||
All catalog versions remain non-runnable until retained-artifact execution is integrated; approval does not enable execution. Original TypeScript source/full-run provenance are not claimed by the bundled-JS catalog. Current legacy workflows remain qualified and reject unsupported catalog version IDs. No financial Rust changes, default cutover, real catalog seeding, trading activation, profiling or benchmarks. The release addon matches the checkout library; both exact test fixtures were stopped. No R01 commit, push or PR. **Next after acceptance/commit: R10 evidence retention; R02 catalog screens are also eligible with disjoint ownership.**
|
||||
|
||||
## Twenty-first-wave handoff — 2026-10-23
|
||||
|
||||
R01 accepted and committed as `4a2e5ad`. R10 is independently reviewed and `validated_uncommitted`; isolated API/database and frontend worktrees are retained under `/tmp/stock-bot-wave21.u7PX8e/`. All 20 implementation/test files match reviewed hashes.
|
||||
|
||||
- **Retained evidence:** Migration 17 replaces definition/run/result deletion cascades with restrictions and protects runs, results and frozen datasets from destructive writes. Immutable run identity/receipt/snapshot/bound dataset fields are guarded; normal progress, lease recovery, cancellation, completion and initial binding remain writable. Legacy pending NULL snapshots still backfill once. Existing R01 artifact/checksum custody is reused.
|
||||
- **Template archive/restore:** The API serializes archive, edit, delete and new-run admission on the parent row. Templates with any run return 409 on deletion, with count and archive guidance; runless/missing deletion retains 204 compatibility. Idempotent accepted receipt replay precedes archive checks. A database admission trigger also covers direct repository creation. Accepted work continues after archive; no separate run-archive lifecycle or purge framework.
|
||||
- **Workbench:** Confirmation-backed archive/restore, archived list filter/badge, viewable read-only settings and disabled fresh submissions. Active cancellation, selected results/trades and ambiguous submission keys survive archive; delayed navigation/filter responses cannot overwrite current state. Archived saved URLs reopen normally.
|
||||
- **Validation:** Full repository gates passed: 93 tooling, 43 utility, 44 calculation, 520 integration and 150 Rust tests (4 manual ignored), plus build/types/contracts/lint/secrets. Real PostgreSQL/Redis: 131 tests / 987 assertions. Chromium: 7 workflows / 79 assertions, including archive during admitted execution/cancellation and restored submission. Strict new/modern changed tests and scoped formatting/lint passed. Full commands/logs/hashes are in the canonical manifest.
|
||||
|
||||
The initial sandbox run could not support native worker IPC or fixture network access; full checks were rerun successfully outside it. Optional broad strict legacy harness checks retain pre-existing errors, recorded in the manifest. Release addon is restored and matches the prior wave hash; Rust code and financial semantics were unchanged. Disposable fixture containers were removed; development services were untouched. No performance work, new R10 commit, push, PR or trading/default activation.
|
||||
|
||||
Legacy economic/provenance limitations remain explicit; retaining evidence does not certify its economics or create missing version history. Next: R02 strategy catalog UI and version-aware setup. R05 still owns retained-artifact execution and canonical durable cutover.
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| [S02 Adapt one SMA strategy for the first canonical path](tasks/S02.md) | P1 / done | S01 | — | TypeScript strategy/quant engineering / M |
|
||||
| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / done | S01, C06, ADR-005 | — | Durable execution/Rust integration / L |
|
||||
| [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / done | S02, S03 | — | TypeScript trading infrastructure / M |
|
||||
| [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / review | S02, F08 | R08 | Quant strategy research / M |
|
||||
| [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / done | S02, F08 | R08 | Quant strategy research / M |
|
||||
| [S06 Retire duplicate simulator paths after cutover proof](tasks/S06.md) | P2 / blocked | S03, S04, R05 | — | TypeScript trading infrastructure / M |
|
||||
|
||||
### E5 — Existing web backtest vertical slice
|
||||
|
|
@ -72,8 +72,8 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [R01 Persist immutable strategy versions and parameter schemas](tasks/R01.md) | P1 / blocked | O01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / blocked | R01, W03, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R01 Persist immutable strategy versions and parameter schemas](tasks/R01.md) | P1 / done | O01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / ready | R01, W03, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / blocked | R01, R10, ADR-006 | — | Full-stack research product / M |
|
||||
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / blocked | R03, W02, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / blocked | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
|
||||
|
|
@ -81,8 +81,8 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / blocked | R06, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / blocked | R06, ADR-006 | — | Quantitative research integrity / M |
|
||||
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M |
|
||||
| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / blocked | R01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / blocked | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M |
|
||||
| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / review | R01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / done | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M |
|
||||
| [R12 Reproduce an original run separately from rerunning current settings](tasks/R12.md) | P1 / blocked | R05, W04, ADR-006 | — | Full-stack reproducible research / S |
|
||||
|
||||
### E7 — Measured research throughput
|
||||
|
|
@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
|
||||
|
||||
The first seventeen waves are committed. **S05 is validated and uncommitted; performance work remains deferred by the owner.** R01/R11 still need ADR-006; the multi-asset mark-policy gate still blocks default activation. No default/paper activation, push or PR is included in this continuation.
|
||||
The first twenty waves are committed, including R01 (`4a2e5ad`). **R10 retention is validated and uncommitted; performance work remains deferred by the owner.** ADR-006 is approved; R02 is ready after R01. The multi-asset mark-policy gate still blocks default activation. No default/paper activation, push or PR is included in this continuation.
|
||||
|
|
|
|||
|
|
@ -1,16 +1,16 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-23.44",
|
||||
"plan_revision": "2026-10-23.46",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "twentieth_wave_review",
|
||||
"plan_status": "twenty_first_wave_review",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "User: comit all and continue after validated R11 handoff named R01 next (2026-10-23). R11 accepted and committed b106c1ca85e853c7fbcd65fc54c83b9f1024f2ed.",
|
||||
"authorized_by": "User: commit and continue with backlog (2026-10-23). R01 accepted and committed 4a2e5ad362f7746a45a694dbcd9c51efac390526.",
|
||||
"tasks": [
|
||||
"R01"
|
||||
"R10"
|
||||
],
|
||||
"permissions": [
|
||||
"R01 isolated implementation, correctness tests, independent review and planning updates; prior R11 commit authorized and completed"
|
||||
"R10 isolated implementation, correctness tests, independent review and planning updates; prior R01 commit authorized and completed"
|
||||
],
|
||||
"excluded": [
|
||||
"performance_profiling_or_optimization",
|
||||
|
|
@ -1390,7 +1390,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "review",
|
||||
"status": "done",
|
||||
"dependencies": [
|
||||
"O01"
|
||||
],
|
||||
|
|
@ -1413,11 +1413,11 @@
|
|||
"assignment": "/root",
|
||||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "4a2e5ad362f7746a45a694dbcd9c51efac390526",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_base": "b106c1ca85e853c7fbcd65fc54c83b9f1024f2ed",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"integration_state": "validated_committed",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"implementation_slices": [
|
||||
{
|
||||
|
|
@ -1442,7 +1442,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "blocked",
|
||||
"status": "ready",
|
||||
"dependencies": [
|
||||
"R01",
|
||||
"W03"
|
||||
|
|
@ -1732,7 +1732,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "blocked",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"R01"
|
||||
],
|
||||
|
|
@ -1750,13 +1750,32 @@
|
|||
"sql-migrations",
|
||||
"web-backtest-service"
|
||||
],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"parallel_policy": "Backend migration/API and frontend in isolated worktrees with pinned archive contract; root owns fixtures/browser integration/planning; independent read-only review.",
|
||||
"assignment": "/root",
|
||||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": []
|
||||
"release_gates": [],
|
||||
"integration_base": "4a2e5ad362f7746a45a694dbcd9c51efac390526",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/s04_controls_audit",
|
||||
"scope": "Migration 17, migration allowlist, service/routes and new PostgreSQL retention scenarios",
|
||||
"worktree": "/tmp/stock-bot-wave21.u7PX8e/backend"
|
||||
},
|
||||
{
|
||||
"owner": "/root/s04_feed_audit",
|
||||
"scope": "Archive/restore API client and backtest UI with focused tests",
|
||||
"worktree": "/tmp/stock-bot-wave21.u7PX8e/frontend"
|
||||
},
|
||||
{
|
||||
"owner": "/root",
|
||||
"scope": "Existing fixture migration compatibility, browser retention workflow, integration and planning"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "R11",
|
||||
|
|
@ -6739,5 +6758,102 @@
|
|||
"51c5b994f16c6c2bc7f095d6d9946457cb62a0ac2df5f1a3a8f2be0516f4be78"
|
||||
],
|
||||
"next": "After acceptance/commit, R10 retained research evidence is the next foundation; R02 catalog UI can proceed in parallel only with disjoint files. Performance remains deferred."
|
||||
},
|
||||
"twenty_first_wave": [
|
||||
"R10"
|
||||
],
|
||||
"twenty_first_wave_base": "4a2e5ad362f7746a45a694dbcd9c51efac390526",
|
||||
"twenty_first_wave_notes": [
|
||||
"Archive templates only; all retained runs/results stay readable. Restore permits new submissions/edits; already admitted work may execute, recover or cancel while archived.",
|
||||
"No run-level archival or purge infrastructure. R01 artifact verification reused; legacy engine/provenance limitations remain.",
|
||||
"Performance work remains paused. No R10 commits, pushes, PRs or trading/default-engine activation."
|
||||
],
|
||||
"twenty_first_wave_validation": {
|
||||
"status": "validated_uncommitted",
|
||||
"log_directory": "/tmp/stock-bot-wave21.u7PX8e",
|
||||
"source_hashes": {
|
||||
"apps/stock/web-api/src/migrations/migration-runner.ts": "85a1cf163c3592df6a1b8a60e536759bbf62846dde62203dd2d13569c8d8ce87",
|
||||
"apps/stock/web-api/src/routes/backtests-v2.routes.ts": "3f146457a3f70835be50b50063cb4228f896800139c5a36aba7c93c7c71bf669",
|
||||
"apps/stock/web-api/src/services/backtest-v2.service.ts": "039265c4ffec0fa94af4b6a73d13078fa6d7e55902b3b7af428799c51a9feb37",
|
||||
"apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx": "8aae36399a7476a88fd487054323f9a4d283e542b70f83cfa29dc7007417a3e1",
|
||||
"apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx": "fbb8a912a55a8e02b119596421dcfdadffc341734fdeb1f8fc20cd6b02091500",
|
||||
"apps/stock/web-app/src/features/backtest/components/ArchiveBacktestDialog.tsx": "90de8f9b6a71a0646e88d8cd2d4c6d74799c5ab77910af344ff72d6fe321f399",
|
||||
"apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx": "caaa048e8cdd9855d5f59c7147b98d6af40ea6f9723d09e6dd6f7ca97f0428db",
|
||||
"apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts": "0d8f15496f1e51be16037df3b54f0ba1325c892c2707ed0f4055d8bbd73440ae",
|
||||
"apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts": "0399eeca8ed54ca927508082e3a5203c34baa9a9af45e14bdf87ede337111c5d",
|
||||
"database/postgres/init/17-research-retention.sql": "f1a932eaf7fa80ed1a4f3868da4d5b5dfcd6d6b0f9de17179310a644cadae63f",
|
||||
"test/e2e/fixture.ts": "922fd7725c4791ec250c06421ed0418a59e03cd72bedfae6f914e140843b0d80",
|
||||
"test/e2e/workbench.test.ts": "bad834a33285b8589d5a1fd85ca68efff650e3e159d6fa5b8f57532a6f7a21c4",
|
||||
"test/integration/backtest-run-controls.test.tsx": "57a6d766a2029173edce22b3d3989c42b54de44925c119e3513af810061c3158",
|
||||
"test/integration/backtest-workflow.test.ts": "3775b2f34b81040e6f52be4f221714ae9ad0d74670db5728e371833be8895a77",
|
||||
"test/integration/research-retention-routes.test.ts": "ad6b51c45519289e6c69758fdb1faec4857ad10d15e69f926fab08d93bb587ec",
|
||||
"test/postgres/dataset-catalog.test.ts": "77e55f497c0c4cb6d952d2ab06b1716f78d700c6899edc62a2284b08b63dec7b",
|
||||
"test/postgres/durable-backtest.test.ts": "96c028f76c13ac2861e325e8bb4a6fda1aace11e1cf0ce2dada4278f71169c59",
|
||||
"test/postgres/migration-runner.test.ts": "39c1fb489fb9ef643e043e59a85a5e962183f7e52833feb0242f1f0db6e93a4e",
|
||||
"test/postgres/research-retention.test.ts": "4bd0edbe962c188886116ab9e86d196c580b5d9405bb78fa69e0e03ae236189a",
|
||||
"test/postgres/research-runtime-isolation.test.ts": "cfd5628da35fe1d84e1a4ed4bb9097f86296819884a8a94ed4f800418e830d0e"
|
||||
},
|
||||
"independent_review": {
|
||||
"owner": "/root/s03_review",
|
||||
"outcome": "No remaining must-fix findings. G1 unchanged financial semantics; G2 SQL retention/admission/recovery and migration compatibility accepted; G3 API/UI/auth accepted. Reviewer inspected source and PostgreSQL log, ran no tests. Integrator subsequently completed all full-check/browser gates with unchanged reviewed hashes.",
|
||||
"backend_archive_sha256": "b71f4155502fd3db4fea130253af3d22543389a9ef1c2de9983228478f80f8be",
|
||||
"frontend_archive_sha256": "914f405bfd6e616beaa06ed05e6abbdcac5a48a54bb5fff341ba5bf15b78d41e"
|
||||
},
|
||||
"checks": [
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"log": "/tmp/stock-bot-wave21.u7PX8e/check-final.log",
|
||||
"outcome": "All repository checks passed: build, source/contracts, 93 tooling/12142 assertions, 43 utility/86, 44 calculation/2285, 520 integration/4554, 150 Rust (4 manual ignored), lint and secret audit."
|
||||
},
|
||||
{
|
||||
"command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32825/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32826/15 bun run test:postgres",
|
||||
"log": "/tmp/stock-bot-wave21.u7PX8e/postgres-final.log",
|
||||
"outcome": "131 tests / 987 assertions passed on disposable fixtures. Includes immutable evidence, archive/admission race, accepted-run recovery/cancel/complete, missing/corrupt dataset failure without provider fallback, migration reapplication, existing paper custody/recovery and isolation."
|
||||
},
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release",
|
||||
"log": "/tmp/stock-bot-wave21.u7PX8e/native-release-final.log",
|
||||
"outcome": "Release addon restored; hash equals checkout release library and prior wave release artifact. No Rust source or economic policy changed."
|
||||
},
|
||||
{
|
||||
"command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32825/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32826/15 bun run test:e2e",
|
||||
"log": "/tmp/stock-bot-wave21.u7PX8e/e2e.log",
|
||||
"outcome": "7 workflows / 79 assertions passed against final built UI/API and release addon. Archive/restore, accepted archived execution/cancellation, readonly settings, history/results/trades reopen, native smoke and existing dataset/submission workflows."
|
||||
},
|
||||
{
|
||||
"command": "bunx tsc --project /tmp/stock-bot-wave21.u7PX8e/tests-tsconfig.json --noEmit",
|
||||
"log": "/tmp/stock-bot-wave21.u7PX8e/strict-tests.log",
|
||||
"outcome": "Passed strict new retention route/PostgreSQL tests plus modified migration/dataset/browser fixtures. Existing broad legacy harness strict errors recorded separately, not suppressed."
|
||||
},
|
||||
{
|
||||
"command": "bunx eslint --no-ignore <new retention and modified migration/dataset/browser tests> --max-warnings 0; bunx prettier --check <all changed TS/TSX>; git diff --check",
|
||||
"logs": [
|
||||
"/tmp/stock-bot-wave21.u7PX8e/scoped-lint.log",
|
||||
"/tmp/stock-bot-wave21.u7PX8e/scoped-format.log"
|
||||
],
|
||||
"outcome": "Passed. Existing legacy control-test curly findings not rewritten; new additions and application lint pass."
|
||||
}
|
||||
],
|
||||
"native_debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff",
|
||||
"native_release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103",
|
||||
"scope": "20 source/migration/test files; archive templates only, keep all run/result/dataset evidence. One additive migration, existing API/hooks/UI. No new services, financial changes, purge or run archive states.",
|
||||
"limitations": [
|
||||
"Archived history retains existing legacy-engine and incomplete-provenance qualifications; R05 still owns canonical durable cutover and full provenance.",
|
||||
"Catalog versions remain non-runnable until R05/A02. Existing R01 artifact/lock checksum paths are reused, not replaced.",
|
||||
"Archival does not cancel already accepted work. Restore is required for new submissions and template edits. No default automatic or operator purge workflow.",
|
||||
"Browser submission receipt keys remain component-lifetime state; archive preserves them but does not add reload/navigation recovery."
|
||||
],
|
||||
"environment_notes": [
|
||||
"Initial sandbox PostgreSQL connections failed; rerun outside sandbox passed against the same disposable fixture.",
|
||||
"Initial sandbox full-check native workers timed out on IPC; interrupted that run and reran the full check outside sandbox successfully. Native release build likewise required subprocess access.",
|
||||
"Optional broad strict check of existing legacy fixtures found pre-existing test-only config/undefined/type errors in backtest-workflow, durable-backtest and runtime-isolation harnesses. No new strict errors found; strict new/modern changed tests pass. See fixture-types.log.",
|
||||
"All 20 final source hashes unchanged since independent review. Exact disposable containers stopped; development services untouched; worktrees/logs retained.",
|
||||
"No performance profiling/benchmarks, trading/default activation, push, PR or new R10 commit."
|
||||
],
|
||||
"stopped_fixture_ids": [
|
||||
"8b23c51e87d1363cc75571e2be24da7dc09322bf4251acbf11bae8ded982f063",
|
||||
"f90476a79b0df259a204bbc2f2015b2b6a8e582a8771729f48775cb18b4bac65"
|
||||
],
|
||||
"next": "After acceptance/commit, R02 delivers the strategy catalog UI and version-aware backtest setup without claiming retained-artifact execution before R05. Performance remains deferred."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -91,3 +91,5 @@ Local commands (not run against development data in this wave):
|
|||
HTTP metadata: `/api/v2/strategies`, `/strategies/:id/versions`, `/strategy-versions/:id`; full bytes use `/:id/artifact`; clone/review/parameter validation use `/:id/clone`, `/:id/reviews`, `/:id/validate`. Publication/clone require `Idempotency-Key`. Catalog mutations require actual operator/service credentials, even when other development routes permit loopback bypass; only operator may review. API-supplied names/flags cannot self-register trusted code.
|
||||
|
||||
Validation: 93 tooling, 509 integration, 150 Rust (four manual ignored), 122 PostgreSQL/Redis and six browser workflows passed, plus source/contracts/build/lint/strict changed-test types. Final release native regressions passed 65 tests. Exact sequencing, hashes, commands and raw logs are canonical in `manifest.json` → `twentieth_wave_validation`. R10 and R02 follow; no current engine switch, candidate execution, trading activation or performance work.
|
||||
|
||||
Accepted and committed as `4a2e5ad` following the owner’s “commit and continue with backlog” instruction. R10 subsequently protects existing backtest history; R02 is the next product task.
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ Scheduling source of truth: [manifest entry R10](../manifest.json). No task is a
|
|||
|
||||
## Intended behavior and implementation scope
|
||||
|
||||
Archive existing templates/runs rather than cascading deletion when they retain run history; protect immutable strategy versions, datasets and artifact references established by R01. Add checksum verification on retrieval. R03 subsequently adds finding-reference constraints using the same retention rule. No automatic purge; explicit operator purge later needs a reference check and confirmation.
|
||||
Archive existing templates and retain their entire run history rather than cascading deletion; protect immutable strategy versions, datasets and artifact references established by R01. Add checksum verification on retrieval. R03 subsequently adds finding-reference constraints using the same retention rule. No automatic purge; explicit operator purge later needs a reference check and confirmation.
|
||||
|
||||
Measurable benefit: Prevents accidental loss of reproducibility.
|
||||
|
||||
|
|
@ -39,7 +39,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
|
|||
## Acceptance criteria
|
||||
|
||||
- Deleting a definition with retained runs cannot cascade-delete those runs/results.
|
||||
- Unreferenced legacy deletion behavior is explicitly tested/documented; archived objects remain reproducible.
|
||||
- Unreferenced legacy deletion behavior is explicitly tested/documented; archived history stays readable and existing replay limitations stay explicit.
|
||||
- Missing/corrupt artifact produces an actionable integrity error; no fallback to current source.
|
||||
|
||||
## Mandatory tests
|
||||
|
|
@ -67,3 +67,19 @@ Report scope changes (if any), fixture expectations, API/schema changes, measure
|
|||
## Predecessor capability — R01
|
||||
|
||||
R01 already protects strategy versions/review events from update/delete and verifies retained artifact/lock checksums on retrieval. Reuse those paths. R10's remaining work is existing template/run/result/dataset retention and compatibility; do not create a second artifact store or repeat the catalog implementation. R01 currently has no run-to-version link; add references only with the task that introduces them.
|
||||
|
||||
## Wave21 execution contract
|
||||
|
||||
R01 accepted in `4a2e5ad`; owner authorized R10 continuation. Archive templates only, with a reversible `archivedAt` timestamp. Do not add an independent run-archive state. `POST /api/v2/backtests/:id/archive` takes strict `{ archived: boolean }`; default lists hide archived templates and `includeArchived=true` includes both. Detail/run/result URLs stay readable.
|
||||
|
||||
New submissions and template edits return 409 until restored. Existing accepted jobs may finish, recover or be cancelled; idempotent receipt replay occurs before archive admission checks. Template deletion with any retained run returns409 with the retained run count and archive guidance; runless/missing deletion keeps204 compatibility. SQL guards protect runs/results/datasets without blocking leases, progress, cancellation or initial dataset binding. Keep legacy NULL snapshot backfill working.
|
||||
|
||||
Reuse existing R01 artifact/lock and dataset retrieval checksum verification. No full catalog payload hashing, purge framework or invented historical provenance. Corruption tests insert historical malformed records initially instead of disabling protections or editing retained evidence.
|
||||
|
||||
## Validated handoff — 2026-10-23
|
||||
|
||||
Migration 17, archive/restore API, deletion conflicts and the web workflow are integrated and independently accepted. All accepted runs/results/datasets are retained; only runless templates can be hard-deleted. Worker claims, recovery, cancellation and completion continue on archived templates. Original keyed submission receipts remain replayable.
|
||||
|
||||
Database tests cover raw DELETE/UPDATE/TRUNCATE protections, admission races/direct repository entry, migration repeat/backfill, terminal writes and legacy NULL history. Missing and corrupt dataset fixtures run through the actual runner and fail without provider fallback or saved results. Existing strategy artifact checksums remain in R01. Browser tests cover confirmation, read-only settings, hidden/visible archived lists, saved trades/results, cancellation and restore/new admission.
|
||||
|
||||
Validation: full repository check passed (520 integration,150 Rust plus supporting gates), 131 PostgreSQL tests and 7 browser workflows. Evidence, reviewed 20-file hashes, environment limitations and commands: `manifest.json` → `twenty_first_wave_validation`. Validated but uncommitted; no default-engine/trading activation or performance work.
|
||||
|
|
|
|||
|
|
@ -285,6 +285,7 @@ export async function fixture(native = false) {
|
|||
'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')
|
||||
|
|
|
|||
|
|
@ -98,6 +98,9 @@ test('browser_cancel_failure', async () => {
|
|||
const runId = f.page.url().split('/').at(-1)!;
|
||||
f.dispatcher.start();
|
||||
await visible(f.page, 'Running');
|
||||
await f.page.getByRole('button', { name: 'Archive backtest', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'Confirm archive', exact: true }).click();
|
||||
await visible(f.page, 'Restore backtest');
|
||||
const acknowledged = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/runs/${runId}/cancel`)
|
||||
);
|
||||
|
|
@ -136,8 +139,13 @@ test('browser_cancel_failure', async () => {
|
|||
const emptyId = f.page.url().split('/').at(-1)!;
|
||||
expect((await f.request(`/api/v2/runs/${emptyId}/results`)).trades).toEqual([]);
|
||||
// A saved completed row whose result is unavailable must not appear as zero trades.
|
||||
await f.pool.query('DELETE FROM backtest_results WHERE run_id=$1', [emptyId]);
|
||||
await f.page.reload();
|
||||
const missingResultId = randomUUID();
|
||||
const definitionId = f.page.url().split('/')[4]!;
|
||||
await f.pool.query(
|
||||
"INSERT INTO runs(id,backtest_id,run_number,status) VALUES ($1,$2,2,'completed')",
|
||||
[missingResultId, definitionId]
|
||||
);
|
||||
await f.page.goto(f.page.url().replace(emptyId, missingResultId));
|
||||
await visible(f.page, 'Run completed, but saved results are unavailable.');
|
||||
await visible(f.page, 'Retry results');
|
||||
expect(
|
||||
|
|
@ -404,3 +412,70 @@ test('browser_intraday_dataset_exact_settings_and_incompatible_submission', asyn
|
|||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('browser_archive_retains_history_and_restore_admits_new_work', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
await f.login();
|
||||
await createInBrowser(f.page, 'Retained browser evidence', true);
|
||||
const savedUrl = f.page.url();
|
||||
const runId = savedUrl.split('/').at(-1)!;
|
||||
const definitionId = savedUrl.split('/')[4]!;
|
||||
await f.page.getByRole('button', { name: 'Archive backtest', exact: true }).click();
|
||||
await visible(f.page, 'Confirm archive');
|
||||
await f.page.getByRole('button', { name: 'Confirm archive', exact: true }).click();
|
||||
await visible(f.page, 'Restore backtest');
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
expect(await f.page.getByPlaceholder('My Strategy Backtest').isDisabled()).toBe(true);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
|
||||
true
|
||||
);
|
||||
await expect(f.request(`/api/v2/backtests/${definitionId}`, 'DELETE')).rejects.toThrow('409');
|
||||
// Already admitted work still starts, binds its dataset, and completes after archival.
|
||||
f.dispatcher.start();
|
||||
await visible(f.page, '25%');
|
||||
expect(await f.page.getByRole('button', { name: 'Cancel run', exact: true }).isEnabled()).toBe(
|
||||
true
|
||||
);
|
||||
f.controlled.completion.resolve();
|
||||
await visible(f.page, 'Completed');
|
||||
const result = await f.request(`/api/v2/runs/${runId}/results`);
|
||||
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'BUY');
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Restore backtest');
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'BUY');
|
||||
expect(f.page.url()).toBe(savedUrl);
|
||||
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
|
||||
await f.page.getByRole('checkbox', { name: 'Show archived backtests', exact: true }).waitFor();
|
||||
await until(
|
||||
async () => (await f.page.locator('tbody tr').count()) === 0,
|
||||
'default list hides archived template'
|
||||
);
|
||||
await f.page.getByRole('checkbox', { name: 'Show archived backtests', exact: true }).check();
|
||||
await f.page.getByText('Retained browser evidence').click();
|
||||
await visible(f.page, 'Restore backtest');
|
||||
await f.page.getByText('#1', { exact: true }).click();
|
||||
await visible(f.page, 'Completed');
|
||||
expect(f.page.url()).toBe(savedUrl);
|
||||
await f.page.getByRole('button', { name: 'Restore backtest', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'Confirm restore', exact: true }).click();
|
||||
await visible(f.page, 'Archive backtest');
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
expect(await f.page.getByPlaceholder('My Strategy Backtest').isEnabled()).toBe(true);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
const accepted = await submitInBrowser(f.page);
|
||||
expect(accepted.status()).toBe(202);
|
||||
expect((await accepted.json()).id).not.toBe(runId);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM runs WHERE backtest_id=$1', [definitionId])).rowCount
|
||||
).toBe(2);
|
||||
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(result);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ function deferred<T>() {
|
|||
}
|
||||
type Request = ReturnType<typeof deferred<Response>> & {
|
||||
path: string;
|
||||
query: string;
|
||||
method: string;
|
||||
signal?: AbortSignal | null;
|
||||
settled: boolean;
|
||||
|
|
@ -127,6 +128,7 @@ const definition = {
|
|||
config: {},
|
||||
createdAt: '2024-01-01',
|
||||
updatedAt: '2024-01-01',
|
||||
archivedAt: null,
|
||||
};
|
||||
|
||||
class TestSocket {
|
||||
|
|
@ -285,6 +287,7 @@ beforeEach(() => {
|
|||
const pending: Request = {
|
||||
...deferred<Response>(),
|
||||
path: new URL(String(input)).pathname,
|
||||
query: new URL(String(input)).search,
|
||||
method: init?.method ?? 'GET',
|
||||
signal: init?.signal,
|
||||
body: typeof init?.body === 'string' ? init.body : undefined,
|
||||
|
|
@ -939,3 +942,223 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('template archive and restore', () => {
|
||||
const archived = { ...definition, archivedAt: '2024-03-01T00:00:00.000Z' };
|
||||
function button(label: string) {
|
||||
const found = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === label || item.getAttribute('aria-label') === label
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(`Missing button ${label}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
test('confirmation archives only the template while active cancellation, history and restore remain available', async () => {
|
||||
await mountPage('running');
|
||||
await flush(() => click('Archive backtest'));
|
||||
expect(host.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe(
|
||||
'Archive backtest'
|
||||
);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => {
|
||||
click('Confirm archive');
|
||||
click('Confirm archive');
|
||||
});
|
||||
const archive = request('/api/v2/backtests/definition/archive', 'POST');
|
||||
expect(JSON.parse(archive.body!)).toEqual({ archived: true });
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
expect(button('Confirm archive').disabled).toBe(true);
|
||||
expect(host.textContent).not.toContain('This backtest is archived.');
|
||||
await flush(() => reply(archive, archived));
|
||||
expect(host.querySelector('[role="dialog"]')).toBeNull();
|
||||
expect(host.textContent).toContain('This backtest is archived.');
|
||||
expect(button('Run current settings').disabled).toBe(true);
|
||||
expect(button('Cancel run').disabled).toBe(false);
|
||||
expect(pageLocation).toBe('/backtests/definition/run/A');
|
||||
expect(polls()).toBe(1);
|
||||
await flush(() => click('Settings'));
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
expect((host.querySelector('input[name="name"]') as HTMLInputElement).disabled).toBe(true);
|
||||
await flush(() => click('Runs'));
|
||||
expect(button('New Run').disabled).toBe(true);
|
||||
await flush(() => click('Restore backtest'));
|
||||
expect(host.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe(
|
||||
'Restore backtest'
|
||||
);
|
||||
await flush(() => click('Confirm restore'));
|
||||
const restore = request('/api/v2/backtests/definition/archive', 'POST');
|
||||
expect(JSON.parse(restore.body!)).toEqual({ archived: false });
|
||||
await flush(() => reply(restore, definition));
|
||||
expect(button('New Run').disabled).toBe(false);
|
||||
expect(button('Run current settings').disabled).toBe(false);
|
||||
expect(host.textContent).not.toContain('This backtest is archived.');
|
||||
expect(pageLocation).toBe('/backtests/definition/run/A');
|
||||
});
|
||||
|
||||
test('archive cancellation writes nothing; failed archive stays open with actionable error and retries', async () => {
|
||||
await mountPage('running');
|
||||
await flush(() => click('Archive backtest'));
|
||||
await flush(() => click('Cancel'));
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => click('Archive backtest'));
|
||||
await flush(() => click('Confirm archive'));
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/backtests/definition/archive', 'POST'),
|
||||
{ error: 'Archive storage is unavailable' },
|
||||
503
|
||||
)
|
||||
);
|
||||
expect(host.querySelector('[role="dialog"]')).not.toBeNull();
|
||||
expect(host.textContent).toContain('Archive storage is unavailable');
|
||||
expect(host.textContent).not.toContain('This backtest is archived.');
|
||||
expect(button('Confirm archive').disabled).toBe(false);
|
||||
await flush(() => click('Confirm archive'));
|
||||
await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), archived));
|
||||
expect(host.textContent).toContain('This backtest is archived.');
|
||||
});
|
||||
|
||||
test('archival preserves a lost submission response key/body and completed evidence; only restore permits new intent', async () => {
|
||||
await mount();
|
||||
await loadDefinition();
|
||||
await flush(() => {
|
||||
void latest.createRun(2);
|
||||
});
|
||||
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
await flush(() => fail(first));
|
||||
await selectRunning('A', 'completed');
|
||||
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
||||
const savedResults = latest.runResults;
|
||||
await flush(() => {
|
||||
void latest.setBacktestArchived('definition', true);
|
||||
});
|
||||
await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), archived));
|
||||
expect(latest.backtest?.archivedAt).toBe(archived.archivedAt);
|
||||
expect(latest.runResults).toBe(savedResults);
|
||||
expect(latest.currentRun?.id).toBe('A');
|
||||
expect(latest.runs.map(run => run.id)).toEqual(['A']);
|
||||
expect(latest.hasPendingSubmission).toBe(true);
|
||||
await flush(() => {
|
||||
void latest.createRun(9);
|
||||
});
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, run('A', 'completed'), 202));
|
||||
expect(latest.hasPendingSubmission).toBe(false);
|
||||
const count = requests.length;
|
||||
await flush(() => {
|
||||
void latest.createRun(9);
|
||||
});
|
||||
expect(requests).toHaveLength(count);
|
||||
expect(latest.submissionError).toContain('Restore this archived backtest');
|
||||
await expect(latest.updateBacktest('definition', { name: 'Disallowed edit' })).rejects.toThrow(
|
||||
'Restore'
|
||||
);
|
||||
expect(requests).toHaveLength(count);
|
||||
await flush(() => {
|
||||
void latest.setBacktestArchived('definition', false);
|
||||
});
|
||||
await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), definition));
|
||||
await flush(() => {
|
||||
void latest.createRun(9);
|
||||
});
|
||||
const fresh = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(fresh.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: 9 });
|
||||
await flush(() => reply(fresh, run('B', 'pending'), 202));
|
||||
expect(latest.runResults).toBe(savedResults);
|
||||
});
|
||||
|
||||
test('archived page still exposes recovery of the frozen submission key', async () => {
|
||||
await mountPage('running');
|
||||
await flush(() => click('Run current settings'));
|
||||
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
await flush(() => fail(first));
|
||||
await flush(() => click('Archive backtest'));
|
||||
await flush(() => click('Confirm archive'));
|
||||
await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), archived));
|
||||
expect(button('Retry submission').disabled).toBe(false);
|
||||
await flush(() => click('Retry submission'));
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, run('A', 'running'), 202));
|
||||
expect(button('Run current settings').disabled).toBe(true);
|
||||
});
|
||||
|
||||
test('late archive completion cannot overwrite a different template after navigation', async () => {
|
||||
await mount();
|
||||
await loadDefinition();
|
||||
await flush(() => {
|
||||
void latest.setBacktestArchived('definition', true);
|
||||
});
|
||||
const previous = request('/api/v2/backtests/definition/archive', 'POST');
|
||||
await loadDefinition('other');
|
||||
await flush(() => reply(previous, archived));
|
||||
expect(latest.backtest?.id).toBe('other');
|
||||
expect(latest.backtest?.archivedAt).toBeNull();
|
||||
expect(latest.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
test('retained-delete conflict surfaces archive guidance without clearing selected evidence', async () => {
|
||||
await mount();
|
||||
await loadDefinition();
|
||||
await selectRunning('A', 'completed');
|
||||
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
||||
let failure: string | undefined;
|
||||
await flush(() => {
|
||||
void latest.deleteBacktest('definition').catch(error => {
|
||||
failure = error.message;
|
||||
});
|
||||
});
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/backtests/definition', 'DELETE'),
|
||||
{
|
||||
error: 'This backtest retains 1 run. Archive it to preserve its research history.',
|
||||
code: 'retained_runs',
|
||||
runCount: 1,
|
||||
},
|
||||
409
|
||||
)
|
||||
);
|
||||
expect(failure).toContain('Archive it');
|
||||
expect(latest.error).toBe(failure);
|
||||
expect(latest.backtest?.id).toBe('definition');
|
||||
expect(latest.currentRun?.id).toBe('A');
|
||||
expect(latest.runResults?.runId).toBe('A');
|
||||
});
|
||||
|
||||
for (const lateFailure of [false, true]) {
|
||||
test(`archive list filter ignores stale ${lateFailure ? 'failure' : 'success'} and keeps truthful loading/empty states`, async () => {
|
||||
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
|
||||
const original = request('/api/v2/backtests');
|
||||
expect(original.query).not.toContain('includeArchived');
|
||||
expect(host.textContent).toContain('Loading backtests...');
|
||||
await flush(() => (host.querySelector('input[type="checkbox"]') as HTMLInputElement).click());
|
||||
const current = requests.find(
|
||||
item => item.path === '/api/v2/backtests' && item !== original && !item.settled
|
||||
)!;
|
||||
expect(current.query).toContain('includeArchived=true');
|
||||
expect(original.signal?.aborted).toBe(true);
|
||||
await flush(() => (lateFailure ? fail(original) : reply(original, [definition])));
|
||||
expect(host.textContent).toContain('Loading backtests...');
|
||||
expect(host.textContent).not.toContain('Network unavailable');
|
||||
await flush(() => reply(current, []));
|
||||
expect(host.textContent).toContain('No backtests yet.');
|
||||
expect(host.textContent).not.toContain('Loading backtests...');
|
||||
await flush(() => (host.querySelector('input[type="checkbox"]') as HTMLInputElement).click());
|
||||
const failed = request('/api/v2/backtests');
|
||||
expect(failed.query).not.toContain('includeArchived');
|
||||
await flush(() => reply(failed, { error: 'Retained history storage is unavailable' }, 503));
|
||||
expect(host.textContent).toContain('Retained history storage is unavailable');
|
||||
await flush(() => click('Retry backtests'));
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
expect(host.textContent).toContain('No active backtests.');
|
||||
expect(host.textContent).not.toContain('Retained history storage is unavailable');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@ async function fixture(
|
|||
});
|
||||
db.public
|
||||
.none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb, archived_at timestamptz,
|
||||
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
|
||||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
|
||||
|
|
|
|||
97
test/integration/research-retention-routes.test.ts
Normal file
97
test/integration/research-retention-routes.test.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
|
||||
const tokens = {
|
||||
operator: 'retention-operator-fixture-not-secret-123456',
|
||||
service: 'retention-service-fixture-not-secret-123456',
|
||||
read: 'retention-reader-fixture-not-secret-123456',
|
||||
};
|
||||
function fixture(secured = false) {
|
||||
const database = {
|
||||
query: mock(async (_query: string, _values?: unknown[]) => ({ rows: [] })),
|
||||
transaction: mock(async () => {
|
||||
throw new Error('Invalid archive request reached storage');
|
||||
}),
|
||||
};
|
||||
const app = new Hono();
|
||||
if (secured) {
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
}).mount(app);
|
||||
}
|
||||
app.route(
|
||||
'/',
|
||||
createBacktestV2Routes({
|
||||
postgres: database,
|
||||
logger: { info() {}, error() {} },
|
||||
} as unknown as IServiceContainer)
|
||||
);
|
||||
return { app, database };
|
||||
}
|
||||
|
||||
describe('research retention route validation', () => {
|
||||
test('archive requires exactly a boolean and rejects malformed JSON before a transaction', async () => {
|
||||
const f = fixture();
|
||||
for (const body of [
|
||||
{},
|
||||
null,
|
||||
[],
|
||||
{ archived: 'true' },
|
||||
{ archived: 1 },
|
||||
{ archived: true, purge: true },
|
||||
{ archived: false, runId: randomUUID() },
|
||||
]) {
|
||||
expect(
|
||||
(
|
||||
await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
).status
|
||||
).toBe(400);
|
||||
}
|
||||
expect(
|
||||
(
|
||||
await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, {
|
||||
method: 'POST',
|
||||
body: '{',
|
||||
})
|
||||
).status
|
||||
).toBe(400);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('includeArchived accepts only literal query booleans and defaults to active templates', async () => {
|
||||
const f = fixture();
|
||||
for (const value of ['1', 'yes', 'TRUE', '']) {
|
||||
expect((await f.app.request(`/api/v2/backtests?includeArchived=${value}`)).status).toBe(400);
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
for (const query of ['', '?includeArchived=false', '?includeArchived=true']) {
|
||||
expect((await f.app.request(`/api/v2/backtests${query}`)).status).toBe(200);
|
||||
}
|
||||
expect(f.database.query.mock.calls.map(call => call[1])).toEqual([
|
||||
[50, 0, false],
|
||||
[50, 0, false],
|
||||
[50, 0, true],
|
||||
]);
|
||||
});
|
||||
test('the existing security boundary prevents anonymous and read-only archive mutations', async () => {
|
||||
const f = fixture(true);
|
||||
for (const token of [undefined, tokens.read]) {
|
||||
const response = await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, {
|
||||
method: 'POST',
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
body: '{"archived":true}',
|
||||
});
|
||||
expect(response.status).toBe(token ? 403 : 401);
|
||||
}
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -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