feat(research): prepare and retain explicit source datasets in the web workbench
This commit is contained in:
parent
06039d17ba
commit
366bee810b
21 changed files with 2677 additions and 76 deletions
|
|
@ -18,6 +18,10 @@ import { createPipelineRoutes } from './pipeline.routes';
|
|||
import { createResearchRoutes } from './research.routes';
|
||||
import { createStrategyRoutes } from './strategies.routes';
|
||||
|
||||
// Source exports carry complete datasets. Keep the web transport from imposing
|
||||
// the old 1 MiB restriction; normalizers still validate every submitted record.
|
||||
export const WEB_API_MAX_REQUEST_BODY_SIZE = Number.MAX_SAFE_INTEGER;
|
||||
|
||||
export function createRoutes(
|
||||
container: IServiceContainer,
|
||||
security: HttpSecurity = createHttpSecurity({ ...httpSecurityOptions(), browserSessions: true })
|
||||
|
|
|
|||
|
|
@ -4,6 +4,11 @@ import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
|||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { canonicalDatasetEntry } from '../services/canonical-research.service';
|
||||
import { DatasetCatalogService } from '../services/dataset-catalog.service';
|
||||
import {
|
||||
DatasetPreparationError,
|
||||
previewDatasetPreparation,
|
||||
retainDatasetPreparation,
|
||||
} from '../services/dataset-preparation.service';
|
||||
|
||||
const logger = getLogger('dataset-catalog-routes');
|
||||
|
||||
|
|
@ -11,6 +16,39 @@ export function createDatasetRoutes(container: IServiceContainer) {
|
|||
const app = new Hono();
|
||||
const catalog = new DatasetCatalogService(requireServices(container, 'postgres').postgres);
|
||||
const database = requireServices(container, 'postgres').postgres;
|
||||
const readBody = async (request: Request): Promise<unknown> => {
|
||||
try {
|
||||
return await request.json();
|
||||
} catch {
|
||||
throw new DatasetPreparationError(400, 'Invalid JSON request');
|
||||
}
|
||||
};
|
||||
app.post('/api/v2/datasets/canonical/preview', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
try {
|
||||
return c.json({ preparation: previewDatasetPreparation(await readBody(c.req.raw)) });
|
||||
} catch (error) {
|
||||
if (error instanceof DatasetPreparationError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
logger.error('Failed to preview source dataset', error);
|
||||
return c.json({ error: 'Source dataset preparation unavailable' }, 500);
|
||||
}
|
||||
});
|
||||
app.post('/api/v2/datasets/canonical/retain', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
try {
|
||||
return c.json({
|
||||
preparation: await retainDatasetPreparation(database, await readBody(c.req.raw)),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof DatasetPreparationError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
logger.error('Failed to retain source dataset', error);
|
||||
return c.json({ error: 'Source dataset retention unavailable' }, 500);
|
||||
}
|
||||
});
|
||||
app.get('/api/v2/datasets/canonical', async c => {
|
||||
try {
|
||||
const limit = c.req.query('limit') ?? '50';
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di';
|
|||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { initializeStockConfig } from '@stock-bot/stock-config';
|
||||
import { createRoutes } from './routes/create-routes';
|
||||
import { createRoutes, WEB_API_MAX_REQUEST_BODY_SIZE } from './routes/create-routes';
|
||||
import { createWebSocketRoute, handleWebSocketConnection } from './routes/websocket.routes';
|
||||
import { BacktestDispatcher } from './services/BacktestDispatcher';
|
||||
import { getWebSocketHandler, type RunSocketData } from './websocket/run-updates';
|
||||
|
|
@ -91,7 +91,7 @@ export async function startServerWithWebSocket() {
|
|||
server = Bun.serve<RunSocketData, {}>({
|
||||
port,
|
||||
hostname: security.hostname,
|
||||
maxRequestBodySize: 1_048_576,
|
||||
maxRequestBodySize: WEB_API_MAX_REQUEST_BODY_SIZE,
|
||||
|
||||
// Handle HTTP requests
|
||||
async fetch(req, server) {
|
||||
|
|
|
|||
|
|
@ -34,6 +34,21 @@ const invalid = (message: string): never => {
|
|||
throw new HistoricalDataRequestError(message);
|
||||
};
|
||||
|
||||
/** The existing workbench gate, shared by retained selection and source preview. */
|
||||
export function canonicalDatasetUnavailableReason(dataset: HistoricalDatasetV2): string | null {
|
||||
if (dataset.manifest.eligibility !== 'eligible') {
|
||||
return 'Canonical research requires an eligible dataset with known timing and action coverage';
|
||||
}
|
||||
if (
|
||||
dataset.manifest.executionSeries.length !== 1 ||
|
||||
dataset.manifest.series.length !== 1 ||
|
||||
dataset.manifest.universe.instrumentIds.length !== 1
|
||||
) {
|
||||
return 'Canonical workbench currently supports one execution asset and one retained series';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function readCanonicalDataset(
|
||||
database: DatasetCatalogQuery,
|
||||
hash: unknown
|
||||
|
|
@ -55,19 +70,9 @@ export async function readCanonicalDataset(
|
|||
if (dataset.manifest.hash !== hash) {
|
||||
return invalid('Retained dataset identity mismatch');
|
||||
}
|
||||
if (dataset.manifest.eligibility !== 'eligible') {
|
||||
return invalid(
|
||||
'Canonical research requires an eligible dataset with known timing and action coverage'
|
||||
);
|
||||
}
|
||||
if (
|
||||
dataset.manifest.executionSeries.length !== 1 ||
|
||||
dataset.manifest.series.length !== 1 ||
|
||||
dataset.manifest.universe.instrumentIds.length !== 1
|
||||
) {
|
||||
return invalid(
|
||||
'Canonical workbench currently supports one execution asset and one retained series'
|
||||
);
|
||||
const unavailable = canonicalDatasetUnavailableReason(dataset);
|
||||
if (unavailable) {
|
||||
return invalid(unavailable);
|
||||
}
|
||||
return dataset;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,89 @@
|
|||
import { z } from 'zod';
|
||||
import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canonical-research';
|
||||
import type { HistoricalDatasetInputV2, HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import { createDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
|
||||
import {
|
||||
retainResearchDataset,
|
||||
type RetainedDatasetStore,
|
||||
} from '../../../orchestrator/src/data/retained-research-dataset';
|
||||
import { canonicalDatasetUnavailableReason } from './canonical-research.service';
|
||||
|
||||
export class DatasetPreparationError extends Error {
|
||||
constructor(
|
||||
readonly status: 400 | 409,
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const previewBody = z.object({ input: z.unknown() }).strict();
|
||||
const retainBody = previewBody
|
||||
.extend({ expectedHash: z.string().regex(/^[a-f0-9]{64}$/) })
|
||||
.strict();
|
||||
|
||||
function normalize(input: unknown): HistoricalDatasetV2 {
|
||||
try {
|
||||
// createDatasetV2 performs the complete strict runtime parse; no metadata is inferred here.
|
||||
return createDatasetV2(input as HistoricalDatasetInputV2);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
const issue = error.issues[0];
|
||||
throw new DatasetPreparationError(
|
||||
400,
|
||||
`Invalid source dataset at ${issue?.path.join('.') || 'input'} (${issue?.code ?? 'invalid'})`
|
||||
);
|
||||
}
|
||||
// The normalizer's ordinary Error messages describe invariant failures without source values.
|
||||
// Platform errors (for example an invalid Intl time zone) may contain submitted values.
|
||||
throw new DatasetPreparationError(
|
||||
400,
|
||||
error instanceof Error && error.constructor === Error
|
||||
? `Invalid source dataset: ${error.message}`
|
||||
: 'Source dataset requires valid complete v2 metadata and bars'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function describe(dataset: HistoricalDatasetV2): CanonicalDatasetPreparation {
|
||||
const reason = canonicalDatasetUnavailableReason(dataset);
|
||||
return {
|
||||
version: 'canonical-dataset-preparation/v1',
|
||||
hash: dataset.manifest.hash,
|
||||
manifest: dataset.manifest,
|
||||
available: reason === null,
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
/** Pure preview: declared source evidence is normalized, never fetched or independently certified. */
|
||||
export function previewDatasetPreparation(body: unknown): CanonicalDatasetPreparation {
|
||||
const parsed = previewBody.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
throw new DatasetPreparationError(400, 'Expected a source dataset input');
|
||||
}
|
||||
return describe(normalize(parsed.data.input));
|
||||
}
|
||||
|
||||
export async function retainDatasetPreparation(
|
||||
database: RetainedDatasetStore,
|
||||
body: unknown
|
||||
): Promise<CanonicalDatasetPreparation> {
|
||||
const parsed = retainBody.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
throw new DatasetPreparationError(
|
||||
400,
|
||||
'Expected a source dataset input and lowercase SHA256 expectedHash'
|
||||
);
|
||||
}
|
||||
const dataset = normalize(parsed.data.input);
|
||||
if (dataset.manifest.hash !== parsed.data.expectedHash) {
|
||||
throw new DatasetPreparationError(
|
||||
409,
|
||||
'Source dataset differs from the preview; preview it again'
|
||||
);
|
||||
}
|
||||
// Keep storage failures separate from malformed input, including conflicting corrupt retained rows.
|
||||
await retainResearchDataset(database, dataset);
|
||||
return describe(dataset);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue