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 { parseFinancialDecimal } from '@stock-bot/types'; import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes'; import { buildExperimentPreview, experimentCandidates, experimentHash, experimentTrialRequest, 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); } describe('experiment HTTP contract', () => { test('mutations require authenticated credential proof including preview/cancel and development bypass', async () => { for (const mode of ['enabled', 'disabled', 'absent'] as const) { const f = fixture(mode); for (const [path, body] of [ ['/preview', JSON.stringify(input)], ['', JSON.stringify({ ...input, previewHash: 'a'.repeat(64) })], [`/${experimentId}/cancel`, '{}'], ]) { expect((await f.request(path, 'POST', body, undefined, 'key')).status).toBe(401); } expect(f.database.query.mock.calls).toHaveLength(0); expect(f.database.transaction.mock.calls).toHaveLength(0); } }); test('read role lists and inspects but cannot mutate; anonymous reads reject', async () => { const f = fixture(); expect((await f.request()).status).toBe(401); expect((await f.request('', 'GET', undefined, 'read')).status).toBe(200); expect((await f.request(`/${experimentId}`, 'GET', undefined, 'read')).status).toBe(404); for (const path of ['/preview', '', `/${experimentId}/cancel`]) { expect((await f.request(path, 'POST', '{}', 'read', 'key')).status).toBe(403); } }); test('strict bodies, malformed IDs, raw reserved parameters and receipt keys reject before storage', async () => { const submission = { ...input, previewHash: 'a'.repeat(64) }; for (const [path, body, key] of [ ['/preview', '{', 'key'], ['/preview', '[]', 'key'], ['/preview', JSON.stringify({ ...input, feeRate: '0' }), 'key'], ['/preview', `{"backtestId":"${backtestId}","name":"bad","grid":{"__proto__":[1]}}`, 'key'], ['', JSON.stringify(submission), undefined], ['', JSON.stringify(submission), 'contains space'], ['', JSON.stringify(submission), 'x'.repeat(201)], ['', JSON.stringify({ ...submission, previewHash: 'bad' }), 'key'], [`/${experimentId}/cancel`, '{"restart":true}', 'key'], ['/bad/cancel', '{}', 'key'], ]) { const f = fixture(); expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400); expect(f.database.query.mock.calls).toHaveLength(0); expect(f.database.transaction.mock.calls).toHaveLength(0); } const f = fixture(); expect((await f.request('/bad', 'GET', undefined, 'read')).status).toBe(400); expect((await f.request('?backtestId=bad', 'GET', undefined, 'read')).status).toBe(400); }); test('accepted experiment receipts replay with202/Location and compact missing children before template eligibility', async () => { const preview = retainedPreview(), submission = { ...input, previewHash: preview.previewHash }, key = 'accepted'; const hash = experimentHash({ version: 1, operation: 'create-experiment', submission }); for (const principal of ['operator', 'service'] as const) { const f = fixture('enabled', async (sql, values) => { if (sql.includes('submission_principal=$1')) { expect(values).toEqual([principal, key]); return { rows: [{ id: experimentId, submission_hash: hash }] }; } if (sql.includes('SELECT r.id')) { return { rows: [] }; } expect(sql).not.toContain('FROM backtests'); return { rows: [ { 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: { completed: 2 }, preview, }, ], }; }); const response = await f.request('', 'POST', JSON.stringify(submission), principal, key); 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 value = await response.json(); expect(value.experiment).toMatchObject({ id: experimentId, cancelRequested: true, trialCount: 2, counts: { completed: 0 }, }); expect(value.experiment.trials.map((t: { status: string }) => t.status)).toEqual([ 'missing', 'missing', ]); } }); test('receipt conflicts and unavailable templates are409, missing is404, unexpected storage/schema errors remain sanitized500', async () => { const conflict = fixture('enabled', async () => ({ rows: [{ id: experimentId, submission_hash: 'other' }], })); expect( ( await conflict.request( '', 'POST', JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }), 'operator', 'key' ) ).status ).toBe(409); const archived = fixture('enabled', async () => ({ rows: [{ id: backtestId, archived_at: '2026-10-24T00:00:00Z' }], })); expect( (await archived.request('/preview', 'POST', JSON.stringify(input), 'operator')).status ).toBe(409); const missing = fixture(); expect( (await missing.request('/preview', 'POST', JSON.stringify(input), 'operator')).status ).toBe(404); expect( (await missing.request(`/${experimentId}/cancel`, 'POST', '{}', 'operator')).status ).toBe(404); for (const error of [new Error('private database detail'), new z.ZodError([])]) { const f = fixture('enabled', async () => { throw error; }); for (const [path, method, body, key] of [ ['', 'GET', undefined, undefined], [`/${experimentId}`, 'GET', undefined, undefined], ['/preview', 'POST', JSON.stringify(input), undefined], ['', 'POST', JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }), 'key'], [`/${experimentId}/cancel`, 'POST', '{}', undefined], ]) { const response = await f.request(path, method, body, 'operator', key); expect(response.status).toBe(500); expect(await response.text()).not.toContain('private'); } } }); test('detail counts use child rows when statuses change after the earlier metadata query', async () => { const preview = retainedPreview(); const f = fixture('enabled', async sql => { if (sql.includes('SELECT r.id')) { return { rows: preview.candidates.map((candidate, index) => { const id = randomUUID(); return { id, backtest_id: backtestId, trial_index: index, trial_key: candidate.trialKey, status: index === 0 ? 'completed' : 'failed', progress: index === 0 ? 100 : 50, cancel_requested: false, attempt_number: 1, manual_retry_count: 0, error: index === 1 ? 'failure' : null, dataset_hash: preview.request.datasetHash, request_snapshot: experimentTrialRequest(preview, candidate, id), }; }), }; } return { rows: [ { id: experimentId, backtest_id: backtestId, name: input.name, created_at: '2026-10-24T00:00:00Z', cancel_requested: false, trial_count: 2, dataset_hash: preview.request.datasetHash, strategy_version_id: preview.request.strategy.versionId, preview_hash: preview.previewHash, counts: { pending: 2 }, preview, }, ], }; }); const response = await f.request(`/${experimentId}`, 'GET', undefined, 'read'); expect(response.status).toBe(200); const { experiment } = await response.json(); expect(experiment.counts).toEqual({ pending: 0, running: 0, paused: 0, completed: 1, failed: 1, cancelled: 0, }); expect(experiment.trials.map((trial: { status: string }) => trial.status)).toEqual([ 'completed', 'failed', ]); expect(experiment.trials.every((trial: { comparable: boolean }) => !trial.comparable)).toBe( true ); }); test('normalized duplicate parameter sets cannot create duplicate trial identity', () => { const preview = retainedPreview(); const descriptor = builtinCatalogDescriptors[1]!; const request = structuredClone(preview.request); request.strategy.package.program = descriptor.program; request.strategy.package.parameterSchema = descriptor.parameterSchema; request.strategy.selection = { ...request.strategy.selection, strategyId: 'mean_reversion', strategyVersion: 'mean-reversion-regime-long-only/v1', parameters: { lookbackPeriod: 2, trendPeriod: 3, momentumPeriod: 1, volatilityPeriod: 2, entryZScore: 1, exitZScore: 0.1, minTrendReturn: -0.5, minMomentumReturn: -0.5, maxVolatility: 1, minNotionalVolume: parseFinancialDecimal('0'), regimeFilter: 'none', }, }; expect(() => experimentCandidates({ ...input, grid: { minNotionalVolume: ['1', '1.0'] } }, request) ).toThrow('Duplicate normalized'); }); });