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) =>