import { randomUUID } from 'node:crypto'; import { expect, mock, test } from 'bun:test'; import type { PoolClient } from 'pg'; import { insertExperimentTrial } from '../../apps/stock/web-api/src/services/insert-experiment-trial'; import { canonicalRunnerFixture } from '../fixtures/canonical-runner'; function trial() { const { request } = canonicalRunnerFixture(); return { runId: request.runId, backtestId: request.backtestId, runNumber: 17, request, experimentId: randomUUID(), trialKey: 'a'.repeat(64), trialIndex: 3, }; } test('the admitted trial and dispatch use the existing connection and exact caller identities', async () => { const input = trial(); const snapshot = structuredClone(input); const query = mock(async (_text: string, _values: unknown[]) => ({ rows: [] })); await insertExperimentTrial({ query } as unknown as PoolClient, input); expect(query).toHaveBeenCalledTimes(2); const [run, dispatch] = query.mock.calls; expect(run?.[0]).toContain("VALUES ($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)"); expect(run?.[1]).toEqual([ input.runId, input.backtestId, 17, input.request, input.request.datasetHash, input.experimentId, input.trialKey, 3, ]); expect(run?.[1][3]).toBe(input.request); expect(dispatch).toEqual(['INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [input.runId]]); expect(input).toEqual(snapshot); }); test('a failed run insert never attempts dispatch and propagates the original transaction failure', async () => { const failure = new Error('duplicate trial'); const query = mock(async () => { throw failure; }); await expect(insertExperimentTrial({ query } as unknown as PoolClient, trial())).rejects.toBe( failure ); expect(query).toHaveBeenCalledTimes(1); }); test('a failed dispatch insert propagates so the caller rolls back the run and whole experiment', async () => { const failure = new Error('dispatch insertion failed'); const query = mock(async (text: string) => { if (text.startsWith('INSERT INTO backtest_dispatch')) { throw failure; } return { rows: [] }; }); await expect(insertExperimentTrial({ query } as unknown as PoolClient, trial())).rejects.toBe( failure ); expect(query).toHaveBeenCalledTimes(2); });