import { createHash, randomUUID as uuidv4 } from 'node:crypto'; import type { PoolClient, QueryResultRow } from 'pg'; import { canonicalRunRequestSchema, type CanonicalReproductionComparison, type CanonicalReproductionPreview, } from '@stock-bot/stock-config/canonical-research'; import { HistoricalDataRequestError } from '@stock-bot/types'; import { canonicalReproductionHash } from '../reproduction-comparison'; import { RunReproductionError, verifyReproductionInputs } from '../run-reproduction'; import { BacktestRetentionError, RunSubmissionConflictError, type BacktestContainer, type Run, type RunSubmission, } from './contracts'; import { mapRun } from './mapping'; import type { BacktestResults } from './results'; /** Focused reproduction operations; transaction order is preserved. */ export class BacktestReproduction { constructor( private readonly container: BacktestContainer, private readonly results: BacktestResults ) {} 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 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.results.getRunResults(source.id); const reproduced = await this.results.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.results.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; } }