feat(research): download validated retained datasets (RP07)
This commit is contained in:
parent
43ea2cc9b6
commit
b959779ada
14 changed files with 1076 additions and 11 deletions
|
|
@ -734,6 +734,27 @@ describe('canonical research workbench', () => {
|
|||
expect(host.textContent).toContain('No fills');
|
||||
});
|
||||
|
||||
test('download uses the immutable result request hash and remains absent from fills-only view', async () => {
|
||||
const value = report();
|
||||
// The action must follow the retained request, without looking up an editable template.
|
||||
const originalHash = 'e'.repeat(64);
|
||||
value.request.datasetHash = originalHash;
|
||||
await mount(createElement(CanonicalResults, { result: value }));
|
||||
expect(requests).toHaveLength(0);
|
||||
await flush(() => click('Download retained dataset'));
|
||||
expect(requests).toHaveLength(1);
|
||||
const download = request(`/api/v2/datasets/canonical/${originalHash}/export`);
|
||||
expect(download.method).toBe('GET');
|
||||
await flush(() =>
|
||||
root!.render(createElement(CanonicalResults, { result: value, fillsOnly: true }))
|
||||
);
|
||||
expect(download.signal?.aborted).toBe(true);
|
||||
expect(host.textContent).not.toContain('Download retained dataset');
|
||||
expect(host.textContent).not.toContain('Downloading retained dataset');
|
||||
expect(host.textContent).toContain('0.12500000');
|
||||
expect(requests).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('explains a partial-session evaluation horizon alongside the unchanged retained CAGR', async () => {
|
||||
const value = report();
|
||||
value.financial.reporting.tradeStart = Date.parse('2024-10-01T14:30:00Z');
|
||||
|
|
|
|||
423
test/integration/dataset-download-ui.test.tsx
Normal file
423
test/integration/dataset-download-ui.test.tsx
Normal file
|
|
@ -0,0 +1,423 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement, type ReactElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import { createDatasetV2FromLegacy, validateDatasetV2 } from '@stock-bot/research/datasets';
|
||||
import type { CanonicalDatasetCatalogEntry } from '@stock-bot/stock-config/canonical-research';
|
||||
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'Event', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
const createUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'createObjectURL');
|
||||
const revokeUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'revokeObjectURL');
|
||||
const clickDescriptor = Object.getOwnPropertyDescriptor(
|
||||
browser.HTMLAnchorElement.prototype,
|
||||
'click'
|
||||
);
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let DatasetDownload: typeof import('../../apps/stock/web-app/src/features/backtest/components/DatasetDownload').DatasetDownload;
|
||||
let CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup;
|
||||
let backtestApiV2: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').backtestApiV2;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
const blobs: Blob[] = [];
|
||||
const revoked: string[] = [];
|
||||
const downloads: { href: string; filename: string; connected: boolean }[] = [];
|
||||
let clickFailure = false;
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (cause: Error) => void;
|
||||
const promise = new Promise<T>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
type Pending = ReturnType<typeof deferred<Response>> & { path: string; init?: RequestInit };
|
||||
const requests: Pending[] = [];
|
||||
const dataset = nativeReplayFixture().dataset;
|
||||
const hash = dataset.manifest.hash;
|
||||
const other = nativeReplayFixture(4).dataset;
|
||||
const exportPath = (identity: string) => `/api/v2/datasets/canonical/${identity}/export`;
|
||||
const entry = (value = dataset): CanonicalDatasetCatalogEntry => ({
|
||||
hash: value.manifest.hash,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
available: true,
|
||||
reason: null,
|
||||
manifest: value.manifest,
|
||||
});
|
||||
const definition: Backtest = {
|
||||
id: 'definition',
|
||||
name: 'Dataset download fixture',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: null,
|
||||
strategyParameters: {},
|
||||
symbols: ['X0.US'],
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: { canonical: {}, datasetHash: hash },
|
||||
archivedAt: null,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
};
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
async function mount(element: ReactElement = createElement(DatasetDownload, { hash })) {
|
||||
root = createRoot(host);
|
||||
await flush(() => root!.render(element));
|
||||
}
|
||||
function button(name = 'Download retained dataset') {
|
||||
const value = [...host.querySelectorAll('button')].find(el => el.textContent?.trim() === name);
|
||||
if (!value) {
|
||||
throw new Error(`Missing button ${name}: ${host.textContent}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function request(path = exportPath(hash)) {
|
||||
const value = requests.find(item => item.path === path);
|
||||
if (!value) {
|
||||
throw new Error(`Missing request ${path}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function json(text = JSON.stringify(dataset), status = 200, type = 'application/json') {
|
||||
return new Response(text, { status, headers: { 'Content-Type': type } });
|
||||
}
|
||||
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
Event: browser.Event,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
({ DatasetDownload } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/DatasetDownload'
|
||||
));
|
||||
({ CanonicalSetup } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup'
|
||||
));
|
||||
({ backtestApiV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = blobs.length = revoked.length = downloads.length = 0;
|
||||
clickFailure = false;
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => {
|
||||
const value = { ...deferred<Response>(), path: new URL(String(url)).pathname, init };
|
||||
requests.push(value);
|
||||
return value.promise; // Deliberately ignore abort to exercise the caller's late-response fences.
|
||||
}) as unknown as typeof browser.fetch;
|
||||
Object.defineProperty(URL, 'createObjectURL', {
|
||||
configurable: true,
|
||||
value: (blob: Blob) => {
|
||||
blobs.push(blob);
|
||||
return `blob:dataset-${blobs.length}`;
|
||||
},
|
||||
});
|
||||
Object.defineProperty(URL, 'revokeObjectURL', {
|
||||
configurable: true,
|
||||
value: (url: string) => revoked.push(url),
|
||||
});
|
||||
Object.defineProperty(browser.HTMLAnchorElement.prototype, 'click', {
|
||||
configurable: true,
|
||||
value: function (this: HTMLAnchorElement) {
|
||||
if (clickFailure) {
|
||||
throw new Error('Browser download failed');
|
||||
}
|
||||
downloads.push({ href: this.href, filename: this.download, connected: this.isConnected });
|
||||
},
|
||||
});
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
await tick();
|
||||
host.remove();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser.happyDOM.close();
|
||||
for (const [target, key, descriptor] of [
|
||||
[URL, 'createObjectURL', createUrlDescriptor],
|
||||
[URL, 'revokeObjectURL', revokeUrlDescriptor],
|
||||
[browser.HTMLAnchorElement.prototype, 'click', clickDescriptor],
|
||||
...keys.map(key => [globalThis, key, originals.get(key)] as const),
|
||||
] as const) {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(target, key, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(target, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('retained dataset download', () => {
|
||||
test('does no network or download work without an explicit click', async () => {
|
||||
await mount();
|
||||
expect(button().type).toBe('button');
|
||||
expect(button().disabled).toBe(false);
|
||||
expect(host.querySelector('[role="alert"]')).toBeNull();
|
||||
expect(requests).toHaveLength(0);
|
||||
expect(blobs).toHaveLength(0);
|
||||
expect(downloads).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('downloads exact received text with converted parent identity, delayed availability and null VWAP', async () => {
|
||||
const source = datasetInput();
|
||||
const converted = createDatasetV2FromLegacy(
|
||||
{
|
||||
metadata: {
|
||||
...source.metadata,
|
||||
series: source.metadata.series.map(series => ({ ...series, availability: 'explicit' })),
|
||||
},
|
||||
bars: source.bars.map((bar, index) => ({
|
||||
...bar,
|
||||
vwap: null,
|
||||
sourceSequence: index + 101,
|
||||
availableAt: source.metadata.calendars[0]!.sessions[index]!.close + 123,
|
||||
})),
|
||||
},
|
||||
'c'.repeat(64)
|
||||
);
|
||||
const bytes = ` \n${JSON.stringify(converted, null, 3)}\n `;
|
||||
let submits = 0;
|
||||
await mount(
|
||||
createElement(
|
||||
'form',
|
||||
{ onSubmit: () => submits++ },
|
||||
createElement(DatasetDownload, { hash: converted.manifest.hash })
|
||||
)
|
||||
);
|
||||
await flush(() => {
|
||||
button().click();
|
||||
button().click();
|
||||
});
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0]!.init?.credentials).toBe('include');
|
||||
expect(requests[0]!.init?.method ?? 'GET').toBe('GET');
|
||||
expect(requests[0]!.init?.body).toBeUndefined();
|
||||
expect(button().disabled).toBe(true);
|
||||
expect(host.querySelector('[role="status"]')?.textContent).toBe(
|
||||
'Downloading retained dataset...'
|
||||
);
|
||||
await flush(() =>
|
||||
request(exportPath(converted.manifest.hash)).resolve(
|
||||
json(bytes, 200, 'application/json; charset=UTF-8')
|
||||
)
|
||||
);
|
||||
expect(blobs).toHaveLength(1);
|
||||
expect(blobs[0]!.type.split(';')[0]).toBe('application/json');
|
||||
expect(await blobs[0]!.text()).toBe(bytes);
|
||||
expect(validateDatasetV2(JSON.parse(await blobs[0]!.text()))).toEqual(converted);
|
||||
expect(downloads).toEqual([
|
||||
{
|
||||
href: 'blob:dataset-1',
|
||||
filename: `dataset-${converted.manifest.hash}.json`,
|
||||
connected: true,
|
||||
},
|
||||
]);
|
||||
expect(browser.document.querySelector('a[download]')).toBeNull();
|
||||
expect(submits).toBe(0);
|
||||
expect(button().disabled).toBe(false);
|
||||
expect(host.querySelector('[role="status"]')).toBeNull();
|
||||
await tick();
|
||||
expect(revoked).toEqual(['blob:dataset-1']);
|
||||
});
|
||||
|
||||
for (const status of [400, 401, 403, 404, 409, 422, 500]) {
|
||||
test(`keeps HTTP ${status} errors on the page without a file or automatic retry`, async () => {
|
||||
await mount();
|
||||
await flush(() => button().click());
|
||||
await flush(() =>
|
||||
request().resolve(Response.json({ error: `Rejected (${status})` }, { status }))
|
||||
);
|
||||
expect(host.querySelector('[role="alert"]')?.textContent).toBe(`Rejected (${status})`);
|
||||
expect(button('Retry dataset download').disabled).toBe(false);
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(blobs).toHaveLength(0);
|
||||
expect(downloads).toHaveLength(0);
|
||||
});
|
||||
}
|
||||
|
||||
const invalidResponses = [
|
||||
['HTML body', () => json('<html>Login</html>')],
|
||||
['HTML type', () => json(JSON.stringify(dataset), 200, 'text/html')],
|
||||
['missing type', () => new Response(JSON.stringify(dataset), { headers: {} })],
|
||||
['unexpected accepted status', () => json(JSON.stringify(dataset), 202)],
|
||||
['partial status', () => json(JSON.stringify(dataset), 206)],
|
||||
['metadata envelope', () => json(JSON.stringify({ dataset: entry() }))],
|
||||
['extra envelope property', () => json(JSON.stringify({ ...dataset, unexpected: true }))],
|
||||
['wrong identity', () => json(JSON.stringify(other))],
|
||||
['missing bars', () => json(JSON.stringify({ manifest: dataset.manifest }))],
|
||||
['bars not an array', () => json(JSON.stringify({ ...dataset, bars: {} }))],
|
||||
['wrong count', () => json(JSON.stringify({ ...dataset, bars: [] }))],
|
||||
[
|
||||
'invalid manifest',
|
||||
() => json(JSON.stringify({ ...dataset, manifest: { ...dataset.manifest, bounds: null } })),
|
||||
],
|
||||
] as const;
|
||||
for (const [name, response] of invalidResponses) {
|
||||
test(`rejects ${name} before creating a download`, async () => {
|
||||
await mount();
|
||||
await flush(() => button().click());
|
||||
await flush(() => request().resolve(response()));
|
||||
expect(host.querySelector('[role="alert"]')?.textContent).toContain('could not be verified');
|
||||
expect(button('Retry dataset download').disabled).toBe(false);
|
||||
expect(blobs).toHaveLength(0);
|
||||
expect(downloads).toHaveLength(0);
|
||||
expect(requests).toHaveLength(1);
|
||||
});
|
||||
}
|
||||
|
||||
for (const failure of ['fetch', 'body'] as const) {
|
||||
test(`explicitly retries a lost ${failure} response with the same hash`, async () => {
|
||||
await mount();
|
||||
await flush(() => button().click());
|
||||
const body = deferred<string>();
|
||||
const response = json();
|
||||
Object.defineProperty(response, 'text', { value: () => body.promise });
|
||||
if (failure === 'fetch') {
|
||||
await flush(() => request().reject(new Error('Connection lost')));
|
||||
} else {
|
||||
await flush(() => request().resolve(response));
|
||||
await flush(() => body.reject(new Error('Body lost')));
|
||||
}
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(downloads).toHaveLength(0);
|
||||
await flush(() => button('Retry dataset download').click());
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(requests[1]!.path).toBe(exportPath(hash));
|
||||
expect(host.querySelector('[role="alert"]')).toBeNull();
|
||||
await flush(() => requests[1]!.resolve(json()));
|
||||
expect(downloads).toHaveLength(1);
|
||||
expect(button().disabled).toBe(false);
|
||||
});
|
||||
}
|
||||
|
||||
for (const change of ['hash', 'unmount'] as const) {
|
||||
for (const late of ['response', 'body'] as const) {
|
||||
test(`${change} fences a late ${late} even when transport ignores cancellation`, async () => {
|
||||
await mount();
|
||||
await flush(() => button().click());
|
||||
const old = request();
|
||||
const body = deferred<string>();
|
||||
const response = json();
|
||||
Object.defineProperty(response, 'text', { value: () => body.promise });
|
||||
if (late === 'body') {
|
||||
await flush(() => old.resolve(response));
|
||||
}
|
||||
await flush(() => {
|
||||
if (change === 'hash') {
|
||||
root!.render(createElement(DatasetDownload, { hash: other.manifest.hash }));
|
||||
} else {
|
||||
root!.unmount();
|
||||
root = undefined;
|
||||
}
|
||||
});
|
||||
expect(old.init?.signal?.aborted).toBe(true);
|
||||
await flush(() => {
|
||||
old.resolve(response);
|
||||
body.resolve(JSON.stringify(dataset));
|
||||
});
|
||||
expect(blobs).toHaveLength(0);
|
||||
expect(downloads).toHaveLength(0);
|
||||
expect(host.querySelector('[role="alert"]')).toBeNull();
|
||||
if (change === 'hash') {
|
||||
expect(button().disabled).toBe(false);
|
||||
await flush(() => button().click());
|
||||
await flush(() =>
|
||||
request(exportPath(other.manifest.hash)).resolve(json(JSON.stringify(other)))
|
||||
);
|
||||
expect(downloads[0]!.filename).toBe(`dataset-${other.manifest.hash}.json`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('releases the Blob URL and allows retry if the browser click fails', async () => {
|
||||
clickFailure = true;
|
||||
await mount();
|
||||
await flush(() => button().click());
|
||||
await flush(() => request().resolve(json()));
|
||||
expect(host.querySelector('[role="alert"]')?.textContent).toBe('Browser download failed');
|
||||
expect(button('Retry dataset download').disabled).toBe(false);
|
||||
expect(browser.document.querySelector('a[download]')).toBeNull();
|
||||
await tick();
|
||||
expect(revoked).toEqual(['blob:dataset-1']);
|
||||
});
|
||||
|
||||
test('invalid hashes and already cancelled requests never fetch', async () => {
|
||||
await expect(backtestApiV2.downloadCanonicalDataset('../invalid')).rejects.toThrow(
|
||||
'dataset hash'
|
||||
);
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(backtestApiV2.downloadCanonicalDataset(hash, controller.signal)).rejects.toThrow();
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('setup exposes only verified selection and cancels export when selection changes', async () => {
|
||||
const saves: unknown[] = [];
|
||||
await mount(
|
||||
createElement(CanonicalSetup, {
|
||||
backtest: definition,
|
||||
onSave: async value => {
|
||||
saves.push(value);
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(host.textContent).not.toContain('Download retained dataset');
|
||||
await flush(() =>
|
||||
request('/api/v2/datasets/canonical').resolve(
|
||||
Response.json({ datasets: [entry(), entry(other)] })
|
||||
)
|
||||
);
|
||||
expect(host.textContent).not.toContain('Download retained dataset');
|
||||
await flush(() =>
|
||||
request(`/api/v2/datasets/canonical/${hash}`).resolve(Response.json({ dataset: entry() }))
|
||||
);
|
||||
expect(button().disabled).toBe(false);
|
||||
await flush(() => button().click());
|
||||
const pending = request();
|
||||
const select = host.querySelector('[aria-label="Canonical dataset"]') as HTMLSelectElement;
|
||||
await flush(() => {
|
||||
select.value = other.manifest.hash;
|
||||
select.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
expect(host.textContent).not.toContain('Download retained dataset');
|
||||
expect(pending.init?.signal?.aborted).toBe(true);
|
||||
await flush(() => pending.resolve(json()));
|
||||
expect(downloads).toHaveLength(0);
|
||||
await flush(() =>
|
||||
request(`/api/v2/datasets/canonical/${other.manifest.hash}`).resolve(
|
||||
Response.json({ dataset: entry(other) })
|
||||
)
|
||||
);
|
||||
await flush(() => button().click());
|
||||
await flush(() =>
|
||||
request(exportPath(other.manifest.hash)).resolve(json(JSON.stringify(other)))
|
||||
);
|
||||
expect(downloads[0]!.filename).toBe(`dataset-${other.manifest.hash}.json`);
|
||||
expect(saves).toHaveLength(0);
|
||||
expect(requests.every(item => (item.init?.method ?? 'GET') === 'GET')).toBe(true);
|
||||
});
|
||||
});
|
||||
311
test/integration/dataset-export.test.ts
Normal file
311
test/integration/dataset-export.test.ts
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
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<unknown> = async () => baseline) {
|
||||
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: true, 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<string, string> = { Authorization: `Bearer ${tokens.admin}` },
|
||||
signal?: AbortSignal
|
||||
) => app.request(path(hash), { headers, signal });
|
||||
return { app, request, database, query, payloadRead, sourceRead, research };
|
||||
}
|
||||
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('existing read, admin, service and browser credentials may export; anonymous and real research credentials may 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]) {
|
||||
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;
|
||||
const denied = await f.request(baseline.manifest.hash, {
|
||||
Authorization: `Bearer ${tokens.research}`,
|
||||
});
|
||||
expect(denied.status).toBe(403);
|
||||
expect(denied.headers.get('Content-Disposition')).toBeNull();
|
||||
expect(f.payloadRead).toHaveBeenCalledTimes(before);
|
||||
// Positive control: this token is recognized by the real resolver for an allowed route.
|
||||
expect(
|
||||
await f.research.authenticate(
|
||||
new Request('http://localhost/api/v2/experiments', {
|
||||
headers: { Authorization: `Bearer ${tokens.research}` },
|
||||
})
|
||||
)
|
||||
).toEqual({ principal: agentId });
|
||||
expect(
|
||||
f.query.mock.calls.filter(call => call[0].includes('FROM research_agents'))
|
||||
).toHaveLength(2);
|
||||
expect(f.sourceRead).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue