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 { CostSensitivityInput } from '@stock-bot/stock-config/cost-sensitivity'; 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 { ExperimentError } from '../../apps/stock/web-api/src/services/experiment-input'; import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; import { canonicalReproductionHash } from '../../apps/stock/web-api/src/services/reproduction-comparison'; 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('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, withCosts = true, capital = 10000) { 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', '24-chronological-validation.sql', '25-walk-forward.sql', ...(withCosts ? ['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 }, 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 = canonicalSmaFixture(), 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: capital, config: { datasetHash: dataset.manifest.hash, dataFrequency: '1m', canonical: canonicalSettings, }, }, { autoStart: false } ); const input: CostSensitivityInput = { backtestId: draft.id, name: 'Explicit cost diagnostics', scenarios: [ { feeRate: '0.001', slippageRate: '0' }, { feeRate: '0', slippageRate: '0.01' }, ], }; 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/cost-sensitivity/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: capital, 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 }); type Fixture = Awaited>; async function submit(f: Fixture, identity = actor()) { await f.review(); const preview = await f.experiments.previewCosts(f.input), body = { ...f.input, previewHash: preview.previewHash }; return { preview, body, identity, experiment: await f.experiments.submitCosts(body, identity) }; } describe.skipIf(!url)('bounded cost-sensitivity experiments', () => { test('pool1 native baseline agrees with ordinary empty-grid; saved scenarios expose exact costs and immutable results', async () => { const f = await fixture(), start = await submit(f); expect(start.experiment.kind).toBe('cost-sensitivity'); expect(start.experiment.trials).toHaveLength(3); const input = { backtestId: f.draft.id, name: 'Ordinary reference', grid: {} }; const preview = await f.experiments.preview(input), ordinary = await f.experiments.submit( { ...input, previewHash: preview.previewHash }, actor() ); for (const trial of [...start.experiment.trials, ...ordinary.trials]) { await f.execute(trial.runId!); } const detail = await f.experiments.get(start.experiment.id); expect(detail.counts.completed).toBe(3); expect(detail.trials.every(t => t.comparable)).toBe(true); const baseline = await f.api.getRunResults(detail.trials[0]!.runId!), reference = await f.api.getRunResults(ordinary.trials[0]!.runId!); expect(canonicalReproductionHash(baseline as CanonicalRunResult)).toBe( canonicalReproductionHash(reference as CanonicalRunResult) ); expect(await f.experiments.get(detail.id)).toEqual(detail); expect((await f.experiments.list()).find(e => e.id === detail.id)!.kind).toBe( 'cost-sensitivity' ); expect((await f.experiments.submitCosts(start.body, start.identity)).id).toBe(detail.id); }, 60000); }); const result = async (f: Fixture, id: string) => (await f.api.getRunResults(id)) as CanonicalRunResult; describe.skipIf(!url)('cost financial and recovery proofs', () => { test('Rust alone applies exact execution fees and adverse slippage, resetting capital for every scenario', async () => { const f = await fixture(); f.input.scenarios.push({ feeRate: '0.02', slippageRate: '0.01' }); const start = await submit(f); const oracle = [ { prices: ['5.00000000', '2.00000000'], fees: '0.70000000', equity: '9969.30000000' }, { prices: ['5.00000000', '2.00000000'], fees: '0.07000000', equity: '9969.93000000' }, { prices: ['5.05000000', '1.98000000'], fees: '0.00000000', equity: '9969.30000000' }, { prices: ['5.05000000', '1.98000000'], fees: '1.40600000', equity: '9967.89400000' }, ]; for (const [index, trial] of start.experiment.trials.entries()) { await f.execute(trial.runId!); const saved = await result(f, trial.runId!), expected = oracle[index]!; expect(String(saved.financial.reporting.initialEquity)).toBe('10000.00000000'); expect(saved.financial.projection.fills.map(fill => String(fill.price))).toEqual( expected.prices ); expect(saved.financial.projection.fills.map(fill => String(fill.quantity))).toEqual([ '10.00000000', '10.00000000', ]); expect(String(saved.financial.projection.valuation.fees)).toBe(expected.fees); expect(String(saved.financial.projection.valuation.equity)).toBe(expected.equity); } }, 60000); test('fee-inclusive funding cannot be bypassed by a lower-cost scenario; unchanged risk may change fills', async () => { const f = await fixture(1, true, 50); f.input.scenarios = [{ feeRate: '0', slippageRate: '0' }]; const start = await submit(f); for (const trial of start.experiment.trials) { await f.execute(trial.runId!); } const baseline = await result(f, start.experiment.trials[0]!.runId!), zero = await result(f, start.experiment.trials[1]!.runId!); expect(baseline.financial.projection.fills).toEqual([]); expect(String(baseline.financial.projection.valuation.cash)).toBe('50.00000000'); expect(zero.financial.projection.fills).toHaveLength(2); expect(String(zero.financial.projection.valuation.cash)).toBe('20.00000000'); expect(baseline.request.policy.matching.risk.maxGrossExposure).toBe( zero.request.policy.matching.risk.maxGrossExposure ); }, 60000); test('frozen source survives template edit, manual retry retains costs and reproduction retains exact economics', async () => { const f = await fixture(), start = await submit(f), trial = start.experiment.trials[1]!, runId = trial.runId!; const snapshot = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])) .rows[0].request_snapshot; const claim = await f.repository.startCanonical(snapshot); await f.repository.fail(runId, 'Cost attempt failure', claim.attemptId); await f.api.updateBacktest(f.draft.id, { name: 'Changed template', initialCapital: 12000, config: { datasetHash: f.dataset.manifest.hash, dataFrequency: '1m', canonical: { ...canonicalSettings, feeRate: '0.03', slippageRate: '0.04' }, }, }); const newReview = await f.review(); const retry = await f.experiments.retryTrial( start.experiment.id, runId, { expectedAttemptNumber: 1, expectedRetryCount: 0 }, actor() ); expect(retry.retry.error).toBe('Cost attempt failure'); expect(retry.retry.reviewId).toBe(newReview.id); expect( (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0] .request_snapshot ).toEqual(snapshot); await f.execute(runId); const original = await result(f, runId); expect(String(original.request.policy.matching.risk.feeRate)).toBe('0.00100000'); const reproduction = await f.api.reproduceRun(runId, actor()); await f.execute(reproduction.id); expect(canonicalReproductionHash(await result(f, reproduction.id))).toBe( canonicalReproductionHash(original) ); expect((await f.experiments.get(start.experiment.id)).preview).toEqual(start.preview); await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow(); await f.review('revoke'); await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); expect((await f.experiments.submitCosts(start.body, start.identity)).id).toBe( start.experiment.id ); await expect(f.experiments.submitCosts(start.body, actor())).rejects.toThrow(); }, 60000); }); describe.skipIf(!url)('cost SQL and admission boundaries', () => { test('first/idempotent upgrade preserves old evidence/leases and leaves v1 callable and non-request guard bodies unchanged', async () => { const f = await fixture(1, false); await f.review(); const input = { backtestId: f.draft.id, name: 'Old sweep', grid: { fastPeriod: [1, 2] } }, preview = await f.experiments.preview(input), ordinary = await f.experiments.submit( { ...input, 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 functions = async () => ( await f.pool.query( 'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace ORDER BY proname' ) ).rows; const oldFunctions = await functions(), migration = readFileSync( new URL('../../database/postgres/init/26-cost-sensitivity.sql', import.meta.url), 'utf8' ); await f.pool.query(migration); expect(await f.snapshot()).toEqual(before); const changed = [ 'require_experiment_manifest', 'require_active_backtest_for_new_run', 'require_experiment_retry_failure', ]; expect( (await functions()).filter( row => oldFunctions.some(old => old.proname === row.proname) && !changed.includes(row.proname) ) ).toEqual(oldFunctions.filter(row => !changed.includes(row.proname))); const expectedBlocks = { require_active_backtest_for_new_run: [ " expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(NEW.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(NEW.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||NEW.id::text));\n expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');", ' expected := experiment_trial_request(experiment.preview,NEW.trial_index,NEW.id);', ], require_experiment_retry_failure: [ " expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(original.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(original.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||original.id::text));\n expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');", ' expected := experiment_trial_request(experiment.preview,original.trial_index,original.id);', ], }; const now = await functions(); for (const [name, [oldBlock, newBlock]] of Object.entries(expectedBlocks)) { expect(now.find(r => r.proname === name)!.definition).toBe( oldFunctions.find(r => r.proname === name)!.definition.replace(oldBlock, newBlock) ); } await f.pool.query(migration); expect(await f.snapshot()).toEqual(before); expect((await submit(f)).experiment.trials).toHaveLength(3); }, 60000); test('late candidate, outbox failure and omitted dispatch roll back all children and receipt', async () => { const f = await fixture(); await f.review(); const preview = await f.experiments.previewCosts(f.input), body = { ...f.input, previewHash: preview.previewHash }; for (const [table, condition, action, message] of [ ['runs', 'NEW.trial_index=2', "RAISE EXCEPTION 'Injected failure';", 'Injected'], [ 'backtest_dispatch', 'EXISTS(SELECT 1 FROM runs r WHERE r.id=NEW.run_id AND r.trial_index=2)', "RAISE EXCEPTION 'Injected failure';", 'Injected', ], ['backtest_dispatch', 'TRUE', 'RETURN NULL;', 'atomically'], ]) { await f.pool.query( `CREATE OR REPLACE FUNCTION cost_injection() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN ${action} END IF; RETURN NEW; END $$` ); await f.pool.query( `CREATE TRIGGER cost_injection BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION cost_injection()` ); const before = await f.snapshot(); await expect(f.experiments.submitCosts(body, actor())).rejects.toThrow(message); expect(await f.snapshot()).toEqual(before); await f.pool.query(`DROP TRIGGER cost_injection ON ${table}`); } expect((await f.experiments.submitCosts(body, actor())).trials).toHaveLength(3); }, 60000); test('same/cross-parent/cross-kind receipt races produce exactly one operation owner', async () => { const f = await fixture(5); await f.review(); const preview = await f.experiments.previewCosts(f.input), body = { ...f.input, previewHash: preview.previewHash }, identity = actor(); const [first, replay] = await Promise.all([ f.experiments.submitCosts(body, identity), f.experiments.submitCosts(body, identity), ]); expect(first.id).toBe(replay.id); const other = await f.cloneTemplate(), otherInput = { ...f.input, backtestId: other.id }, otherPreview = await f.experiments.previewCosts(otherInput), cross = actor(); const race = await Promise.allSettled([ f.experiments.submitCosts(body, cross), f.experiments.submitCosts({ ...otherInput, previewHash: otherPreview.previewHash }, cross), ]); expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1); expect(race.filter(r => r.status === 'rejected')).toHaveLength(1); const normalInput = { backtestId: f.draft.id, name: 'Parameter sweep', grid: {} }, normal = await f.experiments.preview(normalInput), mixed = actor(); const mixedRace = await Promise.allSettled([ f.experiments.submitCosts(body, mixed), f.experiments.submit({ ...normalInput, previewHash: normal.previewHash }, mixed), ]); expect(mixedRace.filter(r => r.status === 'fulfilled')).toHaveLength(1); expect(mixedRace.filter(r => r.status === 'rejected')).toHaveLength(1); for (const item of [...race, ...mixedRace]) { if (item.status === 'rejected') { expect(item.reason).toBeInstanceOf(ExperimentError); expect(item.reason.status).toBe(409); } } expect((await f.pool.query('SELECT count(*)::int n FROM research_experiments')).rows[0].n).toBe( 3 ); await expect(f.experiments.submitCosts({ ...body, name: 'Changed' }, identity)).rejects.toThrow( 'different' ); }, 60000); test('SQL targets exact source, baseline, cost shape, parameters and two-path request isolation', async () => { const f = await fixture(), start = await submit(f), row = ( await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [start.experiment.id]) ).rows[0]; const validate = async (preview: unknown) => f.pool.query( 'SELECT validate_cost_manifest(jsonb_populate_record(NULL::research_experiments,$1))', [{ ...row, preview }] ); await validate(start.preview); for (const [mutate, message] of [ [(p: typeof start.preview) => (p.source.input.grid = { fastPeriod: [1] }), 'empty-grid'], [ (p: typeof start.preview) => (p.request = structuredClone({ ...p.request, name: 'Foreign' })), 'empty-grid', ], [ (p: typeof start.preview) => (p.candidates[0]!.costs = { feeRate: '0', slippageRate: '0' }), 'exact ordered', ], [ (p: typeof start.preview) => (p.candidates[1]!.parameters = { fastPeriod: 1, slowPeriod: 3 }), 'fixed parameters', ], [ (p: typeof start.preview) => (p.candidates[1]!.costs = { feeRate: '0.001', slippageRate: '0.00000000' }), 'exact ordered', ], [ (p: typeof start.preview) => { p.input.scenarios[0]!.slippageRate = '1.00000000'; p.candidates[1]!.costs.slippageRate = '1.00000000'; }, 'canonical bounds', ], [ (p: typeof start.preview) => { p.input.scenarios[0] = { ...p.candidates[0]!.costs }; p.candidates[1]!.costs = { ...p.candidates[0]!.costs }; }, 'distinct', ], ] as const) { const preview = structuredClone(start.preview); mutate(preview); await expect(validate(preview)).rejects.toThrow(message); } const ordinaryInput = { backtestId: f.draft.id, name: 'Ordinary', grid: {} }, normal = await f.experiments.preview(ordinaryInput); await expect( f.pool.query( 'INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash) VALUES($1,$2,$3,$4,$5,$6,$7,$8)', [ randomUUID(), f.draft.id, ordinaryInput.name, { ...normal, candidates: normal.candidates.map(c => ({ ...c, costs: { feeRate: '0', slippageRate: '0' }, })), }, normal.previewHash, 'operator', randomUUID(), 'a'.repeat(64), ] ) ).rejects.toThrow('cannot contain'); const clone = { ...row, id: randomUUID(), submission_key: randomUUID() }; await expect( f.pool.query( 'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)', [clone] ) ).rejects.toThrow('atomically'); const run = ( await f.pool.query('SELECT * FROM runs WHERE id=$1', [start.experiment.trials[1]!.runId]) ).rows[0]; const inserted = async (mutate: (r: Record) => void) => { const client = await f.pool.connect(); try { await client.query('BEGIN'); const exp = { ...row, id: randomUUID(), submission_key: randomUUID() }; await client.query( 'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)', [exp] ); const id = randomUUID(), candidate = { ...run, id, experiment_id: exp.id, run_number: 999, request_snapshot: structuredClone(run.request_snapshot), }; candidate.request_snapshot.runId = id; candidate.request_snapshot.policy.matching.risk.ledger.sessionId = id; candidate.request_snapshot.policy.matching.risk.ledger.accountId = `research:${id}`; mutate(candidate); await client.query('INSERT INTO runs SELECT * FROM jsonb_populate_record(NULL::runs,$1)', [ candidate, ]); } finally { await client.query('ROLLBACK'); client.release(); } }; await expect( inserted(r => (r.request_snapshot.policy.matching.risk.feeRate = '0.90000000')) ).rejects.toThrow('exact frozen'); await expect( inserted(r => (r.request_snapshot.policy.matching.halfSpreadRate = '0.10000000')) ).rejects.toThrow('exact frozen'); await expect(inserted(r => (r.trial_index = 99))).rejects.toThrow('exact candidate'); expect((await f.experiments.get(start.experiment.id)).trials).toHaveLength(3); }, 60000); test('cancel overlaps a blocked manual retry, leaving no live work and retaining failure evidence', async () => { const f = await fixture(5), start = await submit(f), runId = start.experiment.trials[1]!.runId!; await f.pool.query( "UPDATE runs SET status='failed',error='Cost failure',completed_at=NOW() WHERE id=$1", [runId] ); const before = (await f.pool.query('SELECT to_jsonb(r) row FROM runs r WHERE id=$1', [runId])) .rows; const blocker = await f.pool.connect(); await blocker.query('BEGIN'); await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.draft.id]); const pending = Promise.allSettled([ f.experiments.retryTrial( start.experiment.id, runId, { expectedAttemptNumber: 0, expectedRetryCount: 0 }, actor() ), ]); try { let count = 0; for (let i = 0; i < 100; i++) { count = Number( ( await f.pool.query( "SELECT count(*)::int n FROM pg_stat_activity WHERE application_name=current_schema() AND wait_event_type='Lock'" ) ).rows[0].n ); if (count > 0) { break; } await new Promise(resolve => setTimeout(resolve, 10)); } expect(count).toBeGreaterThan(0); await f.experiments.cancel(start.experiment.id); await blocker.query('COMMIT'); } finally { await blocker.query('ROLLBACK'); blocker.release(); } const outcome = (await pending)[0]!; expect(outcome.status).toBe('rejected'); if (outcome.status === 'rejected') { expect(outcome.reason).toBeInstanceOf(ExperimentError); expect(outcome.reason.status).toBe(409); } expect( (await f.pool.query('SELECT to_jsonb(r) row FROM runs r WHERE id=$1', [runId])).rows ).toEqual(before); const detail = await f.experiments.get(start.experiment.id); expect(detail.cancelRequested).toBe(true); expect(detail.trials.filter(t => t.status === 'cancelled')).toHaveLength(2); }, 60000); });