feat(research): prepare stored data by declared sessions (RP03)

This commit is contained in:
Boki 2026-10-27 01:07:45 -04:00
parent 302ba60e53
commit d2b78eacdf
10 changed files with 805 additions and 72 deletions

View file

@ -7,6 +7,7 @@ import type {
FinancialDecimal,
HistoricalDatasetInputV2,
HistoricalDatasetManifestV2,
HistoricalDatasetMetadataV2,
} from '@stock-bot/types';
import { parseFinancialDecimal } from '@stock-bot/types';
import { builtinStrategySelectionSchema } from './builtin-strategy';
@ -214,8 +215,23 @@ export interface CanonicalDatasetPreparation {
reason: string | null;
}
/** One materialized storage read; retention must use this input without requerying. */
/** Intersections only: declarations are supplied by the caller, never inferred from source bars. */
export function declaredStoredSourceWindows(metadata: HistoricalDatasetMetadataV2) {
const series = metadata.series[0];
const calendar = metadata.calendars.find(item => item.id === series?.calendarId);
return (calendar?.sessions ?? [])
.map(session => ({
date: session.date,
start: Math.max(session.open, metadata.bounds.warmupStart),
end: Math.min(session.close, metadata.bounds.tradeEnd),
}))
.filter(window => window.start < window.end)
.sort((left, right) => left.start - right.start);
}
/** Materialized source capture; retention must use this input without requerying. */
export interface CanonicalStoredSourcePreparation {
selection?: 'declared-sessions';
input: HistoricalDatasetInputV2;
preparation: CanonicalDatasetPreparation;
}

View file

@ -1,6 +1,9 @@
import { z } from 'zod';
import { parseHistoricalDatasetMetadataV2 } from '@stock-bot/research/datasets';
import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research';
import {
declaredStoredSourceWindows,
type CanonicalStoredSourcePreparation,
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetInputV2, HistoricalDatasetMetadataV2 } from '@stock-bot/types';
import {
HistoricalStorageError,
@ -16,7 +19,9 @@ export class StoredDatasetPreparationError extends Error {
super(message);
}
}
const bodySchema = z.object({ metadata: z.unknown() }).strict();
const bodySchema = z
.object({ metadata: z.unknown(), selection: z.literal('declared-sessions').optional() })
.strict();
function freeze<T>(value: T): T {
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
Object.values(value).forEach(freeze);
@ -24,10 +29,16 @@ function freeze<T>(value: T): T {
}
return value;
}
function metadataFromBody(body: unknown): HistoricalDatasetMetadataV2 {
function metadataFromBody(body: unknown): {
metadata: HistoricalDatasetMetadataV2;
selection?: 'declared-sessions';
} {
try {
const parsed = bodySchema.parse(body);
return freeze(parseHistoricalDatasetMetadataV2(parsed.metadata));
return {
metadata: freeze(parseHistoricalDatasetMetadataV2(parsed.metadata)),
...(parsed.selection ? { selection: parsed.selection } : {}),
};
} catch (error) {
const path = error instanceof z.ZodError ? error.issues[0]?.path.join('.') : undefined;
throw new StoredDatasetPreparationError(
@ -39,14 +50,14 @@ function metadataFromBody(body: unknown): HistoricalDatasetMetadataV2 {
}
}
/** Materialize one explicit stored EOD query. Captured bytes, not this mutable query, are retained. */
/** Capture the explicit range or declared session windows. Retention never repeats these reads. */
export async function prepareStoredDataset(
body: unknown,
storage: Pick<StorageService, 'getHistoricalBars'>,
signal: AbortSignal
): Promise<CanonicalStoredSourcePreparation> {
signal.throwIfAborted();
const metadata = metadataFromBody(body);
const { metadata, selection } = metadataFromBody(body);
const series = metadata.series[0];
if (
!series ||
@ -64,60 +75,79 @@ export async function prepareStoredDataset(
'Stored source supports one EOD raw 1m/5m/1h series with interval-start timestamps and declared interval-end-assumption availability'
);
}
let rows;
try {
rows = await storage.getHistoricalBars(
series.instrumentId,
new Date(metadata.bounds.warmupStart),
new Date(metadata.bounds.tradeEnd),
series.interval,
{ adjustment: 'raw', timestamp: 'utc-instant' },
signal,
'eod'
const windows =
selection === 'declared-sessions'
? declaredStoredSourceWindows(metadata)
: [{ start: metadata.bounds.warmupStart, end: metadata.bounds.tradeEnd }];
if (!windows.length) {
throw new StoredDatasetPreparationError(
422,
'No declared sessions intersect the requested bounds'
);
} catch (error) {
}
const captured: Array<
Omit<HistoricalDatasetInputV2['bars'][number], 'timestamp' | 'sourceSequence'> & {
timestamp: number;
}
> = [];
for (const window of windows) {
signal.throwIfAborted();
if (error instanceof HistoricalStorageError && error.code === 'missing-range') {
let rows;
try {
rows = await storage.getHistoricalBars(
series.instrumentId,
new Date(window.start),
new Date(window.end),
series.interval,
{ adjustment: 'raw', timestamp: 'utc-instant' },
signal,
'eod'
);
} catch (error) {
signal.throwIfAborted();
if (error instanceof HistoricalStorageError && error.code === 'missing-range') {
throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range');
}
if (error instanceof HistoricalStorageError && error.code === 'provider-unavailable') {
throw new StoredDatasetPreparationError(503, 'EOD historical storage is unavailable');
}
throw error;
}
signal.throwIfAborted();
if (!rows.length) {
throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range');
}
if (error instanceof HistoricalStorageError && error.code === 'provider-unavailable') {
throw new StoredDatasetPreparationError(503, 'EOD historical storage is unavailable');
}
throw error;
}
signal.throwIfAborted();
if (!rows.length) {
throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range');
}
for (const row of rows) {
if (
row.symbol !== series.instrumentId ||
row.source !== 'eod' ||
row.interpolated === true ||
!(row.timestamp instanceof Date) ||
!Number.isSafeInteger(row.timestamp.getTime()) ||
row.timestamp.getTime() < metadata.bounds.warmupStart ||
row.timestamp.getTime() >= metadata.bounds.tradeEnd
) {
throw new Error('Stored source returned inconsistent bar identity or range');
}
}
const input: HistoricalDatasetInputV2 = freeze({
metadata,
// Ordinal is deterministic adapter ordering, not a vendor publication sequence.
bars: [...rows]
.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime())
.map((row, sourceSequence) => ({
for (const row of rows) {
if (
row.symbol !== series.instrumentId ||
row.source !== 'eod' ||
row.interpolated === true ||
!(row.timestamp instanceof Date) ||
!Number.isSafeInteger(row.timestamp.getTime()) ||
row.timestamp.getTime() < window.start ||
row.timestamp.getTime() >= window.end
) {
throw new Error('Stored source returned inconsistent bar identity or range');
}
// Snapshot scalars now: a subsequent asynchronous read may reuse mutable adapter rows.
captured.push({
seriesId: series.id,
timestamp: row.timestamp.getTime(),
sourceSequence,
open: row.open,
high: row.high,
low: row.low,
close: row.close,
volume: row.volume,
...(row.vwap === undefined ? {} : { vwap: row.vwap }),
})),
});
}
}
const input: HistoricalDatasetInputV2 = freeze({
metadata,
// Ordinal is deterministic adapter ordering, not a vendor publication sequence.
bars: captured
.sort((a, b) => a.timestamp - b.timestamp)
.map((row, sourceSequence) => ({ ...row, sourceSequence })),
});
let preparation;
try {
@ -132,5 +162,5 @@ export async function prepareStoredDataset(
throw error;
}
signal.throwIfAborted();
return freeze({ input, preparation });
return freeze({ input, preparation, ...(selection ? { selection } : {}) });
}

View file

@ -2,7 +2,11 @@ import { useEffect, useRef, useState } from 'react';
import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
import { backtestApiV2, DatasetPreparationRequestError } from '../services/backtestApiV2';
import {
backtestApiV2,
DatasetPreparationRequestError,
storedSourceSessionScope,
} from '../services/backtestApiV2';
import { StoredSourceInspector } from './StoredSourceInspector';
export interface DatasetPreparationState {
@ -19,7 +23,7 @@ interface Retention {
input: unknown;
preview: CanonicalDatasetPreparation;
}
type InputMode = 'export' | 'stored-eod';
type InputMode = 'export' | 'stored-eod' | 'stored-eod-sessions';
const instant = (value: number) => new Date(value).toISOString();
export function DatasetPreparation({ disabled, begin, onStateChange, onRetained }: Props) {
const [mode, setMode] = useState<InputMode>('export');
@ -71,7 +75,7 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
};
const changeMode = (next: string) => {
if (
(next !== 'export' && next !== 'stored-eod') ||
(next !== 'export' && next !== 'stored-eod' && next !== 'stored-eod-sessions') ||
next === modeRef.current ||
disabled ||
captured.current ||
@ -147,8 +151,12 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
state(true, true);
try {
const result =
selectedMode === 'stored-eod'
? await backtestApiV2.previewStoredDataset(selectedSource.value, abort.signal)
selectedMode !== 'export'
? await backtestApiV2.previewStoredDataset(
selectedSource.value,
abort.signal,
selectedMode === 'stored-eod-sessions' ? 'declared-sessions' : undefined
)
: {
input: selectedSource.value,
preparation: await backtestApiV2.previewDataset(selectedSource.value, abort.signal),
@ -239,6 +247,8 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
}
}
};
const sessionWindows =
mode === 'stored-eod-sessions' && input ? storedSourceSessionScope(input.value) : null;
return (
<section aria-label="Source dataset preparation" className="space-y-3 text-sm">
<p>
@ -258,9 +268,10 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
>
<option value="export">Source export</option>
<option value="stored-eod">Stored EOD intraday bars</option>
<option value="stored-eod-sessions">Stored EOD — declared sessions only</option>
</select>
</label>
{mode === 'stored-eod' && (
{mode !== 'export' && (
<p>
Load one EOD instrument from existing storage using raw 1m, 5m or 1h interval-start bars.
Supply complete metadata with interval-end-assumption availability. Source sequence is a
@ -269,7 +280,7 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
uses that captured snapshot without querying storage again.
</p>
)}
{mode === 'stored-eod' && (
{mode !== 'export' && (
<StoredSourceInspector disabled={disabled || Boolean(intent) || Boolean(phase)} />
)}
<label className="block">
@ -292,6 +303,29 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
Selected {mode === 'export' ? 'export' : 'metadata'}: {input.filename}
</p>
)}
{mode === 'stored-eod-sessions' && (
<section aria-label="Declared session selection" className="space-y-2">
<p>
Reads only the declared calendar sessions intersecting warmup start through trading end.
Rows outside those explicit windows are not requested. Invalid or empty selected
sessions fail preparation; bars are never shortened to fit. This does not verify the
calendar or establish gap-free coverage.
</p>
{sessionWindows === null ? (
<p>Supply complete single-series metadata to view the declared UTC query windows.</p>
) : sessionWindows.length === 0 ? (
<p>No declared sessions intersect the requested bounds.</p>
) : (
<ul aria-label="Declared UTC query windows">
{sessionWindows.map(window => (
<li key={window.date}>
{window.date}: {instant(window.start)} — {instant(window.end)} (end exclusive)
</li>
))}
</ul>
)}
</section>
)}
{phase && (
<p role="status">
{phase === 'reading'
@ -353,10 +387,11 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
)}
{preview && (
<section aria-label="Prepared dataset metadata" className="space-y-2 break-words">
{mode === 'stored-eod' && (
{mode !== 'export' && (
<p>
Stored source: EOD · Query bounds (UTC, end exclusive):{' '}
{instant(preview.manifest.bounds.warmupStart)} —{' '}
Stored source: EOD ·{' '}
{mode === 'stored-eod-sessions' ? 'Declared sessions within bounds' : 'Query bounds'}{' '}
(UTC, end exclusive): {instant(preview.manifest.bounds.warmupStart)} —{' '}
{instant(preview.manifest.bounds.tradeEnd)}
</p>
)}

View file

@ -4,7 +4,10 @@ import {
preparationManifestSchema,
} from '@stock-bot/research/dataset-contracts';
import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution';
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
import {
canonicalRunRequestSchema,
declaredStoredSourceWindows,
} from '@stock-bot/stock-config/canonical-research';
import type {
CanonicalDatasetCatalogEntry,
CanonicalDatasetPreparation,
@ -218,14 +221,29 @@ function metadataIdentity(value: PreparationMetadata) {
.sort((a, b) => compareText(a.instrumentId, b.instrumentId)),
});
}
/** Preview caller declarations only; the server still validates the complete metadata and bars. */
export function storedSourceSessionScope(raw: unknown) {
const parsed = preparationMetadata.safeParse(raw);
return parsed.success && parsed.data.series.length === 1
? declaredStoredSourceWindows(parsed.data)
: null;
}
export function parseStoredDatasetPreparation(
raw: unknown,
suppliedMetadata: unknown
suppliedMetadata: unknown,
selection?: CanonicalStoredSourcePreparation['selection']
): CanonicalStoredSourcePreparation {
const envelope = z
.object({ input: storedSourceInput, preparation: z.unknown() })
.object({
input: storedSourceInput,
preparation: z.unknown(),
selection: z.literal('declared-sessions').optional(),
})
.strict()
.parse(raw);
if (envelope.selection !== selection) {
throw new Error('The stored source response does not match the requested selection.');
}
const preparation = parseDatasetPreparation(envelope.preparation);
const expected = preparationMetadata.parse(suppliedMetadata);
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
@ -268,7 +286,7 @@ export function parseStoredDatasetPreparation(
) {
throw new Error('The stored source response does not match its metadata and prepared dataset.');
}
return { input, preparation };
return { input, preparation, ...(selection ? { selection } : {}) };
}
export class DatasetPreparationRequestError extends Error {
constructor(
@ -317,12 +335,13 @@ export const backtestApiV2 = {
prepareDatasetRequest({ input, expectedHash }, signal),
async previewStoredDataset(
metadata: unknown,
signal?: AbortSignal
signal?: AbortSignal,
selection?: CanonicalStoredSourcePreparation['selection']
): Promise<CanonicalStoredSourcePreparation> {
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical/stored-source`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ metadata }),
body: JSON.stringify({ metadata, ...(selection ? { selection } : {}) }),
signal,
});
if (!response.ok) {
@ -332,7 +351,7 @@ export const backtestApiV2 = {
if (response.status !== 200) {
throw new Error('Unexpected stored source status');
}
return parseStoredDatasetPreparation(await response.json(), metadata);
return parseStoredDatasetPreparation(await response.json(), metadata, selection);
} catch {
throw new Error('The stored source response could not be verified.');
}