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 { createHttpSecurity } from '@stock-bot/di'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient } from '@stock-bot/postgres'; import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; import type { ChronologicalValidationInput, ChronologicalValidationPreview, } from '@stock-bot/stock-config/chronological-validation'; 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 { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes'; import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service'; import { experimentHash } from '../../apps/stock/web-api/src/services/experiment-input'; import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; import { selectValidationWinner, validationEqual, validationEvidence, validationPhasePreview, } from '../../apps/stock/web-api/src/services/validation-evidence'; import { retainResearchDataset } from '../../scripts/import-research-dataset'; import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; import { canonicalSettings } from '../fixtures/canonical-research'; import { chronologicalDataset } from '../fixtures/chronological-validation'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('chronological-validation'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const cleanup: (() => Promise)[] = []; let packages: ReturnType | undefined; const tokens = { operator: 'chronological-operator-fixture-not-a-real-secret-1234', service: 'chronological-service-fixture-not-a-real-secret-1234', }; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function fixture(poolMax = 1, withValidation = true) { if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { throw new Error('Disposable safety database required'); } const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', ''); const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${schema}`); // A single connection detects accidental nested pool reads while the admission lock is held. 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', '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', ...(withValidation ? ['24-chronological-validation.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 }, api = new BacktestServiceV2(container), experiments = new ExperimentsService(container), catalog = new StrategyCatalogService(container); const version = await catalog.seedBuiltin( 'Validation SMA', (await (packages ??= packageBuiltinStrategies()))[0]!, 'seed' ); const data = chronologicalDataset(), dataset = data.dataset; await retainResearchDataset(pool, dataset); const draft = await api.createBacktest( { name: 'Validation template', strategy: 'catalog', strategyVersionId: version.id, strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, symbols: ['X0.US'], startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), initialCapital: 10000, config: { datasetHash: dataset.manifest.hash, dataFrequency: '1m', canonical: canonicalSettings, }, }, { autoStart: false } ); const input: ChronologicalValidationInput = { backtestId: draft.id, name: 'Three explicit windows', grid: { fastPeriod: [1, 2], slowPeriod: [3] }, recipe: data.recipe, }; const app = new Hono(); createHttpSecurity({ adminToken: tokens.operator, serviceToken: tokens.service, environment: 'test', hostname: '127.0.0.1', }).mount(app); app.route('/', createExperimentRoutes(container)); const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') => app.request('/api/v2/experiments/validation/preview', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` }, body: JSON.stringify(raw), }); const review = async (decision: 'approve' | 'revoke' = 'approve') => { await catalog.reviewVersion( version.id, { decision, reason: 'Disposable validation proof' }, 'operator' ); return (await catalog.getVersionReviews(version.id)).at(-1)!; }; const snapshot = async () => { const tables = ( await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [ schema, ]) ).rows; const rows: Record = {}; for (const { tablename } of tables) { const quoted = '"' + String(tablename).replaceAll('"', '""') + '"'; rows[String(tablename)] = ( await pool.query( `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t` ) ).rows[0].rows; } return rows; }; const validations = new ChronologicalValidationService(container); const repository = new PostgresBacktestRunRepository(postgres); const execute = async (id: string) => { const engine = new RustBacktestAdapter({ logger, storage: { async getHistoricalBars() { throw new Error('No provider reads allowed'); }, }, }); const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger }); try { await runner.runQueued(id); } finally { await runner.shutdown(); } }; return { cloneTemplate: async (sourceDataset = dataset) => api.createBacktest( { name: 'Other validation template', strategy: 'catalog', strategyVersionId: version.id, strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, symbols: ['X0.US'], startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(), endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(), initialCapital: 10000, config: { datasetHash: sourceDataset.manifest.hash, dataFrequency: '1m', canonical: canonicalSettings, }, }, { autoStart: false } ), validations, repository, execute, api, pool, postgres, experiments, catalog, version, draft, dataset, input, request, review, snapshot, }; } const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key }); async function submit(f: Awaited>, key = randomUUID()) { await f.review(); const preview = await f.experiments.previewValidation(f.input); const body = { ...f.input, previewHash: preview.previewHash }, identity = actor(key); return { preview, body, identity, validation: await f.validations.submit(body, identity) }; } async function train(f: Awaited>, id: string) { const detail = await f.validations.get(id); for (const trial of detail.phases[0].experiment!.trials) { await f.execute(trial.runId!); } } describe.skipIf(!url)('durable chronological validation', () => { test('native training→write-once winner→same-winner holdouts→historical report and immutable receipt reopen', async () => { const f = await fixture(), start = await submit(f), id = start.validation.id; expect(start.validation.name).toBe(f.input.name); expect(start.validation.phases.map(p => p.status)).toEqual([ 'admitted', 'not-admitted', 'not-admitted', ]); expect(start.validation.phases[0].experiment!.name).toBe(f.input.name + ' · train'); expect(await f.experiments.list()).toEqual([]); expect((await f.validations.list())[0]!.id).toBe(id); expect(await f.validations.submit(start.body, start.identity)).toEqual(start.validation); await expect( f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) ).rejects.toThrow('Every train'); await train(f, id); const before = await f.validations.get(id); expect(before.actions.select.available).toBe(true); const newest = await f.review(); await f.pool.query( 'UPDATE backtests SET name=\'Changed template\',strategy_parameters=\'{"fastPeriod":1,"slowPeriod":4}\' WHERE id=$1', [f.draft.id] ); const selectActor = actor(), selectBody = { previewHash: start.preview.previewHash }; const selected = await f.validations.select(id, selectBody, selectActor); expect(selected.receipt.operation).toBe('select-and-admit-holdouts'); const selection = selected.validation.selection!; expect(selection.training.map(e => e.sourceCandidateIndex)).toEqual([0, 1]); expect(selection.reviewId).toBe(newest.id); expect(selection.training.every(e => e.metrics.totalReturn !== null)).toBe(true); const ranked = [...selection.training].sort( (a, b) => b.metrics.totalReturn! - a.metrics.totalReturn! || a.sourceCandidateIndex - b.sourceCandidateIndex ); expect(selection.winner.index).toBe(ranked[0]!.sourceCandidateIndex); for (const phase of selected.validation.phases.slice(1)) { expect(phase.experiment!.trials).toHaveLength(1); expect(phase.experiment!.name).toBe(f.input.name + ' · ' + phase.phase); expect(phase.experiment!.preview.request.strategy.reviewId).toBe(newest.id); expect( validationEqual( phase.experiment!.preview.request.strategy.selection.parameters, selection.winner.parameters ) ).toBe(true); expect(phase.experiment!.preview.request.name).toBe(start.preview.source.request.name); await f.execute(phase.experiment!.trials[0]!.runId!); } expect((await f.validations.select(id, selectBody, selectActor)).receipt).toEqual( selected.receipt ); await expect(f.validations.select(id, selectBody, actor())).rejects.toThrow('another receipt'); await f.review('revoke'); await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ f.version.strategyId, ]); await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); const finalActor = actor(), finalBody = { previewHash: start.preview.previewHash, selectionHash: selection.selectionHash, }; const finalized = await f.validations.finalize(id, finalBody, finalActor), report = finalized.validation.report!; expect(report.training).toEqual(selection.training); expect(report.validation.sourceCandidateIndex).toBe(selection.winner.index); expect(report.test.sourceCandidateIndex).toBe(selection.winner.index); expect(report.validation.parameters).toEqual(report.test.parameters); expect(report.reset).toBe('initial-capital-empty-positions'); expect(finalized.validation.stage).toBe('reported'); expect((await f.validations.get(id)).report).toEqual(report); await f.validations.cancel(id); expect((await f.validations.finalize(id, finalBody, finalActor)).receipt).toEqual( finalized.receipt ); expect((await f.validations.select(id, selectBody, selectActor)).receipt).toEqual( selected.receipt ); expect((await f.validations.submit(start.body, start.identity)).id).toBe(id); await expect(f.validations.finalize(id, finalBody, actor())).rejects.toThrow('another receipt'); expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(4); expect( (await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n ).toBe(3); for (const field of [ 'validation_manifest', 'validation_selection', 'validation_report', 'validation_phase', ]) { await expect( f.pool.query(`UPDATE research_experiments SET ${field}=NULL WHERE id=$1`, [id]) ).rejects.toThrow(); } }, 60_000); test('ordinary and direct SQL cancellation latch the whole workflow, including pending heldout claims', async () => { const f = await fixture(), first = await submit(f); await f.experiments.cancel(first.validation.id); expect( (await f.validations.get(first.validation.id)).phases[0].experiment!.trials.every( t => t.status === 'cancelled' ) ).toBe(true); await expect( f.validations.select(first.validation.id, { previewHash: first.preview.previewHash }, actor()) ).rejects.toThrow('uncancelled'); const second = await submit(f); await train(f, second.validation.id); const selected = await f.validations.select( second.validation.id, { previewHash: second.preview.previewHash }, actor() ); await f.pool.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [ second.validation.id, ]); const detail = await f.validations.get(second.validation.id); expect(detail.phases.every(p => p.experiment!.cancelRequested)).toBe(true); for (const child of selected.validation.phases.slice(1)) { const id = child.experiment!.trials[0]!.runId!; await f.execute(id); expect((await f.pool.query('SELECT status FROM runs WHERE id=$1', [id])).rows[0].status).toBe( 'cancelled' ); } await expect( f.validations.finalize( detail.id, { previewHash: detail.previewHash, selectionHash: detail.selection!.selectionHash }, actor() ) ).rejects.toThrow('uncancelled'); await expect( f.pool.query('UPDATE research_experiments SET cancel_requested=FALSE WHERE id=$1', [ detail.id, ]) ).rejects.toThrow(); }, 60_000); test('a corrupted heldout dataset or numerically forged training analytics cannot seal selection', async () => { const f = await fixture(), start = await submit(f); await train(f, start.validation.id); const heldout = start.preview.partitions[1].dataset.hash; await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER'); await f.pool.query( "UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,close}','999') WHERE hash=$1", [heldout] ); await expect( f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor()) ).rejects.toThrow('content validation'); expect((await f.validations.get(start.validation.id)).selection).toBeNull(); const sourceDataset = ( await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [ start.preview.source.dataset.hash, ]) ).rows[0].payload; const { prepareChronologicalValidation } = await import( '../../apps/stock/web-api/src/services/validation-preview' ); const prepared = prepareChronologicalValidation(f.input, start.preview.source, sourceDataset); await f.pool.query('UPDATE backtest_datasets SET payload=$2 WHERE hash=$1', [ heldout, prepared.datasets.validation, ]); const runId = start.validation.phases[0].experiment!.trials[0]!.runId!; await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); await f.pool.query( "UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,metrics,totalReturn}','900') WHERE run_id=$1", [runId] ); await expect( f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor()) ).rejects.toThrow('analytics validation'); expect((await f.validations.get(start.validation.id)).selection).toBeNull(); expect( (await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n ).toBe(1); }, 60_000); }); async function selectionDocument(f: Awaited>, validationId: string) { const detail = await f.validations.get(validationId), training = []; for (const trial of detail.phases[0].experiment!.trials) { const result = (await f.api.getRunResults(trial.runId!)) as CanonicalRunResult; training.push(validationEvidence('train', validationId, trial, trial.index, result)); } const manifest = { version: 'chronological-validation-selection/v1' as const, id: randomUUID(), validationId, previewHash: detail.previewHash, createdAt: new Date().toISOString(), principal: 'operator' as const, reviewId: (await f.catalog.getVersionReviews(f.version.id)).at(-1)!.id, winner: selectValidationWinner(detail.preview.source.candidates, training), training, holdoutExperimentIds: { validation: randomUUID(), test: randomUUID() }, }; return { ...manifest, selectionHash: experimentHash(manifest), _receipt: { key: randomUUID(), hash: 'a'.repeat(64) }, }; } describe.skipIf(!url)('durable validation adversarial boundaries', () => { test('first/idempotent SQL24 upgrade preserves ordinary requests/results/receipts and active leases', async () => { const f = await fixture(1, false); await f.review(); const ordinaryInput = { backtestId: f.draft.id, name: 'Existing ordinary sweep', grid: { fastPeriod: [1, 2] }, }; const preview = await f.experiments.preview(ordinaryInput); const ordinary = await f.experiments.submit( { ...ordinaryInput, previewHash: preview.previewHash }, actor() ); await f.execute(ordinary.trials[0]!.runId!); const pending = ordinary.trials[1]!.runId!, request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending])) .rows[0].request_snapshot; await f.repository.startCanonical(request); const before = await f.snapshot(); const names = [ 'require_active_backtest_for_new_run', 'require_experiment_retry_failure', 'guard_manual_trial_retry', 'require_consumed_trial_retry', ]; const functionBodies = async () => ( await f.pool.query( 'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace AND proname=ANY($1) ORDER BY proname', [names] ) ).rows; const priorFunctions = await functionBodies(); const migration = readFileSync( new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url), 'utf8' ); await f.pool.query(migration); const after = await f.snapshot(); after.research_experiments = (after.research_experiments as Record[]).map( ({ validation_manifest: _manifest, validation_parent_id: _parent, validation_phase: _phase, validation_selection: _selection, validation_report: _report, ...row }) => row ); expect(after).toEqual(before); expect(await functionBodies()).toEqual(priorFunctions); const first = await f.snapshot(); await f.pool.query(migration); expect(await f.snapshot()).toEqual(first); expect((await f.experiments.list())[0]!.id).toBe(ordinary.id); const current = await submit(f); expect(current.validation.stage).toBe('training'); expect( (await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [pending])).rows[0] ).toMatchObject({ status: 'running', attempt_number: 1 }); }, 60_000); test('SQL independently rejects mixed shapes, changed source/slice/policy, premature or incorrect winners and incomplete commits', async () => { const f = await fixture(), start = await submit(f), id = start.validation.id; const sourceRow = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [id])) .rows[0]; const insertRoot = async ( manifest: ChronologicalValidationPreview, phase: string | null = 'train' ) => { const trainPreview = validationPhasePreview(manifest, 'train'); return f.pool.query( `INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash,validation_manifest,validation_phase) VALUES($1,$2,$3,$4,$5,'operator',$6,$7,$8,$9)`, [ randomUUID(), f.draft.id, trainPreview.input.name, trainPreview, trainPreview.previewHash, randomUUID(), 'a'.repeat(64), manifest, phase, ] ); }; for (const mutate of [ (p: ChronologicalValidationPreview) => { p.source.request.policy.matching.risk.feeRate = '0.02000000' as typeof p.source.request.policy.matching.risk.feeRate; }, (p: ChronologicalValidationPreview) => { p.partitions[0].request.policy.matching.risk.maxGrossExposure = '999999.00000000' as (typeof p.partitions)[0]['request']['policy']['matching']['risk']['maxGrossExposure']; }, (p: ChronologicalValidationPreview) => { p.partitions[0].counts.admittedWarmup++; }, (p: ChronologicalValidationPreview) => { p.partitions[0].dataset = structuredClone(p.source.dataset); }, (p: ChronologicalValidationPreview) => { p.input.recipe.train.tradeStart++; }, (p: ChronologicalValidationPreview) => { p.source.candidates[0]!.parameters.fastPeriod = 99; }, ]) { const manifest = structuredClone(start.preview); mutate(manifest); await expect(insertRoot(manifest)).rejects.toThrow(); } await expect(insertRoot(start.preview, null)).rejects.toThrow(); // A correct root without its run/outbox set fails at COMMIT, not merely at service validation. await expect(insertRoot(start.preview)).rejects.toThrow('complete exact run'); expect( (await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n ).toBe(1); await train(f, id); const correct = await selectionDocument(f, id); for (const mutate of [ (s: typeof correct) => { s.winner = structuredClone(start.preview.source.candidates[1 - correct.winner.index]!); }, (s: typeof correct) => { s.training[0]!.metrics.totalReturn = 999; }, (s: typeof correct) => { s.training.reverse(); }, (s: typeof correct) => { s.training.pop(); }, (s: typeof correct) => { s.training[0]!.datasetHash = start.preview.partitions[1].dataset.hash; }, ]) { const changed = structuredClone(correct); mutate(changed); await expect( f.pool.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [ id, changed, ]) ).rejects.toThrow(); } await expect( f.pool.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [ id, correct, ]) ).rejects.toThrow('atomically admit both'); expect((await f.validations.get(id)).selection).toBeNull(); expect( ( await f.pool.query('SELECT preview,submission_key FROM research_experiments WHERE id=$1', [ id, ]) ).rows[0] ).toEqual({ preview: sourceRow.preview, submission_key: sourceRow.submission_key }); }, 60_000); test('injected training/outbox/second-holdout insert failures roll back every new input, receipt and selection', async () => { const f = await fixture(); await f.review(); const preview = await f.experiments.previewValidation(f.input), body = { ...f.input, previewHash: preview.previewHash }; const fail = async (table: string, name: string, condition: string) => { await f.pool.query( `CREATE OR REPLACE FUNCTION ${name}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN RAISE EXCEPTION 'Injected ${name}'; END IF; RETURN NEW; END $$` ); await f.pool.query( `CREATE TRIGGER ${name} BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION ${name}()` ); }; for (const [table, condition] of [ ['runs', 'NEW.trial_index=1'], ['backtest_dispatch', 'TRUE'], ]) { await fail(table!, 'injected_root_failure', condition!); const before = await f.snapshot(); await expect(f.validations.submit(body, actor())).rejects.toThrow('Injected'); expect(await f.snapshot()).toEqual(before); await f.pool.query(`DROP TRIGGER injected_root_failure ON ${table}`); } const root = await f.validations.submit(body, actor()); await train(f, root.id); await fail('research_experiments', 'injected_holdout_failure', "NEW.validation_phase='test'"); const before = await f.snapshot(); await expect( f.validations.select(root.id, { previewHash: preview.previewHash }, actor()) ).rejects.toThrow('Injected'); expect(await f.snapshot()).toEqual(before); await f.pool.query('DROP TRIGGER injected_holdout_failure ON research_experiments'); expect( (await f.validations.select(root.id, { previewHash: preview.previewHash }, actor())) .validation.phases ).toHaveLength(3); }, 60_000); test('same and cross-parent receipt races have exactly one atomic owner; conflicting intent never gains children', async () => { const f = await fixture(5); await f.review(); const preview = await f.experiments.previewValidation(f.input), body = { ...f.input, previewHash: preview.previewHash }, same = actor(); const [first, replay] = await Promise.all([ f.validations.submit(body, same), f.validations.submit(body, same), ]); expect(first.id).toBe(replay.id); const other = await f.cloneTemplate(), otherInput = { ...f.input, backtestId: other.id }; const otherPreview = await f.experiments.previewValidation(otherInput), otherBody = { ...otherInput, previewHash: otherPreview.previewHash }; const key = actor(), results = await Promise.allSettled([ f.validations.submit(body, key), f.validations.submit(otherBody, key), ]); expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1); expect(results.filter(r => r.status === 'rejected')).toHaveLength(1); const second = await f.validations.submit(otherBody, actor()); await train(f, first.id); await train(f, second.id); const action = actor(), selections = await Promise.allSettled([ f.validations.select(first.id, { previewHash: preview.previewHash }, action), f.validations.select(second.id, { previewHash: otherPreview.previewHash }, action), ]); expect(selections.filter(r => r.status === 'fulfilled')).toHaveLength(1); expect(selections.filter(r => r.status === 'rejected')).toHaveLength(1); const selectedRoot = selections[0]!.status === 'fulfilled' ? first : second; const selectedBody = { previewHash: selectedRoot.previewHash }; const a = await f.validations.select(selectedRoot.id, selectedBody, action); const [b, c] = await Promise.all([ f.validations.select(selectedRoot.id, selectedBody, action), f.validations.select(selectedRoot.id, selectedBody, action), ]); expect(b.receipt).toEqual(a.receipt); expect(c.receipt).toEqual(a.receipt); expect( ( await f.pool.query( "SELECT count(*)::int AS n FROM research_experiments WHERE validation_phase IN ('validation','test')" ) ).rows[0].n ).toBe(2); }, 60_000); test('failed training and holdout trials reuse existing manual retry receipts and immutable requests', async () => { const f = await fixture(), start = await submit(f), training = start.validation.phases[0].experiment!.trials[0]!, runId = training.runId!; const request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])) .rows[0].request_snapshot; const claim = await f.repository.startCanonical(request); await f.repository.fail(runId, 'Training fixture failure', claim.attemptId); await expect( f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor()) ).rejects.toThrow('Every train'); await f.experiments.retryTrial( start.validation.id, runId, { expectedAttemptNumber: 1, expectedRetryCount: 0 }, actor() ); await train(f, start.validation.id); await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow(); const selected = await f.validations.select( start.validation.id, { previewHash: start.preview.previewHash }, actor() ), child = selected.validation.phases[1].experiment!, childRun = child.trials[0]!.runId!; await f.pool.query( "UPDATE runs SET status='failed',error='Before claim',completed_at=NOW() WHERE id=$1", [childRun] ); await f.experiments.retryTrial( child.id, childRun, { expectedAttemptNumber: 0, expectedRetryCount: 0 }, actor() ); await f.execute(childRun); await f.execute(selected.validation.phases[2].experiment!.trials[0]!.runId!); const saved = await f.validations.finalize( start.validation.id, { previewHash: start.preview.previewHash, selectionHash: selected.validation.selection!.selectionHash, }, actor() ); expect(saved.validation.report).not.toBeNull(); expect( (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0] .request_snapshot ).toEqual(request); expect( (await f.experiments.listTrialRetries(start.validation.id, runId))[0]!.previousAttemptNumber ).toBe(1); expect( (await f.experiments.listTrialRetries(child.id, childRun))[0]!.previousAttemptNumber ).toBe(0); }, 60_000); }); describe.skipIf(!url)('durable validation isolation proofs', () => { test('selection racing direct SQL cancellation leaves no live orphan holdout work', async () => { const f = await fixture(4), start = await submit(f); await train(f, start.validation.id); const outcomes = await Promise.allSettled([ f.validations.select( start.validation.id, { previewHash: start.preview.previewHash }, actor() ), f.pool.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [ start.validation.id, ]), ]); expect(outcomes[1]!.status).toBe('fulfilled'); const detail = await f.validations.get(start.validation.id); expect(detail.cancelRequested).toBe(true); const children = ( await f.pool.query( 'SELECT id,cancel_requested FROM research_experiments WHERE validation_parent_id=$1', [detail.id] ) ).rows; expect(children.length).toBe(detail.selection ? 2 : 0); expect(children.every(c => c.cancel_requested)).toBe(true); const childRuns = ( await f.pool.query( 'SELECT r.status,r.cancel_requested FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.validation_parent_id=$1', [detail.id] ) ).rows; expect(childRuns.every(r => r.status === 'cancelled' && r.cancel_requested)).toBe(true); expect(detail.report).toBeNull(); }, 60_000); test('changing only future test prices cannot change native training scores or frozen winner', async () => { const f = await fixture(), first = await submit(f); await train(f, first.validation.id); const chosen = await f.validations.select( first.validation.id, { previewHash: first.preview.previewHash }, actor() ); const changed = chronologicalDataset(900).dataset; await retainResearchDataset(f.pool, changed); const template = await f.cloneTemplate(changed), secondInput = { ...f.input, backtestId: template.id }; const preview = await f.experiments.previewValidation(secondInput); const second = await f.validations.submit( { ...secondInput, previewHash: preview.previewHash }, actor() ); expect(preview.partitions[0].dataset.hash).toBe(first.preview.partitions[0].dataset.hash); expect(preview.partitions[2].dataset.hash).not.toBe(first.preview.partitions[2].dataset.hash); await train(f, second.id); const next = await f.validations.select( second.id, { previewHash: preview.previewHash }, actor() ); expect(next.validation.selection!.winner).toEqual(chosen.validation.selection!.winner); expect(next.validation.selection!.training.map(e => e.metrics)).toEqual( chosen.validation.selection!.training.map(e => e.metrics) ); expect( ( await f.pool.query( "SELECT count(*)::int AS n FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.validation_phase IN ('validation','test') AND r.status<>'pending'" ) ).rows[0].n ).toBe(0); }, 60_000); test('missing, failed, incomparable and unavailable training candidates each block durable selection', async () => { const f = await fixture(), start = await submit(f), id = start.validation.id, trial = start.validation.phases[0].experiment!.trials[0]!; await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); await f.pool.query( 'UPDATE runs SET experiment_id=NULL,trial_index=NULL,trial_key=NULL WHERE id=$1', [trial.runId] ); expect((await f.validations.get(id)).phases[0].experiment!.trials[0]!.status).toBe('missing'); await expect( f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) ).rejects.toThrow('Every train'); await f.pool.query('UPDATE runs SET experiment_id=$2,trial_index=$3,trial_key=$4 WHERE id=$1', [ trial.runId, id, trial.index, trial.trialKey, ]); await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); await f.pool.query( "UPDATE runs SET status='failed',error='Incomplete candidate',completed_at=NOW() WHERE id=$1", [trial.runId] ); await expect( f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) ).rejects.toThrow('Every train'); await f.experiments.retryTrial( id, trial.runId!, { expectedAttemptNumber: 0, expectedRetryCount: 0 }, actor() ); await train(f, id); const result = ( await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [ trial.runId, ]) ).rows[0].canonical_result; await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); for (const changed of [ { ...result, financial: { ...result.financial, identity: { ...result.financial.identity, datasetHash: 'a'.repeat(64) }, }, }, { ...result, analytics: { ...result.analytics, metrics: { ...result.analytics.metrics, totalReturn: null }, unavailable: { ...result.analytics.unavailable, totalReturn: 'nonfinite-result' }, }, }, ]) { await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [ trial.runId, changed, ]); await expect( f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) ).rejects.toThrow(); expect((await f.validations.get(id)).selection).toBeNull(); expect( ( await f.pool.query( 'SELECT count(*)::int AS n FROM research_experiments WHERE validation_parent_id=$1', [id] ) ).rows[0].n ).toBe(0); } await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [ trial.runId, result, ]); }, 60_000); });