diff --git a/apps/stock/config/src/contracts/canonical-research.ts b/apps/stock/config/src/contracts/canonical-research.ts index 76ca27e2..94b105bd 100644 --- a/apps/stock/config/src/contracts/canonical-research.ts +++ b/apps/stock/config/src/contracts/canonical-research.ts @@ -187,3 +187,24 @@ export function parseCanonicalFinancialResult(input: unknown, request: Canonical request.policy ); } + +/** Reproduce retained inputs on the exact installed build; no historical binary provisioning. */ +export interface CanonicalReproductionPreview { + originalRunId: string; + backtestId: string; + available: boolean; + reason: string | null; + request: CanonicalRunRequest | null; + /** Current approval required for a fresh admission; historical approval stays in request. */ + currentReviewId: string | null; +} +export interface CanonicalReproductionComparison { + version: 'canonical-reproduction/v1'; + runId: string; + backtestId: string; + originalRunId: string | null; + status: 'not-reproduction' | 'pending' | 'unavailable' | 'match' | 'mismatch'; + reason: string | null; + originalHash: string | null; + reproducedHash: string | null; +} diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 0a6a53a3..6cf0dc2c 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -60,7 +60,8 @@ export async function runMigrations(container: IServiceContainer): Promise f === '17-research-retention.sql' || f === '18-backtest-strategy-versions.sql' || f === '19-canonical-research.sql' || - f === '20-research-workspace.sql') + f === '20-research-workspace.sql' || + f === '21-run-reproduction.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 82fad44c..47f85395 100644 --- a/apps/stock/web-api/src/routes/backtests-v2.routes.ts +++ b/apps/stock/web-api/src/routes/backtests-v2.routes.ts @@ -1,6 +1,6 @@ import { Hono } from 'hono'; import { z } from 'zod'; -import { getVerifiedHttpPrincipal } from '@stock-bot/di'; +import { getCredentialHttpPrincipal, getVerifiedHttpPrincipal } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; import { @@ -13,6 +13,7 @@ import { CatalogExecutionUnavailableError, RunSubmissionConflictError, } from '../services/backtest-v2.service'; +import { RunReproductionError } from '../services/run-reproduction'; import { StrategyCatalogError } from '../services/strategy-catalog.service'; const logger = getLogger('backtests-v2-routes'); @@ -184,6 +185,79 @@ export function createBacktestV2Routes(container: IServiceContainer) { } }); + app.get('/api/v2/runs/:id/reproduction', async c => { + c.header('Cache-Control', 'no-store'); + const id = z.string().uuid().safeParse(c.req.param('id')); + if (!id.success) { + return c.json({ error: 'Invalid original run ID' }, 400); + } + try { + return c.json(await backtestService.getReproductionPreview(id.data)); + } catch (error) { + if (error instanceof RunReproductionError) { + return c.json({ error: error.message, code: error.code }, error.status); + } + logger.error('Failed to preview reproduction', error); + return c.json({ error: 'Could not inspect original run reproduction' }, 500); + } + }); + + app.post('/api/v2/runs/:id/reproduce', async c => { + c.header('Cache-Control', 'no-store'); + const principal = getCredentialHttpPrincipal(c.req.raw); + if (!principal) { + return c.json({ error: 'Verified credential principal required' }, 401); + } + let originalRunId: string; + let key: string; + try { + originalRunId = z.string().uuid().parse(c.req.param('id')); + key = z + .string() + .regex(/^[\x21-\x7e]{1,200}$/) + .parse(c.req.header('Idempotency-Key')); + z.object({}) + .strict() + .parse(await c.req.json()); + } catch { + return c.json( + { error: 'Use a valid run ID, an empty object and a 1–200 visible ASCII Idempotency-Key' }, + 400 + ); + } + try { + const run = await backtestService.reproduceRun(originalRunId, { principal, key }); + c.header('Location', `/api/v2/runs/${run.id}`); + return c.json(run, 202); + } catch (error) { + if (error instanceof RunReproductionError) { + return c.json({ error: error.message, code: error.code }, error.status); + } + if (error instanceof BacktestRetentionError || error instanceof RunSubmissionConflictError) { + return c.json({ error: error.message }, 409); + } + logger.error('Failed to reproduce original run', error); + return c.json({ error: 'Could not reproduce original run' }, 500); + } + }); + + app.get('/api/v2/runs/:id/reproduction-comparison', async c => { + c.header('Cache-Control', 'no-store'); + const id = z.string().uuid().safeParse(c.req.param('id')); + if (!id.success) { + return c.json({ error: 'Invalid run ID' }, 400); + } + try { + return c.json(await backtestService.getReproductionComparison(id.data)); + } catch (error) { + if (error instanceof RunReproductionError) { + return c.json({ error: error.message, code: error.code }, error.status); + } + logger.error('Failed to compare reproduction', error); + return c.json({ error: 'Could not compare retained reproduction results' }, 500); + } + }); + app.get('/api/v2/runs/:id', async c => { try { const run = await backtestService.getRun(c.req.param('id')); 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 5b33a053..68765862 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -16,6 +16,8 @@ import { import { canonicalRunRequestSchema, parseCanonicalFinancialResult, + type CanonicalReproductionComparison, + type CanonicalReproductionPreview, type CanonicalRunCapability, type CanonicalRunResult, type ResearchRunResult, @@ -33,6 +35,8 @@ import type { WebSocketHandler } from '../websocket/run-updates'; import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result'; import { admitCanonicalRequest, validateCanonicalSetup } from './canonical-research.service'; import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service'; +import { canonicalReproductionHash } from './reproduction-comparison'; +import { RunReproductionError, verifyReproductionInputs } from './run-reproduction'; import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service'; const logger = getLogger('backtest-v2-service'); @@ -78,6 +82,7 @@ export interface Backtest { } export interface Run { + originalRunId: string | null; dataset: BacktestRunDatasetSelection; id: string; backtestId: string; @@ -504,6 +509,224 @@ export class BacktestServiceV2 { return this.mapRun(row); } + /** Preview validates retained inputs without admitting work or consulting current settings. */ + async getReproductionPreview(originalRunId: string): Promise { + return this.container.postgres.transaction(async client => { + const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId])) + .rows[0]; + if (!source) { + throw new RunReproductionError(404, 'Original run not found'); + } + const preview: CanonicalReproductionPreview = { + originalRunId, + backtestId: source.backtest_id, + available: false, + reason: null, + request: null, + currentReviewId: null, + }; + try { + const request = await this.originalCanonicalRequest(client, source); + preview.request = request; + const parent = ( + await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [ + source.backtest_id, + ]) + ).rows[0]; + if (!parent || parent.archived_at !== null) { + throw new RunReproductionError( + 409, + 'Backtest is archived; restore it before reproducing a run' + ); + } + preview.currentReviewId = await verifyReproductionInputs(client, this.container, request); + preview.available = true; + } catch (cause) { + if (!(cause instanceof RunReproductionError)) { + throw cause; + } + preview.reason = cause.message; + } + return preview; + }); + } + + async reproduceRun(originalRunId: string, submission: RunSubmission): Promise { + if ( + !submission || + !['operator', 'service'].includes(submission.principal) || + !/^[\x21-\x7e]{1,200}$/.test(submission.key) + ) { + throw new HistoricalDataRequestError('Reproduction requires a verified submission receipt'); + } + const submissionHash = createHash('sha256') + .update( + JSON.stringify({ + version: 1, + operation: 'reproduce-original', + originalRunId, + }) + ) + .digest('hex'); + const row = await this.container.postgres.transaction(async client => { + const replay = async () => { + const saved = ( + await client.query( + 'SELECT * FROM runs WHERE submission_principal=$1 AND submission_key=$2', + [submission.principal, submission.key] + ) + ).rows[0]; + if (saved && saved.submission_hash !== submissionHash) { + throw new RunSubmissionConflictError(); + } + return saved; + }; + const previous = await replay(); + if (previous) { + return previous; + } + const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId])) + .rows[0]; + if (!source) { + throw new RunReproductionError(404, 'Original run not found'); + } + const parent = ( + await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [ + source.backtest_id, + ]) + ).rows[0]; + const concurrent = await replay(); + if (concurrent) { + return concurrent; + } + if (!parent || parent.archived_at !== null) { + throw new BacktestRetentionError('backtest_archived'); + } + const original = await this.originalCanonicalRequest(client, source); + const reviewId = await verifyReproductionInputs(client, this.container, original); + const runId = uuidv4(); + const snapshot = structuredClone(original); + snapshot.runId = runId; + snapshot.policy.matching.risk.ledger.sessionId = runId; + snapshot.policy.matching.risk.ledger.accountId = `research:${runId}`; + snapshot.strategy.reviewId = reviewId; + canonicalRunRequestSchema.parse(snapshot); + const inserted = await client.query( + `INSERT INTO runs + (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash, + submission_principal,submission_key,submission_hash,original_run_id) + SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending'::run_status,NULL,$3::jsonb,$4,$5,$6,$7,$8 + FROM runs WHERE backtest_id=$2 + ON CONFLICT (submission_principal,submission_key) DO NOTHING RETURNING *`, + [ + runId, + source.backtest_id, + JSON.stringify(snapshot), + snapshot.datasetHash, + submission.principal, + submission.key, + submissionHash, + originalRunId, + ] + ); + if (!inserted.rows[0]) { + const winner = await replay(); + if (!winner) { + throw new Error('Concurrent reproduction disappeared; retry with the same key'); + } + return winner; + } + await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]); + return inserted.rows[0]; + }); + return this.mapRun(row); + } + + async getReproductionComparison(runId: string): Promise { + const current = (await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [runId])) + .rows[0]; + if (!current) { + throw new RunReproductionError(404, 'Run not found'); + } + const comparison: CanonicalReproductionComparison = { + version: 'canonical-reproduction/v1', + runId, + backtestId: current.backtest_id, + originalRunId: current.original_run_id ?? null, + status: 'not-reproduction', + reason: null, + originalHash: null, + reproducedHash: null, + }; + if (!comparison.originalRunId) { + return comparison; + } + if (['pending', 'running', 'paused'].includes(current.status)) { + return { ...comparison, status: 'pending', reason: 'The reproduction has not completed' }; + } + if (current.status !== 'completed') { + return { + ...comparison, + status: 'unavailable', + reason: 'The reproduction did not complete successfully', + }; + } + const source = ( + await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [ + comparison.originalRunId, + ]) + ).rows[0]; + if (!source || source.status !== 'completed' || source.backtest_id !== current.backtest_id) { + return { + ...comparison, + status: 'unavailable', + reason: 'The original completed run is unavailable', + }; + } + const original = await this.getRunResults(source.id); + const reproduced = await this.getRunResults(runId); + if (!original || !reproduced || !('kind' in original) || !('kind' in reproduced)) { + return { + ...comparison, + status: 'unavailable', + reason: 'Complete canonical results are unavailable', + }; + } + const originalHash = canonicalReproductionHash(original); + const reproducedHash = canonicalReproductionHash(reproduced); + return { + ...comparison, + originalHash, + reproducedHash, + status: originalHash === reproducedHash ? 'match' : 'mismatch', + }; + } + + private async originalCanonicalRequest(client: PoolClient, source: QueryResultRow) { + if (source.status !== 'completed') { + throw new RunReproductionError(409, 'Only completed original runs can be reproduced'); + } + if (source.request_snapshot?.kind !== 'canonical-research/v1') { + throw new RunReproductionError( + 409, + 'The original run lacks compatible frozen canonical inputs' + ); + } + const request = canonicalRunRequestSchema.parse(source.request_snapshot); + if ( + request.runId !== source.id || + request.backtestId !== source.backtest_id || + request.datasetHash !== source.dataset_hash + ) { + throw new Error('The retained canonical source identity is inconsistent'); + } + const result = await this.getRunResults(source.id, client); + if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') { + throw new RunReproductionError(409, 'The original canonical result is unavailable'); + } + return request; + } + async getRun(id: string): Promise { const result = await this.container.postgres.query('SELECT * FROM runs WHERE id = $1', [id]); @@ -755,6 +978,7 @@ export class BacktestServiceV2 { private mapRun(row: QueryResultRow): Run { return { + originalRunId: row.original_run_id ?? null, dataset: datasetSelectionForRun(row), id: row.id, backtestId: row.backtest_id, diff --git a/apps/stock/web-api/src/services/reproduction-comparison.ts b/apps/stock/web-api/src/services/reproduction-comparison.ts new file mode 100644 index 00000000..e82f1235 --- /dev/null +++ b/apps/stock/web-api/src/services/reproduction-comparison.ts @@ -0,0 +1,49 @@ +import { createHash } from 'node:crypto'; +import { + canonicalRunRequestSchema, + parseCanonicalFinancialResult, + type CanonicalRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; + +/** Call with a retained result validated by getRunResults. This copies facts; + * it never recalculates financial values or statistically approximates equality. + * Only new admission identities are normalized. Market sessions, owner/decision/ + * order/fill IDs and every ordered financial/reporting fact remain significant. */ +export function canonicalReproductionHash(result: CanonicalRunResult): string { + const request = canonicalRunRequestSchema.parse(result.request); + if ( + result.kind !== 'canonical-result/v1' || + result.status !== 'completed' || + result.financialEngine !== 'rust' || + result.strategyExecution !== 'typescript-retained-builtin/v1' || + result.runId !== request.runId || + result.backtestId !== request.backtestId + ) { + throw new Error('Reproduction comparison requires matching canonical result identity'); + } + const financial = parseCanonicalFinancialResult(result.financial, request); + // Parsed objects are detached. Do not recursively erase similarly named fields: + // riskSession.sessionId, for example, is a real economic clock input. + request.runId = 'run'; + request.strategy.reviewId = 'admission-review'; + request.policy.matching.risk.ledger.sessionId = 'run'; + request.policy.matching.risk.ledger.accountId = 'account'; + financial.identity.sessionId = 'run'; + financial.policy.matching.risk.ledger.sessionId = 'run'; + financial.policy.matching.risk.ledger.accountId = 'account'; + financial.view.portfolio.sessionId = 'run'; + financial.view.portfolio.accountId = 'account'; + return createHash('sha256') + .update( + canonicalStrategyJson({ + version: 'canonical-reproduction/v1', + financialEngine: result.financialEngine, + strategyExecution: result.strategyExecution, + request, + financial, + analytics: result.analytics, + }) + ) + .digest('hex'); +} diff --git a/apps/stock/web-api/src/services/run-reproduction.ts b/apps/stock/web-api/src/services/run-reproduction.ts new file mode 100644 index 00000000..24eeed96 --- /dev/null +++ b/apps/stock/web-api/src/services/run-reproduction.ts @@ -0,0 +1,104 @@ +import type { PoolClient } from 'pg'; +import type { IServiceContainer } from '@stock-bot/services'; +import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import { HistoricalDataRequestError } from '@stock-bot/types'; +import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build'; +import { readCanonicalDataset } from './canonical-research.service'; +import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service'; + +export class RunReproductionError extends Error { + readonly code = 'run_reproduction_unavailable'; + constructor( + public readonly status: 404 | 409, + message: string + ) { + super(message); + } +} + +/** Under the parent lock, validate the ORIGINAL version, never current template settings. */ +export async function verifyReproductionInputs( + client: PoolClient, + container: IServiceContainer, + request: CanonicalRunRequest +): Promise { + const selected = ( + await client.query( + `SELECT v.strategy_id,v.origin,s.archived_at FROM strategy_versions v + JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 FOR UPDATE OF s`, + [request.strategy.versionId] + ) + ).rows[0]; + if ( + !selected || + selected.strategy_id !== request.strategy.familyId || + selected.origin !== 'builtin' + ) { + throw new RunReproductionError(409, 'The original retained built-in version is unavailable'); + } + if (selected.archived_at !== null) { + throw new RunReproductionError(409, 'The original strategy family is archived'); + } + const review = ( + await client.query( + 'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1', + [request.strategy.versionId] + ) + ).rows[0]; + if (review?.decision !== 'approve') { + throw new RunReproductionError( + 409, + 'The original strategy version requires current operator approval' + ); + } + try { + const pkg = await new StrategyCatalogService(container).getVersionArtifact( + request.strategy.versionId, + client + ); + if (canonicalStrategyJson(pkg) !== canonicalStrategyJson(request.strategy.package)) { + throw new RunReproductionError( + 409, + 'The retained strategy artifact differs from the original request' + ); + } + const dataset = await readCanonicalDataset(client, request.datasetHash); + const execution = dataset.manifest.executionSeries[0]; + if ( + execution?.instrumentId !== request.strategy.selection.instrumentId || + execution.seriesId !== request.strategy.selection.seriesId + ) { + throw new RunReproductionError( + 409, + 'The retained dataset does not match the original execution series' + ); + } + } catch (cause) { + if (cause instanceof StrategyCatalogError || cause instanceof HistoricalDataRequestError) { + throw new RunReproductionError(409, cause.message); + } + throw cause; + } + let build; + try { + build = await readCanonicalBuildIdentity(); + } catch (cause) { + if ( + cause && + typeof cause === 'object' && + 'code' in cause && + ['ENOENT', 'ENOTDIR', 'EACCES'].includes(String(cause.code)) + ) { + throw new RunReproductionError(409, 'The original canonical build is not installed'); + } + throw cause; + } + if (canonicalStrategyJson(build) !== canonicalStrategyJson(request.build)) { + throw new RunReproductionError( + 409, + 'The original worker/native/runtime build is not installed; historical build execution is unavailable' + ); + } + return review.id; +} diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index 80409446..7054532a 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -16,6 +16,7 @@ import { CanonicalResults } from './components/CanonicalResults'; import { CanonicalSetup } from './components/CanonicalSetup'; import { RunControlsCompact } from './components/RunControlsCompact'; import { RunDataset } from './components/RunDataset'; +import { RunReproduction } from './components/RunReproduction'; import { RunsListWithMetrics } from './components/RunsListWithMetrics'; import { useBacktestV2 } from './hooks/useBacktestV2'; import type { BacktestConfig } from './types/backtest.types'; @@ -510,6 +511,7 @@ export function BacktestDetailPageV2() { )} {currentRun && (
+

Run current settings

)} {currentRun && } -
{renderTabContent()}
+
+ {currentRun && + currentRun.id === runId && + currentRun.backtestId === id && + backtest?.id === id && } + {renderTabContent()} +
{showFinding && findingResult && ( ; +} +function Reproduction({ run, archived }: Props) { + const navigate = useNavigate(); + const alive = useRef(false); + const pending = useRef(false); + const intent = useRef<{ originalRunId: string; backtestId: string; key: string } | null>(null); + const [open, setOpen] = useState(false); + const [preview, setPreview] = useState(null); + const [previewError, setPreviewError] = useState(''); + const [loading, setLoading] = useState(false); + const [reload, setReload] = useState(0); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(''); + const [hasIntent, setHasIntent] = useState(false); + const [ambiguous, setAmbiguous] = useState(false); + const [comparison, setComparison] = useState(null); + const [comparisonError, setComparisonError] = useState(''); + const [comparisonLoading, setComparisonLoading] = useState(false); + const [comparisonReload, setComparisonReload] = useState(0); + useUnsavedWarning(hasIntent); + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + }; + }, []); + useEffect(() => { + if (!open) { + return; + } + let current = true; + const controller = new AbortController(); + setLoading(true); + setPreviewError(''); + setPreview(null); + void backtestApiV2 + .reproductionPreview(run.id, controller.signal) + .then(value => { + if (value.originalRunId !== run.id || value.backtestId !== run.backtestId) { + throw new Error('The reproduction preview belongs to a different run or backtest'); + } + if (current) { + setPreview(value); + } + }) + .catch(cause => { + if (current) { + setPreviewError( + cause instanceof Error ? cause.message : 'Could not load original inputs' + ); + } + }) + .finally(() => { + if (current) { + setLoading(false); + } + }); + return () => { + current = false; + controller.abort(); + }; + }, [open, reload, run.id, run.backtestId, run.status, archived]); + useEffect(() => { + if (!run.originalRunId) { + return; + } + let current = true; + const controller = new AbortController(); + setComparison(null); + setComparisonError(''); + setComparisonLoading(true); + void backtestApiV2 + .reproductionComparison(run.id, controller.signal) + .then(value => { + if ( + value.runId !== run.id || + value.backtestId !== run.backtestId || + value.originalRunId !== run.originalRunId || + value.status === 'not-reproduction' + ) { + throw new Error('The reproduction comparison does not match this run and its original'); + } + if (current) { + setComparison(value); + } + }) + .catch(cause => { + if (current) { + setComparisonError(cause instanceof Error ? cause.message : 'Could not load comparison'); + } + }) + .finally(() => { + if (current) { + setComparisonLoading(false); + } + }); + return () => { + current = false; + controller.abort(); + }; + }, [run.id, run.backtestId, run.originalRunId, run.status, comparisonReload]); + + const canCreate = !archived && !loading && !previewError && preview?.available && preview.request; + const submit = async () => { + if (pending.current || (!intent.current && !canCreate)) { + return; + } + // A retry retains this exact source/key even if a later preview is unavailable. + intent.current ??= { + originalRunId: run.id, + backtestId: run.backtestId, + key: crypto.randomUUID(), + }; + const captured = intent.current; + pending.current = true; + setHasIntent(true); + setSubmitting(true); + setError(''); + try { + const admitted = await backtestApiV2.reproduceRun(captured.originalRunId, captured.key); + if ( + admitted.backtestId !== captured.backtestId || + admitted.originalRunId !== captured.originalRunId + ) { + throw new ReproductionSubmissionError( + 'The accepted reproduction belongs to a different source. Retry the same submission to verify it.', + null + ); + } + if (alive.current) { + intent.current = null; + setHasIntent(false); + navigate( + `/backtests/${encodeURIComponent(admitted.backtestId)}/run/${encodeURIComponent(admitted.id)}` + ); + } + } catch (cause) { + if (alive.current) { + setError(cause instanceof Error ? cause.message : 'Could not reproduce original run'); + setAmbiguous(!(cause instanceof ReproductionSubmissionError) || cause.ambiguous); + } + } finally { + pending.current = false; + if (alive.current) { + setSubmitting(false); + } + } + }; + const close = () => { + if (!pending.current) { + setOpen(false); + } + }; + return ( +
+
+ +

Use this run's retained inputs. New Run and Rerun use current settings.

+
+ {run.originalRunId && ( +
+

+ Reproduction of{' '} + + Open original run + {' '} + ({run.originalRunId}) +

+ {comparisonLoading &&

Loading reproduction comparison...

} + {comparisonError &&

{comparisonError}

} + {comparison && ( + <> +

+ {comparison.status === 'match' + ? 'Economic results match the original.' + : comparison.status === 'mismatch' + ? 'Economic results differ from the original.' + : comparison.status === 'pending' + ? 'Reproduction comparison pending completion.' + : 'Reproduction comparison unavailable.'} +

+ {comparison.reason &&

{comparison.reason}

} +

Comparison policy: {comparison.version}

+ {comparison.originalHash && ( +

+ Original economic hash: {comparison.originalHash} +

+ )} + {comparison.reproducedHash && ( +

+ Reproduced economic hash: {comparison.reproducedHash} +

+ )} +

+ The server compares retained inputs and saved results, excluding new run identities + and execution duration. A match is not strategy validation. +

+ + )} + +
+ )} + { + if (!value) { + close(); + } + }} + > + +
+ + Reproduce original + +

Original run: {run.id}

+

+ This submits a new run using the original dataset, strategy version, parameters, seed + and policies. Current template settings are not used. The same installed engine build + and current strategy approval are required. +

+ {loading &&

Loading original inputs...

} + {previewError &&

{previewError}

} + {archived && ( +

+ This backtest is archived. Restore it before creating a new reproduction. +

+ )} + {preview && !preview.available && ( +

+ Original reproduction unavailable:{' '} + {preview.reason ?? 'Retained inputs cannot be reproduced.'} +

+ )} + {preview?.request && ( +
+

Original retained inputs

+

Name: {preview.request.name}

+

Dataset: {preview.request.datasetHash}

+

+ Strategy version:{' '} + + {preview.request.strategy.versionId} + +

+

+ Asset: {preview.request.strategy.selection.instrumentId} · Series:{' '} + {preview.request.strategy.selection.seriesId} +

+

Random seed: {preview.request.strategy.selection.seed}

+

+ Initial capital: {preview.request.policy.matching.risk.ledger.initialCapital}{' '} + {preview.request.policy.matching.risk.ledger.baseCurrency} +

+

+ Original review: {preview.request.strategy.reviewId} · Current approval:{' '} + {preview.currentReviewId ?? 'Unavailable'} +

+
+ + Exact parameters, financial policies and build + +
+                    {JSON.stringify(
+                      {
+                        strategy: preview.request.strategy.selection,
+                        artifact: {
+                          ...preview.request.strategy.package.artifact,
+                          content: undefined,
+                        },
+                        dependencyLock: {
+                          ...preview.request.strategy.package.dependencyLock,
+                          content: undefined,
+                        },
+                        policy: preview.request.policy,
+                        analyticsPolicy: preview.request.analyticsPolicy,
+                        modelArtifacts: preview.request.modelArtifacts,
+                        build: preview.request.build,
+                      },
+                      null,
+                      2
+                    )}
+                  
+
+
+ )} + + {error &&

{error}

} + {hasIntent && ( +

+ {ambiguous ? 'The previous request may already have been accepted. ' : ''}Retry uses + the same source and submission key to recover that run. +

+ )} +
+ + {hasIntent && ( + + )} + +
+
+
+
+
+ ); +} 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 7c5c38a4..4f3037ff 100644 --- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts @@ -1,5 +1,8 @@ +import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; import type { CanonicalDatasetCatalogEntry, + CanonicalReproductionComparison, + CanonicalReproductionPreview, CanonicalRunCapability, ResearchRunResult, } from '@stock-bot/stock-config/canonical-research'; @@ -29,6 +32,7 @@ export interface Backtest { export interface Run { id: string; + originalRunId?: string | null; backtestId: string; runNumber: number; status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused'; @@ -84,7 +88,137 @@ async function requestError(response: Response, fallback: string): Promise= 500; + } +} +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); +const nullableText = (value: unknown) => value === null || typeof value === 'string'; +const hashOrNull = (value: unknown) => + value === null || (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)); + export const backtestApiV2 = { + async reproductionPreview( + id: string, + signal?: AbortSignal + ): Promise { + const response = await fetch( + `${API_BASE_URL}/api/v2/runs/${encodeURIComponent(id)}/reproduction`, + { signal } + ); + if (!response.ok) { + throw await requestError(response, 'Could not check original-run reproduction'); + } + const body: unknown = await response.json(); + if ( + !isRecord(body) || + body.originalRunId !== id || + typeof body.backtestId !== 'string' || + typeof body.available !== 'boolean' || + !nullableText(body.reason) || + !nullableText(body.currentReviewId) + ) { + throw new Error('The original-run preview response could not be verified'); + } + const request = body.request === null ? null : canonicalRunRequestSchema.parse(body.request); + if ( + (request && (request.runId !== id || request.backtestId !== body.backtestId)) || + (body.available && (!request || !body.currentReviewId)) + ) { + throw new Error('The original-run preview does not match its retained source'); + } + return { + originalRunId: id, + backtestId: body.backtestId, + available: body.available, + reason: body.reason as string | null, + currentReviewId: body.currentReviewId as string | null, + request, + }; + }, + async reproduceRun(originalRunId: string, submissionKey: string): Promise { + let response: Response; + try { + response = await fetch( + `${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey }, + body: '{}', + } + ); + } catch { + throw new ReproductionSubmissionError( + 'The reproduction response was lost. Retry with this same submission key to recover the accepted run.', + null + ); + } + if (!response.ok) { + const error = await requestError(response, 'Could not reproduce original run'); + throw new ReproductionSubmissionError(error.message, response.status); + } + const body: unknown = await response.json().catch(() => null); + if ( + response.status !== 202 || + !isRecord(body) || + typeof body.id !== 'string' || + !body.id || + body.id === originalRunId || + typeof body.backtestId !== 'string' || + body.originalRunId !== originalRunId || + !['pending', 'running', 'completed', 'failed', 'cancelled', 'paused'].includes( + String(body.status) + ) + ) { + throw new ReproductionSubmissionError( + 'The accepted reproduction response could not be verified. Retry with this same submission key.', + null + ); + } + return body as unknown as Run; + }, + async reproductionComparison( + id: string, + signal?: AbortSignal + ): Promise { + const response = await fetch( + `${API_BASE_URL}/api/v2/runs/${encodeURIComponent(id)}/reproduction-comparison`, + { signal } + ); + if (!response.ok) { + throw await requestError(response, 'Could not load reproduction comparison'); + } + const body: unknown = await response.json(); + if ( + !isRecord(body) || + body.version !== 'canonical-reproduction/v1' || + body.runId !== id || + typeof body.backtestId !== 'string' || + !nullableText(body.originalRunId) || + !nullableText(body.reason) || + !hashOrNull(body.originalHash) || + !hashOrNull(body.reproducedHash) || + !['not-reproduction', 'pending', 'unavailable', 'match', 'mismatch'].includes( + String(body.status) + ) || + (['match', 'mismatch'].includes(String(body.status)) && + (!body.originalRunId || !body.originalHash || !body.reproducedHash)) || + (body.status === 'match' && body.originalHash !== body.reproducedHash) || + (body.status === 'mismatch' && body.originalHash === body.reproducedHash) + ) { + throw new Error('The reproduction comparison response could not be verified'); + } + return body as unknown as CanonicalReproductionComparison; + }, + async canonicalCapability(id: string, signal?: AbortSignal): Promise { const response = await fetch( `${API_BASE_URL}/api/v2/backtests/${encodeURIComponent(id)}/canonical-capability`, diff --git a/database/postgres/init/21-run-reproduction.sql b/database/postgres/init/21-run-reproduction.sql new file mode 100644 index 00000000..786c31c6 --- /dev/null +++ b/database/postgres/init/21-run-reproduction.sql @@ -0,0 +1,147 @@ +-- Reproduction is a new admission with immutable lineage, not a template rewrite. +ALTER TABLE runs ADD COLUMN IF NOT EXISTS original_run_id UUID; +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='runs_original_run_id_fkey' AND conrelid='runs'::regclass) THEN + ALTER TABLE runs ADD CONSTRAINT runs_original_run_id_fkey FOREIGN KEY (original_run_id) REFERENCES runs(id) ON DELETE RESTRICT; + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='runs_original_not_self' AND conrelid='runs'::regclass) THEN + ALTER TABLE runs ADD CONSTRAINT runs_original_not_self CHECK (original_run_id IS NULL OR original_run_id<>id); + END IF; +END $$; + +CREATE OR REPLACE FUNCTION protect_run_evidence_identity() RETURNS trigger +LANGUAGE plpgsql AS $$ BEGIN + IF NEW.original_run_id IS DISTINCT FROM OLD.original_run_id + OR 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 $$; + +CREATE OR REPLACE FUNCTION require_active_backtest_for_new_run() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; snapshot JSONB; original RECORD; expected JSONB; +BEGIN + SELECT * INTO parent FROM backtests WHERE id=NEW.backtest_id FOR UPDATE; + IF NOT FOUND THEN RETURN NEW; END IF; + IF parent.archived_at IS NOT NULL THEN + RAISE EXCEPTION 'Backtest is archived; restore it before submitting a new run' USING ERRCODE='23514'; + END IF; + snapshot := NEW.request_snapshot; + IF NEW.original_run_id IS NOT NULL THEN + SELECT r.*,br.canonical_result INTO original FROM runs r + LEFT JOIN backtest_results br ON br.run_id=r.id WHERE r.id=NEW.original_run_id; + IF (original.id IS NOT NULL AND original.id<>NEW.id + AND original.backtest_id=NEW.backtest_id AND original.status='completed' + AND original.request_snapshot->>'kind'='canonical-research/v1' + AND original.request_snapshot->>'runId'=original.id::text + AND original.request_snapshot->>'backtestId'=NEW.backtest_id::text + AND original.request_snapshot->>'datasetHash'=original.dataset_hash + AND original.canonical_result->>'kind'='canonical-result/v1' + AND original.canonical_result->>'status'='completed' + AND original.canonical_result->>'runId'=original.id::text + AND original.canonical_result->>'backtestId'=NEW.backtest_id::text + AND original.canonical_result->'request'=original.request_snapshot + AND original.canonical_result->>'financialEngine'='rust' + AND original.canonical_result->>'strategyExecution'='typescript-retained-builtin/v1' + AND NEW.dataset_hash=original.dataset_hash + AND NEW.status='pending' AND NEW.speed_multiplier IS NULL + AND NEW.submission_principal IN ('operator','service') + AND NEW.submission_key ~ '^[!-~]{1,200}$' + AND NEW.submission_hash ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN + RAISE EXCEPTION 'Reproduction requires a completed canonical source in the same backtest and a submission receipt' USING ERRCODE='23514'; + END IF; + SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v + JOIN strategies s ON s.id=v.strategy_id + WHERE v.id::text=original.request_snapshot#>>'{strategy,versionId}' FOR UPDATE OF s; + SELECT id,decision INTO approval FROM strategy_review_events + WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1; + IF (selected.origin='builtin' AND selected.family_archived IS NULL + AND approval.decision='approve' + AND original.request_snapshot#>>'{strategy,origin}'='builtin' + AND original.request_snapshot#>>'{strategy,familyId}'=selected.strategy_id::text + AND original.request_snapshot#>'{strategy,package}'=selected.envelope) IS NOT TRUE THEN + RAISE EXCEPTION 'Reproduction requires the currently approved original retained built-in version' USING ERRCODE='23514'; + END IF; + expected := jsonb_set(original.request_snapshot, '{runId}', to_jsonb(NEW.id::text)); + expected := jsonb_set(expected, '{policy,matching,risk,ledger,sessionId}', to_jsonb(NEW.id::text)); + expected := jsonb_set(expected, '{policy,matching,risk,ledger,accountId}', to_jsonb('research:'||NEW.id::text)); + expected := jsonb_set(expected, '{strategy,reviewId}', to_jsonb(approval.id::text)); + IF snapshot IS DISTINCT FROM expected THEN + RAISE EXCEPTION 'Reproduction must preserve the original frozen request except run identities and current approval' USING ERRCODE='23514'; + END IF; + SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash; + IF (retained#>>'{manifest,version}'='2' + AND retained#>>'{manifest,eligibility}'='eligible' + AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1 + AND jsonb_array_length(retained#>'{manifest,series}')=1 + AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1 + AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1 + AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1 + AND snapshot#>>'{policy,allow_exploratory}'='false' + AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}' + AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN + RAISE EXCEPTION 'Reproduction requires the original eligible retained single-asset dataset' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + IF parent.strategy_version_id IS NULL AND parent.strategy <> 'catalog' THEN + IF snapshot->>'kind'='canonical-research/v1' THEN + RAISE EXCEPTION 'Canonical research requires a catalog template' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + IF (snapshot->>'kind'='canonical-research/v1' + AND snapshot->>'runId'=NEW.id::text + AND snapshot->>'backtestId'=NEW.backtest_id::text + AND snapshot#>>'{strategy,versionId}'=parent.strategy_version_id::text + AND snapshot->>'datasetHash'=NEW.dataset_hash + AND NEW.status='pending' AND NEW.speed_multiplier IS NULL) IS NOT TRUE THEN + RAISE EXCEPTION 'Catalog strategy execution requires an admitted canonical request' USING ERRCODE='23514'; + END IF; + -- This is the same family lock used by operator review and archive. Later + -- review changes affect new admissions, never rewrite accepted snapshots. + SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v + JOIN strategies s ON s.id=v.strategy_id WHERE v.id=parent.strategy_version_id FOR UPDATE OF s; + SELECT id,decision INTO approval FROM strategy_review_events + WHERE version_id=parent.strategy_version_id ORDER BY ordinal DESC LIMIT 1; + IF (selected.origin='builtin' AND selected.family_archived IS NULL + AND approval.decision='approve' + AND snapshot#>>'{strategy,origin}'='builtin' + AND snapshot#>>'{strategy,familyId}'=selected.strategy_id::text + AND snapshot#>>'{strategy,reviewId}'=approval.id::text + AND snapshot#>'{strategy,package}'=selected.envelope + AND snapshot#>'{strategy,selection,parameters}'=parent.strategy_parameters + AND snapshot#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text) IS NOT TRUE THEN + RAISE EXCEPTION 'Canonical research requires the exact approved retained built-in version' USING ERRCODE='23514'; + END IF; + SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash; + IF (retained#>>'{manifest,version}'='2' + AND retained#>>'{manifest,eligibility}'='eligible' + AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1 + AND jsonb_array_length(retained#>'{manifest,series}')=1 + AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1 + AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1 + AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1 + AND snapshot#>>'{policy,allow_exploratory}'='false' + AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}' + AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}' + AND snapshot#>>'{policy,matching,series,0,instrumentId}'=snapshot#>>'{strategy,selection,instrumentId}' + AND snapshot#>>'{policy,matching,series,0,seriesId}'=snapshot#>>'{strategy,selection,seriesId}') IS NOT TRUE THEN + RAISE EXCEPTION 'Canonical research requires one eligible retained v2 execution asset' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END $$; + diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 5a10c939..97d4bffc 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,8 +1,8 @@ # Revised development roadmap -Baseline `b7aeca4` · execution 2026-10-24 · **R03 committed; R04 workspace validated and awaiting acceptance/commit** +Baseline `b7aeca4` · execution 2026-10-24 · **R04 committed; R12 original reproduction validated and awaiting acceptance/commit** -Authorization update: the owner requested “commit and continue”. R03 is committed as `ee45257`; R04 is implemented under ADR-006. Performance work remains paused. New R04 commits, pushes, PRs and trading/default-engine operations remain outside this continuation’s scope. +Authorization update: the owner requested “how far are we in the backlog, also commit and continue”. R04 is committed as `e3bd708`; R12 is implemented under ADR-006 using the accepted retained-input R05 component. **33/45 scheduled tasks are committed; R12 is the next validated task.** Full R05 remains partial. Performance work remains paused. New R12 commits, pushes, PRs and trading/default-engine operations remain outside this continuation's scope. ## Strategy and review outcome @@ -568,3 +568,18 @@ The initial sandbox check stalled on native-worker IPC; permitted checks passed. No backend financial authority, second evidence store or creation-receipt framework was added. Initial metadata creation still cannot guarantee exactly-once semantics across an ambiguous response; the UI makes this explicit. No performance work, new-wave commit, push, PR, candidate execution, default/multi-asset activation or trading operation occurred. **Recommended next product slice: R12 original-run reproduction**, limited to already-retained inputs and a supported installed build. The current manifest still blocks R12 on full R05. Before implementation, record its narrower component prerequisite and pin lineage/admission/current-approval rules; migration 19 presently binds ordinary admission to current template settings, so snapshot copying alone is insufficient. Keep R05 incomplete, R06/S06 gated, and historical build provisioning/source preparation outside that slice. + +## Twenty-sixth-wave handoff — 2026-10-24 + +R04 is accepted and committed as `e3bd708`. R12 is independently reviewed and `validated_uncommitted`. Twenty-six implementation/test files add original reproduction through the existing durable runner, retained artifacts and financial engine. Backend/frontend agents used disjoint worktrees under `/tmp/stock-bot-wave26.38tu9A/`; root owned shared contracts, comparison, migrations/fixtures and browser integration. + +- **Original versus current:** the run detail previews the original dataset, immutable strategy version, parameters, financial policies and build. Reproduce original creates a new linked run; ordinary submission continues to use current template settings. Missing inputs or unsupported builds remain explicit, with old results readable. +- **Guarded admission:** authenticated preview/POST/comparison routes preserve the original economic request. Only new run/session/account identities and current approval of the original version change. Migration 21 enforces immutable lineage, retained identity and source-copy guards. Accepted idempotency receipts precede current eligibility checks; no provider or current-code fallback. +- **Comparison:** versioned server-side hashes cover the complete validated request, Rust financial envelope and canonical analytics. Normalize only admission identity; retain actual market sessions, owner/order/fill IDs, monetary strings, null reasons and ordered arrays. No second accounting implementation. +- **UI reliability:** ambiguous submissions retain the same intent/key; late responses cannot navigate away from a newer selection. Lineage and match/mismatch diagnostics survive reload. The existing controls test now restores its own ResizeObserver harness correctly. +- **Validation:** full repository check passed, including **662 integration and 150 Rust tests** (4 manual Rust ignored), build/source/contracts/secrets/lint and 93 tooling/43 utility/44 calculation tests. Full PostgreSQL/Redis: **169 tests / 1376 assertions**. Chromium: **9 workflows / 215 assertions**, including actual original-versus-current execution and receipt replay. Focused SQL: **10 / 97**; independent UI: **106 / 555**; independent HTTP/hash: **10 / 96**. Strict changed-test types, scoped lint/format and diff checks passed. +- **Recorded identity:** source archive/hash and all 26 authored file hashes are in `manifest.json` → `twenty_sixth_wave_validation`. Release addon SHA256 `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103` matches the previous wave; no Rust semantics changed. Both exact disposable test containers were stopped; development services were untouched. + +Scope is completed retained canonical single-asset trusted built-ins on the same installed build. Hash agreement proves matching retained economic outputs, not statistical validity or profitability. Historical executable provisioning, provider-to-v2 preparation, candidate isolation and multi-asset/default cutover are not included. R05 remains partial; R06/S06 remain blocked. No performance optimization, profiling, benchmark, new-wave commit, push, PR or trading operation occurred. + +**Recommended next wave:** an R06 retained-input experiment component, then a focused R07 sweep UI against pinned APIs. One immutable strategy version, eligible single-asset dataset, installed build and fixed policies; deterministic bounded parameter grids expand into the existing durable runs/outbox. Independent review confirms provider preparation is not required for those retained inputs. Before execution, record component prerequisites without marking full R05/R06 complete or silently releasing R06/R07/S06. Experiment admission needs its own SQL guard against the immutable manifest; do not mutate templates per trial or misuse reproduction lineage. Failed retry must preserve diagnostics and fencing; if omitted initially, leave R06 partial. No parallel worker scheduler or performance work. Root owns contracts/browser integration; one backend owner and one frontend owner can work with an independent reviewer. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index afd2361e..ea456d31 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First twenty-four waves committed; R04 is validated and uncommitted.** R03 is accepted as `ee45257`. The workspace now connects projects, revisioned narratives, linked strategies and exact saved-run findings through the existing APIs. Broader R05 remains in progress. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-fifth-wave-handoff--2026-10-24) and manifest execution scope. +**First twenty-five waves committed; R12 is validated and uncommitted.** R04 is accepted as `e3bd708`. Original-run reproduction now preserves retained inputs independently of current settings, with lineage, repeat-safe submission and economic comparison. **33 of 45 scheduled tasks are committed (73% by count); R12 adds one validated task awaiting acceptance/commit.** Broader R05 remains in progress. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-sixth-wave-handoff--2026-10-24) and manifest execution scope. ## One source of truth @@ -75,7 +75,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [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 / done | R01, W03, ADR-006 | W04 | Full-stack research product / M | | [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / done | R01, R10, ADR-006 | — | Full-stack research product / M | -| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / review | R03, W02, ADR-006 | W04 | Full-stack research product / M | +| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / done | R03, W02, ADR-006 | W04 | Full-stack research product / M | | [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M | | [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / blocked | R05, ADR-006 | — | Full-stack research product / M | | [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / blocked | R06, ADR-006 | W04 | Full-stack research product / M | @@ -83,7 +83,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [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 / done | 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 | +| [R12 Reproduce an original run separately from rerunning current settings](tasks/R12.md) | P1 / review | Accepted R05 retained-input component; W04/R01/R10/F08/S02/D01/W03/C06, 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. -R03 is committed; R04 awaits acceptance/commit after independent review and full integration/browser checks. R12 original-run reproduction is the recommended next product slice, but its current manifest dependency on full R05 remains blocked. Before execution, explicitly scope it to retained, single-asset, same-installed-build inputs and pin guarded reproduction admission without weakening current authorization. R05 source preparation and broader cutover remain incomplete; R06/S06 are not unblocked. Performance and multi-asset/default/paper activation remain excluded. +R04 is committed; R12 awaits acceptance/commit after independent review and full repository/PostgreSQL/browser checks. R12 uses the accepted retained-input R05 component, not full R05 completion. Recommended next: an R06 retained-dataset experiment component and focused R07 UI after the planning owner records narrower prerequisites. Provider preparation is independent of sweeps over already eligible retained data. R05 broader cutover remains incomplete; R06/S06 are not unblocked. Performance and multi-asset/default/paper activation remain excluded. diff --git a/docs/development/backlog/dependencies.mmd b/docs/development/backlog/dependencies.mmd index 684e29ba..c32bb2d2 100644 --- a/docs/development/backlog/dependencies.mmd +++ b/docs/development/backlog/dependencies.mmd @@ -160,7 +160,14 @@ flowchart TD ADR003 --> R11 ADR006 --> R11 W04 -. release only .-> R11 - R05 --> R12 + %% R12 also requires R05's accepted retained-input component (618fb9e), not full cutover. + R01 --> R12 + R10 --> R12 + F08 --> R12 + S02 --> R12 + D01 --> R12 + W03 --> R12 + C06 --> R12 W04 --> R12 ADR006 --> R12 F07 --> P03 diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index b73849f2..14b69b5e 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,14 +1,14 @@ { "schema_version": 1, - "plan_revision": "2026-10-24.54", + "plan_revision": "2026-10-24.56", "repository_base": "b7aeca4", - "plan_status": "twenty_fifth_wave_validated_uncommitted", + "plan_status": "twenty_sixth_wave_validated_uncommitted", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: commit and continue after validated R03 handoff naming R04; R03 committed ee4525750741a314cbaaaf9f316b114c10dfd846.", - "tasks": ["R04"], + "authorized_by": "User: how far are we in the backlog, also commit and continue after R04 handoff naming original reproduction; R04 committed e3bd708838ce17a4da0bc2b4d6be701b72625dd8", + "tasks": ["R12"], "permissions": [ - "R04 research workspace, saved-result finding UI, browser/interaction tests, isolated implementation and independent review" + "Scoped same-installed-build retained canonical single-asset reproduction; independent implementation/review, fixtures and validation" ], "excluded": [ "performance_profiling_or_optimization", @@ -23,7 +23,7 @@ "multi_asset_activation", "other_backlog_tasks", "AI_execution_or_credentials", - "R03_backend_or_financial_contract_changes_without_demonstrated_need" + "historical_binary_provisioning" ], "pending_policy_decisions": [ "ADR-007", @@ -1238,7 +1238,7 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "review", + "status": "done", "dependencies": ["R03", "W02"], "decision_dependencies": ["ADR-006"], "task_file": "backlog/tasks/R04.md", @@ -1250,10 +1250,10 @@ "assignment": "/root", "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "e3bd708838ce17a4da0bc2b4d6be701b72625dd8", "blocker": null, "release_gates": ["W04"], - "integration_state": "validated_uncommitted", + "integration_state": "validated_committed", "integration_base": "ee4525750741a314cbaaaf9f316b114c10dfd846", "worktree": "/home/boki/repos/stock-bot", "implementation_slices": [ @@ -1514,8 +1514,8 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "blocked", - "dependencies": ["R05", "W04"], + "status": "review", + "dependencies": ["W04", "R01", "R10", "F08", "S02", "D01", "W03", "C06"], "decision_dependencies": ["ADR-006"], "task_file": "backlog/tasks/R12.md", "findings": ["WEB-03", "WEB-04", "KEEP-02"], @@ -1523,12 +1523,41 @@ "specialization": "Full-stack reproducible research", "write_locks": ["web-backtest-service", "web-backtest-detail"], "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": null, + "assignment": "/root", "branch": null, "pull_request": null, "completed_commit": null, "blocker": null, - "release_gates": [] + "release_gates": [], + "integration_state": "validated_uncommitted", + "integration_base": "e3bd708838ce17a4da0bc2b4d6be701b72625dd8", + "worktree": "/home/boki/repos/stock-bot", + "satisfied_component_dependencies": [ + { + "task": "R05", + "scope": "Accepted retained-input single-asset canonical durable runner/provenance slice only; source preparation/default cutover not required", + "commit": "618fb9e33cebc1fde4869eb1f975a12c55bd9b94" + } + ], + "implementation_slices": [ + { + "owner": "/root", + "scope": "Shared DTO/comparison projection, migration fixture integration, browser and planning" + }, + { + "owner": "/root/r12_backend", + "worktree": "/tmp/stock-bot-wave26.38tu9A/backend", + "scope": "Admission/API/migration21 and focused SQL/HTTP tests" + }, + { + "owner": "/root/r12_frontend", + "worktree": "/tmp/stock-bot-wave26.38tu9A/frontend", + "scope": "Reproduction preview/retry/lineage/comparison UI and DOM tests" + } + ], + "reviewed_by": "/root/r04_review", + "review_notes": "Independent backend/SQL/hash and frontend review accepted. Root full repository, PostgreSQL and Chromium gates passed. Original retained inputs remain independent of mutable template settings; current approval, immutable lineage and repeat-safe receipts remain enforced.", + "verification_reference": "ROADMAP.md#twenty-sixth-wave-handoff--2026-10-24" }, { "id": "P01", @@ -6330,7 +6359,7 @@ "R05 remains partial, R06/S06 remain gated; performance and AI/trading activation remain excluded." ], "twenty_fifth_wave_validation": { - "state": "validated_uncommitted", + "state": "validated_committed", "log_directory": "/tmp/stock-bot-wave25.X7zzoe", "integration_base": "ee4525750741a314cbaaaf9f316b114c10dfd846", "source_archive": "/tmp/stock-bot-wave25.X7zzoe/r04-integrated-source.tar", @@ -6403,6 +6432,98 @@ "Chromium only; existing build bundle-size/Rust warnings remain." ], "cleanup": "Both exact --rm PostgreSQL/Redis fixture containers stopped successfully. All 17 authored source/test hashes reverified; worktrees and logs retained. Development/production services and data untouched.", - "next": "Recommend a scoped R12 same-installed-build original-run reproduction slice after explicitly recording dependence on the accepted R05 retained-input component and pinning guarded reproduction admission/approval. R12 remains blocked in the manifest until that planning step; keep full R05 in progress and R06/S06 gated." + "next": "Recommend a scoped R12 same-installed-build original-run reproduction slice after explicitly recording dependence on the accepted R05 retained-input component and pinning guarded reproduction admission/approval. R12 remains blocked in the manifest until that planning step; keep full R05 in progress and R06/S06 gated.", + "completed_commit": "e3bd708838ce17a4da0bc2b4d6be701b72625dd8" + }, + "twenty_sixth_wave": ["R12"], + "twenty_sixth_wave_base": "e3bd708838ce17a4da0bc2b4d6be701b72625dd8", + "twenty_sixth_wave_notes": [ + "Root narrowed R12 to accepted R05 retained-input component after independent code review; R05 remains partial and R06/S06 blocked.", + "Reproduction preserves frozen economic inputs, current original-version approval and repeat-safe receipts. No current-template dependency or historical executable manager." + ], + "twenty_sixth_wave_validation": { + "state": "validated_uncommitted", + "log_directory": "/tmp/stock-bot-wave26.38tu9A", + "integration_base": "e3bd708838ce17a4da0bc2b4d6be701b72625dd8", + "source_archive": "/tmp/stock-bot-wave26.38tu9A/r12-integrated-source.tar", + "source_archive_sha256": "61ceb44bf8aa10a93e160f0ad7c8964748ae548c06a07b6954e5018688e0927a", + "source_file_count": 26, + "source_sha256": { + "apps/stock/config/src/contracts/canonical-research.ts": "d18421e275cd90d98cf05f352f7f6858580cb7cdc26124b535bfc45518521714", + "apps/stock/web-api/src/migrations/migration-runner.ts": "c4105e10b612ad1fa186f66714bb31318d4c70fab5a50229a66f7f96432b3853", + "apps/stock/web-api/src/routes/backtests-v2.routes.ts": "499a6b53c2dffedb341cbcb9b51339ab9e113584f074eb2ea92dadf2833f09a4", + "apps/stock/web-api/src/services/backtest-v2.service.ts": "76f02ff5dd60cd4b70718a2cf3703092b4f2cccb579b65c851524f4030706532", + "apps/stock/web-api/src/services/reproduction-comparison.ts": "5bde63cb6922f396ae53d5c4817c651f0a20d014deed1d9ea6d7a082c426537b", + "apps/stock/web-api/src/services/run-reproduction.ts": "02690bf2e001a6495413700aa1fcfc2accac7d12aee4369aedd5b25c10fe6ce5", + "apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx": "96f4bcbc3024d9713dc9585b8afccc058c69bcee6f715fa486ac2911b0bbb92d", + "apps/stock/web-app/src/features/backtest/components/RunReproduction.tsx": "b23f235049f9c80a317b8ca38202cd1857ea460bc9b5e009d6926e1de21bdef1", + "apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts": "23d8a64fac4fcc3254166f1457a3b9f1c20d81d7b379c469b5171f51efabeea9", + "database/postgres/init/21-run-reproduction.sql": "25d6f8f6bc23666d01f104be0e1c625822450c0c08b1c2ffaa31915d2b88c6cb", + "test/e2e/fixture.ts": "7ce1d95bc95a583cd937e036d9f584149af938515d1c588dbbd952a1b5a6f295", + "test/e2e/workbench.test.ts": "d19fa08c6a8a01e3fc9e66065a1e108816bae79c3c70a11d6457321f6b3e5a7c", + "test/integration/backtest-run-controls.test.tsx": "ca9e33508bd825821fd8ade631dec8a622ed019ad20eb6ec13b6c9957d4f37e8", + "test/integration/reproduction-comparison.test.ts": "e3a61f53c2a79f553f4be234e0b07e761543354b7c617351a1e75fa6ee7cb4fd", + "test/integration/run-reproduction-api.test.ts": "108f72299cdce927694d476a98797f3039bda4c0ee5b34b76cf94023a23b7a65", + "test/integration/run-reproduction-ui.test.tsx": "c72e7a07b823f44f583cf30d9e393027293991619f336b1e6fba99bde17a3c58", + "test/postgres/canonical-durable-backtest.test.ts": "774f394ac61d32cef241b9ef7f2267b66bcb8feb072b2545da23f37f23e3c192", + "test/postgres/canonical-research.test.ts": "c87bf4453f53daf9872d70cb2475060d39b53dbd59f0c32c615eb6795d40b697", + "test/postgres/catalog-backtest-drafts.test.ts": "d47dd06f9a43dd36b15fe3f3649408cbcf89ca8a7e62c644dc32479d11098bd0", + "test/postgres/dataset-catalog.test.ts": "51c976c966ae0dc92f8b1395521c058a89eb0543f5efe5a6930109a4e3c9652a", + "test/postgres/durable-backtest.test.ts": "e42912c8c2f366abec9ac3104c3f2eb2a083dc03595374455c1d755a537e48fe", + "test/postgres/migration-runner.test.ts": "093eb76e2e718b3930dc4efb805cc97ce33cf262d590eb73a99fb3920d83286b", + "test/postgres/research-retention.test.ts": "805a7403e07bee0c3dff5bf4d8eefa61fcbea8daaa31f45d2bbbd7e61d10ec98", + "test/postgres/research-runtime-isolation.test.ts": "c58d461555ae07b47f599f9f99187a4ba36c22ed7ff05bb1b403dab317a4197a", + "test/postgres/research-workspace.test.ts": "620836176bddf0dc927a812217087372baa279890b754cfe297236037374a93c", + "test/postgres/run-reproduction.test.ts": "f357a08fa4333f4beacb6aef1b6169cdbe6278229d2eab9f54d460af207dec32" + }, + "checks": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "/tmp/stock-bot-wave26.38tu9A/check.log", + "outcome": "All repository checks passed: build/source/contracts/secrets/lint; 93 tooling, 43 utility, 44 calculation, 662 integration and 150 Rust tests (4 manual Rust ignored)." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:postgres", + "log": "/tmp/stock-bot-wave26.38tu9A/postgres.log", + "outcome": "169 tests / 1376 assertions passed across 19 files. Focused R12 PostgreSQL gate separately passed 10 tests / 97 assertions, including real native parity, concurrency, admission guards, migration upgrade and corruption/mismatch diagnostics." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:e2e", + "log": "/tmp/stock-bot-wave26.38tu9A/e2e.log", + "outcome": "9 Chromium workflows / 215 assertions passed. Real retained execution, template mutation, original-input preview/reproduction, duplicate receipt replay, economic hash match, reload/source lineage and separate current-settings execution; original results unchanged." + }, + { + "command": "bunx tsc --project /tmp/stock-bot-wave26.38tu9A/tests-tsconfig.json --noEmit", + "log": "/tmp/stock-bot-wave26.38tu9A/integrated-types-final.log", + "outcome": "Strict changed/new tests and dependent sources passed after final browser assertions." + }, + { + "command": "bunx eslint --max-warnings 0; bunx prettier --check ; git diff --check", + "log": "/tmp/stock-bot-wave26.38tu9A/scoped-lint-final.log", + "outcome": "Scoped lint, formatting and diff checks passed. Existing controls test received only its ResizeObserver harness ownership fix; unrelated existing test-file curly findings were not expanded into cleanup." + }, + { + "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", + "log": "/tmp/stock-bot-wave26.38tu9A/native-release.log", + "outcome": "Release addon restored after repository checks. SHA256 ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103 matches checkout release library and previous wave; no Rust changes." + } + ], + "reviews": [ + { + "reviewer": "/root/r04_review", + "scope": "Backend admission, SQL21 lineage/retained identity guards, complete economic hash projection, frontend intent/retry/late-response behavior and focused tests", + "outcome": "Accepted verified implementation hashes; independently ran combined 106 UI tests / 555 assertions and 10 HTTP/hash tests / 96 assertions. Root owns final integrated database/browser gates.", + "next_wave_note": "Independent reviewer confirms retained-dataset experiments do not technically require provider-to-v2 preparation. Existing R06/R07 dependencies remain blocked until the planning owner records a narrow component scope. Full R05 completion must not require A02 candidate execution, which would introduce a cycle through A01/R06." + } + ], + "limitations": [ + "Completed canonical retained single-asset trusted built-ins on the exact installed build only. Legacy, incomplete, missing/corrupt retained inputs and unavailable historical builds cannot be reproduced; existing results remain readable.", + "New reproduction requires active parent/original strategy family and latest approval of the original version. Accepted receipt retries return the same run even after eligibility changes. No execution permission is derived from old approval alone.", + "Hash equality is versioned deterministic economic-output comparison, not statistical validation or proof of strategy merit. Only admission identities are normalized; actual financial policies, market session IDs, ownership, ordered fills and null analytics are retained.", + "Full R05 remains incomplete; R06/S06 stay blocked. No source preparation, candidate execution, multi-asset/default activation, paper/live operation, historical binary manager, AI execution, performance work or benchmark runs.", + "Chromium only; existing build bundle-size/Rust warnings remain. No new-wave commit, push or PR." + ], + "cleanup": "Both exact --rm PostgreSQL/Redis fixture containers stopped successfully. All 26 source/test hashes frozen; source archive, worktrees and logs retained. Development/production services and data untouched.", + "next": "Recommend an R06 retained-input experiment component using one immutable strategy version, eligible single-asset dataset, installed build and bounded parameter grid; a focused R07 UI component may follow pinned APIs. Before execution, explicitly record component prerequisites rather than treating full R05/R06 as complete. Reuse durable runs/outbox with guarded experiment admission; do not mutate templates per trial or misuse reproduction lineage. Keep provider preparation, candidate isolation, multi-asset/default cutover and performance work separately gated." } } diff --git a/docs/development/backlog/tasks/R12.md b/docs/development/backlog/tasks/R12.md index 3b24c30c..9c9e9d6a 100644 --- a/docs/development/backlog/tasks/R12.md +++ b/docs/development/backlog/tasks/R12.md @@ -31,7 +31,7 @@ Write locks: web-backtest-service, web-backtest-detail. One agent owns this chan ## Dependencies and blockers -Implementation requires [R05](R05.md), [W04](W04.md) integrated. +Implementation requires the accepted retained-input/single-asset durable execution component of [R05](R05.md) (`618fb9e`), plus [W04](W04.md) and the integrated R01/R10/F08/S02/D01/W03/C06 prerequisites. Provider-to-v2 preparation and broader R05 cutover are independent; R05 remains incomplete. This component dependency was verified and recorded by the planning owner on 2026-10-24 under the owner's continuation authorization. Architecture decisions: ADR-006. Agents may not independently amend their policies. @@ -65,3 +65,21 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Handoff Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done. + +## Pinned execution scope — 2026-10-24 + +Reproduce completed retained canonical single-asset built-in runs on the exact installed worker/native/runtime build. Add immutable `original_run_id` lineage; use the existing durable runner, submission receipts and outbox. Missing/corrupt inputs or unsupported historical builds fail explicitly. No historical executable provisioning, source inference or default activation. + +A fresh reproduction requires active parent/original strategy family and current approval of the **original** version, even if the template now selects another version. Copy the original request, changing only fresh run/session/account identities and the current approval receipt. Preserve all economic inputs. Receipt retries precede current eligibility checks; ordinary and reproduction intents use distinct hashes under the same principal/key uniqueness. SQL must enforce the source-copy relationship and retained identity alongside ordinary admission. + +Expose read-only preview, POST reproduction and read-only result comparison. Compare versioned canonical hashes of the complete validated frozen request, financial envelope and analytics, normalizing only run/account identity and admission-review fields. Keep real market-session IDs, ownership, ordered fills, monetary strings, nulls and limitations. Do not recalculate finances or rewrite retained results. The UI separates original reproduction from current-settings submission, preserves retry keys after ambiguous responses and shows lineage/comparison after reload. + +Root owns shared DTO/comparison and integration; backend/frontend worktrees have disjoint actual files. Current assignment, authority and validation live in the manifest. + +## Implemented handoff — 2026-10-24 + +The pinned scope is implemented and independently reviewed; scheduling remains `review` / `validated_uncommitted` in the manifest. Shared preview/comparison DTOs live in `apps/stock/config/src/contracts/canonical-research.ts`; `run-reproduction.ts` checks retained admission eligibility and `reproduction-comparison.ts` hashes validated economic inputs/outputs. Migration 21 protects source-copy lineage and financial identity. GET `/api/v2/runs/:id/reproduction`, POST `/api/v2/runs/:id/reproduce` and GET `/api/v2/runs/:id/reproduction-comparison` are authenticated. POST accepts only an empty object plus an idempotency key; it returns 202 and Location for the new or previously accepted run. + +`RunReproduction.tsx` consumes the same APIs, shows exact retained inputs, preserves keys after ambiguous submissions and displays source lineage and comparison. Current-settings submission is separate. The expanded Chromium research flow mutates the template, reproduces the original native result, retries the same receipt, reopens lineage, then proves a new ordinary run uses changed settings. PostgreSQL tests cover current original-version approval, direct SQL guards, retention, upgrade, corruption, concurrent receipts and economic parity/mismatch. Full gate outcomes and source hashes are recorded in the twenty-sixth-wave roadmap/manifest handoff. + +No old binary provisioning or inference of missing provenance was added. R05 remains partial and R06/S06 gates remain intact. diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index 12a9392c..a8f423fe 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -292,6 +292,7 @@ export async function fixture(browser: Browser, native = false) { '18-backtest-strategy-versions.sql', '19-canonical-research.sql', '20-research-workspace.sql', + '21-run-reproduction.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index 7cb985d8..36e6d32f 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -1049,6 +1049,114 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_ await f.page.waitForURL(completedUrl); await visible(f.page, '9969.30000000'); expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result); + + // Original reproduction is independent of subsequent mutable template edits. + await f.request(`/api/v2/backtests/${backtestId}`, 'PUT', { + name: 'Changed current settings', + initialCapital: 20000, + strategyParameters: { fastPeriod: 1, slowPeriod: 2 }, + config: { ...sent.config, canonical: { ...sent.config.canonical, feeRate: '0.02', seed: 7 } }, + }); + await f.page.reload(); + await visible(f.page, 'Canonical research result'); + await f.page.getByRole('button', { name: 'Reproduce original', exact: true }).click(); + const reproductionDialog = f.page.getByRole('dialog', { + name: 'Reproduce original', + exact: true, + }); + const originalInputs = reproductionDialog.getByRole('region', { + name: 'Original retained inputs', + exact: true, + }); + await originalInputs.waitFor({ state: 'visible' }); + expect(await originalInputs.textContent()).toContain(retained.hash); + expect(await originalInputs.textContent()).toContain(selected.id); + await reproductionDialog + .getByText('Exact parameters, financial policies and build', { exact: true }) + .click(); + expect(await originalInputs.locator('pre').textContent()).toContain( + '"initialCapital": "10000.00000000"' + ); + expect(await originalInputs.locator('pre').textContent()).toContain('"fastPeriod": 2'); + const reproducing = f.page.waitForResponse( + response => + response.request().method() === 'POST' && + response.url().endsWith(`/runs/${run.id}/reproduce`) + ); + await reproductionDialog + .getByRole('button', { name: 'Confirm reproduction', exact: true }) + .click(); + const reproducedResponse = await reproducing; + expect(reproducedResponse.status()).toBe(202); + expect(reproducedResponse.request().headers()['idempotency-key']).toBeTruthy(); + expect(reproducedResponse.request().postDataJSON()).toEqual({}); + const reproducedRun = await reproducedResponse.json(); + expect(reproducedRun.originalRunId).toBe(run.id); + expect(reproducedRun.id).not.toBe(run.id); + expect(reproducedResponse.headers().location).toBe(`/api/v2/runs/${reproducedRun.id}`); + await f.page.waitForURL(`${f.origin}/backtests/${backtestId}/run/${reproducedRun.id}`); + const duplicate = await f.page.evaluate( + async ({ sourceId, key }) => { + const response = await fetch(`/api/v2/runs/${sourceId}/reproduce`, { + method: 'POST', + credentials: 'include', + headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key }, + body: '{}', + }); + return { status: response.status, run: await response.json() }; + }, + { sourceId: run.id, key: reproducedResponse.request().headers()['idempotency-key']! } + ); + expect(duplicate.status).toBe(202); + expect(duplicate.run.id).toBe(reproducedRun.id); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2); + await visible(f.page, 'Economic results match the original.'); + const comparison = await f.request(`/api/v2/runs/${reproducedRun.id}/reproduction-comparison`); + expect(comparison.status).toBe('match'); + expect(comparison.originalHash).toMatch(/^[a-f0-9]{64}$/); + expect(comparison.reproducedHash).toBe(comparison.originalHash); + const reproducedResult = (await f.request( + `/api/v2/runs/${reproducedRun.id}/results` + )) as CanonicalRunResult; + expect(reproducedResult.request.strategy.selection).toEqual(result.request.strategy.selection); + expect(reproducedResult.request.build).toEqual(result.request.build); + expect(reproducedResult.request.datasetHash).toBe(result.request.datasetHash); + expect(String(reproducedResult.request.policy.matching.risk.ledger.initialCapital)).toBe( + '10000.00000000' + ); + expect(reproducedResult.financial.projection).toEqual(result.financial.projection); + expect(reproducedResult.analytics).toEqual(result.analytics); + await f.page.reload(); + await visible(f.page, 'Economic results match the original.'); + await f.page.getByRole('link', { name: 'Open original run', exact: true }).click(); + await f.page.waitForURL(completedUrl); + await visible(f.page, '9969.30000000'); + + // Ordinary submission still freezes the current settings and has no reproduction lineage. + await f.page.getByRole('button', { name: 'Runs', exact: true }).click(); + const currentResponse = await submitInBrowser(f.page); + expect(currentResponse.status()).toBe(202); + const currentRun = await currentResponse.json(); + expect(currentRun.originalRunId).toBeNull(); + await visible(f.page, 'Canonical research result'); + const currentResult = (await f.request( + `/api/v2/runs/${currentRun.id}/results` + )) as CanonicalRunResult; + expect(String(currentResult.request.policy.matching.risk.ledger.initialCapital)).toBe( + '20000.00000000' + ); + expect(currentResult.request.strategy.selection.parameters).toEqual({ + fastPeriod: 1, + slowPeriod: 2, + }); + expect(currentResult.request.strategy.selection.seed).toBe(7); + expect(String(currentResult.request.policy.matching.risk.feeRate)).toBe('0.02000000'); + expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result); + expect( + (await f.pool.query('SELECT original_run_id FROM runs WHERE id=$1', [reproducedRun.id])) + .rows[0].original_run_id + ).toBe(run.id); + expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(3); expect(f.historicalDataReads).toEqual([]); expect(f.unexpectedNetwork).toEqual([]); } finally { diff --git a/test/integration/backtest-run-controls.test.tsx b/test/integration/backtest-run-controls.test.tsx index 9c719b90..10f02208 100644 --- a/test/integration/backtest-run-controls.test.tsx +++ b/test/integration/backtest-run-controls.test.tsx @@ -10,7 +10,13 @@ import type { // Local to this file: no global preload, browser server or second test runner. const browser = new GlobalWindow({ url: 'http://localhost:5173' }); -const globals = ['window', 'document', 'WebSocket', 'IS_REACT_ACT_ENVIRONMENT'] as const; +const globals = [ + 'window', + 'document', + 'WebSocket', + 'ResizeObserver', + 'IS_REACT_ACT_ENVIRONMENT', +] as const; const savedGlobals = new Map( globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]) ); @@ -252,6 +258,7 @@ beforeAll(async () => { window: browser, document: browser.document, WebSocket: TestSocket, + ResizeObserver: browser.ResizeObserver, IS_REACT_ACT_ENVIRONMENT: true, })) Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); diff --git a/test/integration/reproduction-comparison.test.ts b/test/integration/reproduction-comparison.test.ts new file mode 100644 index 00000000..25788927 --- /dev/null +++ b/test/integration/reproduction-comparison.test.ts @@ -0,0 +1,159 @@ +import { randomUUID } from 'node:crypto'; +import { beforeAll, expect, test } from 'bun:test'; +import { + canonicalRunRequestSchema, + type CanonicalRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; +import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; +import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; +import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; +import { canonicalReproductionHash } from '../../apps/stock/web-api/src/services/reproduction-comparison'; +import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; +import { canonicalSmaFixture } from '../fixtures/canonical-sma'; + +let original: CanonicalRunResult; +let reproduced: CanonicalRunResult; +beforeAll(async () => { + const pkg = (await packageBuiltinStrategies())[0]!; + const versionId = randomUUID(); + const fixture = canonicalSmaFixture([`strategy:${versionId}`]); + const runId = randomUUID(); + fixture.config.matching.risk.ledger.sessionId = runId; + fixture.config.matching.risk.ledger.accountId = `research:${runId}`; + const request = canonicalRunRequestSchema.parse({ + kind: 'canonical-research/v1', + runId, + backtestId: randomUUID(), + name: 'Comparison fixture', + strategy: { + familyId: randomUUID(), + versionId, + origin: 'builtin', + reviewId: randomUUID(), + package: pkg, + selection: fixture.selections[0], + }, + datasetHash: fixture.dataset.manifest.hash, + policy: fixture.config, + analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, + // Projection fixtures; admission/build verification is covered by PostgreSQL native tests. + build: { + version: 1, + workerSha256: 'a'.repeat(64), + engineWrapperSha256: 'b'.repeat(64), + engineBinarySha256: 'c'.repeat(64), + dependencyLockSha256: 'd'.repeat(64), + runtime: 'bun', + runtimeVersion: 'fixture', + platform: 'fixture', + arch: 'fixture', + }, + modelArtifacts: [], + }); + const execute = (input: typeof request): CanonicalRunResult => { + const financial = runStrategyReplay( + prepareReplayLoad(fixture.dataset, input.policy), + [createBuiltinStrategy(input.strategy.selection)], + { resultFormat: 'report' } + ).result; + const report = buildCanonicalBacktestReport(financial, input.analyticsPolicy); + return { + kind: 'canonical-result/v1', + runId: input.runId, + backtestId: input.backtestId, + status: 'completed', + completedAt: new Date().toISOString(), + executionTime: 1, + financialEngine: 'rust', + strategyExecution: 'typescript-retained-builtin/v1', + request: input, + ...report, + }; + }; + original = execute(request); + const next = structuredClone(request); + next.runId = randomUUID(); + next.policy.matching.risk.ledger.sessionId = next.runId; + next.policy.matching.risk.ledger.accountId = `research:${next.runId}`; + next.strategy.reviewId = randomUUID(); + reproduced = execute(next); +}); + +test('economic_hash_parity: two actual replays ignore only admission identities and wall-clock metadata', () => { + expect(original.runId).not.toBe(reproduced.runId); + expect(original.request.strategy.reviewId).not.toBe(reproduced.request.strategy.reviewId); + expect(original.financial.projection.fills).toHaveLength(2); + expect(original.financial.projection.fills).toEqual(reproduced.financial.projection.fills); + const before = JSON.stringify([original, reproduced]); + expect(canonicalReproductionHash(original)).toMatch(/^[a-f0-9]{64}$/); + expect(canonicalReproductionHash(original)).toBe(canonicalReproductionHash(reproduced)); + expect(JSON.stringify([original, reproduced])).toBe(before); +}); + +test('economic hash retains fees, ordered fills, decision ownership, risk, nulls and statistical facts', () => { + const changes: ((value: CanonicalRunResult) => void)[] = [ + value => { + value.financial.projection.valuation.fees = parseFinancialDecimal('9'); + }, + value => { + value.financial.projection.fills[0]!.fee.amount = parseFinancialDecimal('0.51'); + }, + value => { + value.financial.projection.fills[0]!.price = parseFinancialDecimal('5.1'); + }, + value => { + value.financial.projection.fills.reverse(); + }, + value => { + value.financial.projection.fills[0]!.orderId = 'different-order'; + }, + value => { + value.financial.projection.fills[0]!.ownerId = 'different-owner'; + value.financial.projection.fills[0]!.decision.ownerId = 'different-owner'; + }, + value => { + value.financial.view.risk.dailyHalted = !value.financial.view.risk.dailyHalted; + }, + value => { + value.analytics.metrics.sharpeRatio = 0; + }, + value => { + value.analytics.metrics.totalReturn = 0; + }, + value => { + value.financial.modelLimitations.push('Additional model limitation'); + }, + value => { + value.request.strategy.selection.seed++; + }, + ]; + for (const change of changes) { + const changed = structuredClone(original); + change(changed); + expect(canonicalReproductionHash(changed)).not.toBe(canonicalReproductionHash(original)); + } +}); + +test('economic hash preserves actual market-session identities and execution policy', () => { + const changed = structuredClone(original); + changed.financial.view.risk.riskSession.sessionId = 'different-market-session'; + expect(canonicalReproductionHash(changed)).not.toBe(canonicalReproductionHash(original)); + const policy = structuredClone(original); + policy.request.policy.matching.risk.feeRate = parseFinancialDecimal('0.02'); + policy.financial.policy.matching.risk.feeRate = parseFinancialDecimal('0.02'); + expect(canonicalReproductionHash(policy)).not.toBe(canonicalReproductionHash(original)); +}); + +test('economic hash rejects mixed result/request/session identities rather than hiding them', () => { + const wrongRun = structuredClone(original); + wrongRun.runId = randomUUID(); + expect(() => canonicalReproductionHash(wrongRun)).toThrow('identity'); + const wrongSession = structuredClone(original); + wrongSession.financial.identity.sessionId = randomUUID(); + expect(() => canonicalReproductionHash(wrongSession)).toThrow(); + const wrongAccount = structuredClone(original); + wrongAccount.financial.view.portfolio.accountId = 'foreign-account'; + expect(() => canonicalReproductionHash(wrongAccount)).toThrow(); +}); diff --git a/test/integration/run-reproduction-api.test.ts b/test/integration/run-reproduction-api.test.ts new file mode 100644 index 00000000..53edb54b --- /dev/null +++ b/test/integration/run-reproduction-api.test.ts @@ -0,0 +1,186 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { describe, expect, mock, test } from 'bun:test'; +import { Hono } from 'hono'; +import { z } from 'zod'; +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: 'reproduction-admin-fixture-not-a-real-secret-1234', + service: 'reproduction-service-fixture-not-a-real-secret-1234', + read: 'reproduction-read-fixture-not-a-real-secret-1234', +}; +const originalRunId = randomUUID(); +const runId = randomUUID(); +const backtestId = randomUUID(); +type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record[] }>; +function fixture( + mode: 'enabled' | 'disabled' | 'absent' = 'enabled', + query: Query = async () => ({ rows: [] }) +) { + const client = { query: mock(query) }; + const database = { + ...client, + transaction: mock( + async (work: (client: { query: Query }) => Promise): Promise => work(client) + ), + }; + const app = new Hono(); + if (mode !== 'absent') { + createHttpSecurity({ + adminToken: tokens.operator, + serviceToken: tokens.service, + readToken: tokens.read, + environment: 'test', + hostname: '127.0.0.1', + disabled: mode === 'disabled', + }).mount(app); + } + app.route('/', createBacktestV2Routes({ postgres: database } as unknown as IServiceContainer)); + return { + database, + request(path: string, method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) { + return app.request(`/api/v2/runs/${path}`, { + method, + headers: { + 'Content-Type': 'application/json', + ...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}), + ...(key !== undefined ? { 'Idempotency-Key': key } : {}), + }, + ...(body === undefined ? {} : { body }), + }); + }, + }; +} +function row(extra: Record = {}) { + return { + id: runId, + backtest_id: backtestId, + original_run_id: originalRunId, + run_number: 2, + status: 'pending', + speed_multiplier: null, + progress: '0', + attempt_number: 0, + created_at: '2026-10-24T00:00:00Z', + updated_at: '2026-10-24T00:00:00Z', + ...extra, + }; +} + +describe('original reproduction HTTP contract', () => { + test('mutation requires credential proof even with development bypass or forged actor', async () => { + for (const mode of ['enabled', 'disabled', 'absent'] as const) { + const f = fixture(mode); + const response = await f.request( + `${originalRunId}/reproduce?actor=operator`, + 'POST', + '{}', + undefined, + 'receipt' + ); + expect(response.status).toBe(401); + expect(f.database.query.mock.calls).toHaveLength(0); + expect(f.database.transaction.mock.calls).toHaveLength(0); + } + }); + test('read-only role may inspect but cannot submit and anonymous reads reject', async () => { + const f = fixture(); + expect((await f.request(`${runId}/reproduction`)).status).toBe(401); + expect((await f.request(`${runId}/reproduction-comparison`)).status).toBe(401); + expect((await f.request(`${runId}/reproduce`, 'POST', '{}', 'read', 'key')).status).toBe(403); + expect((await f.request(`${runId}/reproduction`, 'GET', undefined, 'read')).status).toBe(404); + }); + test('strict original-run IDs, body and required keys reject financial overrides before storage', async () => { + for (const [id, body, key] of [ + [originalRunId, '{}', undefined], + [originalRunId, '{}', 'contains space'], + [originalRunId, '{}', 'x'.repeat(201)], + [originalRunId, '{', 'key'], + [originalRunId, 'null', 'key'], + [originalRunId, '[]', 'key'], + [originalRunId, '{"feeRate":"0"}', 'key'], + [originalRunId, '{"originalRunId":"other"}', 'key'], + ['not-uuid', '{}', 'key'], + ]) { + const f = fixture(); + expect((await f.request(`${id}/reproduce`, 'POST', body, 'operator', key)).status).toBe(400); + expect(f.database.query.mock.calls).toHaveLength(0); + expect(f.database.transaction.mock.calls).toHaveLength(0); + } + const f = fixture(); + expect((await f.request('bad/reproduction', 'GET', undefined, 'read')).status).toBe(400); + expect((await f.request('bad/reproduction-comparison', 'GET', undefined, 'read')).status).toBe( + 400 + ); + }); + test('an accepted receipt returns its original run and Location before eligibility checks', async () => { + const key = 'already-admitted'; + const hash = createHash('sha256') + .update(JSON.stringify({ version: 1, operation: 'reproduce-original', originalRunId })) + .digest('hex'); + for (const principal of ['operator', 'service'] as const) { + const f = fixture('enabled', async (sql, values) => { + expect(sql).toContain('submission_principal=$1'); + expect(values).toEqual([principal, key]); + return { rows: [row({ submission_hash: hash })] }; + }); + const reply = await f.request(`${originalRunId}/reproduce`, 'POST', '{}', principal, key); + expect(reply.status).toBe(202); + expect(reply.headers.get('Location')).toBe(`/api/v2/runs/${runId}`); + expect(reply.headers.get('Cache-Control')).toBe('no-store'); + expect(await reply.json()).toMatchObject({ id: runId, originalRunId, backtestId }); + expect(f.database.query.mock.calls).toHaveLength(1); + } + }); + test('receipt intent conflict is409, missing source404, incomplete preview is unavailable', async () => { + const conflict = fixture('enabled', async () => ({ + rows: [row({ submission_hash: 'different' })], + })); + expect( + (await conflict.request(`${originalRunId}/reproduce`, 'POST', '{}', 'operator', 'key')).status + ).toBe(409); + const missing = fixture(); + expect( + (await missing.request(`${originalRunId}/reproduce`, 'POST', '{}', 'operator', 'key')).status + ).toBe(404); + const pending = fixture('enabled', async () => ({ rows: [row()] })); + const preview = await pending.request(`${runId}/reproduction`, 'GET', undefined, 'read'); + expect(preview.status).toBe(200); + expect(await preview.json()).toMatchObject({ + originalRunId: runId, + backtestId, + available: false, + request: null, + }); + const compare = await pending.request( + `${runId}/reproduction-comparison`, + 'GET', + undefined, + 'read' + ); + expect(await compare.json()).toMatchObject({ + runId, + originalRunId, + status: 'pending', + originalHash: null, + }); + }); + test('unexpected database and retained schema failures remain sanitized500, never input400 or available', async () => { + for (const failure of [new Error('private connection info'), new z.ZodError([])]) { + const f = fixture('enabled', async () => { + throw failure; + }); + for (const [path, method, body, key] of [ + [`${runId}/reproduction`, 'GET', undefined, undefined], + [`${runId}/reproduction-comparison`, 'GET', undefined, undefined], + [`${runId}/reproduce`, 'POST', '{}', 'key'], + ] as const) { + const response = await f.request(path, method, body, 'operator', key); + expect(response.status).toBe(500); + expect(await response.text()).not.toContain('private connection'); + } + } + }); +}); diff --git a/test/integration/run-reproduction-ui.test.tsx b/test/integration/run-reproduction-ui.test.tsx new file mode 100644 index 00000000..28ff4a7f --- /dev/null +++ b/test/integration/run-reproduction-ui.test.tsx @@ -0,0 +1,558 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import { GlobalWindow } from 'happy-dom'; +import { act, createElement, type ReactElement } from 'react'; +import type { Root } from 'react-dom/client'; +import { + canonicalRunRequestSchema, + type CanonicalReproductionComparison, + type CanonicalReproductionPreview, +} from '@stock-bot/stock-config/canonical-research'; +import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; +import type { Run } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'; +import { nativeReplayFixture } from '../fixtures/native-replay'; + +const browser = new GlobalWindow({ url: 'http://localhost:5173' }); +const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const; +const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); +let createRoot: typeof import('react-dom/client').createRoot; +let router: typeof import('react-router-dom'); +let RunReproduction: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunReproduction').RunReproduction; +let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2; +let root: Root | undefined; +let host: HTMLDivElement; +let navigate: ReturnType; +let location = ''; +const sourceId = '11111111-1111-4111-8111-111111111111'; +const otherId = '22222222-2222-4222-8222-222222222222'; +const backtestId = '33333333-3333-4333-8333-333333333333'; +const versionId = '44444444-4444-4444-8444-444444444444'; +function deferred() { + let resolve!: (value: T) => void; + let reject!: (cause: Error) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} +type Pending = ReturnType> & { + path: string; + method: string; + body: unknown; + headers: Headers; + settled: boolean; + signal?: AbortSignal | null; +}; +const requests: Pending[] = []; +function request(path: string, method = 'GET') { + const found = requests.find( + item => item.path === path && item.method === method && !item.settled + ); + if (!found) { + throw new Error( + `Missing ${method} ${path}: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(',')}` + ); + } + return found; +} +function reply(item: Pending, value: unknown, status = 200) { + item.settled = true; + item.resolve(Response.json(value, { status })); +} +async function flush(action: () => void = () => {}) { + await act(async () => { + action(); + await Promise.resolve(); + }); +} +function button(label: string) { + const item = [...host.querySelectorAll('button')].find( + item => item.textContent?.trim() === label + ); + if (!item) { + throw new Error(`Missing ${label}: ${host.textContent}`); + } + return item; +} +function Probe() { + navigate = router.useNavigate(); + location = router.useLocation().pathname; + return null; +} +async function render(element: ReactElement, path = `/backtests/${backtestId}/run/${sourceId}`) { + root ??= createRoot(host); + await flush(() => + root!.render( + createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe)) + ) + ); +} +const run = (id = sourceId, extra: Partial = {}): Run => ({ + id, + backtestId, + runNumber: 1, + status: 'completed', + speedMultiplier: null, + progress: 100, + createdAt: '2026-10-24', + updatedAt: '2026-10-24', + originalRunId: null, + ...extra, +}); +function preview( + id = sourceId, + extra: Partial = {} +): CanonicalReproductionPreview { + const owner = `strategy:${versionId}`; + const { config, dataset } = nativeReplayFixture(3, 1, [owner]); + config.matching.risk.ledger.sessionId = id; + config.matching.risk.ledger.accountId = `research:${id}`; + const builtin = builtinCatalogDescriptors[0]!; + const request = canonicalRunRequestSchema.parse({ + kind: 'canonical-research/v1', + runId: id, + backtestId, + name: 'Frozen original inputs', + strategy: { + familyId: '55555555-5555-4555-8555-555555555555', + versionId, + origin: 'builtin', + reviewId: '66666666-6666-4666-8666-666666666666', + package: { + version: 1, + program: builtin.program, + parameterSchema: builtin.parameterSchema, + artifact: { + format: 'esm-bundle/v1', + entryExport: builtin.entryExport, + content: 'Never execute this code', + sha256: 'a'.repeat(64), + }, + dependencyLock: { format: 'bun-lock/v1', content: 'Retained lock', sha256: 'b'.repeat(64) }, + source: { revision: 'c'.repeat(40), dirty: false }, + build: { tool: 'bun', version: '1.2.17', target: 'browser' }, + }, + selection: { + strategyId: builtin.program.strategyId, + strategyVersion: builtin.program.strategyVersion, + ownerId: owner, + seed: 17, + instrumentId: 'X0.US', + seriesId: 'X0.US:1m', + ownerBudget: '100', + parameters: { fastPeriod: 2, slowPeriod: 3 }, + }, + }, + datasetHash: dataset.manifest.hash, + policy: config, + analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, + build: { + version: 1, + workerSha256: 'a'.repeat(64), + engineWrapperSha256: 'b'.repeat(64), + engineBinarySha256: 'c'.repeat(64), + dependencyLockSha256: 'd'.repeat(64), + runtime: 'bun', + runtimeVersion: '1.2.17', + platform: 'linux', + arch: 'x64', + }, + modelArtifacts: [], + }); + return { + originalRunId: id, + backtestId, + available: true, + reason: null, + currentReviewId: '77777777-7777-4777-8777-777777777777', + request, + ...extra, + }; +} +const comparison = ( + status: CanonicalReproductionComparison['status'] = 'match' +): CanonicalReproductionComparison => ({ + version: 'canonical-reproduction/v1', + runId: otherId, + backtestId, + originalRunId: sourceId, + status, + reason: null, + originalHash: ['match', 'mismatch'].includes(status) ? 'a'.repeat(64) : null, + reproducedHash: + status === 'match' ? 'a'.repeat(64) : status === 'mismatch' ? 'b'.repeat(64) : null, +}); +async function open(source = run(), archived = false) { + await render(createElement(RunReproduction, { run: source, archived })); + await flush(() => button('Reproduce original').click()); +} +async function ready(source = run(), archived = false) { + await open(source, archived); + const value = preview(source.id); + await flush(() => reply(request(`/api/v2/runs/${source.id}/reproduction`), value)); + return value; +} +const post = () => request(`/api/v2/runs/${sourceId}/reproduce`, 'POST'); +beforeAll(async () => { + for (const [key, value] of Object.entries({ + window: browser, + document: browser.document, + Event: browser.Event, + ResizeObserver: browser.ResizeObserver, + IS_REACT_ACT_ENVIRONMENT: true, + })) { + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + } + ({ createRoot } = await import('react-dom/client')); + router = await import('react-router-dom'); + ({ RunReproduction } = await import( + '../../apps/stock/web-app/src/features/backtest/components/RunReproduction' + )); + ({ BacktestDetailPageV2 } = await import( + '../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2' + )); +}); +beforeEach(() => { + requests.length = 0; + location = ''; + host = browser.document.createElement('div') as unknown as HTMLDivElement; + browser.document.body.append(host as never); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); + Object.defineProperty(browser, 'fetch', { + configurable: true, + value: (input: unknown, init?: RequestInit) => { + const url = new URL(String(input)); + const item: Pending = { + ...deferred(), + path: url.pathname + url.search, + method: init?.method ?? 'GET', + body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, + headers: new Headers(init?.headers), + signal: init?.signal, + settled: false, + }; + requests.push(item); + return item.promise; // Ignore abort deliberately; component identity must fence late replies. + }, + }); +}); +afterEach(async () => { + if (root) { + await flush(() => root!.unmount()); + } + root = undefined; + host.remove(); +}); +afterAll(async () => { + await browser.happyDOM.close(); + for (const key of keys) { + const old = originals.get(key); + if (old) { + Object.defineProperty(globalThis, key, old); + } else { + Reflect.deleteProperty(globalThis, key); + } + } +}); + +describe('original-run reproduction UI', () => { + test('preview is read-only, renders exact retained inputs, and double-click admission sends only source/key', async () => { + const value = await ready(); + expect(host.textContent).toContain('Frozen original inputs'); + expect(host.textContent).toContain(value.request!.datasetHash); + expect(host.textContent).toContain(versionId); + expect(host.textContent).toContain('Random seed: 17'); + expect(host.querySelector('pre')?.textContent).toContain('"fastPeriod": 2'); + expect(host.querySelector('pre')?.textContent).toContain( + value.request!.build.engineBinarySha256 + ); + expect(host.querySelector('pre')?.textContent).not.toContain('Never execute this code'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + const submit = button('Confirm reproduction'); + await flush(() => { + submit.click(); + submit.click(); + }); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + expect(post().body).toEqual({}); + expect(post().headers.get('Idempotency-Key')).toMatch(/^[a-f0-9-]{36}$/); + await flush(() => + reply(post(), run(otherId, { originalRunId: sourceId, status: 'pending' }), 202) + ); + expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`); + }); + test('loading and failed preview do not become unavailable provenance and read retry does not submit', async () => { + await open(); + expect(host.textContent).toContain('Loading original inputs...'); + expect(button('Confirm reproduction').disabled).toBe(true); + await flush(() => + reply(request(`/api/v2/runs/${sourceId}/reproduction`), { error: 'Store offline' }, 503) + ); + expect(host.textContent).toContain('Store offline'); + expect(host.textContent).not.toContain('Original reproduction unavailable'); + await flush(() => button('Refresh original inputs').click()); + await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview())); + expect(button('Confirm reproduction').disabled).toBe(false); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + }); + test.each([ + 'Legacy run lacks retained provenance', + 'Original strategy approval was revoked', + 'Installed build is unsupported', + ])('%s displays an explicit unavailable reason with no fallback', async reason => { + await open(); + await flush(() => + reply( + request(`/api/v2/runs/${sourceId}/reproduction`), + preview(sourceId, { available: false, reason, request: null, currentReviewId: null }) + ) + ); + expect(host.textContent).toContain(reason); + expect(button('Confirm reproduction').disabled).toBe(true); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + }); + test('an archived parent blocks fresh admission even if a stale preview says available', async () => { + await ready(run(), true); + expect(host.textContent).toContain('This backtest is archived'); + expect(button('Confirm reproduction').disabled).toBe(true); + }); + test.each(['lost', 'malformed', 'wrong-parent', 'server-error'])( + '%s response retains the key across close, refresh, archive and explicit retry', + async failure => { + await ready(); + await flush(() => button('Confirm reproduction').click()); + const first = post(); + const key = first.headers.get('Idempotency-Key'); + await flush(() => { + if (failure === 'lost') { + first.settled = true; + first.reject(new Error('Lost')); + } else if (failure === 'malformed') { + reply(first, {}, 202); + } else if (failure === 'wrong-parent') { + reply(first, run(otherId, { originalRunId: sourceId, backtestId: 'wrong' }), 202); + } else { + reply(first, { error: 'Response unavailable' }, 500); + } + }); + expect(host.textContent).toContain('previous request may already have been accepted'); + await flush(() => button('Close').click()); + await render(createElement(RunReproduction, { run: run(), archived: true })); + await flush(() => button('Reproduce original').click()); + await flush(() => + reply( + request(`/api/v2/runs/${sourceId}/reproduction`), + preview(sourceId, { available: false, reason: 'Archived', currentReviewId: null }) + ) + ); + expect(button('Retry reproduction').disabled).toBe(false); + await flush(() => button('Retry reproduction').click()); + expect(post().headers.get('Idempotency-Key')).toBe(key); + expect(post().body).toEqual({}); + await flush(() => reply(post(), run(otherId, { originalRunId: sourceId }), 202)); + expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`); + } + ); + test.each([400, 401, 404, 409])( + 'HTTP %s never automatically retries or changes the receipt', + async status => { + await ready(); + await flush(() => button('Confirm reproduction').click()); + const first = post(); + const key = first.headers.get('Idempotency-Key'); + await flush(() => reply(first, { error: `Definite rejection ${status}` }, status)); + expect(host.textContent).toContain(`Definite rejection ${status}`); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + await flush(() => button('Retry reproduction').click()); + expect(post().headers.get('Idempotency-Key')).toBe(key); + } + ); + test('a new receipt requires deliberate confirmation and fresh eligible preview', async () => { + await ready(); + await flush(() => button('Confirm reproduction').click()); + const first = post(); + await flush(() => reply(first, { error: 'Conflict' }, 409)); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); + await flush(() => button('Start new reproduction').click()); + expect(button('Retry reproduction')).toBeTruthy(); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); + await flush(() => button('Start new reproduction').click()); + expect(button('Confirm reproduction').disabled).toBe(true); + await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview())); + await flush(() => button('Confirm reproduction').click()); + expect(post().headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key')); + }); + test('source and parent mismatched preview fails closed', async () => { + await open(); + await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview(otherId))); + expect(button('Confirm reproduction').disabled).toBe(true); + expect(host.textContent).toContain('could not be verified'); + await flush(() => button('Refresh original inputs').click()); + const wrong = preview(); + wrong.backtestId = otherId; + wrong.request!.backtestId = otherId; + await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), wrong)); + expect(host.textContent).toContain('different run or backtest'); + expect(button('Confirm reproduction').disabled).toBe(true); + }); + test('late preview and late accepted mutation cannot navigate or overwrite a new selection', async () => { + await open(); + const oldPreview = request(`/api/v2/runs/${sourceId}/reproduction`); + await render(createElement(RunReproduction, { run: run(otherId), archived: false })); + await flush(() => reply(oldPreview, preview())); + expect(host.querySelector('[role="dialog"]')).toBeNull(); + await ready(); + await flush(() => button('Confirm reproduction').click()); + const oldPost = post(); + await render(createElement(RunReproduction, { run: run(otherId), archived: false })); + await flush(() => navigate(`/backtests/${backtestId}/run/${otherId}`)); + await flush(() => reply(oldPost, run('accepted-late', { originalRunId: sourceId }), 202)); + expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`); + expect(host.querySelector('[role="dialog"]')).toBeNull(); + }); + test.each(['match', 'mismatch', 'pending', 'unavailable'] as const)( + 'saved reproduction displays server %s, exact source lineage and no invented result', + async status => { + await render( + createElement(RunReproduction, { + run: run(otherId, { originalRunId: sourceId }), + archived: false, + }) + ); + expect(host.textContent).toContain('Loading reproduction comparison'); + const link = host.querySelector('a'); + expect(link?.getAttribute('href')).toBe(`/backtests/${backtestId}/run/${sourceId}`); + const value = comparison(status); + if (status === 'unavailable') { + value.reason = 'No completed saved result'; + } + await flush(() => reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), value)); + expect(host.textContent).toContain( + { + match: 'Economic results match the original.', + mismatch: 'Economic results differ from the original.', + pending: 'Reproduction comparison pending completion.', + unavailable: 'Reproduction comparison unavailable.', + }[status] + ); + if (value.originalHash) { + expect(host.textContent).toContain(value.originalHash); + } + if (status === 'unavailable') { + expect(host.textContent).toContain(value.reason!); + } + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + } + ); + test('comparison errors, malformed matches and foreign sources cannot display a successful match', async () => { + await render( + createElement(RunReproduction, { + run: run(otherId, { originalRunId: sourceId }), + archived: false, + }) + ); + await flush(() => + reply( + request(`/api/v2/runs/${otherId}/reproduction-comparison`), + { error: 'Unavailable store' }, + 503 + ) + ); + expect(host.textContent).toContain('Unavailable store'); + expect(host.textContent).not.toContain('Economic results match'); + await flush(() => button('Refresh comparison').click()); + await flush(() => + reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), { + ...comparison(), + originalHash: null, + }) + ); + expect(host.textContent).toContain('could not be verified'); + await flush(() => button('Refresh comparison').click()); + await flush(() => + reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), { + ...comparison(), + reproducedHash: 'b'.repeat(64), + }) + ); + expect(host.textContent).toContain('could not be verified'); + await flush(() => button('Refresh comparison').click()); + await flush(() => + reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), { + ...comparison(), + originalRunId: 'foreign', + }) + ); + expect(host.textContent).toContain('does not match'); + expect(host.textContent).not.toContain('Economic results match'); + }); + test('status changes invalidate late comparisons and request committed completion', async () => { + await render( + createElement(RunReproduction, { + run: run(otherId, { originalRunId: sourceId, status: 'running' }), + archived: false, + }) + ); + const old = request(`/api/v2/runs/${otherId}/reproduction-comparison`); + old.settled = true; + await render( + createElement(RunReproduction, { + run: run(otherId, { originalRunId: sourceId }), + archived: false, + }) + ); + await flush(() => + reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), comparison()) + ); + await flush(() => old.resolve(Response.json(comparison('pending')))); + expect(host.textContent).toContain('Economic results match the original.'); + expect(host.textContent).not.toContain('pending completion'); + }); + test('parent uses original preview even when current catalog configuration cannot execute', async () => { + await render( + createElement( + router.Routes, + null, + createElement(router.Route, { + path: '/backtests/:id/run/:runId', + element: createElement(BacktestDetailPageV2), + }) + ) + ); + await flush(() => { + reply(request(`/api/v2/backtests/${backtestId}`), { + id: backtestId, + name: 'Different current setup', + strategy: 'catalog', + strategyVersionId: 'different-version', + strategyParameters: {}, + symbols: ['OTHER'], + startDate: '2024-01-01', + endDate: '2024-01-02', + initialCapital: 20000, + config: {}, + archivedAt: null, + createdAt: '2024-01-01', + updatedAt: '2024-01-01', + }); + reply(request(`/api/v2/backtests/${backtestId}/runs`), [run()]); + }); + await flush(() => { + reply(request(`/api/v2/backtests/${backtestId}/canonical-capability`), { + available: false, + reason: 'Current version unavailable', + }); + reply(request(`/api/v2/runs/${sourceId}`), run()); + }); + await flush(() => + reply(request(`/api/v2/runs/${sourceId}/results`), { error: 'Missing display result' }, 404) + ); + expect(host.textContent).toContain('Current version unavailable'); + expect(host.textContent).toContain('Run current settings'); + expect(button('Reproduce original').disabled).toBe(false); + await flush(() => button('Reproduce original').click()); + await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview())); + expect(button('Confirm reproduction').disabled).toBe(false); + expect(host.textContent).toContain('Frozen original inputs'); + }); +}); diff --git a/test/postgres/canonical-durable-backtest.test.ts b/test/postgres/canonical-durable-backtest.test.ts index dfb9dcc2..31d33e4f 100644 --- a/test/postgres/canonical-durable-backtest.test.ts +++ b/test/postgres/canonical-durable-backtest.test.ts @@ -62,6 +62,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', + '21-run-reproduction.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') diff --git a/test/postgres/canonical-research.test.ts b/test/postgres/canonical-research.test.ts index 0d540227..cc72f38e 100644 --- a/test/postgres/canonical-research.test.ts +++ b/test/postgres/canonical-research.test.ts @@ -61,6 +61,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) { '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', + '21-run-reproduction.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/postgres/catalog-backtest-drafts.test.ts b/test/postgres/catalog-backtest-drafts.test.ts index 1402f0cf..abe52aa8 100644 --- a/test/postgres/catalog-backtest-drafts.test.ts +++ b/test/postgres/catalog-backtest-drafts.test.ts @@ -100,6 +100,7 @@ async function fixture() { '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', + '21-run-reproduction.sql', ]) { await pool.query(sql(name)); } diff --git a/test/postgres/dataset-catalog.test.ts b/test/postgres/dataset-catalog.test.ts index a84b6a3d..70587717 100644 --- a/test/postgres/dataset-catalog.test.ts +++ b/test/postgres/dataset-catalog.test.ts @@ -73,6 +73,7 @@ async function fixture() { '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', + '21-run-reproduction.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/postgres/durable-backtest.test.ts b/test/postgres/durable-backtest.test.ts index a7471564..499de6d6 100644 --- a/test/postgres/durable-backtest.test.ts +++ b/test/postgres/durable-backtest.test.ts @@ -84,6 +84,7 @@ async function fixture() { '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', + '21-run-reproduction.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 687f395a..846bc9cb 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -23,6 +23,7 @@ const migrations = [ '18-backtest-strategy-versions.sql', '19-canonical-research.sql', '20-research-workspace.sql', + '21-run-reproduction.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { diff --git a/test/postgres/research-retention.test.ts b/test/postgres/research-retention.test.ts index 052dbb97..7ac3275b 100644 --- a/test/postgres/research-retention.test.ts +++ b/test/postgres/research-retention.test.ts @@ -24,7 +24,9 @@ const retention = '\n' + sql('18-backtest-strategy-versions.sql') + '\n' + - sql('19-canonical-research.sql'); + sql('19-canonical-research.sql') + + '\n' + + sql('21-run-reproduction.sql'); const request = { name: 'Retained evidence', strategy: 'sma-crossover', diff --git a/test/postgres/research-runtime-isolation.test.ts b/test/postgres/research-runtime-isolation.test.ts index 86e74bcb..9e74f82c 100644 --- a/test/postgres/research-runtime-isolation.test.ts +++ b/test/postgres/research-runtime-isolation.test.ts @@ -69,6 +69,7 @@ async function fixture() { '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', + '21-run-reproduction.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') diff --git a/test/postgres/research-workspace.test.ts b/test/postgres/research-workspace.test.ts index ed9f0ff2..9ed97647 100644 --- a/test/postgres/research-workspace.test.ts +++ b/test/postgres/research-workspace.test.ts @@ -60,6 +60,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) { '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', + '21-run-reproduction.sql', ]) { await pool.query(sql(name)); } diff --git a/test/postgres/run-reproduction.test.ts b/test/postgres/run-reproduction.test.ts new file mode 100644 index 00000000..d0d27ea1 --- /dev/null +++ b/test/postgres/run-reproduction.test.ts @@ -0,0 +1,602 @@ +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 type { + CanonicalRunRequest, + CanonicalRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; +import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; +import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; +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 { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; +import { retainResearchDataset } from '../../scripts/import-research-dataset'; +import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; +import { canonicalSettings } from '../fixtures/canonical-research'; +import { canonicalSmaFixture } from '../fixtures/canonical-sma'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('run-reproduction'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: (() => Promise)[] = []; +let packages: ReturnType | undefined; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); +async function fixture(poolMax = 4, withReproduction = true) { + const dataset = canonicalSmaFixture().dataset; + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Disposable safety database required'); + } + const schema = 'stock_bot_safety_reproduce_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + application_name: schema, + max: poolMax, + 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', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + '09-backtest-run-contract.sql', + '10-durable-backtest-dispatch.sql', + '12-historical-datasets.sql', + '14-backtest-submission.sql', + '16-strategy-catalog.sql', + '17-research-retention.sql', + '18-backtest-strategy-versions.sql', + '19-canonical-research.sql', + ...(withReproduction ? ['21-run-reproduction.sql'] : []), + ]) { + await pool.query( + readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') + ); + } + 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 container = { postgres, logger }; + const api = new BacktestServiceV2(container); + const catalog = new StrategyCatalogService(container); + const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!; + const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed'); + await retainResearchDataset(pool, dataset); + const definition = { + name: 'Canonical API', + strategy: 'catalog', + strategyVersionId: version.id, + strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, + symbols: dataset.manifest.executionSeries.map(s => s.instrumentId), + startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), + endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), + initialCapital: 10000, + config: { + datasetHash: dataset.manifest.hash, + dataFrequency: dataset.manifest.series[0]!.interval, + canonical: canonicalSettings, + }, + }; + const draft = await api.createBacktest(definition, { autoStart: false }); + const approve = async () => { + await catalog.reviewVersion( + version.id, + { decision: 'approve', reason: 'Reviewed retained builtin' }, + 'operator' + ); + return (await catalog.getVersionReviews(version.id)).at(-1)!; + }; + const execute = async (id: string) => { + const engine = new RustBacktestAdapter({ + logger, + storage: { + async getHistoricalBars() { + throw new Error('Canonical execution must never load provider data'); + }, + }, + }); + const runner = new BacktestRunner({ + engine, + engineName: 'native', + repository: new PostgresBacktestRunRepository(postgres), + logger, + }); + try { + await runner.runQueued(id); + } finally { + await runner.shutdown(); + } + }; + return { + pool, + schema, + api, + catalog, + pkg, + version, + draft, + definition, + dataset, + approve, + execute, + app: new Hono().route('/', createBacktestV2Routes(container)), + }; +} + +const receipt = (key: string = randomUUID()) => ({ principal: 'operator' as const, key }); +async function completed(f: Awaited>) { + await f.approve(); + const run = await f.api.createRun({ backtestId: f.draft.id }); + await f.execute(run.id); + const result = await f.api.getRunResults(run.id); + if (!result || !('kind' in result)) { + throw new Error('Expected real canonical result'); + } + return { run, result }; +} +function copied(request: CanonicalRunRequest, id: string, reviewId = request.strategy.reviewId) { + const snapshot = structuredClone(request); + snapshot.runId = id; + snapshot.policy.matching.risk.ledger.sessionId = id; + snapshot.policy.matching.risk.ledger.accountId = `research:${id}`; + snapshot.strategy.reviewId = reviewId; + return snapshot; +} +async function insertCopy( + f: Awaited>, + sourceId: string, + snapshot: CanonicalRunRequest, + parent = f.draft.id +) { + return f.pool.query( + `INSERT INTO runs + (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,original_run_id, + submission_principal,submission_key,submission_hash) + SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending',NULL,$3,$4,$5,'operator',$6,$7 + FROM runs WHERE backtest_id=$2 RETURNING *`, + [snapshot.runId, parent, snapshot, snapshot.datasetHash, sourceId, randomUUID(), 'a'.repeat(64)] + ); +} + +describe.skipIf(!url)('retained original-run reproduction', () => { + test('reproduce_after_template_provider_change: original executable/input identities and economic_hash_parity survive another selected version', async () => { + const f = await fixture(1); + const { run, result } = await completed(f); + const originalRows = ( + await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [run.id]) + ).rows; + const otherPackage = (await (packages ??= packageBuiltinStrategies()))[1]!; + const otherVersion = await f.catalog.seedBuiltin( + 'Other current template', + otherPackage, + 'other' + ); + await f.api.updateBacktest(f.draft.id, { + name: 'New template name', + strategyVersionId: otherVersion.id, + strategyParameters: { + lookbackPeriod: 2, + trendPeriod: 3, + momentumPeriod: 1, + volatilityPeriod: 2, + entryZScore: 1, + exitZScore: 0.1, + minTrendReturn: -0.5, + minMomentumReturn: -0.5, + maxVolatility: 1, + minNotionalVolume: '0', + regimeFilter: 'none', + }, + initialCapital: 12000, + config: { ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '0.02' } }, + }); + await f.catalog.reviewVersion( + f.version.id, + { decision: 'revoke', reason: 'Require new review' }, + 'operator' + ); + const approval = await f.approve(); + expect(approval.id).not.toBe(result.request.strategy.reviewId); + const preview = await f.api.getReproductionPreview(run.id); + expect(preview.available).toBe(true); + expect(preview.request).toEqual(result.request); + expect(preview.currentReviewId).toBe(approval.id); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); + const key = receipt(); + const reproduced = await f.api.reproduceRun(run.id, key); + expect(reproduced.originalRunId).toBe(run.id); + expect(reproduced.id).not.toBe(run.id); + expect(reproduced.backtestId).toBe(run.backtestId); + expect((await f.api.getReproductionComparison(reproduced.id)).status).toBe('pending'); + const admitted = ( + await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [reproduced.id]) + ).rows[0].request_snapshot; + expect(admitted).toEqual(copied(result.request, reproduced.id, approval.id)); + // Storage is a provider-read failure fixture; both jobs must use the retained bytes. + await f.execute(reproduced.id); + const repeated = (await f.api.getRunResults(reproduced.id)) as CanonicalRunResult; + expect(String(repeated.financial.projection.valuation.equity)).toBe('9969.30000000'); + expect(String(repeated.financial.projection.valuation.fees)).toBe('0.70000000'); + expect(repeated.financial.projection.fills).toEqual(result.financial.projection.fills); + const comparison = await f.api.getReproductionComparison(reproduced.id); + expect(comparison.status).toBe('match'); + expect(comparison.originalHash).toMatch(/^[a-f0-9]{64}$/); + expect(comparison.reproducedHash).toBe(comparison.originalHash); + expect(await f.api.getRunResults(run.id)).toEqual(result); + expect( + (await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [run.id])).rows + ).toEqual(originalRows); + expect((await f.api.getBacktest(f.draft.id))?.strategyVersionId).toBe(otherVersion.id); + expect((await f.api.getReproductionComparison(run.id)).status).toBe('not-reproduction'); + // Accepted receipts survive later eligibility changes; no second dispatch is admitted. + await f.catalog.reviewVersion( + f.version.id, + { decision: 'revoke', reason: 'No new work' }, + 'operator' + ); + await f.catalog.updateStrategy(f.version.strategyId, { archived: true }, 'operator'); + await f.api.archiveBacktest(f.draft.id, true); + expect((await f.api.reproduceRun(run.id, key)).id).toBe(reproduced.id); + expect((await f.api.getReproductionPreview(run.id)).available).toBe(false); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('archived'); + await f.api.archiveBacktest(f.draft.id, false); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('family is archived'); + await f.catalog.updateStrategy(f.version.strategyId, { archived: false }, 'operator'); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow( + 'current operator approval' + ); + expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(2); + }); + + test('comparison reports economic differences without tolerances or rewriting the original', async () => { + const f = await fixture(); + const { run, result } = await completed(f); + const copy = await f.api.reproduceRun(run.id, receipt()); + await f.execute(copy.id); + const first = await f.api.getReproductionComparison(copy.id); + expect(first.status).toBe('match'); + const changed = structuredClone(await f.api.getRunResults(copy.id)) as CanonicalRunResult; + changed.financial.view.risk.dailyHalted = !changed.financial.view.risk.dailyHalted; + // Simulate divergent valid financial diagnostics in this disposable result only. + await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); + await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [ + changed, + copy.id, + ]); + const mismatch = await f.api.getReproductionComparison(copy.id); + expect(mismatch.status).toBe('mismatch'); + expect(mismatch.originalHash).toBe(first.originalHash); + expect(mismatch.reproducedHash).not.toBe(mismatch.originalHash); + expect(await f.api.getRunResults(run.id)).toEqual(result); + }); + + test('concurrent duplicate receipts are one run/outbox and operations or original identities never alias', async () => { + const f = await fixture(); + const { run } = await completed(f); + const key = receipt('simultaneous'); + const copies = await Promise.all( + Array.from({ length: 5 }, () => f.api.reproduceRun(run.id, key)) + ); + expect(new Set(copies.map(copy => copy.id)).size).toBe(1); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2); + expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(2); + await expect(f.api.createRun({ backtestId: f.draft.id }, key)).rejects.toThrow( + 'different run request' + ); + await expect(f.api.reproduceRun(randomUUID(), key)).rejects.toThrow('different run request'); + const ordinaryKey = receipt('ordinary'); + await f.api.createRun({ backtestId: f.draft.id }, ordinaryKey); + await expect(f.api.reproduceRun(run.id, ordinaryKey)).rejects.toThrow('different run request'); + const other = await f.api.createBacktest( + { ...f.definition, name: 'Second template' }, + { autoStart: false } + ); + const second = await f.api.createRun({ backtestId: other.id }); + await f.execute(second.id); + const racingKey = receipt('cross-parent'); + const racers = await Promise.allSettled([ + f.api.reproduceRun(run.id, racingKey), + f.api.reproduceRun(second.id, racingKey), + ]); + expect(racers.filter(value => value.status === 'fulfilled')).toHaveLength(1); + expect(racers.filter(value => value.status === 'rejected')).toHaveLength(1); + expect( + (await f.pool.query('SELECT * FROM runs WHERE submission_key=$1', [racingKey.key])).rowCount + ).toBe(1); + }); + + test('SQL copy guard rejects altered economics, cross-parent sources, missing receipts and rewritten lineage', async () => { + const f = await fixture(); + const { run, result } = await completed(f); + for (const mutation of [ + (value: CanonicalRunRequest) => { + value.name = 'Rewritten'; + }, + (value: CanonicalRunRequest) => { + value.strategy.selection.parameters = { fastPeriod: 6, slowPeriod: 7 }; + }, + (value: CanonicalRunRequest) => { + value.policy.matching.risk.feeRate = + '0.00000000' as typeof value.policy.matching.risk.feeRate; + }, + (value: CanonicalRunRequest) => { + value.strategy.reviewId = randomUUID(); + }, + (value: CanonicalRunRequest) => { + value.build.workerSha256 = 'b'.repeat(64); + }, + (value: CanonicalRunRequest) => { + value.policy.matching.risk.ledger.accountId = 'wrong'; + }, + ]) { + const snapshot = copied(result.request, randomUUID()); + mutation(snapshot); + await expect(insertCopy(f, run.id, snapshot)).rejects.toThrow( + 'preserve the original frozen request' + ); + } + const other = await f.api.createBacktest( + { ...f.definition, name: 'Other parent' }, + { autoStart: false } + ); + await expect( + insertCopy(f, run.id, copied(result.request, randomUUID()), other.id) + ).rejects.toThrow('same backtest'); + const id = randomUUID(); + await expect(insertCopy(f, id, copied(result.request, id))).rejects.toThrow( + 'completed canonical source' + ); + const accepted = await f.api.reproduceRun(run.id, receipt()); + await expect( + f.pool.query('UPDATE runs SET original_run_id=NULL WHERE id=$1', [accepted.id]) + ).rejects.toThrow('immutable'); + await expect( + f.pool.query('UPDATE runs SET original_run_id=$1 WHERE id=$2', [accepted.id, run.id]) + ).rejects.toThrow('immutable'); + await expect( + f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [{}, accepted.id]) + ).rejects.toThrow('immutable'); + const direct = copied(result.request, randomUUID()); + await expect( + f.pool.query( + `INSERT INTO runs(id,backtest_id,run_number,status,request_snapshot,dataset_hash,original_run_id) + VALUES($1,$2,100,'pending',$3,$4,$5)`, + [direct.runId, f.draft.id, direct, direct.datasetHash, run.id] + ) + ).rejects.toThrow('submission receipt'); + // Reapplying migration keeps all source/result/receipt rows and lineage unchanged. + const before = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows; + await f.pool.query( + readFileSync( + new URL('../../database/postgres/init/21-run-reproduction.sql', import.meta.url), + 'utf8' + ) + ); + expect((await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows).toEqual(before); + expect(await f.api.getRunResults(run.id)).toEqual(result); + await f.api.cancelRun(accepted.id); + expect((await f.api.getReproductionComparison(accepted.id)).status).toBe('unavailable'); + expect((await f.api.getReproductionComparison(accepted.id)).originalHash).toBeNull(); + }); + + test('missing_original_artifact and corrupt retained dataset fail without admission or provider fallback', async () => { + const f = await fixture(); + const { run, result } = await completed(f); + await f.pool.query('ALTER TABLE strategy_versions DISABLE TRIGGER USER'); + const broken = structuredClone(f.pkg); + broken.artifact.content += '\n// damaged retained bytes'; + await f.pool.query('UPDATE strategy_versions SET envelope=$1 WHERE id=$2', [ + broken, + f.version.id, + ]); + const unavailable = await f.api.getReproductionPreview(run.id); + expect(unavailable.available).toBe(false); + expect(unavailable.reason).toContain('hash mismatch'); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('hash mismatch'); + await f.pool.query('UPDATE strategy_versions SET envelope=$1 WHERE id=$2', [ + f.pkg, + f.version.id, + ]); + await f.pool.query('ALTER TABLE strategy_versions ENABLE TRIGGER USER'); + await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER'); + const badDataset = { + ...f.dataset, + bars: f.dataset.bars.map((bar, index) => + index === 0 ? { ...bar, close: bar.close + 1 } : bar + ), + }; + await f.pool.query('UPDATE backtest_datasets SET payload=$1 WHERE hash=$2', [ + badDataset, + f.dataset.manifest.hash, + ]); + expect((await f.api.getReproductionPreview(run.id)).available).toBe(false); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('content validation'); + await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER ALL'); + await f.pool.query('DELETE FROM backtest_datasets WHERE hash=$1', [f.dataset.manifest.hash]); + expect((await f.api.getReproductionPreview(run.id)).reason).toContain('not found'); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('not found'); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); + expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1); + expect(await f.api.getRunResults(run.id)).toEqual(result); + }); + + test('unsupported_engine_version is explicit and accepted receipt replay survives later installed-build mismatch', async () => { + const f = await fixture(); + const { run, result } = await completed(f); + const key = receipt(); + const accepted = await f.api.reproduceRun(run.id, key); + const historical = structuredClone(result); + historical.request.build.runtimeVersion = 'historical-unsupported'; + // Simulate an older stored build in this disposable schema; never change installed binaries. + await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); + await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); + await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [ + historical.request, + run.id, + ]); + await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [ + historical, + run.id, + ]); + await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); + await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER'); + const preview = await f.api.getReproductionPreview(run.id); + expect(preview.available).toBe(false); + expect(preview.reason).toContain('not installed'); + expect(preview.request?.build.runtimeVersion).toBe('historical-unsupported'); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('not installed'); + expect((await f.api.reproduceRun(run.id, key)).id).toBe(accepted.id); + expect(await f.api.getRunResults(run.id)).toEqual(historical); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2); + }); + + test('current original-family archive serializes with reproduction admission', async () => { + const f = await fixture(); + const { run } = await completed(f); + const blocker = await f.pool.connect(); + await blocker.query('BEGIN'); + await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.version.strategyId]); + let settled = false; + const pending = f.api.reproduceRun(run.id, receipt()).finally(() => { + settled = true; + }); + const outcome = pending.then( + value => ({ value, error: null }), + error => ({ value: null, error }) + ); + try { + for (let attempt = 0; attempt < 200; attempt++) { + const waiters = await f.pool.query( + `SELECT count(*)::int AS count FROM pg_stat_activity + WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE '%FOR UPDATE OF s%'`, + [f.schema] + ); + if (waiters.rows[0].count > 0) { + break; + } + if (attempt === 199) { + throw new Error('Reproduction did not wait on original-family lock'); + } + await new Promise(resolve => setTimeout(resolve, 5)); + } + expect(settled).toBe(false); + await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ + f.version.strategyId, + ]); + await blocker.query('COMMIT'); + expect((await outcome).error?.message).toContain('family is archived'); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); + } finally { + await blocker.query('ROLLBACK'); + blocker.release(); + } + }); + + test('first SQL21 upgrade preserves existing results, snapshots, receipts and active lease state', async () => { + const f = await fixture(4, false); + const { run, result } = await completed(f); + const key = receipt('pre-upgrade'); + const active = await f.api.createRun({ backtestId: f.draft.id }, key); + await f.pool.query( + `UPDATE runs SET status='running',attempt_number=2,attempt_id=$1, + lease_expires_at=NOW()+INTERVAL '1 hour',progress=25 WHERE id=$2`, + [randomUUID(), active.id] + ); + const before = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows; + const dispatch = (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows; + await f.pool.query( + readFileSync( + new URL('../../database/postgres/init/21-run-reproduction.sql', import.meta.url), + 'utf8' + ) + ); + const after = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows; + expect( + after.map(({ original_run_id, ...row }) => { + expect(original_run_id).toBeNull(); + return row; + }) + ).toEqual(before); + expect((await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows).toEqual( + dispatch + ); + expect((await f.api.createRun({ backtestId: f.draft.id }, key)).id).toBe(active.id); + expect(await f.api.getRunResults(run.id)).toEqual(result); + const copy = await f.api.reproduceRun(run.id, receipt()); + await f.execute(copy.id); + expect((await f.api.getReproductionComparison(copy.id)).status).toBe('match'); + }); + + test('corrupt retained canonical request or result is a sanitized server failure, never a valid preview or input400', async () => { + const f = await fixture(); + const { run, result } = await completed(f); + await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); + await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [ + { ...result.request, policy: {} }, + run.id, + ]); + const response = await f.app.request(`/api/v2/runs/${run.id}/reproduction`); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: 'Could not inspect original run reproduction' }); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow(); + await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [result.request, run.id]); + await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); + await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); + const corrupt = structuredClone(result); + corrupt.analytics.metrics.totalReturn = 99; + await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [ + corrupt, + run.id, + ]); + expect((await f.app.request(`/api/v2/runs/${run.id}/reproduction`)).status).toBe(500); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('does not match'); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); + expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1); + }); + + test('incomplete, missing and legacy source inputs are explicit unavailable states', async () => { + const f = await fixture(); + await f.approve(); + const run = await f.api.createRun({ backtestId: f.draft.id }); + expect((await f.api.getReproductionPreview(run.id)).reason).toContain('completed'); + await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('completed'); + await expect(f.api.getReproductionPreview(randomUUID())).rejects.toThrow('not found'); + await expect(f.api.getReproductionComparison(randomUUID())).rejects.toThrow('not found'); + // Legacy rows remain readable and acquire NULL lineage after additive migration. + const legacy = await f.api.createBacktest( + { + name: 'Legacy', + strategy: 'sma', + symbols: ['X0.US'], + startDate: '2024-01-01', + endDate: '2024-01-02', + initialCapital: 10000, + }, + { autoStart: false } + ); + const legacyRun = await f.api.createRun({ backtestId: legacy.id }); + await f.pool.query("UPDATE runs SET status='completed' WHERE id=$1", [legacyRun.id]); + expect((await f.api.getRun(legacyRun.id))?.originalRunId).toBeNull(); + expect((await f.api.getReproductionPreview(legacyRun.id)).reason).toContain( + 'frozen canonical inputs' + ); + expect((await f.api.getReproductionComparison(legacyRun.id)).status).toBe('not-reproduction'); + }); +});