diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index a7c29384..a9b75d73 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -53,7 +53,8 @@ export async function runMigrations(container: IServiceContainer): Promise f === '10-durable-backtest-dispatch.sql' || f === '11-simulation-execution-ledger.sql' || f === '12-historical-datasets.sql' || - f === '13-strategy-recovery.sql') + f === '13-strategy-recovery.sql' || + f === '14-backtest-submission.sql') ) // Explicit additive migration allowlist; never replay destructive init migrations .sort(); diff --git a/apps/stock/web-api/src/routes/backtests-v2.routes.ts b/apps/stock/web-api/src/routes/backtests-v2.routes.ts index d0b59e6c..502d913b 100644 --- a/apps/stock/web-api/src/routes/backtests-v2.routes.ts +++ b/apps/stock/web-api/src/routes/backtests-v2.routes.ts @@ -1,8 +1,9 @@ import { Hono } from 'hono'; +import { getVerifiedHttpPrincipal } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; import { isBacktestRequestError } from '@stock-bot/stock-config/backtest'; -import { BacktestServiceV2 } from '../services/backtest-v2.service'; +import { BacktestServiceV2, RunSubmissionConflictError } from '../services/backtest-v2.service'; const logger = getLogger('backtests-v2-routes'); @@ -40,7 +41,11 @@ export function createBacktestV2Routes(container: IServiceContainer) { app.post('/api/v2/backtests', async c => { try { const body = await c.req.json(); - const backtest = await backtestService.createBacktest(body); + if (body.autoStart !== undefined && typeof body.autoStart !== 'boolean') { + return c.json({ error: 'autoStart must be a boolean' }, 400); + } + // Omitted autoStart preserves legacy clients. New web clients explicitly save only. + const backtest = await backtestService.createBacktest(body, { autoStart: body.autoStart }); return c.json(backtest, 201); } catch (error) { logger.error('Failed to create backtest', error); @@ -91,15 +96,29 @@ export function createBacktestV2Routes(container: IServiceContainer) { app.post('/api/v2/backtests/:backtestId/runs', async c => { try { + const key = c.req.header('Idempotency-Key'); + const principal = getVerifiedHttpPrincipal(c.req.raw); + if (key !== undefined && !principal) { + return c.json({ error: 'Verified submission principal required' }, 401); + } + if (key !== undefined && !/^[\x21-\x7e]{1,200}$/.test(key)) { + return c.json( + { error: 'Idempotency-Key must contain 1–200 visible ASCII characters' }, + 400 + ); + } const body = await c.req.json(); - const run = await backtestService.createRun({ - backtestId: c.req.param('backtestId'), - speedMultiplier: body.speedMultiplier, - }); + const run = await backtestService.createRun( + { backtestId: c.req.param('backtestId'), speedMultiplier: body.speedMultiplier }, + key !== undefined && principal ? { principal, key } : undefined + ); c.header('Location', `/api/v2/runs/${run.id}`); return c.json(run, 202); } catch (error) { logger.error('Failed to create run', error); + if (error instanceof RunSubmissionConflictError) { + return c.json({ error: error.message }, 409); + } if (isBacktestRequestError(error)) { return c.json({ error: error.message }, 400); } diff --git a/apps/stock/web-api/src/routes/create-routes.ts b/apps/stock/web-api/src/routes/create-routes.ts index 78c243bf..f6dd6132 100644 --- a/apps/stock/web-api/src/routes/create-routes.ts +++ b/apps/stock/web-api/src/routes/create-routes.ts @@ -26,7 +26,7 @@ export function createRoutes( cors({ origin: security.allowedOrigins, allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], - allowHeaders: ['Content-Type', 'Authorization'], + allowHeaders: ['Content-Type', 'Authorization', 'Idempotency-Key'], credentials: true, }) ); diff --git a/apps/stock/web-api/src/services/backtest-v2.service.ts b/apps/stock/web-api/src/services/backtest-v2.service.ts index 30ea4113..5caaa182 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -1,4 +1,4 @@ -import { randomUUID as uuidv4 } from 'node:crypto'; +import { createHash, randomUUID as uuidv4 } from 'node:crypto'; import type { QueryResultRow } from 'pg'; import { authenticatedServiceFetch } from '@stock-bot/di'; import { at } from '@stock-bot/invariants'; @@ -6,6 +6,7 @@ import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest'; import type { BacktestRunResult } from '@stock-bot/types'; +import { HistoricalDataRequestError } from '@stock-bot/types'; import { getWebSocketHandler } from '../websocket/run-updates'; import type { WebSocketHandler } from '../websocket/run-updates'; import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result'; @@ -63,6 +64,18 @@ export interface RunRequest { speedMultiplier?: number | null; } +export interface RunSubmission { + principal: 'operator' | 'service'; + key: string; +} + +export class RunSubmissionConflictError extends Error { + constructor() { + super('This submission key was already used for a different run request'); + this.name = 'RunSubmissionConflictError'; + } +} + export class BacktestServiceV2 { private container: IServiceContainer & { postgres: NonNullable }; private wsHandler: WebSocketHandler | null = null; @@ -208,17 +221,55 @@ export class BacktestServiceV2 { } // Run operations - async createRun(request: RunRequest): Promise { + async createRun(request: RunRequest, submission?: RunSubmission): Promise { const runId = uuidv4(); + const multiplier = request.speedMultiplier ?? null; + if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) { + throw new HistoricalDataRequestError('Speed multiplier must be positive or null'); + } + // Hash submission intent, not the mutable definition or newly generated run ID. + // A retry after an edit must still return the original run and its frozen snapshot. + const submissionHash = submission + ? createHash('sha256') + .update( + JSON.stringify({ + version: 1, + backtestId: request.backtestId, + speedMultiplier: multiplier, + }) + ) + .digest('hex') + : null; const row = await this.container.postgres.transaction(async client => { + const replay = async () => { + if (!submission) { + return undefined; + } + const existing = await client.query( + 'SELECT * FROM runs WHERE submission_principal = $1 AND submission_key = $2', + [submission.principal, submission.key] + ); + const saved = existing.rows[0]; + if (saved && saved.submission_hash !== submissionHash) { + throw new RunSubmissionConflictError(); + } + return saved; + }; + const previous = await replay(); + if (previous) { + return previous; + } const parent = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [ request.backtestId, ]); if (!parent.rows.length) { throw new Error('Backtest not found'); } + const concurrent = await replay(); + if (concurrent) { + return concurrent; + } const definition = this.mapBacktest(at(parent.rows, 0)); - const multiplier = request.speedMultiplier ?? null; const snapshot = backtestRequestFromDefinition(definition, { runId, backtestId: definition.id, @@ -226,11 +277,31 @@ export class BacktestServiceV2 { }); const result = await client.query( `INSERT INTO runs - (id, backtest_id, run_number, speed_multiplier, status, request_snapshot) - SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb - FROM runs WHERE backtest_id = $2 RETURNING *`, - [runId, request.backtestId, multiplier, JSON.stringify(snapshot)] + (id, backtest_id, run_number, speed_multiplier, status, request_snapshot, + submission_principal, submission_key, submission_hash) + SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb, $5, $6, $7 + FROM runs WHERE backtest_id = $2 + ${submission ? 'ON CONFLICT (submission_principal, submission_key) DO NOTHING' : ''} + RETURNING *`, + [ + runId, + request.backtestId, + multiplier, + JSON.stringify(snapshot), + submission?.principal ?? null, + submission?.key ?? null, + submissionHash, + ] ); + // Different parent locks can race for one principal/key. The unique index waits for + // the winner's transaction; this next READ COMMITTED query sees its committed row. + if (!result.rows.length) { + const winner = await replay(); + if (!winner) { + throw new Error('Concurrent submission disappeared; retry with the same key'); + } + return winner; + } await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]); return at(result.rows, 0); }); diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index 496d5b47..fcf8aebf 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -1,5 +1,5 @@ import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline'; -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { useWebSocket } from '@/hooks/useWebSocket'; import { BacktestConfiguration } from './components/BacktestConfiguration'; @@ -25,6 +25,7 @@ export function BacktestDetailPageV2() { const navigate = useNavigate(); const [activeTab, setActiveTab] = useState('details'); const [showNewRun, setShowNewRun] = useState(false); + const navigationGeneration = useRef(0); const { backtest, @@ -33,6 +34,9 @@ export function BacktestDetailPageV2() { runResults, isLoading, error, + submissionError, + isSubmitting, + hasPendingSubmission, loadBacktest, updateBacktest, createRun, @@ -55,6 +59,14 @@ export function BacktestDetailPageV2() { }, }); + useEffect(() => { + navigationGeneration.current++; + setShowNewRun(false); + return () => { + navigationGeneration.current++; + }; + }, [id, runId]); + useEffect(() => { if (id) { void loadBacktest(id); @@ -101,10 +113,10 @@ export function BacktestDetailPageV2() { // Handle new run creation const handleCreateRun = useCallback(async () => { + const generation = navigationGeneration.current; const newRun = await createRun(null); - setShowNewRun(false); - // Navigate to the new run - if (newRun && id) { + if (newRun && id && generation === navigationGeneration.current) { + setShowNewRun(false); navigate(`/backtests/${id}/run/${newRun.id}`); } }, [createRun, navigate, id]); @@ -112,11 +124,9 @@ export function BacktestDetailPageV2() { // Handle rerun const handleRerun = useCallback( async (speedMultiplier: number | null) => { - // Pass null for max speed (no limit) + const generation = navigationGeneration.current; const newRun = await createRun(speedMultiplier); - - // Navigate to the new run's URL - if (newRun && id) { + if (newRun && id && generation === navigationGeneration.current) { navigate(`/backtests/${id}/run/${newRun.id}`); } }, @@ -217,21 +227,30 @@ export function BacktestDetailPageV2() { {showNewRun && (
-

Start New Run

+

Run current settings

- This will start a new backtest run with the current configuration. + Submit the current configuration, not a reproduction of a previous run. A retry + recovers the original submission if it was already accepted.

)} @@ -373,6 +394,22 @@ export function BacktestDetailPageV2() { {/* Tab Content */}
+ {submissionError && ( +
+

+ Run submission failed: {submissionError}. Retry to recover the same submission. +

+ {!showNewRun && ( + + )} +
+ )} {error && (

diff --git a/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx index c65c15dd..3b7e88f1 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx @@ -32,18 +32,6 @@ export function BacktestListPageV2() { loadBacktests(); }, []); - const handleCreateBacktest = async (config: Omit) => { - try { - const newBacktest = await backtestApiV2.createBacktest(config); - await loadBacktests(); - setShowCreateDialog(false); - navigate(`/backtests/${newBacktest.id}`); - } catch (err) { - setError('Failed to create backtest'); - browserLog.error(err); - } - }; - const columns: ColumnDef[] = [ { accessorKey: 'name', @@ -134,8 +122,14 @@ export function BacktestListPageV2() { {showCreateDialog && ( setShowCreateDialog(false)} - onCreate={handleCreateBacktest} + onClose={() => { + setShowCreateDialog(false); + void loadBacktests(); + }} + onCreated={(created, run) => { + setShowCreateDialog(false); + navigate(`/backtests/${created.id}${run ? `/run/${run.id}` : ''}`); + }} /> )}

diff --git a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx index 5c165944..bc864fb5 100644 --- a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx @@ -1,14 +1,14 @@ import { XMarkIcon } from '@heroicons/react/24/solid'; -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { parseInstrumentId } from '@stock-bot/types'; -import type { Backtest } from '../services/backtestApiV2'; +import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2'; interface CreateBacktestDialogProps { onClose: () => void; - onCreate: (config: Omit) => void; + onCreated: (backtest: Backtest, run?: Run) => void; } -export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialogProps) { +export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialogProps) { const [formData, setFormData] = useState({ name: '', strategy: 'moving-average', @@ -22,23 +22,91 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog }); const [symbolInput, setSymbolInput] = useState(''); + const [phase, setPhase] = useState<'idle' | 'saving' | 'submitting'>('idle'); + const isSubmitting = phase !== 'idle'; + const [error, setError] = useState(null); + const saved = useRef(null); + const submission = useRef<{ key: string; body: { speedMultiplier: null } } | null>(null); + const pending = useRef(false); + const active = useRef(true); - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault(); + useEffect(() => { + active.current = true; + return () => { + active.current = false; + }; + }, []); - if (!formData.name.trim()) { - alert('Please enter a backtest name'); + const close = () => { + // A list refresh before this write settles could miss the newly saved row. + if (pending.current && !saved.current) { + return; + } + active.current = false; + onClose(); + }; + + const handleSubmit = async (runAfterSave: boolean) => { + if (pending.current || !active.current) { return; } - onCreate({ - ...formData, - config: { - commission: formData.commission, - slippage: formData.slippage, - dataPolicy: { adjustment: formData.priceAdjustment, timestamp: 'utc-session-date' }, - }, - }); + if (!formData.name.trim()) { + setError('Please enter a backtest name'); + return; + } + + pending.current = true; + setPhase(saved.current ? 'submitting' : 'saving'); + setError(null); + try { + if (!saved.current) { + const created = await backtestApiV2.createBacktest({ + name: formData.name, + strategy: formData.strategy, + symbols: formData.symbols, + startDate: formData.startDate, + endDate: formData.endDate, + initialCapital: formData.initialCapital, + config: { + commission: formData.commission, + slippage: formData.slippage, + dataPolicy: { adjustment: formData.priceAdjustment, timestamp: 'utc-session-date' }, + }, + }); + if (!active.current) { + return; + } + saved.current = created; + } + let run: Run | undefined; + if (runAfterSave) { + setPhase('submitting'); + submission.current ??= { key: crypto.randomUUID(), body: { speedMultiplier: null } }; + run = await backtestApiV2.createRun( + saved.current.id, + submission.current.body, + submission.current.key + ); + } + if (active.current) { + onCreated(saved.current, run); + } + } catch (err) { + if (active.current) { + const detail = err instanceof Error ? err.message : 'Please try again.'; + setError( + saved.current + ? `Backtest saved, but run submission failed. Retry submission to recover the same run. ${detail}` + : `Failed to save backtest. ${detail}` + ); + } + } finally { + pending.current = false; + if (active.current) { + setPhase('idle'); + } + } }; const addSymbol = () => { @@ -68,192 +136,228 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog

Create New Backtest

-
-
- - setFormData({ ...formData, name: e.target.value })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - placeholder="My Strategy Backtest" - required - /> -
- -
- - -
- -
- -
+ {error && ( +

+ {error} +

+ )} + { + e.preventDefault(); + void handleSubmit(saved.current !== null); + }} + className="space-y-6" + > +
+
+ setSymbolInput(e.target.value)} - onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), addSymbol())} - className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - placeholder="Instrument ID (e.g., AAPL.US)" + value={formData.name} + onChange={e => setFormData({ ...formData, name: e.target.value })} + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + placeholder="My Strategy Backtest" + required /> - +
+
+ {formData.symbols.map(symbol => ( + - - - - ))} + {symbol} + + + ))} +
-
-
- - -
- -
- setFormData({ ...formData, startDate: e.target.value })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - required - /> +
-
- - setFormData({ ...formData, endDate: e.target.value })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - required - /> + +
+
+ + setFormData({ ...formData, startDate: e.target.value })} + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + required + /> +
+
+ + setFormData({ ...formData, endDate: e.target.value })} + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + required + /> +
-
-
- - - setFormData({ ...formData, initialCapital: parseFloat(e.target.value) || 0 }) - } - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - min="0" - step="1000" - required - /> -
- -
- setFormData({ ...formData, commission: parseFloat(e.target.value) || 0 }) + setFormData({ ...formData, initialCapital: parseFloat(e.target.value) || 0 }) } className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" min="0" - step="0.01" + step="1000" + required />
-
- - - setFormData({ ...formData, slippage: parseFloat(e.target.value) || 0 }) - } - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - min="0" - step="0.01" - /> -
-
+
+
+ + + setFormData({ ...formData, commission: parseFloat(e.target.value) || 0 }) + } + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + min="0" + step="0.01" + /> +
+
+ + + setFormData({ ...formData, slippage: parseFloat(e.target.value) || 0 }) + } + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + min="0" + step="0.01" + /> +
+
+
+ {!saved.current && ( + + )}
diff --git a/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx b/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx index 89470f11..fa80ebe1 100644 --- a/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx +++ b/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx @@ -6,6 +6,8 @@ interface RunControlsCompactProps { cancelRequested: boolean; onCancel: () => void; onRerun: (speed: number | null) => void; + isSubmitting?: boolean; + hasPendingSubmission?: boolean; } export function RunControlsCompact({ @@ -13,6 +15,8 @@ export function RunControlsCompact({ cancelRequested, onCancel, onRerun, + isSubmitting = false, + hasPendingSubmission = false, }: RunControlsCompactProps) { const active = ['pending', 'running', 'paused'].includes(run.status); const requested = active && (cancelRequested || run.cancelRequested); @@ -38,9 +42,10 @@ export function RunControlsCompact({ )} diff --git a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts index 7aed9320..47046db0 100644 --- a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts +++ b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts @@ -24,9 +24,21 @@ export function useBacktestV2() { const [isRunLoading, setIsRunLoading] = useState(false); const [error, setError] = useState(null); const [runError, setRunError] = useState(null); + const [submissionError, setSubmissionError] = useState(null); + const [isSubmitting, setIsSubmitting] = useState(false); const [cancelRequested, setCancelRequested] = useState(false); const mounted = useRef(true); const backtestGeneration = useRef(0); + const loadedBacktestId = useRef(null); + const selectionGeneration = useRef(0); + // The intent survives an ambiguous response and configuration edits. Only an + // acknowledged submission (or leaving this definition) releases its key. + const submission = useRef<{ + backtestId: string; + key: string; + body: { speedMultiplier: number | null }; + pending: boolean; + } | null>(null); const selection = useRef(null); const cancellation = useRef(null); @@ -36,6 +48,7 @@ export function useBacktestV2() { ); const stopMonitoring = useCallback(() => { + selectionGeneration.current++; const selected = selection.current; selection.current = null; cancellation.current = null; @@ -165,6 +178,12 @@ export function useBacktestV2() { const loadBacktest = useCallback(async (id: string) => { const generation = ++backtestGeneration.current; + if (loadedBacktestId.current !== id) { + submission.current = null; + setSubmissionError(null); + setIsSubmitting(false); + } + loadedBacktestId.current = id; setIsBacktestLoading(true); setError(null); setBacktest(null); @@ -205,6 +224,10 @@ export function useBacktestV2() { try { const created = await backtestApiV2.createBacktest(request); if (mounted.current && generation === backtestGeneration.current) { + loadedBacktestId.current = created.id; + submission.current = null; + setSubmissionError(null); + setIsSubmitting(false); setBacktest(created); setRuns([]); await selectRun(undefined); @@ -256,6 +279,10 @@ export function useBacktestV2() { try { await backtestApiV2.deleteBacktest(id); if (mounted.current && generation === backtestGeneration.current) { + loadedBacktestId.current = null; + submission.current = null; + setSubmissionError(null); + setIsSubmitting(false); setBacktest(null); setRuns([]); await selectRun(undefined); @@ -276,29 +303,44 @@ export function useBacktestV2() { const createRun = useCallback( async (speedMultiplier: number | null = null) => { - if (!backtest) { + if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) { return undefined; } - const generation = backtestGeneration.current; - const selected = selection.current; - setIsBacktestLoading(true); - setError(null); + const intent = (submission.current ??= { + backtestId: backtest.id, + key: crypto.randomUUID(), + body: { speedMultiplier }, + pending: false, + }); + intent.pending = true; + const selectedGeneration = selectionGeneration.current; + const ownsSubmission = () => mounted.current && submission.current === intent; + const ownsSelection = () => + ownsSubmission() && selectionGeneration.current === selectedGeneration; + setIsSubmitting(true); + setSubmissionError(null); try { - const created = await backtestApiV2.createRun(backtest.id, { speedMultiplier }); - if (!mounted.current || generation !== backtestGeneration.current) { + const created = await backtestApiV2.createRun(intent.backtestId, intent.body, intent.key); + if (!ownsSubmission()) { return undefined; } - setRuns(previous => [created, ...previous]); - // The route owns selection. Never navigate away from a newer user selection. - return selection.current === selected ? created : undefined; + const selected = ownsSelection(); + submission.current = null; + setIsSubmitting(false); + if (!selected) { + return undefined; + } + setRuns(previous => [created, ...previous.filter(run => run.id !== created.id)]); + return created; } catch (err) { - if (mounted.current && generation === backtestGeneration.current) { - setError(messageOf(err, 'Failed to create run')); + if (ownsSubmission()) { + setSubmissionError(messageOf(err, 'Failed to submit run')); } return undefined; } finally { - if (mounted.current && generation === backtestGeneration.current) { - setIsBacktestLoading(false); + intent.pending = false; + if (ownsSubmission()) { + setIsSubmitting(false); } } }, @@ -349,6 +391,9 @@ export function useBacktestV2() { runResults, isLoading: isBacktestLoading || isRunLoading, error: runError ?? error, + submissionError, + isSubmitting, + hasPendingSubmission: submission.current !== null, cancelRequested, loadBacktest, createBacktest, diff --git a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts index b2a28df3..b53feced 100644 --- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts @@ -64,7 +64,8 @@ export const backtestApiV2 = { headers: { 'Content-Type': 'application/json', }, - body: JSON.stringify(request), + // Web saves are deliberately separate from durable run submission. + body: JSON.stringify({ ...request, autoStart: false }), }); if (!response.ok) { @@ -123,11 +124,16 @@ export const backtestApiV2 = { }, // Run operations - async createRun(backtestId: string, request?: CreateRunRequest): Promise { + async createRun( + backtestId: string, + request?: CreateRunRequest, + submissionKey?: string + ): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, { method: 'POST', headers: { 'Content-Type': 'application/json', + ...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}), }, body: JSON.stringify(request || {}), }); diff --git a/database/postgres/init/14-backtest-submission.sql b/database/postgres/init/14-backtest-submission.sql new file mode 100644 index 00000000..82add180 --- /dev/null +++ b/database/postgres/init/14-backtest-submission.sql @@ -0,0 +1,20 @@ +-- Legacy/keyless submissions remain NULL and retain their existing behavior. +ALTER TABLE runs ADD COLUMN IF NOT EXISTS submission_principal TEXT; +ALTER TABLE runs ADD COLUMN IF NOT EXISTS submission_key TEXT; +ALTER TABLE runs ADD COLUMN IF NOT EXISTS submission_hash TEXT; + +DO $$ BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint WHERE conname = 'runs_submission_complete' + AND conrelid = 'runs'::regclass + ) THEN + ALTER TABLE runs ADD CONSTRAINT runs_submission_complete CHECK ( + (submission_principal IS NULL AND submission_key IS NULL AND submission_hash IS NULL) + OR (submission_principal IS NOT NULL AND submission_key IS NOT NULL AND submission_hash IS NOT NULL) + ); + END IF; +END $$; + +-- A key belongs to a verified server principal, not to a mutable definition or session. +CREATE UNIQUE INDEX IF NOT EXISTS runs_submission_unique + ON runs (submission_principal, submission_key); diff --git a/libs/core/di/src/http/security.ts b/libs/core/di/src/http/security.ts index b2caadc5..24529b5e 100644 --- a/libs/core/di/src/http/security.ts +++ b/libs/core/di/src/http/security.ts @@ -2,6 +2,12 @@ import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypt import type { Hono, MiddlewareHandler } from 'hono'; type Role = 'read' | 'admin' | 'service'; +const verifiedPrincipals = new WeakMap(); + +/** Server-owned identity established only after successful HTTP authorization. */ +export function getVerifiedHttpPrincipal(request: Request): 'operator' | 'service' | undefined { + return verifiedPrincipals.get(request); +} export interface HttpSecurityOptions { readToken?: string; adminToken?: string; @@ -142,6 +148,7 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp return { role, cookie: true }; } function authorize(request: Request, admin = false): Response | undefined { + verifiedPrincipals.delete(request); const identity = authenticate(request); if (!identity) { return Response.json( @@ -161,6 +168,9 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp ) { return Response.json({ error: 'Untrusted request origin' }, { status: 403 }); } + if (identity.role !== 'read') { + verifiedPrincipals.set(request, identity.role === 'service' ? 'service' : 'operator'); + } return undefined; } const middleware: MiddlewareHandler = async (context, next) => { diff --git a/libs/core/di/src/index.ts b/libs/core/di/src/index.ts index 4dda1d89..bbb3b79a 100644 --- a/libs/core/di/src/index.ts +++ b/libs/core/di/src/index.ts @@ -6,6 +6,7 @@ export { createHttpSecurity, httpSecurityOptions, authenticatedServiceFetch, + getVerifiedHttpPrincipal, } from './http/security'; export type { HttpSecurity, HttpSecurityOptions } from './http/security'; export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator'; diff --git a/scripts/test/security.test.ts b/scripts/test/security.test.ts index d9450d9a..78fca88c 100644 --- a/scripts/test/security.test.ts +++ b/scripts/test/security.test.ts @@ -1,11 +1,14 @@ import { readFileSync } from 'node:fs'; import { expect, test } from 'bun:test'; import { Hono } from 'hono'; +import { createHttpSecurity as createApiSecurity } from '@stock-bot/di'; import { getLogger } from '@stock-bot/logger'; import type { IServiceContainer } from '@stock-bot/services'; import { createPipelineRoutes } from '../../apps/stock/web-api/src/routes/pipeline.routes'; +import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; +import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes'; import { createWebSocketRoute } from '../../apps/stock/web-api/src/routes/websocket.routes'; -import { createHttpSecurity, type HttpSecurityOptions } from '../../libs/core/di/src/http/security'; +import { createHttpSecurity, getVerifiedHttpPrincipal, type HttpSecurityOptions } from '../../libs/core/di/src/http/security'; import { redactLogValue } from '../../libs/core/logger/src/redact'; import { parseReferenceDataResetRequest } from '../../libs/core/types/src/reference-data'; import { unexpectedTrackedEnvironmentFiles } from '../audit-secrets'; @@ -56,6 +59,44 @@ test('HTTP security fails closed and insecure mode is loopback-development only' expect(createHttpSecurity({ disabled: true }).hostname).toBe('127.0.0.1'); }); +test('submission principals are stable server identities across bearer/cookie renewal and ignore spoofed headers', async () => { + const f = fixture(); + f.app.post('/api/principal', context => context.json({ principal: getVerifiedHttpPrincipal(context.req.raw) })); + const post = (headers: HeadersInit) => f.app.request('/api/principal', { method: 'POST', headers }); + expect(await (await post({ ...bearer(), 'X-Principal': 'service' })).json()).toEqual({ principal: 'operator' }); + expect(await (await post(bearer(options.serviceToken))).json()).toEqual({ principal: 'service' }); + const cookies: string[] = []; + for (let i = 0; i < 2; i++) { + const session = await login(f.app); + const Cookie = session.headers.get('set-cookie')!.split(';')[0]!; + cookies.push(Cookie); + expect(await (await post({ Cookie, Origin: 'http://ui.test', 'X-Principal': 'attacker' })).json()).toEqual({ principal: 'operator' }); + } + expect(cookies[0]).not.toBe(cookies[1]); + expect((await post(bearer(options.readToken))).status).toBe(403); + expect((await post({ 'X-Principal': 'operator' })).status).toBe(401); + expect(getVerifiedHttpPrincipal(new Request('http://api.test', { headers: { 'X-Principal': 'operator' } }))).toBeUndefined(); +}); + +test('keyed run routes fail closed without verified security and support trusted CORS preflight', async () => { + const services = { logger: getLogger('submission-security'), postgres: {} } as IServiceContainer; + const path = '/api/v2/backtests/00000000-0000-4000-8000-000000000001/runs'; + const request = { method: 'POST', headers: { 'Idempotency-Key': 'key', 'X-Principal': 'operator' }, body: '{}' }; + const bare = createBacktestV2Routes(services); + expect((await bare.request(path, request)).status).toBe(401); + const app = createRoutes(services, createApiSecurity(options)); + expect((await app.request(path, request)).status).toBe(401); + expect((await app.request(path, { ...request, headers: { ...request.headers, ...bearer(options.readToken) } })).status).toBe(403); + expect((await app.request(path, { ...request, headers: { ...bearer(), 'Idempotency-Key': '' } })).status).toBe(400); + const preflight = await app.request(path, { method: 'OPTIONS', headers: { + Origin: 'http://ui.test', 'Access-Control-Request-Method': 'POST', + 'Access-Control-Request-Headers': 'content-type,idempotency-key', + } }); + expect(preflight.status).toBe(204); + expect(preflight.headers.get('Access-Control-Allow-Headers')?.toLowerCase()).toContain('idempotency-key'); + expect(preflight.headers.get('Access-Control-Allow-Origin')).toBe('http://ui.test'); +}); + test('anonymous/invalid access is rejected; readers cannot mutate; service/admin can', async () => { const f = fixture(); expect((await f.app.request('/health')).status).toBe(200); diff --git a/test/integration/backtest-run-controls.test.tsx b/test/integration/backtest-run-controls.test.tsx index f87bae42..558de185 100644 --- a/test/integration/backtest-run-controls.test.tsx +++ b/test/integration/backtest-run-controls.test.tsx @@ -3,6 +3,7 @@ import { GlobalWindow } from 'happy-dom'; import { act, createElement, type ReactElement } from 'react'; import type { Root } from 'react-dom/client'; import type { + Backtest, Run, RunResult, } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'; @@ -22,11 +23,15 @@ let useBacktestV2: typeof import('../../apps/stock/web-app/src/features/backtest let useWebSocket: typeof import('../../apps/stock/web-app/src/hooks/useWebSocket').useWebSocket; let RunControlsCompact: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact').RunControlsCompact; let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2; +let CreateBacktestDialog: typeof import('../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog').CreateBacktestDialog; +let BacktestListPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestListPageV2').BacktestListPageV2; let router: typeof import('react-router-dom'); let root: Root | undefined; let host: HTMLDivElement; let latest: ReturnType; let renders = 0; +let pageLocation = ''; +let navigatePage: ReturnType; let now = 0; let timerId = 0; const timers = new Map< @@ -48,6 +53,8 @@ type Request = ReturnType> & { method: string; signal?: AbortSignal | null; settled: boolean; + body?: string; + headers: Headers; }; const requests: Request[] = []; function request(path: string, method = 'GET') { @@ -168,9 +175,10 @@ async function advance(ms: number) { } const polls = () => [...timers.values()].filter(timer => timer.delay === 1000).length; function click(label: string) { - const button = [...host.querySelectorAll('button')].find( - item => item.getAttribute('aria-label') === label || item.textContent?.trim() === label - ); + const buttons = [...host.querySelectorAll('button')]; + const button = + buttons.find(item => item.textContent?.trim() === label) ?? + buttons.find(item => item.getAttribute('aria-label') === label); if (!button) throw new Error(`Missing button ${label}`); button.click(); } @@ -217,7 +225,8 @@ async function mountPage(status: Run['status']) { path: '/backtests/:id/run/:runId', element: createElement(BacktestDetailPageV2), }) - ) + ), + createElement(LocationProbe) ) ); await flush(() => { @@ -230,6 +239,12 @@ async function mountPage(status: Run['status']) { }); } +function LocationProbe() { + pageLocation = router.useLocation().pathname; + navigatePage = router.useNavigate(); + return null; +} + beforeAll(async () => { for (const [key, value] of Object.entries({ window: browser, @@ -249,12 +264,19 @@ beforeAll(async () => { ({ BacktestDetailPageV2 } = await import( '../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2' )); + ({ CreateBacktestDialog } = await import( + '../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog' + )); + ({ BacktestListPageV2 } = await import( + '../../apps/stock/web-app/src/features/backtest/BacktestListPageV2' + )); router = await import('react-router-dom'); }); beforeEach(() => { requests.length = 0; TestSocket.instances.length = 0; renders = 0; + pageLocation = ''; now = 0; timers.clear(); host = browser.document.createElement('div') as unknown as HTMLDivElement; @@ -265,6 +287,8 @@ beforeEach(() => { path: new URL(String(input)).pathname, method: init?.method ?? 'GET', signal: init?.signal, + body: typeof init?.body === 'string' ? init.body : undefined, + headers: new Headers(init?.headers), settled: false, }; requests.push(pending); @@ -482,12 +506,12 @@ describe('run selection and persisted status authority', () => { await selectRunning(); expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([ 'Cancel run', - 'Rerun', + 'Run current settings', ]); await selectRunning('B', 'paused'); expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([ 'Cancel run', - 'Rerun', + 'Run current settings', ]); }); @@ -571,3 +595,347 @@ describe('actual detail page result states', () => { expect(host.textContent).toContain('Performance'); }); }); + +async function nameBacktest() { + await flush(() => { + const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!; + Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call( + input, + 'Fixture' + ); + input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event); + }); +} + +async function loadDefinition(id = 'definition') { + await flush(() => { + void latest.loadBacktest(id); + }); + await flush(() => { + reply(request(`/api/v2/backtests/${id}`), { ...definition, id }); + reply(request(`/api/v2/backtests/${id}/runs`), []); + }); +} + +describe('explicit save and repeat-safe run submission', () => { + test('save_only: definition save explicitly disables auto-start and makes no run request', async () => { + const created: Backtest[] = []; + await mount( + createElement(CreateBacktestDialog, { + onClose: () => {}, + onCreated: value => created.push(value), + }) + ); + await nameBacktest(); + await flush(() => { + click('Save'); + click('Save'); + }); + const saving = request('/api/v2/backtests', 'POST'); + expect(JSON.parse(saving.body!).autoStart).toBe(false); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + await flush(() => reply(saving, definition)); + expect(created).toEqual([definition]); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + }); + + for (const failure of ['rejection', 'lost successful response'] as const) { + test(`save_and_run_failure: ${failure} retries the saved definition, frozen body and key`, async () => { + const created: { definition: Backtest; run?: Run }[] = []; + await mount( + createElement(CreateBacktestDialog, { + onClose: () => {}, + onCreated: (value, submitted) => created.push({ definition: value, run: submitted }), + }) + ); + await nameBacktest(); + await flush(() => { + click('Save and run'); + click('Save and run'); + }); + await flush(() => reply(request('/api/v2/backtests', 'POST'), definition)); + const first = request('/api/v2/backtests/definition/runs', 'POST'); + expect(first.headers.get('Idempotency-Key')).toBeTruthy(); + expect(JSON.parse(first.body!)).toEqual({ speedMultiplier: null }); + // In the lost-response case the server has accepted A; the transport fails. + await flush(() => + failure === 'rejection' + ? reply(first, { error: 'Submission unavailable' }, 503) + : fail(first) + ); + expect(created).toHaveLength(0); + expect(host.textContent).toContain('Backtest saved, but run submission failed'); + expect(host.querySelector('fieldset')!.disabled).toBe(true); + await flush(() => { + click('Retry submission'); + click('Retry submission'); + }); + const retry = request('/api/v2/backtests/definition/runs', 'POST'); + expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); + expect(retry.body).toBe(first.body); + expect(requests.filter(item => item.path === '/api/v2/backtests')).toHaveLength(1); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(3); + await flush(() => reply(retry, run('A', 'pending'), 202)); + expect(created).toEqual([{ definition, run: run('A', 'pending') }]); + }); + } + + for (const boundary of ['definition', 'submission'] as const) { + test(`dialog unmount during ${boundary} ignores late completion and navigation`, async () => { + let navigated = false; + await mount( + createElement(CreateBacktestDialog, { + onClose: () => {}, + onCreated: () => { + navigated = true; + }, + }) + ); + await nameBacktest(); + await flush(() => click('Save and run')); + if (boundary === 'submission') { + await flush(() => reply(request('/api/v2/backtests', 'POST'), definition)); + } + await flush(() => root!.unmount()); + root = undefined; + await flush(() => + reply( + request( + boundary === 'definition' ? '/api/v2/backtests' : '/api/v2/backtests/definition/runs', + 'POST' + ), + boundary === 'definition' ? definition : run('A') + ) + ); + expect(navigated).toBe(false); + expect(requests.filter(item => item.method === 'POST')).toHaveLength( + boundary === 'definition' ? 1 : 2 + ); + }); + } + + test('closing cannot race the definition write and refresh a list before the row exists', async () => { + await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2))); + await flush(() => reply(request('/api/v2/backtests'), [])); + await flush(() => click('New Backtest')); + await nameBacktest(); + // The ref guard must work before the disabled state has rendered. + await flush(() => { + click('Save and run'); + click('Close backtest dialog'); + }); + expect(host.querySelector('[aria-label="Close backtest dialog"]')).not.toBeNull(); + expect( + requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET') + ).toHaveLength(1); + await flush(() => click('Close')); + expect( + requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET') + ).toHaveLength(1); + await flush(() => reply(request('/api/v2/backtests', 'POST'), definition)); + const submitting = request('/api/v2/backtests/definition/runs', 'POST'); + await flush(() => click('Close')); + await flush(() => reply(request('/api/v2/backtests'), [definition])); + await flush(() => reply(submitting, run('A', 'pending'), 202)); + expect(host.textContent).toContain('Create and manage backtest configurations'); + expect(host.querySelector('[aria-label="Close backtest dialog"]')).toBeNull(); + }); + + test('closing saved-but-failed dialog reloads the real list without navigating', async () => { + await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2))); + await flush(() => reply(request('/api/v2/backtests'), [])); + await flush(() => click('New Backtest')); + await nameBacktest(); + await flush(() => click('Save and run')); + await flush(() => reply(request('/api/v2/backtests', 'POST'), definition)); + await flush(() => fail(request('/api/v2/backtests/definition/runs', 'POST'))); + await flush(() => click('Close')); + await flush(() => reply(request('/api/v2/backtests'), [definition])); + // Virtualized rows need real layout (W04). Here verify the refetch and that + // the real list, not a detail route, remains mounted after closing. + expect( + requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET') + ).toHaveLength(2); + expect(host.textContent).toContain('Create and manage backtest configurations'); + expect(host.textContent).not.toContain('Retry submission'); + }); + + for (const intent of ['Save', 'Save and run'] as const) { + test(`real list ${intent} navigates only after the requested operation succeeds`, async () => { + await mount( + createElement( + router.MemoryRouter, + { initialEntries: ['/backtests'] }, + createElement( + router.Routes, + null, + createElement(router.Route, { + path: '/backtests', + element: createElement(BacktestListPageV2), + }), + createElement(router.Route, { + path: '/backtests/:id', + element: createElement('p', null, 'Saved definition'), + }), + createElement(router.Route, { + path: '/backtests/:id/run/:runId', + element: createElement('p', null, 'Submitted run'), + }) + ), + createElement(LocationProbe) + ) + ); + await flush(() => reply(request('/api/v2/backtests'), [])); + await flush(() => click('New Backtest')); + await nameBacktest(); + await flush(() => click(intent)); + expect(pageLocation).toBe('/backtests'); + await flush(() => reply(request('/api/v2/backtests', 'POST'), definition)); + if (intent === 'Save and run') { + expect(pageLocation).toBe('/backtests'); + await flush(() => + reply(request('/api/v2/backtests/definition/runs', 'POST'), run('A', 'pending'), 202) + ); + } + expect(pageLocation).toBe( + `/backtests/definition${intent === 'Save and run' ? '/run/A' : ''}` + ); + }); + } + + test('closing new-run confirmation prevents late successful submission from navigating', async () => { + await mountPage('failed'); + await flush(() => click('Runs')); + await flush(() => click('New Run')); + await flush(() => click('Run current settings')); + const submitting = request('/api/v2/backtests/definition/runs', 'POST'); + await flush(() => click('Cancel')); + await flush(() => reply(submitting, run('B', 'pending'), 202)); + expect(pageLocation).toBe('/backtests/definition/run/A'); + expect(host.textContent).not.toContain('Submit the current configuration'); + }); + + test('changing the actual run route prevents late submission navigation', async () => { + await mountPage('failed'); + await flush(() => click('Run current settings')); + const submitting = request('/api/v2/backtests/definition/runs', 'POST'); + await flush(() => { + void navigatePage('/backtests/definition/run/B'); + }); + await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed'))); + await flush(() => reply(submitting, run('C', 'pending'), 202)); + expect(pageLocation).toBe('/backtests/definition/run/B'); + expect(requests.some(item => item.path === '/api/v2/runs/C')).toBe(false); + }); + + test('submission errors remain visible after selecting another run and retry the same intent', async () => { + await mountPage('failed'); + await flush(() => click('Run current settings')); + const submitting = request('/api/v2/backtests/definition/runs', 'POST'); + await flush(() => { + void navigatePage('/backtests/definition/run/B'); + }); + await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed', { error: 'B failure' }))); + await flush(() => fail(submitting)); + expect(pageLocation).toBe('/backtests/definition/run/B'); + expect(host.textContent).toContain('Run submission failed: Network unavailable'); + expect(host.textContent).toContain('Run failed: B failure'); + await flush(() => click('Retry submission')); + const retry = request('/api/v2/backtests/definition/runs', 'POST'); + expect(retry.body).toBe(submitting.body); + expect(retry.headers.get('Idempotency-Key')).toBe(submitting.headers.get('Idempotency-Key')); + }); + + test('detail retries freeze payload/key across settings edits; acknowledged next intent has a fresh key', async () => { + await mount(); + await loadDefinition(); + await flush(() => { + void latest.createRun(2); + void latest.createRun(9); + }); + const first = request('/api/v2/backtests/definition/runs', 'POST'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + expect(latest.isSubmitting).toBe(true); + await flush(() => fail(first)); + expect(latest.submissionError).toContain('Network unavailable'); + await flush(() => { + void latest.updateBacktest('definition', { initialCapital: 2000 }); + }); + await flush(() => + reply(request('/api/v2/backtests/definition', 'PUT'), { ...definition, initialCapital: 2000 }) + ); + // A status reader may already have learned the run accepted before the lost response. + await selectRunning('A'); + 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', 'pending'), 202)); + expect(latest.runs.filter(item => item.id === 'A')).toHaveLength(1); + await flush(() => { + void latest.createRun(9); + }); + const next = request('/api/v2/backtests/definition/runs', 'POST'); + expect(next.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key')); + expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: 9 }); + await flush(() => reply(next, run('B', 'pending'), 202)); + expect(latest.runs.map(item => item.id)).toEqual(['B', 'A']); + }); + + test('new-run form remains open and submission failure is visible alongside a polling failure', async () => { + await mountPage('running'); + await advance(1000); + await flush(() => fail(request('/api/v2/runs/A'))); + await flush(() => click('Runs')); + await flush(() => click('New Run')); + await flush(() => { + click('Run current settings'); + click('Run current settings'); + }); + const first = request('/api/v2/backtests/definition/runs', 'POST'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + await flush(() => reply(first, { error: 'Submission unavailable' }, 503)); + expect(host.textContent).toContain('Run submission failed'); + expect(host.textContent).toContain('Network unavailable'); + expect(host.textContent).toContain('Submit the current configuration'); + await flush(() => click('Retry submission')); + const retry = request('/api/v2/backtests/definition/runs', 'POST'); + expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); + expect(retry.body).toBe(first.body); + }); + + for (const change of ['selection', 'backtest', 'unmount'] as const) { + test(`late submission completion cannot navigate or replace newer ${change}`, async () => { + await mount(); + await loadDefinition(); + let completed: Run | undefined; + await flush(() => { + void latest.createRun().then(value => { + completed = value; + }); + }); + const first = request('/api/v2/backtests/definition/runs', 'POST'); + if (change === 'selection') { + await selectRunning('B'); + } else if (change === 'backtest') { + await loadDefinition('other'); + } else { + await flush(() => root!.unmount()); + root = undefined; + } + const rendered = renders; + await flush(() => reply(first, run('A', 'pending'), 202)); + expect(completed).toBeUndefined(); + expect(latest.runs.some(item => item.id === 'A')).toBe(false); + if (change === 'selection') { + expect(latest.currentRun?.id).toBe('B'); + } else if (change === 'backtest') { + expect(latest.backtest?.id).toBe('other'); + } else { + expect(renders).toBe(rendered); + } + }); + } +}); diff --git a/test/integration/backtest-workflow.test.ts b/test/integration/backtest-workflow.test.ts index c76e7ca9..e196e3b0 100644 --- a/test/integration/backtest-workflow.test.ts +++ b/test/integration/backtest-workflow.test.ts @@ -83,6 +83,7 @@ async function fixture( started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz, request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0, dataset_hash text, lease_expires_at timestamptz, cancel_requested boolean DEFAULT false, + submission_principal text, submission_key text, submission_hash text, created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number)); CREATE TABLE backtest_dispatch (run_id uuid PRIMARY KEY REFERENCES runs(id), next_publish_at timestamptz DEFAULT NOW(), last_published_at timestamptz, publish_count integer DEFAULT 0); diff --git a/test/postgres/durable-backtest.test.ts b/test/postgres/durable-backtest.test.ts index 7b1323c5..cf3eeb6f 100644 --- a/test/postgres/durable-backtest.test.ts +++ b/test/postgres/durable-backtest.test.ts @@ -3,7 +3,9 @@ import { randomUUID } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; +import { Hono } from 'hono'; import { Pool } from 'pg'; +import { createHttpSecurity } from '@stock-bot/di'; import { HandlerRegistry } from '@stock-bot/handler-registry'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient } from '@stock-bot/postgres'; @@ -21,7 +23,10 @@ import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-d import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; 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 { + BacktestServiceV2, + RunSubmissionConflictError, +} 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 }); @@ -74,6 +79,7 @@ async function fixture() { '09-backtest-run-contract.sql', '10-durable-backtest-dispatch.sql', '12-historical-datasets.sql', + '14-backtest-submission.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') @@ -204,6 +210,216 @@ async function fixture() { } describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => { + test('idempotent_submission_postgres_race: one snapshot/outbox, canonical null speed and stable original intent after edits', async () => { + const f = await fixture(); + const submission = { principal: 'operator' as const, key: 'same-intent' }; + const runs = await Promise.all( + Array.from({ length: 8 }, (_, i) => + f.api.createRun( + { backtestId: f.definition.id, ...(i % 2 ? { speedMultiplier: null } : {}) }, + submission + ) + ) + ); + expect(new Set(runs.map(run => run.id)).size).toBe(1); + const original = await f.snapshot(runs[0]!.id); + await f.api.updateBacktest(f.definition.id, { + initialCapital: 12345, + config: { fastPeriod: 4, slowPeriod: 9 }, + }); + expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe( + runs[0]!.id + ); + expect(await f.snapshot(runs[0]!.id)).toEqual(original); + expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1); + expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); + await expect( + f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 2 }, submission) + ).rejects.toBeInstanceOf(RunSubmissionConflictError); + }); + + test('submission_key_conflict: different definitions racing for one principal/key cannot both commit', async () => { + const f = await fixture(); + const second = await f.api.createBacktest( + { + ...f.definition, + startDate: f.definition.startDate.toISOString(), + endDate: f.definition.endDate.toISOString(), + name: 'Second', + }, + { autoStart: false } + ); + const barrierKey = parseInt(randomUUID().slice(0, 7), 16); + await f.pool + .query(`CREATE FUNCTION delay_submission() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + PERFORM pg_advisory_xact_lock_shared(40303, ${barrierKey}); RETURN NEW; END $$; + CREATE TRIGGER delay_submission BEFORE INSERT ON runs FOR EACH ROW EXECUTE FUNCTION delay_submission()`); + const submission = { principal: 'operator' as const, key: 'cross-definition' }; + const barrier = await f.pool.connect(); + await barrier.query('SELECT pg_advisory_lock(40303, $1)', [barrierKey]); + const submissions = Promise.allSettled( + [f.definition.id, second.id].map(backtestId => f.api.createRun({ backtestId }, submission)) + ); + try { + // Both parent-row locks are held, neither run exists yet, and both transactions + // are inside their INSERT. Releasing shared waiters forces the unique-index race. + await until( + async () => + ( + await f.pool.query( + "SELECT count(*)::int AS count FROM pg_locks WHERE locktype = 'advisory' AND classid = 40303 AND objid = $1 AND NOT granted", + [barrierKey] + ) + ).rows[0].count === 2 + ); + expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); + } finally { + await barrier.query('SELECT pg_advisory_unlock(40303, $1)', [barrierKey]); + barrier.release(); + } + const outcomes = await submissions; + expect(outcomes.filter(outcome => outcome.status === 'fulfilled')).toHaveLength(1); + const rejection = outcomes.find(outcome => outcome.status === 'rejected'); + expect(rejection?.status === 'rejected' && rejection.reason).toBeInstanceOf( + RunSubmissionConflictError + ); + const committed = (await f.pool.query('SELECT * FROM runs')).rows; + expect(committed).toHaveLength(1); + expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); + const otherId = committed[0].backtest_id === f.definition.id ? second.id : f.definition.id; + await expect(f.api.createRun({ backtestId: otherId }, submission)).rejects.toBeInstanceOf( + RunSubmissionConflictError + ); + }); + + test('different principals can reuse keys; concurrent distinct and legacy submissions preserve run numbering', async () => { + const f = await fixture(); + const runs = await Promise.all([ + f.api.createRun({ backtestId: f.definition.id }, { principal: 'operator', key: 'shared' }), + f.api.createRun({ backtestId: f.definition.id }, { principal: 'service', key: 'shared' }), + ...Array.from({ length: 4 }, (_, i) => + f.api.createRun( + { backtestId: f.definition.id }, + { principal: 'operator', key: `intent-${i}` } + ) + ), + f.api.createRun({ backtestId: f.definition.id }), + f.api.createRun({ backtestId: f.definition.id }), + ]); + expect(new Set(runs.map(run => run.id)).size).toBe(8); + expect(runs.map(run => run.runNumber).sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + expect( + (await f.pool.query('SELECT * FROM runs WHERE submission_key IS NULL')).rows + ).toHaveLength(2); + expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(8); + }); + + test('outbox failure rolls back the submission claim and retry creates exactly one run', async () => { + const f = await fixture(); + await f.pool + .query(`CREATE FUNCTION reject_submission_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + RAISE EXCEPTION 'injected submission outbox failure'; END $$; + CREATE TRIGGER reject_submission_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_submission_outbox()`); + const submission = { principal: 'operator' as const, key: 'retry-after-rollback' }; + await expect(f.api.createRun({ backtestId: f.definition.id }, submission)).rejects.toThrow( + 'injected submission' + ); + expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); + await f.pool.query('DROP TRIGGER reject_submission_outbox ON backtest_dispatch'); + const created = await f.api.createRun({ backtestId: f.definition.id }, submission); + expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe( + created.id + ); + expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); + }); + + test('save_only route honors autoStart; authenticated keyed submissions return202/Location or409', async () => { + const f = await fixture(); + const app = new Hono(); + createHttpSecurity({ disabled: true, environment: 'test' }).mount(app); + app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger })); + const body = { ...f.definition, autoStart: false }; + expect( + ( + await app.request('/api/v2/backtests', { + method: 'POST', + body: JSON.stringify({ ...body, autoStart: 'false' }), + }) + ).status + ).toBe(400); + const saved = await app.request('/api/v2/backtests', { + method: 'POST', + body: JSON.stringify(body), + }); + expect(saved.status).toBe(201); + const definition = await saved.json(); + expect(await f.api.listRuns(definition.id)).toHaveLength(0); + const post = (payload: object) => + app.request(`/api/v2/backtests/${definition.id}/runs`, { + method: 'POST', + headers: { 'Idempotency-Key': 'route-retry' }, + body: JSON.stringify(payload), + }); + const response = await post({}); + expect(response.status).toBe(202); + const run = await response.json(); + expect(response.headers.get('Location')).toBe(`/api/v2/runs/${run.id}`); + expect((await (await post({ speedMultiplier: null })).json()).id).toBe(run.id); + expect((await post({ speedMultiplier: 2 })).status).toBe(409); + const legacy = await app.request('/api/v2/backtests', { + method: 'POST', + body: JSON.stringify({ ...body, autoStart: undefined }), + }); + expect(await f.api.listRuns((await legacy.json()).id)).toHaveLength(1); + }); + + test('cookie renewal and admin bearer replay the same operator submission while service keys are separate', async () => { + const f = await fixture(); + const adminToken = 'submission-fixture-admin-not-a-secret-123456'; + const serviceToken = 'submission-fixture-service-not-a-secret-123456'; + const app = new Hono(); + createHttpSecurity({ + adminToken, + serviceToken, + browserSessions: true, + origins: ['http://ui.test'], + }).mount(app); + app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger })); + const submit = async (headers: Record) => { + const response = await app.request(`/api/v2/backtests/${f.definition.id}/runs`, { + method: 'POST', + headers: { + 'Idempotency-Key': 'authenticated-intent', + 'X-Principal': 'spoofed', + ...headers, + }, + body: '{}', + }); + expect(response.status).toBe(202); + return (await response.json()).id as string; + }; + const original = await submit({ Authorization: `Bearer ${adminToken}` }); + for (let i = 0; i < 2; i++) { + const login = await app.request('/api/auth/session', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Origin: 'http://ui.test' }, + body: JSON.stringify({ token: adminToken }), + }); + expect(login.status).toBe(200); + expect( + await submit({ + Cookie: login.headers.get('Set-Cookie')!.split(';')[0]!, + Origin: 'http://ui.test', + }) + ).toBe(original); + } + expect(await submit({ Authorization: `Bearer ${serviceToken}` })).not.toBe(original); + expect( + (await f.pool.query('SELECT submission_principal FROM runs ORDER BY run_number')).rows + ).toEqual([{ submission_principal: 'operator' }, { submission_principal: 'service' }]); + expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(2); + }); + test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 0b451a4b..fc3c0246 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -17,6 +17,7 @@ const migrations = [ '11-simulation-execution-ledger.sql', '12-historical-datasets.sql', '13-strategy-recovery.sql', + '14-backtest-submission.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { @@ -130,6 +131,40 @@ 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')) { + await f.pool.query( + readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') + ); + } + const backtestId = randomUUID(); + const runId = randomUUID(); + await f.pool.query( + `INSERT INTO backtests (id,name,strategy,symbols,start_date,end_date,initial_capital) + VALUES ($1,'Legacy','sma-crossover','["A.US"]','2024-01-01','2024-02-01',10000)`, + [backtestId] + ); + await f.pool.query( + "INSERT INTO runs (id,backtest_id,run_number,status,request_snapshot) VALUES ($1,$2,1,'completed','{\"legacy\":true}')", + [runId, backtestId] + ); + await f.startup().run(); + const row = (await f.pool.query('SELECT * FROM runs WHERE id = $1', [runId])).rows[0]; + expect(row.request_snapshot).toEqual({ legacy: true }); + expect(row.status).toBe('completed'); + expect([row.submission_principal, row.submission_key, row.submission_hash]).toEqual([ + null, + null, + null, + ]); + await expect( + f.pool.query("UPDATE runs SET submission_key = 'incomplete' WHERE id = $1", [runId]) + ).rejects.toThrow('runs_submission_complete'); + await f.startup().run(); + expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1); + }); + test('two_concurrent_startups_same_client_lock and precheck_inside_lock', async () => { const f = await fixture(); const firstAtPrecheck = gate();