feat(research): download validated retained datasets (RP07)

This commit is contained in:
Boki 2026-10-27 10:59:19 -04:00
parent 43ea2cc9b6
commit b959779ada
14 changed files with 1076 additions and 11 deletions

View file

@ -3,7 +3,11 @@ import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { StorageService } from '../../../orchestrator/src/services/StorageService';
import { canonicalDatasetEntry } from '../services/canonical-research.service';
import {
canonicalDatasetEntry,
CanonicalDatasetReadError,
readCanonicalDataset,
} from '../services/canonical-research.service';
import { DatasetCatalogService } from '../services/dataset-catalog.service';
import {
DatasetPreparationError,
@ -156,6 +160,38 @@ export function createDatasetRoutes(container: IServiceContainer) {
return c.json({ error: 'Failed to list canonical datasets' }, 500);
}
});
app.get('/api/v2/datasets/canonical/:hash/export', async c => {
c.header('Cache-Control', 'no-store');
c.header('X-Content-Type-Options', 'nosniff');
try {
c.req.raw.signal.throwIfAborted();
const hash = c.req.param('hash');
const dataset = await readCanonicalDataset(database, hash, c.req.raw.signal);
c.req.raw.signal.throwIfAborted();
return Response.json(dataset, {
headers: {
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
'Content-Disposition': `attachment; filename="dataset-${hash}.json"`,
},
});
} catch (error) {
if (c.req.raw.signal.aborted) {
return Response.json(
{ error: 'Dataset export cancelled' },
{
status: 499,
headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
}
);
}
if (error instanceof CanonicalDatasetReadError) {
return c.json({ error: error.message }, error.status);
}
logger.error('Failed to export canonical dataset', error);
return c.json({ error: 'Failed to export canonical dataset' }, 500);
}
});
app.get('/api/v2/datasets/canonical/:hash', async c => {
try {
const hash = c.req.param('hash');

View file

@ -50,6 +50,16 @@ const invalid = (message: string): never => {
throw new HistoricalDataRequestError(message);
};
/** Read rejection statuses for exports; existing callers may still catch the base request error. */
export class CanonicalDatasetReadError extends HistoricalDataRequestError {
constructor(
readonly status: 400 | 404 | 409 | 422,
message: string
) {
super(message);
}
}
/** The existing workbench gate, shared by retained selection and source preview. */
export function canonicalDatasetUnavailableReason(dataset: HistoricalDatasetV2): string | null {
return datasetUnavailableReason(dataset.manifest);
@ -61,28 +71,31 @@ export function canonicalDatasetUnavailableReason(dataset: HistoricalDatasetV2):
*/
export async function readCanonicalDataset(
database: DatasetCatalogQuery,
hash: unknown
hash: unknown,
signal?: AbortSignal
): Promise<HistoricalDatasetV2> {
signal?.throwIfAborted();
if (typeof hash !== 'string' || !/^[a-f0-9]{64}$/.test(hash)) {
return invalid('Choose an explicitly retained v2 dataset');
throw new CanonicalDatasetReadError(400, 'Choose an explicitly retained v2 dataset');
}
const row = (await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [hash]))
.rows[0];
signal?.throwIfAborted();
if (!row) {
return invalid('Selected canonical dataset was not found');
throw new CanonicalDatasetReadError(404, 'Selected canonical dataset was not found');
}
let dataset;
try {
dataset = validateDatasetV2(row.payload);
} catch {
return invalid('Retained v2 dataset failed content validation');
throw new CanonicalDatasetReadError(409, 'Retained v2 dataset failed content validation');
}
if (dataset.manifest.hash !== hash) {
return invalid('Retained dataset identity mismatch');
throw new CanonicalDatasetReadError(409, 'Retained dataset identity mismatch');
}
const unavailable = canonicalDatasetUnavailableReason(dataset);
if (unavailable) {
return invalid(unavailable);
throw new CanonicalDatasetReadError(422, unavailable);
}
return dataset;
}

View file

@ -3,6 +3,7 @@ import { Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'rec
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import type { CanonicalMetrics } from '@stock-bot/types';
import { actionClass } from '@/features/strategies/components/StrategyParameterForm';
import { DatasetDownload } from './DatasetDownload';
const tableClass = 'w-full text-sm text-left border-collapse';
const cell = 'p-2 border-b border-border align-top';
@ -146,6 +147,7 @@ export function CanonicalResults({
</dd>
</div>
</dl>
<DatasetDownload hash={request.datasetHash} />
<details>
<summary className="cursor-pointer">Immutable configuration and reporting policy</summary>
<pre className="mt-2 text-xs overflow-auto max-h-96">

View file

@ -19,6 +19,7 @@ import {
type Backtest,
type CreateBacktestRequest,
} from '../services/backtestApiV2';
import { DatasetDownload } from './DatasetDownload';
import { DatasetPreparation, type DatasetPreparationState } from './DatasetPreparation';
type PolicyKey = Exclude<keyof CanonicalResearchSettings, 'version'>;
@ -693,6 +694,7 @@ export function CanonicalSetup({
</div>
</dl>
)}
{selectedFields && <DatasetDownload hash={hash} />}
<details className="space-y-3 rounded-md border border-border p-3">
<summary className="cursor-pointer font-medium">
Prepare dataset from source export

View file

@ -0,0 +1,80 @@
import { useEffect, useRef, useState } from 'react';
import { actionClass } from '@/features/strategies/components/StrategyParameterForm';
import { backtestApiV2 } from '../services/backtestApiV2';
/** Changing the dataset discards pending transport state before another download is possible. */
export function DatasetDownload({ hash }: { hash: string }) {
return <Download key={hash} hash={hash} />;
}
function Download({ hash }: { hash: string }) {
const alive = useRef(false);
const pending = useRef<AbortController | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
pending.current?.abort();
};
}, []);
const download = async () => {
if (!alive.current || pending.current) {
return;
}
const controller = new AbortController();
pending.current = controller;
setLoading(true);
setError('');
const current = () =>
alive.current && !controller.signal.aborted && pending.current === controller;
try {
const text = await backtestApiV2.downloadCanonicalDataset(hash, controller.signal);
if (!current()) {
return;
}
const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
const anchor = document.createElement('a');
try {
anchor.href = url;
anchor.download = `dataset-${hash}.json`;
document.body.append(anchor);
anchor.click();
} finally {
anchor.remove();
// Allow the browser to consume the click before releasing the URL, even after unmount.
setTimeout(() => URL.revokeObjectURL(url), 0);
}
} catch (cause) {
if (current()) {
setError(cause instanceof Error ? cause.message : 'Could not download retained dataset');
}
} finally {
if (current()) {
pending.current = null;
setLoading(false);
}
}
};
return (
<div className="space-y-2">
<button
type="button"
className={actionClass}
disabled={loading}
onClick={() => void download()}
>
{error ? 'Retry dataset download' : 'Download retained dataset'}
</button>
{loading && <p role="status">Downloading retained dataset...</p>}
{error && (
<p role="alert" className="text-error text-sm">
{error}
</p>
)}
</div>
);
}

View file

@ -354,6 +354,41 @@ async function prepareDatasetRequest(
}
export const backtestApiV2 = {
async downloadCanonicalDataset(hash: string, signal?: AbortSignal): Promise<string> {
if (!/^[a-f0-9]{64}$/.test(hash)) {
throw new Error('Enter a retained dataset hash of 64 lowercase hexadecimal characters.');
}
signal?.throwIfAborted();
const response = await fetch(
`${API_BASE_URL}/api/v2/datasets/canonical/${encodeURIComponent(hash)}/export`,
{ signal }
);
if (!response.ok) {
throw await requestError(response, 'Could not download retained dataset');
}
try {
if (
response.status !== 200 ||
response.headers.get('Content-Type')?.split(';')[0]?.trim().toLowerCase() !==
'application/json'
) {
throw new Error('Unexpected dataset download response');
}
const text = await response.text();
signal?.throwIfAborted();
const value = z
.object({ manifest: manifestSchema, bars: z.array(z.unknown()) })
.strict()
.parse(JSON.parse(text));
if (value.manifest.hash !== hash || value.manifest.barCount !== value.bars.length) {
throw new Error('Unexpected dataset download identity');
}
// Preserve the received representation. Full content/hash validation belongs to the server.
return text;
} catch {
throw new Error('The retained dataset download response could not be verified.');
}
},
previewDataset: (input: unknown, signal?: AbortSignal) =>
prepareDatasetRequest({ input }, signal),
retainDataset: (input: unknown, expectedHash: string, signal?: AbortSignal) =>

View file

@ -110,6 +110,51 @@ an unsaved settings draft does not change a run. Explicit discard, leaving this
backtest and reloading do not provide persistent draft recovery. Save settings and
resolve retention before leaving if you need to keep the work.
## Downloading a retained snapshot for local exploration
Choose **Download retained dataset** beneath a verified dataset in **Settings →
Canonical research setup**, or beside a saved canonical result's **Immutable configuration
and reporting policy**. The saved-result action uses that run's original dataset hash,
even if the editable backtest now selects another dataset. Downloading neither saves
settings nor starts a run.
The file is `dataset-<hash>.json`, containing the complete v2 `{manifest, bars}` snapshot.
The API validates retained content and identity before returning it; timestamps,
availability delays, source ordinals, null values and any parent hash are preserved.
This is identical dataset content, not a promise of original JSON formatting. The
manifest hash is the canonical dataset identity, not a checksum of downloaded file bytes.
Open the file in VS Code or a notebook, or give it to your local AI exploration tools.
For a quick TypeScript inspection with Bun:
```ts
const dataset = await Bun.file('/path/to/dataset-<hash>.json').json();
console.log(dataset.manifest);
console.table(dataset.bars.slice(0, 5));
```
Treat this as inspection of frozen observations, not validation of a trading hypothesis.
When testing features, respect each bar's `availableAt`; the file includes the entire
historical range, including observations unavailable to an earlier decision.
To retain the same file in another initialized research database, set
`RESEARCH_DATASET_DATABASE_URL` explicitly to that database and use the existing importer:
```sh
bun run scripts/import-research-dataset.ts --file '/path/to/dataset-<hash>.json'
```
The importer validates the full snapshot and repeats safely for an already retained hash.
This file is distinct from the source-input JSON accepted by **Prepare dataset from source
export**; use the importer for the complete retained snapshot.
Export supports the existing eligible single-asset canonical dataset selection. Missing,
corrupt and unsupported snapshots return an error instead of a file. A failed download
offers **Retry dataset download**; changing the selected hash cancels the pending action.
The endpoint is `GET /api/v2/datasets/canonical/:hash/export`, using existing read, operator,
service or browser-session access. Research-agent tokens remain unable to call dataset
routes; a user can supply the downloaded file to local tools explicitly.
## Verification
`bun run check` includes complete-range reads without row caps, acceptance beyond the

View file

@ -15,3 +15,5 @@ Ownership: backend agent owns `canonical-research.service.ts`, `datasets.routes.
Acceptance/tests: full downloaded JSON validates with identical manifest and every bar; converted parent, delayed availableAt, source ordinals and null VWAP survive. Invalid hashes avoid storage; missing/corrupt/mismatched/unsupported data never attach; internal errors are sanitized; cancellation fences delivery. Existing role access and research-token denial hold. Actual PostgreSQL export followed by the existing CLI import is idempotent, with unchanged unrelated tables. Real browser downloads from a selected dataset and an original run whose editable template now points elsewhere; file identity must match each source. Malformed/HTML/mismatched responses and delayed selection changes cannot create a download. No run/template/source writes from export.
Gates: focused API/UI/read tests, app/authored-test types, strict lint and production build; root full repository check, relevant disposable PostgreSQL tests and Chromium workbench. Document JSON inspection and existing CLI reimport; the file is a retained v2 snapshot, distinct from the source-input preparation uploader. Risk: exporting a mutable template's new dataset instead of original run input, or presenting a transport error as a data file. No broad research framework is needed.
Accepted October 27, 2026. Independent review accepted API, UI and root fixture changes; 66 focused tests / 591 assertions plus 25 independent probes passed. Root full repository check passed, including 1,316 integration and 150 Rust tests. Disposable PostgreSQL passed 14 tests / 183 assertions, including actual export-to-CLI repeated import with unchanged custody. Chromium passed all 21 scenarios / 721 assertions, downloading real files from selected data and original run provenance after the template changes. [Combined evidence](../../real-data-research.md) records exact checks and limitations; [usage](../../../backtest-datasets.md#downloading-a-retained-snapshot-for-local-exploration) covers local inspection and reimport. No financial semantics, access grants or deferred optimization changed.

View file

@ -133,3 +133,22 @@ Combined validation:
- Application and authored-test types, focused lint, formatting/diff checks and production frontend build passed. The browser used isolated PostgreSQL/Redis fixtures, removed after validation. No development dataset, research execution or paper/live state was changed.
Logs: `/tmp/stock-bot-rp05-root-check.log`, `/tmp/stock-bot-rp05-browser.log`, `/tmp/stock-bot-rp05-browser-focused.log`, `/tmp/stock-bot-rp05-root-test-types.log`, and `/tmp/stock-bot-rp06-baseline-regression.log`. Current manifest: 71 accepted scheduled tasks, seven deferred conditional tasks and four merged redirects, 82 IDs total. No conditional performance or monitoring work was activated.
## RP07 — Retained dataset export for local research
Owner continuation on October 27 authorized this follow-up; planning commit `43ea2cc9` records the frozen API/UI contract. Existing catalog endpoints returned descriptors without bars, forcing local exploration to reach into the database. The new `GET /api/v2/datasets/canonical/:hash/export` reuses `readCanonicalDataset` once to return the validated full v2 `{manifest,bars}` snapshot. It preserves canonical identity, converted parent hashes, timestamps, availability delays, source ordinals and null VWAP. JSON formatting and downloaded-file byte hashes are not dataset identity guarantees.
The loader's typed rejection extends its existing request-error base, preserving admission/catalog catches and messages. Invalid, missing, corrupt/mismatched and unsupported datasets return 400, 404, 409 and 422 respectively; unexpected errors are sanitized. Route-handled responses are no-store/nosniff, and only validated success receives an attachment filename. Cancellation fences delivery. Existing authentication is unchanged; tests use the real research-credential resolver to prove dataset routes remain unavailable to research-agent tokens.
A shared download action appears for a verified setup selection and full canonical results. Result downloads use the original immutable request hash, independently of the editable template. The browser checks the response envelope/identity, preserves the received text, supports retry, prevents duplicate clicks and fences pending bodies on hash change/unmount. Full content/hash validation stays on the server; there is no browser financial engine or new export format. [Usage](../backtest-datasets.md#downloading-a-retained-snapshot-for-local-exploration) covers VS Code/notebook inspection and the existing CLI importer.
Independent backend review accepted both implementation halves: 66 focused tests / 591 assertions and 25 additional transport/authentication probes passed. The reviewer also accepted root's PostgreSQL/browser fixtures; independent frontend review accepted the usage documentation. Implementer checks passed application/authored-test types, strict lint and production builds.
Root validation:
- `CARGO_BUILD_JOBS=2 bun run check`: passed — 134 tooling, 43 utility, 44 calculation, 1,316 integration and 150 Rust tests. Existing 14 conditional integration skips and 4 ignored Rust measurements remain. Build, types, contract checks, strict lint and secret audit passed.
- Disposable PostgreSQL: 14 tests / 183 assertions across dataset-source preparation, stored-source preparation and canonical research. The actual export performs one payload read; its received JSON validates, is imported through the real CLI twice, and leaves every fixture table unchanged. Unsupported/corrupt retained rows return no attachment.
- Root-authored browser/PostgreSQL test typecheck and formatting/diff checks passed.
- Chromium: all 21 workbench scenarios passed with 721 assertions. Actual downloaded files from a verified selection and a reopened native result validate in full. The latter's template is deliberately changed to a distinct retained dataset first; export still delivers the original run dataset and leaves the replacement settings, one run and one dispatch unchanged. The fills-only view exposes no download action.
Logs: `/tmp/stock-bot-rp07-root-check.log`, `/tmp/stock-bot-rp07-postgres.log`, `/tmp/stock-bot-rp07-browser.log`, `/tmp/stock-bot-rp07-root-test-types.log`, `/tmp/stock-bot-rp07-api-independent.log` and `/tmp/stock-bot-rp07-ui-independent.log`. Tests use disposable PostgreSQL/Redis fixtures; no development research runs or paper/live operations were performed. Export retains the existing eligible single-asset/single-series gate. Performance, monitoring and conditional replay extraction remain deferred.

View file

@ -1,4 +1,5 @@
import { createHash, randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { chromium, type Browser, type Request } from 'playwright';
import {
@ -33,10 +34,14 @@ import type {
} from '@stock-bot/stock-config/walk-forward';
import type {
HistoricalDatasetInputV2,
HistoricalDatasetV2,
ResearchArtifact,
ResearchFindingSource,
} from '@stock-bot/types';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import {
createDatasetV2,
validateDatasetV2,
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
@ -63,6 +68,32 @@ afterAll(async () => {
});
const fixture = (native = false) => createFixture(browser, native);
async function downloadDatasetInBrowser(
f: Awaited<ReturnType<typeof fixture>>,
expected: HistoricalDatasetV2
) {
const hash = expected.manifest.hash;
const responding = f.page.waitForResponse(response =>
response.url().endsWith(`/api/v2/datasets/canonical/${hash}/export`)
);
const downloading = f.page.waitForEvent('download');
await f.page.getByRole('button', { name: 'Download retained dataset', exact: true }).click();
const response = await responding;
expect(response.status()).toBe(200);
expect(response.headers()['cache-control']).toBe('no-store');
expect(response.headers()['content-disposition']).toBe(
`attachment; filename="dataset-${hash}.json"`
);
const download = await downloading;
expect(download.suggestedFilename()).toBe(`dataset-${hash}.json`);
expect(await download.failure()).toBeNull();
const path = await download.path();
if (!path) {
throw new Error('Expected a downloaded fixture file');
}
expect(validateDatasetV2(JSON.parse(readFileSync(path, 'utf8')))).toEqual(expected);
}
test('operator_provisions_bounded_agent_views_usage_and_revokes_without_corrupting_accepted_work_browser', async () => {
const f = await fixture(true);
try {
@ -1857,7 +1888,7 @@ test('canonical_native_smoke', async () => {
const f = await fixture(true);
try {
await f.login();
const { id } = await createCanonicalInBrowser(f, 'Actual Rust browser smoke');
const { id, dataset } = await createCanonicalInBrowser(f, 'Actual Rust browser smoke');
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
await f.page.getByLabel('Backtest name', { exact: true }).fill('Unsaved native research draft');
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
@ -1896,10 +1927,29 @@ test('canonical_native_smoke', async () => {
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, result.financial.projection.fills[0].side);
await visible(f.page, result.financial.projection.fills[0].price);
expect(
await f.page.getByRole('button', { name: 'Download retained dataset', exact: true }).count()
).toBe(0);
// The editable template moves to a different retained source; this run's
// export must still resolve its immutable original request hash.
const replacement = canonicalSmaFixture(['A'], { volume: 2000 }).dataset;
await retainResearchDataset(f.pool, replacement);
const template = await f.request(`/api/v2/backtests/${id}`);
await f.request(`/api/v2/backtests/${id}`, 'PUT', {
config: { ...template.config, datasetHash: replacement.manifest.hash },
});
await f.page.reload();
await visible(f.page, 'Completed');
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
await visible(f.page, result.request.datasetHash);
await downloadDatasetInBrowser(f, dataset);
expect((await f.request(`/api/v2/backtests/${id}`)).config.datasetHash).toBe(
replacement.manifest.hash
);
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(1);
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
1
);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
@ -2433,6 +2483,7 @@ test('canonical_dataset_browser_reuses_older_pages_and_known_hash_without_new_ru
() => choice.inputValue().then(value => value === known.manifest.hash),
'known hash selection'
);
await downloadDatasetInBrowser(f, known);
expect(await f.request(`/api/v2/backtests/${id}`)).toEqual(before);
await f.page.getByRole('button', { name: 'Load more canonical datasets', exact: true }).click();
await choice.locator(`option[value="${older.manifest.hash}"]`).waitFor({ state: 'attached' });

View file

@ -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');

View 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);
});
});

View 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();
});
});

View file

@ -230,6 +230,9 @@ describe.skipIf(!url)('source-export preparation with retained PostgreSQL custod
await expect(readCanonicalDataset(f.pool, prepared.hash)).rejects.toThrow(
prepared.reason ?? 'missing reason'
);
const exported = await f.routes.request(`/api/v2/datasets/canonical/${prepared.hash}/export`);
expect(exported.status).toBe(422);
expect(exported.headers.get('Content-Disposition')).toBeNull();
expect((await f.pool.query('SELECT count(*) AS n FROM runs')).rows).toEqual([{ n: '0' }]);
});
@ -255,16 +258,21 @@ describe.skipIf(!url)('source-export preparation with retained PostgreSQL custod
await expect(readCanonicalDataset(f.pool, dataset.manifest.hash)).rejects.toThrow(
'content validation'
);
const exported = await f.routes.request(
`/api/v2/datasets/canonical/${dataset.manifest.hash}/export`
);
expect(exported.status).toBe(409);
expect(exported.headers.get('Content-Disposition')).toBeNull();
expect(await f.snapshot()).toEqual(before);
});
test('existing --file CLI retains the same v2 identity and safely repeats against the web-prepared row', async () => {
test('validated export feeds the existing --file CLI with identical retained identity and no custody writes', async () => {
const f = await fixture(),
input = datasetInput(),
dataset = createDatasetV2(input);
const directory = await mkdtemp(join(tmpdir(), 'source-preparation-cli-'));
cleanup.push(() => rm(directory, { recursive: true, force: true }));
const file = join(directory, 'dataset.json');
await writeFile(file, JSON.stringify(dataset));
const connection = new URL(url ?? '');
connection.searchParams.set('options', `-c search_path=${f.schema}`);
const execute = async (args: string[]) => {
@ -288,6 +296,22 @@ describe.skipIf(!url)('source-export preparation with retained PostgreSQL custod
200
);
const before = await f.snapshot();
const reads = f.queryCount;
const exported = await f.routes.request(
`/api/v2/datasets/canonical/${dataset.manifest.hash}/export`
);
expect(exported.status).toBe(200);
expect(exported.headers.get('Content-Type')).toContain('application/json');
expect(exported.headers.get('Cache-Control')).toBe('no-store');
expect(exported.headers.get('X-Content-Type-Options')).toBe('nosniff');
expect(exported.headers.get('Content-Disposition')).toBe(
`attachment; filename="dataset-${dataset.manifest.hash}.json"`
);
const exportedText = await exported.text();
expect(validateDatasetV2(JSON.parse(exportedText))).toEqual(dataset);
expect(f.queryCount).toBe(reads + 1);
expect(await f.snapshot()).toEqual(before);
await writeFile(file, exportedText);
const cli = await execute(['--file', file]);
expect(cli.code).toBe(0);
expect(JSON.parse(cli.out)).toEqual({
@ -296,6 +320,7 @@ describe.skipIf(!url)('source-export preparation with retained PostgreSQL custod
eligibility: dataset.manifest.eligibility,
limitations: dataset.manifest.limitations,
});
expect((await execute(['--file', file])).code).toBe(0);
expect(await f.snapshot()).toEqual(before);
const flags = await execute(['--source-hash', dataset.manifest.hash]);
expect(flags.code).toBe(1);