import { describe, expect, mock, test } from 'bun:test'; import { Hono } from 'hono'; import { createHttpSecurity } from '@stock-bot/di'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { createDatasetV2, createDatasetV2FromLegacy, validateDatasetV2, } from '@stock-bot/research/datasets'; import type { IServiceContainer } from '@stock-bot/services'; import { HistoricalDataRequestError } from '@stock-bot/types'; import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; import { canonicalDatasetEntry, CanonicalDatasetReadError, readCanonicalDataset, } from '../../apps/stock/web-api/src/services/canonical-research.service'; import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service'; import { datasetInput } from '../fixtures/historical-v2/dataset'; import { nativeReplayFixture } from '../fixtures/native-replay'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('dataset-export-test'); const tokens = { admin: 'dataset-export-admin-fixture-not-a-secret', service: 'dataset-export-service-fixture-not-a-secret', read: 'dataset-export-read-fixture-not-a-secret', research: 'sb-research.dataset-export-fixture', }; const agentId = 'agent:00000000-0000-4000-8000-000000000001'; const payloadSql = 'SELECT payload FROM backtest_datasets WHERE hash=$1'; const baseline = createDatasetV2(datasetInput()); const path = (hash = baseline.manifest.hash) => `/api/v2/datasets/canonical/${hash}/export`; function fixture(load: () => Promise = async () => baseline) { let researchEnabled = true; const payloadRead = mock(load); const query = mock(async (sql: string, values?: unknown[]) => { if (sql === 'SELECT id,enabled,policy FROM research_agents WHERE token_hash=$1') { return { rows: [{ id: agentId, enabled: researchEnabled, policy: { allowedProjectIds: [] } }], }; } if (sql !== payloadSql || values?.length !== 1) { throw new Error('Unexpected query: export must not write or read other tables'); } const payload = await payloadRead(); return { rows: payload === undefined ? [] : [{ payload: structuredClone(payload) }] }; }); const sourceRead = mock(async () => { throw new Error('Export must not read source storage'); }); const database = { query }; const container = { logger, postgres: database, mongodb: { find: sourceRead, aggregate: sourceRead }, questdb: { query: sourceRead }, } as unknown as IServiceContainer; const research = new ResearchAgentsService(container); const app = new Hono(); createHttpSecurity({ adminToken: tokens.admin, serviceToken: tokens.service, readToken: tokens.read, environment: 'test', browserSessions: true, resolveResearchCredential: request => research.authenticate(request), }).mount(app); app.route('/', createDatasetRoutes(container)); const request = ( hash = baseline.manifest.hash, headers: Record = { Authorization: `Bearer ${tokens.admin}` }, signal?: AbortSignal ) => app.request(path(hash), { headers, signal }); return { app, request, database, query, payloadRead, sourceRead, research, revokeResearch: () => { researchEnabled = false; }, }; } function responseHeaders(response: Response) { expect(response.headers.get('Cache-Control')).toBe('no-store'); expect(response.headers.get('X-Content-Type-Options')).toBe('nosniff'); expect(response.headers.get('Content-Type')).toContain('application/json'); } function converted() { const source = datasetInput(); return createDatasetV2FromLegacy( { metadata: { ...source.metadata, series: source.metadata.series.map(series => ({ ...series, availability: 'explicit' })), }, bars: source.bars.map((bar, index) => ({ ...bar, sourceSequence: 7 + index * 101, availableAt: source.metadata.calendars[0]!.sessions[index]!.close + 30000, vwap: null, })), }, 'a'.repeat(64) ); } describe('validated canonical dataset export', () => { test('exports the full unchanged v2 object through one validated payload read, without source or database writes', async () => { for (const dataset of [baseline, converted()]) { const before = structuredClone(dataset); const f = fixture(async () => dataset); const response = await f.request(dataset.manifest.hash); expect(response.status).toBe(200); responseHeaders(response); expect(response.headers.get('Content-Disposition')).toBe( `attachment; filename="dataset-${dataset.manifest.hash}.json"` ); const downloaded = await response.json(); expect(Object.keys(downloaded).sort()).toEqual(['bars', 'manifest']); expect(downloaded).toEqual(dataset); expect(validateDatasetV2(downloaded)).toEqual(dataset); expect(dataset).toEqual(before); expect(f.query.mock.calls).toEqual([[payloadSql, [dataset.manifest.hash]]]); expect(f.payloadRead).toHaveBeenCalledTimes(1); expect(f.sourceRead).not.toHaveBeenCalled(); } const legacy = converted(); expect(legacy.manifest.parentDatasetHash).toBe('a'.repeat(64)); expect(legacy.bars.map(bar => bar.sourceSequence)).toEqual([7, 108, 209]); expect( legacy.bars.every(bar => bar.availableAt === bar.intervalEnd + 30000 && bar.vwap === null) ).toBe(true); }); test('invalid hashes never query storage and retain their existing base error and message', async () => { const f = fixture(); for (const hash of ['not-a-hash', 'A'.repeat(64), '1'.repeat(63)]) { const response = await f.request(hash); expect(response.status).toBe(400); responseHeaders(response); expect(response.headers.get('Content-Disposition')).toBeNull(); expect(await response.json()).toEqual({ error: 'Choose an explicitly retained v2 dataset' }); } expect(f.query).not.toHaveBeenCalled(); const failure = await readCanonicalDataset(f.database, null).catch(error => error); expect(failure).toBeInstanceOf(CanonicalDatasetReadError); expect(failure).toBeInstanceOf(HistoricalDataRequestError); expect(failure.status).toBe(400); expect(f.query).not.toHaveBeenCalled(); }); test('missing, corrupt, mismatched and unsupported snapshots never become attachments', async () => { const corrupt = structuredClone(baseline); Object.assign(corrupt.bars[0]!, { volume: corrupt.bars[0]!.volume + 1 }); const source = datasetInput(); const exploratory = createDatasetV2({ ...source, metadata: { ...source.metadata, universe: { ...source.metadata.universe, selection: 'unknown', asOf: null }, }, }); const multiAsset = nativeReplayFixture(3, 2).dataset; const cases = [ { payload: undefined, hash: baseline.manifest.hash, status: 404, message: 'Selected canonical dataset was not found', }, { payload: { manifest: {}, bars: [] }, hash: baseline.manifest.hash, status: 409, message: 'Retained v2 dataset failed content validation', }, { payload: corrupt, hash: baseline.manifest.hash, status: 409, message: 'Retained v2 dataset failed content validation', }, { payload: baseline, hash: 'b'.repeat(64), status: 409, message: 'Retained dataset identity mismatch', }, { payload: exploratory, hash: exploratory.manifest.hash, status: 422, message: 'Canonical research requires an eligible dataset with known timing and action coverage', }, { payload: multiAsset, hash: multiAsset.manifest.hash, status: 422, message: 'Canonical workbench currently supports one execution asset and one retained series', }, ]; for (const item of cases) { const f = fixture(async () => item.payload); const response = await f.request(item.hash); expect(response.status).toBe(item.status); responseHeaders(response); expect(response.headers.get('Content-Disposition')).toBeNull(); expect(await response.json()).toEqual({ error: item.message }); expect(f.query.mock.calls).toEqual([[payloadSql, [item.hash]]]); expect(f.sourceRead).not.toHaveBeenCalled(); const failure = await readCanonicalDataset(f.database, item.hash).catch(error => error); expect(failure).toBeInstanceOf(CanonicalDatasetReadError); expect(failure).toBeInstanceOf(HistoricalDataRequestError); expect(failure.status).toBe(item.status); expect(failure.message).toBe(item.message); // Existing descriptor callers still catch the base type and expose unavailable data. expect( await canonicalDatasetEntry(f.database, { hash: item.hash, created_at: new Date('2026-01-01T00:00:00Z'), }) ).toMatchObject({ hash: item.hash, available: false, manifest: null, reason: item.message }); } }); test('unexpected storage failures are sanitized and cannot leave attachment headers', async () => { const f = fixture(async () => { throw new Error('private transport credentials and detail'); }); const response = await f.request(); expect(response.status).toBe(500); responseHeaders(response); expect(response.headers.get('Content-Disposition')).toBeNull(); expect(await response.json()).toEqual({ error: 'Failed to export canonical dataset' }); expect(f.payloadRead).toHaveBeenCalledTimes(1); expect(f.sourceRead).not.toHaveBeenCalled(); }); test('cancellation before or during the only payload read prevents delivery and validation of returned data', async () => { const early = new AbortController(); early.abort(); const f = fixture(); const earlyResponse = await f.request(baseline.manifest.hash, undefined, early.signal); expect(earlyResponse.status).toBe(499); responseHeaders(earlyResponse); expect(earlyResponse.headers.get('Content-Disposition')).toBeNull(); expect(f.query).not.toHaveBeenCalled(); await expect( readCanonicalDataset(f.database, baseline.manifest.hash, early.signal) ).rejects.toThrow(); expect(f.query).not.toHaveBeenCalled(); const late = new AbortController(); const delayed = fixture(async () => { late.abort(); return { malformed: 'must not validate this after cancellation' }; }); const lateResponse = await delayed.request(baseline.manifest.hash, undefined, late.signal); expect(lateResponse.status).toBe(499); responseHeaders(lateResponse); expect(lateResponse.headers.get('Content-Disposition')).toBeNull(); expect(await lateResponse.json()).toEqual({ error: 'Dataset export cancelled' }); expect(delayed.payloadRead).toHaveBeenCalledTimes(1); const direct = new AbortController(); await expect( readCanonicalDataset( { query: async () => { direct.abort(new Error('cancelled after query')); return { rows: [{ payload: {} }] }; }, }, baseline.manifest.hash, direct.signal ) ).rejects.toThrow('cancelled after query'); }); test('read, admin, service, browser and research credentials export; anonymous and revoked credentials do not', async () => { const f = fixture(); expect((await f.request(baseline.manifest.hash, {})).status).toBe(401); expect(f.query).not.toHaveBeenCalled(); for (const token of [tokens.read, tokens.admin, tokens.service, tokens.research]) { expect( (await f.request(baseline.manifest.hash, { Authorization: `Bearer ${token}` })).status ).toBe(200); } for (const token of [tokens.read, tokens.admin]) { const login = await f.app.request('/api/auth/session', { method: 'POST', headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), }); expect(login.status).toBe(200); const cookie = login.headers.get('Set-Cookie')?.split(';')[0]; expect(cookie).toBeDefined(); expect((await f.request(baseline.manifest.hash, { Cookie: cookie! })).status).toBe(200); } const before = f.payloadRead.mock.calls.length; f.revokeResearch(); const denied = await f.request(baseline.manifest.hash, { Authorization: `Bearer ${tokens.research}`, }); expect(denied.status).toBe(401); expect(denied.headers.get('Content-Disposition')).toBeNull(); expect(f.payloadRead).toHaveBeenCalledTimes(before); expect( f.query.mock.calls.filter(call => call[0].includes('FROM research_agents')) ).toHaveLength(2); expect(f.sourceRead).not.toHaveBeenCalled(); }); });