import { randomUUID } from 'node:crypto'; import { describe, expect, mock, test } from 'bun:test'; import { Hono } from 'hono'; import { z } from 'zod'; import { createHttpSecurity } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/services'; import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes'; import { buildExperimentPreview, experimentHash, PREVIEW_RUN_ID, } from '../../apps/stock/web-api/src/services/experiment-input'; import { canonicalSmaFixture } from '../fixtures/canonical-sma'; const tokens = { operator: 'experiment-admin-fixture-not-a-real-secret-1234', service: 'experiment-service-fixture-not-a-real-secret-1234', read: 'experiment-read-fixture-not-a-real-secret-1234', }; const backtestId = randomUUID(), experimentId = randomUUID(); const input = { backtestId, name: 'Sweep', grid: { fastPeriod: [1, 2] } }; type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record[] }>; function fixture( mode: 'enabled' | 'disabled' | 'absent' = 'enabled', query: Query = async () => ({ rows: [] }) ) { const client = { query: mock(query) }; const database = { ...client, transaction: mock(async (work: (client: { query: Query }) => Promise) => work(client)), }; const app = new Hono(); if (mode !== 'absent') { createHttpSecurity({ adminToken: tokens.operator, serviceToken: tokens.service, readToken: tokens.read, environment: 'test', hostname: '127.0.0.1', disabled: mode === 'disabled', }).mount(app); } app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer)); return { database, request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) { return app.request(`/api/v2/experiments${path}`, { method, headers: { 'Content-Type': 'application/json', ...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}), ...(key === undefined ? {} : { 'Idempotency-Key': key }), }, ...(body === undefined ? {} : { body }), }); }, }; } function retainedPreview() { const version = randomUUID(), owner = `strategy:${version}`; const fixture = canonicalSmaFixture([owner]); const descriptor = builtinCatalogDescriptors[0]!; const policy = structuredClone(fixture.config); policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID; policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`; const request = canonicalRunRequestSchema.parse({ kind: 'canonical-research/v1', runId: PREVIEW_RUN_ID, backtestId, name: 'Template', strategy: { familyId: randomUUID(), versionId: version, origin: 'builtin', reviewId: randomUUID(), package: { version: 1, program: descriptor.program, parameterSchema: descriptor.parameterSchema, artifact: { format: 'esm-bundle/v1', entryExport: descriptor.entryExport, content: 'fixture', sha256: 'a'.repeat(64), }, dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) }, source: { revision: 'c'.repeat(40), dirty: false }, build: { tool: 'bun', version: 'fixture', target: 'browser' }, }, selection: fixture.selections[0], }, datasetHash: fixture.dataset.manifest.hash, policy, analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, build: { version: 1, workerSha256: 'a'.repeat(64), engineWrapperSha256: 'b'.repeat(64), engineBinarySha256: 'c'.repeat(64), dependencyLockSha256: 'd'.repeat(64), runtime: 'bun', runtimeVersion: 'fixture', platform: 'linux', arch: 'x64', }, modelArtifacts: [], }); return buildExperimentPreview(input, request, fixture.dataset.manifest); } const runId = randomUUID(); const retryBody = { expectedAttemptNumber: 1, expectedRetryCount: 0 }; const path = `/${experimentId}/trials/${runId}`; function savedRetry(overrides: Record = {}) { return { id: randomUUID(), experiment_id: experimentId, run_id: runId, trial_key: 'a'.repeat(64), retry_number: 1, previous_attempt_number: 1, previous_attempt_id: null, error: null, progress: '14.25', current_simulation_date: null, started_at: null, completed_at: '2026-10-24T10:00:00.123456Z', paused_at: null, failure_updated_at: '2026-10-24T10:00:00.654321Z', recorded_at: '2026-10-24T10:00:01.000001Z', principal: 'operator', review_id: randomUUID(), submission_hash: 'a'.repeat(64), ...overrides, }; } function detailRow(preview: ReturnType) { return { id: experimentId, backtest_id: backtestId, name: input.name, created_at: '2026-10-24T00:00:00Z', cancel_requested: true, trial_count: 2, dataset_hash: preview.request.datasetHash, strategy_version_id: preview.request.strategy.versionId, preview_hash: preview.previewHash, counts: {}, preview, }; } describe('failed trial retry HTTP contract', () => { test('credential proof/read role/strict body/counters/IDs/receipt key gate storage', async () => { for (const mode of ['enabled', 'disabled', 'absent'] as const) { const f = fixture(mode); expect( (await f.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), undefined, 'key')) .status ).toBe(401); expect(f.database.transaction.mock.calls).toHaveLength(0); } const read = fixture(); expect( (await read.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), 'read', 'key')).status ).toBe(403); expect((await read.request(`${path}/retries`)).status).toBe(401); for (const [target, body, key] of [ [path, '{}', 'key'], [path, '{', 'key'], [path, JSON.stringify({ ...retryBody, expectedRetryCount: -1 }), 'key'], [path, JSON.stringify({ ...retryBody, expectedAttemptNumber: 1.5 }), 'key'], [path, JSON.stringify({ ...retryBody, expectedAttemptNumber: 2147483648 }), 'key'], [path, JSON.stringify({ ...retryBody, parameters: { fastPeriod: 2 } }), 'key'], [path, JSON.stringify(retryBody), undefined], [path, JSON.stringify(retryBody), 'bad key'], [path, JSON.stringify(retryBody), 'x'.repeat(201)], [`/bad/trials/${runId}`, JSON.stringify(retryBody), 'key'], [`/${experimentId}/trials/bad`, JSON.stringify(retryBody), 'key'], ]) { const f = fixture(); expect((await f.request(`${target}/retry`, 'POST', body, 'operator', key)).status).toBe(400); expect(f.database.query.mock.calls).toHaveLength(0); expect(f.database.transaction.mock.calls).toHaveLength(0); } expect( (await read.request(`/${experimentId}/trials/bad/retries`, 'GET', undefined, 'read')).status ).toBe(400); }); test('accepted receipt replay returns202/current detail before current eligibility and preserves historical timestamp precision', async () => { const preview = retainedPreview(); const hash = experimentHash({ version: 1, operation: 'retry-experiment-trial', experimentId, runId, ...retryBody, }); for (const principal of ['operator', 'service'] as const) { const saved = savedRetry({ principal, submission_hash: hash, trial_key: preview.candidates[0]!.trialKey, }); const f = fixture('enabled', async (sql, values) => { if (sql.includes('h.principal=$1')) { expect(values).toEqual([principal, 'accepted']); return { rows: [saved] }; } if (sql.includes('SELECT r.id')) { return { rows: [] }; } expect(sql).not.toContain('FROM backtests'); expect(sql).not.toContain('FOR UPDATE'); return { rows: [detailRow(preview)] }; }); const response = await f.request( `${path}/retry`, 'POST', JSON.stringify(retryBody), principal, 'accepted' ); expect(response.status).toBe(202); expect(response.headers.get('Location')).toBe(`/api/v2/experiments/${experimentId}`); expect(response.headers.get('Cache-Control')).toBe('no-store'); const result = await response.json(); expect(result.retry).toMatchObject({ id: saved.id, runId, experimentId, principal, previousAttemptId: null, error: null, progress: 14.25, completedAt: '2026-10-24T10:00:00.123456Z', failureUpdatedAt: '2026-10-24T10:00:00.654321Z', }); expect(result.experiment.cancelRequested).toBe(true); expect(result.experiment.trials[0]).toMatchObject({ status: 'missing', attemptNumber: 0, retryCount: 0, }); expect(result.retry).not.toHaveProperty('submission_hash'); } }); test('history returns ordered immutable snapshots and membership uses404/409 without accepting another experiment', async () => { const saved = savedRetry(); const f = fixture('enabled', async sql => { if (sql.includes('SELECT id FROM research_experiments')) { return { rows: [{ id: experimentId }] }; } if (sql.includes('SELECT experiment_id FROM runs')) { return { rows: [{ experiment_id: experimentId }] }; } expect(sql).toContain('ORDER BY h.retry_number'); expect(sql).not.toContain('canonical_result'); return { rows: [saved] }; }); const response = await f.request(`${path}/retries`, 'GET', undefined, 'read'); expect(response.status).toBe(200); expect((await response.json()).retries[0]).toMatchObject({ id: saved.id, retryNumber: 1 }); const missing = fixture(); expect((await missing.request(`${path}/retries`, 'GET', undefined, 'read')).status).toBe(404); const wrong = fixture('enabled', async sql => ({ rows: sql.includes('research_experiments') ? [{ id: experimentId }] : [{ experiment_id: randomUUID() }], })); expect((await wrong.request(`${path}/retries`, 'GET', undefined, 'read')).status).toBe(409); }); test('conflict/missing/stale are explicit and arbitrary database/schema faults remain sanitized500', async () => { const conflict = fixture('enabled', async () => ({ rows: [savedRetry()] })); expect( ( await conflict.request( `${path}/retry`, 'POST', JSON.stringify(retryBody), 'operator', 'key' ) ).status ).toBe(409); const missing = fixture(); expect( (await missing.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), 'operator', 'key')) .status ).toBe(404); const stale = fixture('enabled', async sql => { if (sql.includes('experiment_trial_retries')) { return { rows: [] }; } if (sql.includes('FROM backtests')) { return { rows: [{ id: backtestId, archived_at: null }] }; } if (sql.includes('FROM research_experiments')) { return { rows: [{ id: experimentId, cancel_requested: false }] }; } return { rows: [ { id: runId, experiment_id: experimentId, status: 'failed', cancel_requested: false, attempt_number: 1, manual_retry_count: 1, }, ], }; }); expect( (await stale.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), 'operator', 'key')) .status ).toBe(409); for (const failure of [new Error('private connection details'), new z.ZodError([])]) { const f = fixture('enabled', async () => { throw failure; }); for (const [suffix, method, body] of [ ['retry', 'POST', JSON.stringify(retryBody)], ['retries', 'GET', undefined], ]) { const response = await f.request(`${path}/${suffix}`, method, body, 'operator', 'key'); expect(response.status).toBe(500); expect(await response.text()).not.toContain('private'); } } }); test('counter projection uses the same child rows as statuses rather than previous summary observations', async () => { const preview = retainedPreview(); const f = fixture('enabled', async sql => sql.includes('SELECT r.id') ? { rows: [ { id: runId, trial_index: 0, trial_key: preview.candidates[0]!.trialKey, status: 'failed', attempt_number: 3, manual_retry_count: 2, progress: 14, cancel_requested: false, error: 'later failure', request_snapshot: null, dataset_hash: preview.request.datasetHash, backtest_id: backtestId, }, ], } : { rows: [detailRow(preview)] } ); const response = await f.request(`/${experimentId}`, 'GET', undefined, 'read'); expect(response.status).toBe(200); expect((await response.json()).experiment.trials[0]).toMatchObject({ status: 'failed', attemptNumber: 3, retryCount: 2, error: 'later failure', }); }); });