stock-bot/test/postgres/run-reproduction.test.ts

611 lines
27 KiB
TypeScript

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<void>)[] = [];
let packages: ReturnType<typeof packageBuiltinStrategies> | 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',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.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<ReturnType<typeof fixture>>) {
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<ReturnType<typeof fixture>>,
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');
});
});