feat(research): prepare and retain explicit source datasets in the web workbench

This commit is contained in:
Boki 2026-10-24 15:06:52 -04:00
parent 06039d17ba
commit 366bee810b
21 changed files with 2677 additions and 76 deletions

View file

@ -175,6 +175,15 @@ export interface CanonicalDatasetCatalogEntry {
reason: string | null;
}
/** Normalized source export; availability describes current workbench support. */
export interface CanonicalDatasetPreparation {
version: 'canonical-dataset-preparation/v1';
hash: string;
manifest: HistoricalDatasetManifestV2;
available: boolean;
reason: string | null;
}
/** Validate the authoritative financial envelope without legacy metric conversion. */
export function parseCanonicalFinancialResult(input: unknown, request: CanonicalRunRequest) {
return parseReplayReportValue(

View file

@ -0,0 +1,23 @@
import { validateDatasetV2 } from './historical-dataset-v2';
export interface RetainedDatasetStore {
query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
}
/** Content-addressed custody shared by explicit CLI import and web source preparation. */
export async function retainResearchDataset(database: RetainedDatasetStore, input: unknown) {
const dataset = validateDatasetV2(input);
await database.query(
'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING',
[dataset.manifest.hash, JSON.stringify(dataset)]
);
const stored = (
await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
dataset.manifest.hash,
])
).rows[0];
if (!stored || validateDatasetV2(stored.payload).manifest.hash !== dataset.manifest.hash) {
throw new Error('Retained dataset content does not match the imported identity');
}
return dataset.manifest;
}

View file

@ -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 })

View file

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

View file

@ -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) {

View file

@ -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;
}

View file

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

View file

@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import {
canonicalResearchSettingsSchema,
type CanonicalDatasetCatalogEntry,
@ -19,6 +19,7 @@ import {
type Backtest,
type CreateBacktestRequest,
} from '../services/backtestApiV2';
import { DatasetPreparation, type DatasetPreparationState } from './DatasetPreparation';
type PolicyKey = Exclude<keyof CanonicalResearchSettings, 'version'>;
const policyFields: {
@ -280,6 +281,17 @@ export function CanonicalSetup({
const [error, setError] = useState<string | null>(null);
const [dirty, setDirty] = useState(false);
const authoritative = useRef(backtest);
const currentBacktest = useRef(backtest);
currentBacktest.current = backtest;
const preparationRef = useRef<DatasetPreparationState>({ busy: false, blocking: false });
const [preparation, setPreparation] = useState(preparationRef.current);
const preparationChanged = useCallback((value: DatasetPreparationState) => {
preparationRef.current = value;
setPreparation(value);
if (value.blocking) {
setDirty(true);
}
}, []);
const pending = useRef(false);
const active = useRef(true);
useUnsavedWarning(dirty);
@ -309,6 +321,8 @@ export function CanonicalSetup({
});
setStrategyValid(false);
setEpoch(value => value + 1);
preparationRef.current = { busy: false, blocking: false };
setPreparation(preparationRef.current);
setDirty(false);
setError(null);
}, [backtest]);
@ -387,7 +401,15 @@ export function CanonicalSetup({
);
const save = async (event: React.FormEvent) => {
event.preventDefault();
if (locked || pending.current || !valid || !selectedFields || !parsed.settings) {
if (
locked ||
pending.current ||
preparationRef.current.busy ||
preparationRef.current.blocking ||
!valid ||
!selectedFields ||
!parsed.settings
) {
return;
}
pending.current = true;
@ -543,6 +565,32 @@ export function CanonicalSetup({
</div>
</dl>
)}
<details className="space-y-3 rounded-md border border-border p-3">
<summary className="cursor-pointer font-medium">
Prepare dataset from source export
</summary>
<DatasetPreparation
key={`${backtest.id}:${epoch}`}
disabled={locked}
begin={() =>
!disabled &&
!pending.current &&
active.current &&
currentBacktest.current === backtest
}
onStateChange={preparationChanged}
onRetained={(retainedHash, available) => {
if (!active.current || currentBacktest.current !== backtest) {
return;
}
if (available) {
setHash(retainedHash);
}
setRetry(value => value + 1);
setDirty(true);
}}
/>
</details>
<StrategySelection
key={epoch}
allowArchivedSelection
@ -588,16 +636,28 @@ export function CanonicalSetup({
{error}
</p>
)}
<button type="submit" className={actionClass} disabled={locked || !valid}>
{preparation.blocking && (
<p role="status">
Retain an available dataset or clear source preparation before saving this setup.
</p>
)}
<button
type="submit"
className={actionClass}
disabled={locked || preparation.busy || preparation.blocking || !valid}
>
{saving ? 'Saving canonical setup...' : 'Save canonical setup'}
</button>{' '}
{onClose && (
<button
type="button"
className={actionClass}
disabled={saving}
disabled={saving || preparation.busy}
onClick={() => {
if (confirmDiscard(dirty)) {
if (pending.current || preparationRef.current.busy) {
return;
}
if (confirmDiscard(dirty || preparationRef.current.blocking)) {
onClose();
}
}}

View file

@ -0,0 +1,373 @@
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';
export interface DatasetPreparationState {
busy: boolean;
blocking: boolean;
}
interface Props {
disabled: boolean;
begin: () => boolean;
onStateChange: (state: DatasetPreparationState) => void;
onRetained: (hash: string, available: boolean) => void;
}
interface Retention {
input: unknown;
preview: CanonicalDatasetPreparation;
}
const instant = (value: number) => new Date(value).toISOString();
export function DatasetPreparation({ disabled, begin, onStateChange, onRetained }: Props) {
const [input, setInput] = useState<{ value: unknown; filename: string } | null>(null);
const [preview, setPreview] = useState<CanonicalDatasetPreparation | null>(null);
const [retained, setRetained] = useState(false),
[error, setError] = useState(''),
[phase, setPhase] = useState<'reading' | 'previewing' | 'retaining' | null>(null);
const [intent, setIntent] = useState<Retention | null>(null);
const source = useRef<{ value: unknown; filename: string } | null>(null);
const prepared = useRef<Retention | null>(null);
const generation = useRef(0),
active = useRef(false),
pending = useRef(false),
captured = useRef<Retention | null>(null),
controller = useRef<AbortController | null>(null),
fileInput = useRef<HTMLInputElement>(null);
const callbacks = useRef({ begin, onStateChange, onRetained });
callbacks.current = { begin, onStateChange, onRetained };
useEffect(() => {
active.current = true;
return () => {
active.current = false;
generation.current++;
controller.current?.abort();
callbacks.current.onStateChange({ busy: false, blocking: false });
};
}, []);
const state = (busy: boolean, blocking: boolean) =>
callbacks.current.onStateChange({ busy, blocking });
const reset = () => {
generation.current++;
controller.current?.abort();
pending.current = false;
captured.current = null;
source.current = null;
prepared.current = null;
setIntent(null);
setInput(null);
setPreview(null);
setRetained(false);
setPhase(null);
setError('');
if (fileInput.current) {
fileInput.current.value = '';
}
state(false, false);
};
const loadFile = async (file: File | undefined) => {
if (disabled || captured.current || !callbacks.current.begin()) {
return;
}
generation.current++;
const revision = generation.current;
controller.current?.abort();
pending.current = true;
prepared.current = null;
source.current = null;
setPreview(null);
setRetained(false);
setInput(null);
setError('');
if (!file) {
reset();
return;
}
setPhase('reading');
state(true, true);
try {
const value: unknown = JSON.parse(await file.text());
if (active.current && revision === generation.current) {
source.current = { value, filename: file.name };
setInput(source.current);
}
} catch (cause) {
if (active.current && revision === generation.current) {
setError(
`Could not read source JSON: ${cause instanceof Error ? cause.message : 'Invalid file'}`
);
}
} finally {
if (active.current && revision === generation.current) {
pending.current = false;
setPhase(null);
state(false, true);
}
}
};
const inspect = async () => {
const selectedSource = source.current;
if (
disabled ||
pending.current ||
captured.current ||
!selectedSource ||
!callbacks.current.begin()
) {
return;
}
pending.current = true;
const revision = ++generation.current;
const abort = new AbortController();
controller.current = abort;
prepared.current = null;
setPhase('previewing');
setPreview(null);
setError('');
setRetained(false);
state(true, true);
try {
const result = await backtestApiV2.previewDataset(selectedSource.value, abort.signal);
if (active.current && revision === generation.current) {
prepared.current = { input: selectedSource.value, preview: result };
setPreview(result);
}
} catch (cause) {
if (active.current && revision === generation.current) {
setError(cause instanceof Error ? cause.message : 'Could not preview dataset');
}
} finally {
if (active.current && revision === generation.current) {
pending.current = false;
setPhase(null);
state(false, true);
}
}
};
const retain = async () => {
if (
disabled ||
pending.current ||
(!captured.current && !prepared.current) ||
!callbacks.current.begin()
) {
return;
}
const target =
captured.current ?? (prepared.current ? structuredClone(prepared.current) : null);
if (!target) {
return;
}
captured.current = target;
setIntent(target);
pending.current = true;
const revision = ++generation.current,
abort = new AbortController();
controller.current = abort;
setPhase('retaining');
setError('');
state(true, true);
const reportRetained = callbacks.current.onRetained;
let accepted = false;
try {
const result = await backtestApiV2.retainDataset(
target.input,
target.preview.hash,
abort.signal
);
if (canonicalStrategyJson(result) !== canonicalStrategyJson(target.preview)) {
throw new Error('Retained dataset descriptor differs from its captured preview.');
}
if (active.current && revision === generation.current) {
accepted = result.available;
prepared.current = null;
setRetained(true);
setPreview(result);
captured.current = null;
setIntent(null);
reportRetained(result.hash, result.available);
}
} catch (cause) {
if (active.current && revision === generation.current) {
if (
cause instanceof DatasetPreparationRequestError &&
(cause.status === 400 || cause.status === 409)
) {
captured.current = null;
prepared.current = null;
setIntent(null);
setPreview(null);
setError(`${cause.message} Preview again or choose a corrected source export.`);
} else {
setError(
`${cause instanceof Error ? cause.message : 'Dataset retention response was lost'} Retry the exact same input and hash; retention may already have succeeded.`
);
}
}
} finally {
if (active.current && revision === generation.current) {
pending.current = false;
setPhase(null);
state(false, !accepted);
}
}
};
return (
<section aria-label="Source dataset preparation" className="space-y-3 text-sm">
<p>
Supply a complete source export with metadata and bars. Sessions, source revisions,
universe, corporate actions and publication availability must be explicit. Declared
provenance is not independent provider certification. Preview writes nothing; retention does
not save settings or start a run.
</p>
<label className="block">
Source dataset JSON
<input
ref={fileInput}
className={fieldClass}
type="file"
accept="application/json,.json"
aria-label="Source dataset JSON"
disabled={disabled || Boolean(intent)}
onChange={event => void loadFile(event.target.files?.[0])}
/>
</label>
{!input && !phase && !error && <p>No source export selected.</p>}
{input && <p>Selected export: {input.filename}</p>}
{phase && (
<p role="status">
{phase === 'reading'
? 'Reading source JSON...'
: phase === 'previewing'
? 'Previewing dataset...'
: 'Retaining dataset...'}
</p>
)}
<div className="flex flex-wrap gap-2">
<button
type="button"
className={actionClass}
disabled={disabled || Boolean(phase) || Boolean(intent) || !input}
onClick={() => void inspect()}
>
Preview dataset
</button>
<button
type="button"
className={actionClass}
disabled={disabled || Boolean(phase) || retained || (!preview && !intent)}
onClick={() => void retain()}
>
{intent ? 'Retry retaining same dataset' : 'Retain dataset'}
</button>
<button
type="button"
className={actionClass}
disabled={disabled || phase === 'retaining'}
onClick={() => {
if (disabled || (pending.current && captured.current) || !callbacks.current.begin()) {
return;
}
if (
!captured.current ||
window.confirm(
'This dataset may already be retained. Clear this preparation and discard its exact retry input and hash?'
)
) {
reset();
}
}}
>
Clear source preparation
</button>
</div>
{error && <p role="alert">{error}</p>}
{intent && !phase && (
<p>Retention is unconfirmed. The exact original input and hash are preserved for retry.</p>
)}
{retained && (
<p role="status">
Dataset retained.{' '}
{preview?.available
? 'The canonical selection will be verified before settings can be saved.'
: 'This data cannot be chosen for canonical execution. The existing selection is unchanged; clear preparation to continue editing.'}
</p>
)}
{preview && (
<section aria-label="Prepared dataset metadata" className="space-y-2 break-words">
<p className="break-all">Dataset hash: {preview.hash}</p>
<p>
{preview.manifest.barCount} bars · Eligibility: {preview.manifest.eligibility} ·{' '}
{preview.available
? 'Available for single-asset canonical setup'
: 'Unavailable for canonical setup'}
</p>
{preview.reason && <p>{preview.reason}</p>}
<p>Warmup start (UTC): {instant(preview.manifest.bounds.warmupStart)}</p>
<p>
Trading bounds (UTC, end exclusive): {instant(preview.manifest.bounds.tradeStart)} —{' '}
{instant(preview.manifest.bounds.tradeEnd)}
</p>
{preview.manifest.series.map(series => (
<div key={series.id} className="space-y-1">
<p>
{series.instrumentId} / {series.interval} · Series: {series.id} · Adjustment:{' '}
{series.adjustment}
</p>
<p>
Timestamp: {series.timestamp} · Availability: {series.availability}
</p>
<p>
Source: {series.source.provider} · Revision: {series.source.revision}
</p>
{series.availability === 'interval-end-assumption' && (
<p>
Availability is explicitly assumed at interval end; actual publication delay is
not verified.
</p>
)}
</div>
))}
{preview.manifest.calendars.map(calendar => (
<p key={calendar.id}>
Calendar: {calendar.id} · Source: {calendar.source} · Revision: {calendar.revision} ·
Time zone: {calendar.timeZone} · Sessions: {calendar.sessions.length} · Coverage:{' '}
{calendar.startDate} — {calendar.endDate}
</p>
))}
<p>
Universe: {preview.manifest.universe.selection} · As of:{' '}
{preview.manifest.universe.asOf === null
? 'Unknown'
: instant(preview.manifest.universe.asOf)}{' '}
· Revision: {preview.manifest.universe.revision} · Instruments:{' '}
{preview.manifest.universe.instrumentIds.join(', ')}
</p>
{preview.manifest.corporateActions.map(coverage => (
<div key={coverage.instrumentId}>
<p>
Corporate actions: {coverage.instrumentId} · {coverage.status} · Revision:{' '}
{coverage.revision} · Coverage: {instant(coverage.start)} — {instant(coverage.end)}{' '}
· Actions: {coverage.actions.length}
</p>
{coverage.actions.map((action, index) => (
<p key={index}>
{action.kind} · {instant(action.effectiveAt)} · {action.reference}
</p>
))}
</div>
))}
{preview.manifest.limitations.map((limitation, index) => (
<p key={index}>{limitation}</p>
))}
<details>
<summary className="cursor-pointer">Exact prepared manifest</summary>
<pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">
{JSON.stringify(preview.manifest, null, 2)}
</pre>
</details>
</section>
)}
</section>
);
}

View file

@ -1,6 +1,8 @@
import { z } from 'zod';
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
import type {
CanonicalDatasetCatalogEntry,
CanonicalDatasetPreparation,
CanonicalReproductionComparison,
CanonicalReproductionPreview,
CanonicalRunCapability,
@ -105,7 +107,204 @@ const nullableText = (value: unknown) => value === null || typeof value === 'str
const hashOrNull = (value: unknown) =>
value === null || (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value));
const preparationText = z.string().min(1);
const preparationHash = z.string().regex(/^[a-f0-9]{64}$/);
const preparationInstant = z.number().int().nonnegative().max(8_640_000_000_000_000);
const preparationDay = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.refine(
value =>
Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value
);
const preparationManifest = z
.object({
version: z.literal(2),
hash: preparationHash,
normalizationRevision: z.literal('historical-normalization-v2'),
parentDatasetHash: z.null(),
volumePolicy: z.literal('reported'),
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
intradayPolicy: z.literal('full-duration-session-contained'),
eligibility: z.enum(['eligible', 'exploratory', 'ineligible']),
limitations: z.array(preparationText),
barCount: z.number().int().positive().safe(),
calendars: z
.array(
z
.object({
id: preparationText,
venue: preparationText,
timeZone: preparationText,
source: preparationText,
revision: preparationText,
startDate: preparationDay,
endDate: preparationDay,
sessions: z
.array(
z
.object({
date: preparationDay,
open: preparationInstant,
close: preparationInstant,
})
.strict()
.refine(value => value.open < value.close)
)
.min(1),
})
.strict()
)
.min(1),
series: z
.array(
z
.object({
id: preparationText,
instrumentId: preparationText,
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
calendarId: preparationText,
venue: preparationText,
source: z.object({ provider: preparationText, revision: preparationText }).strict(),
timestamp: z.enum(['session-date', 'interval-start', 'interval-end']),
availability: z.enum(['explicit', 'interval-end-assumption']),
adjustment: z.enum(['raw', 'provider-adjusted']),
})
.strict()
)
.min(1),
executionSeries: z
.array(z.object({ instrumentId: preparationText, seriesId: preparationText }).strict())
.min(1),
bounds: z
.object({
warmupStart: preparationInstant,
tradeStart: preparationInstant,
tradeEnd: preparationInstant,
})
.strict()
.refine(value => value.warmupStart <= value.tradeStart && value.tradeStart < value.tradeEnd),
universe: z
.object({
selection: z.enum(['point-in-time', 'current-constituents', 'unknown']),
asOf: preparationInstant.nullable(),
revision: preparationText,
instrumentIds: z.array(preparationText).min(1),
})
.strict(),
corporateActions: z
.array(
z
.object({
instrumentId: preparationText,
status: z.enum(['unknown', 'action-free', 'known-actions']),
start: preparationInstant,
end: preparationInstant,
revision: preparationText,
actions: z.array(
z
.object({
effectiveAt: preparationInstant,
kind: z.enum(['split', 'dividend', 'other']),
reference: preparationText,
})
.strict()
),
})
.strict()
)
.min(1),
})
.strict();
const datasetPreparationSchema = z
.object({
version: z.literal('canonical-dataset-preparation/v1'),
hash: preparationHash,
manifest: preparationManifest,
available: z.boolean(),
reason: preparationText.nullable(),
})
.strict();
export function parseDatasetPreparation(
raw: unknown,
expectedHash?: string
): CanonicalDatasetPreparation {
const value = datasetPreparationSchema.parse(raw),
manifest = value.manifest;
const available =
manifest.eligibility === 'eligible' &&
manifest.executionSeries.length === 1 &&
manifest.series.length === 1 &&
manifest.universe.instrumentIds.length === 1;
if (
value.hash !== manifest.hash ||
(expectedHash !== undefined && value.hash !== expectedHash) ||
value.available !== available ||
(value.available ? value.reason !== null : value.reason === null) ||
new Set(manifest.series.map(item => item.id)).size !== manifest.series.length ||
new Set(manifest.calendars.map(item => item.id)).size !== manifest.calendars.length ||
manifest.series.some(
item =>
!manifest.calendars.some(
calendar => calendar.id === item.calendarId && calendar.venue === item.venue
)
) ||
manifest.executionSeries.some(
item =>
!manifest.series.some(
series => series.id === item.seriesId && series.instrumentId === item.instrumentId
)
)
) {
throw new Error('The dataset preparation response could not be verified.');
}
return value;
}
export class DatasetPreparationRequestError extends Error {
constructor(
message: string,
public readonly status: number
) {
super(message);
this.name = 'DatasetPreparationRequestError';
}
}
async function prepareDatasetRequest(
body: { input: unknown; expectedHash?: string },
signal?: AbortSignal
): Promise<CanonicalDatasetPreparation> {
const operation = body.expectedHash === undefined ? 'preview' : 'retain';
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical/${operation}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal,
});
if (!response.ok) {
throw new DatasetPreparationRequestError(
(await requestError(response, `Could not ${operation} dataset`)).message,
response.status
);
}
try {
if (response.status !== 200) {
throw new Error('Unexpected dataset preparation status');
}
const envelope = z
.object({ preparation: z.unknown() })
.strict()
.parse(await response.json());
return parseDatasetPreparation(envelope.preparation, body.expectedHash);
} catch {
throw new Error('The dataset preparation response could not be verified.');
}
}
export const backtestApiV2 = {
previewDataset: (input: unknown, signal?: AbortSignal) =>
prepareDatasetRequest({ input }, signal),
retainDataset: (input: unknown, expectedHash: string, signal?: AbortSignal) =>
prepareDatasetRequest({ input, expectedHash }, signal),
async reproductionPreview(
id: string,
signal?: AbortSignal

View file

@ -1,8 +1,8 @@
# Revised development roadmap
**First thirty-three waves committed; R09 research source citations are validated and ready to commit.** R07 functional comparison is committed as `46a4f13`; **36 of 45 scheduled tasks are fully committed (80% by count)**, with R09 in review. R05 remains partial, and R07 retains its paused table measurement.
**First thirty-four waves committed; R05 explicit source-export preparation is validated and ready to commit.** R09 is committed as `06039d1`; **37 of 45 scheduled tasks are fully committed (82% by count)**. Full R05 remains partial, and R07 retains its paused table measurement.
Authorization update: the owner requested “commit and continue”. R07 functional comparison was committed as `46a4f13`; supported R09 evidence citations are now independently reviewed and validated. Performance work remains paused. No new-wave commit, push, PR, candidate execution or trading/default activation occurred.
Authorization update: the owner requested “commit and continue”. R09 citations were committed as `06039d1`; the R05 explicit source-export preparation slice is now independently reviewed and validated. Performance work remains paused. No new-wave commit, push, PR, candidate execution or trading/default activation occurred.
## Strategy and review outcome
@ -697,3 +697,17 @@ All final gates passed: **1024 integration /150 Rust** tests, plus 93 tooling, 4
Independent review accepted backend/frontend overlays and root contracts/browser/compatibility changes. Thirty source/test/config/SQL file hashes, exact archive, native identities and logs are recorded in `manifest.json` → `thirty_fourth_wave_validation`, under `/tmp/stock-bot-wave34.02YVEd/`. Archive SHA256: `7df43baf277dc28d7ee186aee233ad13c134b20e0bd86a7300688acb6e0fd8af`. The unchanged release engine was restored before final database/browser gates. Both exact disposable containers were stopped; development services were untouched.
R09 is in review pending acceptance/commit. R05 provider preparation/default cutover, R07 paused measurement, pending architecture approvals and candidate/AI/multiasset/paper/live activation gates remain unchanged. No performance measurements, new-wave commit, push or PR occurred.
## Thirty-fifth-wave handoff — 2026-10-24
R09 was accepted and committed as `06039d1`. R05's explicit source-export preparation slice is independently reviewed and validated; new changes are uncommitted. Full R05 remains partial for durable provider-query preparation/first-run binding and broader default cutover. Current stores do not prove publication times, retained calendars, universe selection or action coverage; none is inferred.
- **Web preparation:** Supply a complete JSON source export (`metadata` and `bars`) inside canonical setup. Preview the normalized hash, exact manifest, UTC bounds, source/calendar/universe/action declarations and availability assumptions without writes. Explicit retention then selects an eligible hash through the existing picker; settings and execution still require separate actions. Existing strategy/policy edits survive. Missing or unsupported evidence remains visible and unavailable for execution.
- **One custody path:** The existing strict normalizer owns content identity and eligibility. A small extracted helper shares immutable insert/readback verification with the unchanged offline import API/CLI, and one extracted existing workbench gate keeps selection/preview consistent. Recomputed hash drift rejects before storage; identical retries/concurrent requests converge on one immutable row. Corrupt retained content fails without overwrite. No new migration, scheduler, simulator or financial semantics.
- **Response and transport behavior:** Captured input/hash survives uncertain retention; definitive 400/409 allows repair. Same-event actions, late reads, changed parent drafts and unmount are fenced. Strict response shape prevents unknown fields being silently discarded. The web server's former 1 MiB restriction is removed with the same explicit setting used by browser fixtures; generic service limits remain unchanged. A real >1 MiB JSON request verifies transport/normalization without claiming unlimited size or measured throughput.
Final validation passed: **1077 integration /150 Rust** tests, plus 93 tooling, 43 utility and 44 calculation cases; build, types, contracts, lint and secret audit. Release **PostgreSQL/Redis: 240 tests /2157 assertions**; **Chromium: 16 workflows /590 assertions**. All affected/new tests passed strict types, and all 16 changed source/test files passed scoped lint/format, hash/DAG and whitespace checks. Four preexisting manual Rust cases remain ignored. The native browser uploads source data, proves zero preview writes and no retention-created jobs, retries the same hash, saves explicit settings, checks the existing hand-calculated fills/fees/equity and reopens saved findings/results. Initial browser failures were selectors, corrected without application changes.
Independent review accepted all eleven agent-owned files plus root contract/transport/browser composition. Review fixed synchronous retry-state clearing, non-strict manifest response parsing and definitive-rejection handling. Exact 16-file archive SHA256 `029dd93e14ee7a9fa72f7b06118c708ce1ecad6711fa6d0411bc0fe2e0ada7fa`, file hashes, reviewer evidence and logs are recorded in `manifest.json` → `thirty_fifth_wave_validation`, under `/tmp/stock-bot-wave35.fQycky/`. The unchanged release engine was restored before final database/browser gates. Both exact disposable containers were stopped; development services were untouched.
Source metadata is supplied evidence, not independently certified provider truth. V1 conversion and automatic provider preparation remain outside this slice. R07 performance measurement and other performance work remain paused; default/multiasset/candidate/AI/paper/live gates are unchanged. No new-wave commit, push or PR occurred.

View file

@ -1,6 +1,6 @@
# Canonical development backlog
**First thirty-three waves committed; R09 research source citations are validated and ready to commit.** R07 functional comparison is committed as `46a4f13`; **36 of 45 scheduled tasks are fully committed (80% by count)**, with R09 in review. R05 remains partial, and R07 retains its paused table measurement.
**First thirty-four waves committed; R05 explicit source-export preparation is validated and ready to commit.** R09 is committed as `06039d1`; **37 of 45 scheduled tasks are fully committed (82% by count)**. Full R05 remains partial, and R07 retains its paused table measurement.
## One source of truth
@ -80,7 +80,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / done | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M |
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (functional committed; measurement paused) | R06, ADR-006 | W04 | Full-stack research product / M |
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / done | R06, ADR-006 | — | Quantitative research integrity / M |
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / review (validated, uncommitted) | R08, committed R07 functional component, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M |
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / done | R08, committed R07 functional component, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M |
| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / done | R01, ADR-006 | — | Full-stack research product / M |
| [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / done | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M |
| [R12 Reproduce an original run separately from rerunning current settings](tasks/R12.md) | P1 / done | Accepted R05 retained-input component; W04/R01/R10/F08/S02/D01/W03/C06, ADR-006 | — | Full-stack reproducible research / S |

View file

@ -1,14 +1,14 @@
{
"schema_version": 1,
"plan_revision": "2026-10-24.71",
"plan_revision": "2026-10-24.72",
"repository_base": "b7aeca4",
"plan_status": "thirty_fourth_wave_validated_awaiting_commit",
"plan_status": "thirty_fifth_wave_validated_awaiting_commit",
"execution_authorized": true,
"execution_scope": {
"authorized_by": "User: commit and continue; accepted R07 functional comparison committed 46a4f13acd5fdce08f1b19e465f428471656269f",
"tasks": ["R09"],
"authorized_by": "User: commit and continue; accepted R09 committed 06039d17bac7220d8504e68d1d4f66896eb13b91",
"tasks": ["R05"],
"permissions": [
"R09 exact experiment/report source links in existing research findings; historical verification, web save/reopen and explicit unavailable regime evidence."
"R05 partial explicit source-export web preparation: read-only normalization preview, exact content-addressed retention and existing canonical dataset selection."
],
"excluded": [
"performance_profiling_or_optimization",
@ -1303,34 +1303,34 @@
"release_gates": [
"Explicit owner disposition of the simultaneous multi-asset mark/risk policy before canonical default activation"
],
"integration_state": "partial_validated_committed",
"integration_base": "d929db707a4894096b8b31ebd25c5e39d15289c1",
"integration_state": "partial_validated_uncommitted",
"integration_base": "06039d17bac7220d8504e68d1d4f66896eb13b91",
"worktree": "/home/boki/repos/stock-bot",
"implementation_slices": [
{
"owner": "/root/r12_backend",
"worktree": "/tmp/stock-bot-wave35.fQycky/backend",
"scope": "Preparation routes/service, shared retention and existing eligibility reuse, focused integration/PostgreSQL tests"
},
{
"owner": "/root/r12_frontend",
"worktree": "/tmp/stock-bot-wave35.fQycky/frontend",
"scope": "Canonical setup source-file panel, existing API client, focused UI tests"
},
{
"owner": "/root",
"scope": "Shared pure contracts, admission/API, migration19, offline dataset import, browser/fixture integration and planning"
},
{
"owner": "/root/s04_controls_audit",
"worktree": "/tmp/stock-bot-wave23.D3gFzn/durable",
"scope": "One durable runner/repository/adapter lifecycle and focused recovery tests"
},
{
"owner": "/root/s03_review",
"worktree": "/tmp/stock-bot-wave23.D3gFzn/worker",
"scope": "Retained executable bytes and exact worker/native build verification with child tests"
},
{
"owner": "/root/s04_feed_audit",
"worktree": "/tmp/stock-bot-wave23.D3gFzn/frontend",
"scope": "Explicit canonical setup/capability and canonical result UI; focused DOM tests"
"scope": "Shared DTO, actual native browser lifecycle, integrated gates and planning"
}
],
"reviewed_by": ["/root/s03_review", "/root/s04_controls_audit", "/root/s04_feed_audit"],
"verification_reference": "ROADMAP.md#twenty-third-wave-handoff--2026-10-23",
"review_notes": "Reviewed retained-builtin/single-asset vertical slice only. Full R05 remains in progress; provider-to-v2 preparation and broader cutover are not claimed. Corrected warmup clock, series/rate/decimal admission mismatches, concurrent approval proof, UI parent identity and drawdown severity.",
"partial_commit": "618fb9e33cebc1fde4869eb1f975a12c55bd9b94"
"reviewed_by": "/root/r04_review",
"verification_reference": "ROADMAP.md#thirty-fifth-wave-handoff--2026-10-24",
"review_notes": "Independent exact-source review accepted explicit source-export preparation component; all integrated gates pass. Existing retained execution remains; full R05 remains partial for provider-query preparation/first binding and broader cutover. No inferred source evidence or activation.",
"partial_commit": "618fb9e33cebc1fde4869eb1f975a12c55bd9b94",
"execution_component": "Explicit source-export JSON preview and content-addressed retention through the existing web canonical setup",
"component_exclusions": [
"No automatic provider-query preparation, durable pending source request/first-run binding, default or multiasset activation; source metadata is supplied evidence, not independently certified.",
"Performance and AI/paper/live activation remain paused or separately gated."
]
},
{
"id": "R06",
@ -1487,7 +1487,7 @@
"epic": "E6",
"priority": "P1",
"severity": "High",
"status": "review",
"status": "done",
"dependencies": ["R08"],
"decision_dependencies": ["ADR-006"],
"task_file": "backlog/tasks/R09.md",
@ -1499,7 +1499,7 @@
"assignment": "/root",
"branch": null,
"pull_request": null,
"completed_commit": null,
"completed_commit": "06039d17bac7220d8504e68d1d4f66896eb13b91",
"blocker": null,
"release_gates": [],
"conditional_release_gates": [
@ -1513,7 +1513,7 @@
}
],
"component_readiness": "R08 and R03 committed; R07 functional component accepted. S05 does not retain per-session as-of regime annotations, so positive regime slicing remains unavailable.",
"integration_state": "validated_uncommitted",
"integration_state": "validated_committed",
"integration_base": "46a4f13acd5fdce08f1b19e465f428471656269f",
"worktree": "/home/boki/repos/stock-bot",
"execution_component": "Exact retained experiment/report citations through existing findings, with explicit unavailable regime evidence",
@ -7403,7 +7403,7 @@
"No performance, native financial changes, candidate/AI/default/multiasset/paper/live activation or new-wave commits/push/PR."
],
"thirty_fourth_wave_validation": {
"state": "validated_uncommitted",
"state": "validated_committed",
"integration_base": "46a4f13acd5fdce08f1b19e465f428471656269f",
"log_directory": "/tmp/stock-bot-wave34.02YVEd",
"scope": "Supported R09 source-linked findings and explicit unavailable-regime state; positive regime slicing requires future retained annotations.",
@ -7499,11 +7499,98 @@
"Existing finding creation remains non-idempotent; ambiguous writes freeze and require checking saved records, without automatic retry.",
"Performance, R07 table measurement, R05 provider/default cutover and candidate/AI/multiasset/paper/live activation remain paused or separately gated."
],
"commits": "Wave33 committed46a4f13. Wave34 remains uncommitted; no push or PR.",
"commits": "Wave34 accepted and committed 06039d17bac7220d8504e68d1d4f66896eb13b91 at owner request; no push or PR.",
"fixture_cleanup": {
"result": "Both exact disposable --rm containers stopped after successful final gates; development services untouched.",
"postgres": "c9d963c8b00dd98b4b4058fa91a9ad19cdf57ca4239853c3d55d8aa3b23e48d1",
"redis": "f5edaed388c92939721f4afe32e18619068587a87b07d12ffadbd38fa2168bd3"
},
"completed_commit": "06039d17bac7220d8504e68d1d4f66896eb13b91"
},
"thirty_fifth_wave_validation": {
"state": "validated_uncommitted",
"integration_base": "06039d17bac7220d8504e68d1d4f66896eb13b91",
"log_directory": "/tmp/stock-bot-wave35.fQycky",
"scope": "Partial R05 explicit source-export web normalization preview and content-addressed retention; existing canonical selection and Rust execution unchanged.",
"source_archive": "/tmp/stock-bot-wave35.fQycky/validated-source.tar.gz",
"source_archive_sha256": "029dd93e14ee7a9fa72f7b06118c708ce1ecad6711fa6d0411bc0fe2e0ada7fa",
"source_hashes": {
"apps/stock/config/src/contracts/canonical-research.ts": "cfe483420deb2d61cd68c66f878ea8f29d24bed93efbdce9ac23475dbe5c1e77",
"apps/stock/orchestrator/src/data/retained-research-dataset.ts": "a58018046fcbb42d84b8f2dba74ffe955cf5ec9edf2ec01a1d4f001a8fa07ab0",
"apps/stock/web-api/src/routes/create-routes.ts": "c5241c0b508e5c72c842c17af427107a7bab0195f59f975ab3302980076b75d9",
"apps/stock/web-api/src/routes/datasets.routes.ts": "4ac8a612fb4f4ce739eb453bd3090bf626be1e7523c64e0ddf02540b1d47ccfa",
"apps/stock/web-api/src/server-with-websocket.ts": "91c3ed7a31c4bfb4e0e5f5dcf632ea3c1fc10996774caac9120fc4e12d105963",
"apps/stock/web-api/src/services/canonical-research.service.ts": "8380dd8441114a7ecb855e7f9e4f6cc5663e20d1ae95f33d6ee90f3ccc263535",
"apps/stock/web-api/src/services/dataset-preparation.service.ts": "3218b47d9274c41c355e2298f65a3b6b46809b856c24f9579f7439af4142f239",
"apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx": "6cbe42e8f2fb26a2dca388df1dea62b4e6d1a6b3d5db345f81c49b18270eb4e9",
"apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx": "ac57b1428752659f4397ac605a320ea0e1588f06e1121a192d0ef81321747e03",
"apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts": "dee06f75602c626e37005113774d1119d3788a1f0e8991e25b8b6693d2478188",
"scripts/import-research-dataset.ts": "82f944dcfae92c4e84ffc1b86d25a1f830c39487d9b60e682ca04b0b5dfcf960",
"test/e2e/fixture.ts": "a6471482ad6e06edc1c1f2ed5445b241b0b824e691d5f24289fbc4bcf38102f9",
"test/e2e/workbench.test.ts": "74564afb5b3ffe69f109963ffed4b5d6ae2bf12d8b30cf2b435c95394754ef0a",
"test/integration/dataset-source-preparation-ui.test.tsx": "1eb22ab01e11189bdd379e64d5d54e1ccb30182e20936882d0c679e9a7d91378",
"test/integration/dataset-source-preparation.test.ts": "2f35cf78e2b41d00561ba3e7c696b00e82a78f06d0f791c9c88271fea01d2c0f",
"test/postgres/dataset-source-preparation.test.ts": "24556cd201985fbd7d126ce1994f86fd53dcfc5487efbabd0439d91e735169ca"
},
"commands": [
{
"command": "CARGO_BUILD_JOBS=2 bun run check",
"log": "integration-check-final.log",
"result": "Passed secret audit/build/types/contracts/lint; 93 tooling, 43 utility, 44 calculation, 1077 integration and 150 Rust tests. Four existing manual Rust cases ignored."
},
{
"command": "bun run test:postgres",
"log": "integration-postgres-final.log",
"result": "Passed final release PostgreSQL/Redis: 240 tests /2157 assertions across28 files; zero failures."
},
{
"command": "bun run test:e2e",
"log": "integration-browser-final.log",
"result": "Passed final production Chromium: 16 workflows /590 assertions; zero failures. Includes actual source JSON preview/retention/picker/save/native oracle and saved finding reopening."
},
{
"command": "Strict all affected/new test TypeScript; explicit sixteen-file ESLint and Prettier",
"logs": [
"root-tests-types-final.log",
"authored-lint-final.log",
"source-format-final.log"
],
"result": "Passed without exclusions for new/affected files."
},
{
"command": "git diff --check; source hashes; task file references/dependency DAG",
"result": "Passed: 16 source/test hashes, 55 unique task files, acyclic dependencies; engine source and all historical SQL unchanged."
}
],
"review": {
"independent_reviewer": "/root/r04_review",
"backend_archive": "/tmp/stock-bot-wave35.fQycky/backend-final.tar",
"backend_archive_sha256": "12bbb5206b7d22d3519c0bac50ef6b27200217f45d37fcc220d2c54c461c1621",
"backend": "Accepted all seven exact integrated files. Focused integration/native/auth8/131; PostgreSQL5/58; compatible normalizer/catalog suite26/251. Types, scoped test types, all-file lint/format pass. Shared custody/CLI reexport and existing eligibility semantics preserved.",
"frontend_archive": "/tmp/stock-bot-wave35.fQycky/frontend-final.tar",
"frontend_archive_sha256": "f4136bb6e3cd8f8590c60cc623fdd2162eee30ffadbd7230a9fa456ecf2a5a44",
"frontend": "Accepted all four exact integrated files. Focused45/166, combined existing/new UI132/662. New tests cover unknown-response exact retries, definitive rejection repair, source/parent stale responses, different-hash selection, disabled/save races and metadata display. Root strict affected-test check passes without the owner local inherited noUnusedParameters exception.",
"root": "Shared DTO, web-only transport setting and fixture, actual existing native browser oracle extended with file preview/retention/reopen accepted. Focused browser1/119,15 unselected workflows skipped; actual >1MiB JSON consumption preserves identical normalized content and zero preview writes. Final full repository, database and browser suites passed on the frozen integrated source.",
"corrections": "Review closed same-event Retain→Clear retry-state loss, response parser unknown-field stripping/direct-source lineage gap, and distinguished definitive400/409 from uncertain retention. First browser failures were exact hash/overbroad calendar selectors; scoped visible metadata selectors fixed them with unchanged application behavior."
},
"engine": {
"debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff",
"release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103",
"note": "Engine source unchanged. Fullcheck built debug; verified unchanged release restored before final database/browser suites."
},
"limits": [
"Source export is complete supplied metadata/bars, not provider retrieval or independent provenance certification. No calendar, universe, action-free coverage or publication-time inference.",
"Preview performs no IO. Exact-hash content custody can retain valid unavailable datasets; current canonical eligibility continues to reject exploratory/ineligible/multiasset execution.",
"R05 remains partial: durable provider-query preparation/first-run binding and broader default cutover are outstanding. No v1 conversion, migrations, new scheduler or financial semantics.",
"Web server small1MiB application restriction removed using MAX_SAFE_INTEGER transport setting and shared browser fixture. This is not an unlimited-size or performance guarantee; generic service boot unchanged.",
"Existing mounted operator/service/admin and browser-origin authorization retained, including existing local AUTH_DISABLED development semantics. No new research-agent credentials.",
"Performance/R07 measurement paused; candidate/AI/multiasset/paper/live/default activation gates unchanged."
],
"commits": "R09 committed06039d1 at owner request. Wave35 changes uncommitted; no push or PR.",
"fixture_cleanup": {
"result": "Both exact disposable --rm containers stopped after final suites passed; development services untouched.",
"postgres": "cd8467b474238ca03f14fc2a0d24a0ff9d400e87c5161957c78b5847f81e42c8",
"redis": "3acb7f10faa1bfe77c0ca72fe58f5a2251770a73f8ed080fc9982571ab4f354d"
}
}
}

View file

@ -105,3 +105,19 @@ Deploy the existing **native research runner (`useRustEngine: true`)**, bundled
- No profiling, performance optimization, benchmark runs, DSL, second job engine, simulator or deployment framework was added.
Final validation and source identity are recorded in `manifest.json` → `twenty_third_wave_validation` and the roadmap handoff.
## Authorized source-export preparation slice — 2026-10-24
Implement explicit web upload of complete `HistoricalDatasetInputV2` source metadata/bars, read-only normalized preview and exact-hash retention into the existing immutable dataset store. Reuse `createDatasetV2`, importer custody and current canonical eligibility. Show source/calendar/action/universe declarations and availability assumptions without claiming independent provider certification. Preview writes nothing; retain does not save a template or start a run. Identical retry/concurrent requests converge on one content-addressed row. Unknown/ineligible or unsupported multiasset datasets remain unavailable for canonical execution.
Acceptance: malformed/missing metadata and invalid bars reject; preview hash drift rejects before persistence; corrupt retained rows fail without overwrite; API authorization/CSRF/no-store preserved; file/input/request changes fence stale UI state; exact retention can retry after lost responses; other setup edits survive. A real browser uploads source JSON, previews without writes, retains, selects, saves and runs the unchanged Rust next-open oracle, then reopens identical provenance. Existing importer CLI and v1 datasets remain intact.
This slice excludes v1 conversion, external provider access, inferred evidence, new migrations/schedulers, financial semantics and any default/multiasset/paper/live/AI activation. Full R05 remains partial for durable provider-query preparation and cutover. No performance measurements.
## Validated source-export handoff — 2026-10-24
The above slice is independently reviewed and `partial_validated_uncommitted` on `06039d1`. The web now previews and retains complete explicit source exports using the same normalizer/custody as existing research, then selects through canonical setup. Existing offline importer behavior and historical datasets remain intact; no SQL or engine source changed. Definitive rejection repair, exact uncertain retries, content corruption/concurrency, parent/late UI state and actual native economics pass. The web transport accepts source requests beyond its former 1 MiB cap; this is a functional correction, not a throughput measurement.
Final gates: repository check 1077 integration /150 Rust plus93 tooling/43 utility/44 calculation tests; PostgreSQL240/2157; Chromium16/590; strict affected-test types, all16-file lint/format/hash/DAG/diff checks. Independent agent overlays and root browser/transport changes are accepted. Four prior manual Rust cases remain ignored. Logs/hashes/limits are in `manifest.json` → `thirty_fifth_wave_validation` and the [roadmap handoff](../../ROADMAP.md#thirty-fifth-wave-handoff--2026-10-24). Both disposable containers were removed.
Full R05 stays `in_progress`: automatic provider-query preparation/first binding and default cutover are not delivered. No performance work or candidate/multiasset/paper/live/AI activation occurred. Changes await the next authorized commit.

View file

@ -79,3 +79,5 @@ Supported scope is independently reviewed and validated on `46a4f13`; status is
Validation: full repository check passed 1024 integration /150 Rust, plus 93 tooling /43 utility /44 calculation tests; final PostgreSQL/Redis 235/2099 and Chromium 16/569. Strict test types, source/test lint, formatting, diff/source hash/DAG checks passed. The real SQL24 upgrade regression confirms missing role metadata fails closed before migration and ordinary experiments qualify afterward. Four preexisting Rust cases remain ignored. Both temporary test containers were removed.
Positive `regime_slice_reconciliation` remains conditional and unrun because no retained as-of annotation contract exists. The unavailable-state UI is tested; S05 alone does not enable classification. No performance work, financial changes or trading/AI activation. Exact hashes, logs, independent review and limits: [wave34 manifest evidence](../manifest.json), [roadmap handoff](../../ROADMAP.md#thirty-fourth-wave-handoff--2026-10-24).
Accepted by owner continuation and committed as `06039d1` on 2026-10-24. Supported R09 is done; conditional regime-annotation limitations remain unchanged.

View file

@ -2,23 +2,9 @@
import { readFile } from 'node:fs/promises';
import { Pool } from 'pg';
import { validateDatasetV2 } from '../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { retainResearchDataset } from '../apps/stock/orchestrator/src/data/retained-research-dataset';
export async function retainResearchDataset(database: Pick<Pool, 'query'>, input: unknown) {
const dataset = validateDatasetV2(input);
await database.query(
'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING',
[dataset.manifest.hash, JSON.stringify(dataset)]
);
const stored = (
await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
dataset.manifest.hash,
])
).rows[0];
if (!stored || validateDatasetV2(stored.payload).manifest.hash !== dataset.manifest.hash) {
throw new Error('Retained dataset content does not match the imported identity');
}
return dataset.manifest;
}
export { retainResearchDataset } from '../apps/stock/orchestrator/src/data/retained-research-dataset';
if (import.meta.main) {
let database: Pool | undefined;

View file

@ -21,7 +21,10 @@ import {
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import type { BacktestConfig } from '../../apps/stock/orchestrator/src/types';
import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes';
import {
createRoutes,
WEB_API_MAX_REQUEST_BODY_SIZE,
} from '../../apps/stock/web-api/src/routes/create-routes';
import {
createWebSocketRoute,
handleWebSocketConnection,
@ -420,6 +423,7 @@ export async function fixture(browser: Browser, native = false) {
const server = Bun.serve<RunSocketData, {}>({
hostname: '127.0.0.1',
port: 0,
maxRequestBodySize: WEB_API_MAX_REQUEST_BODY_SIZE,
async fetch(request, server) {
const pathname = new URL(request.url).pathname;
if (pathname === '/ws' && request.headers.get('upgrade') === 'websocket') {

View file

@ -3,6 +3,7 @@ import { afterAll, beforeAll, expect, test } from 'bun:test';
import { chromium, type Browser, type Request } from 'playwright';
import {
canonicalResearchSettingsSchema,
type CanonicalDatasetPreparation,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type {
@ -28,7 +29,11 @@ import type {
WalkForwardDetail,
WalkForwardPreview,
} from '@stock-bot/stock-config/walk-forward';
import type { ResearchArtifact, ResearchFindingSource } from '@stock-bot/types';
import type {
HistoricalDatasetInputV2,
ResearchArtifact,
ResearchFindingSource,
} from '@stock-bot/types';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
@ -2109,7 +2114,25 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
f.page.on('dialog', dialog => void dialog.accept());
try {
const oracle = canonicalSmaFixture();
const retained = await retainResearchDataset(f.pool, oracle.dataset);
const retained = oracle.dataset.manifest;
const { calendars, series, executionSeries, bounds, universe, corporateActions } = retained;
// Explicit synthetic source export, with the same reviewed next-open oracle.
// The browser submits raw source rows; only the server normalizes/hashes them.
const source: HistoricalDatasetInputV2 = {
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
bars: oracle.dataset.bars.map(bar => ({
seriesId: bar.seriesId,
timestamp: bar.intervalStart,
availableAt: bar.availableAt,
sourceSequence: bar.sourceSequence,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap,
})),
};
const seeded = await f.seedCatalog();
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
expect(selected.reviewStatus).toBe('pending');
@ -2216,7 +2239,93 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
);
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
await f.page.getByRole('button', { name: 'Configure canonical research', exact: true }).click();
await f.page.getByLabel('Canonical dataset', { exact: true }).selectOption(retained.hash);
await f.page.getByLabel('Initial capital (USD)', { exact: true }).fill('10000');
const templateBeforePreparation = await f.request(`/api/v2/backtests/${backtestId}`);
const preparationCounts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM backtest_datasets) AS datasets,
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
).rows[0];
expect(await preparationCounts()).toEqual({ datasets: 0, runs: 0, dispatch: 0 });
await f.page.getByText('Prepare dataset from source export', { exact: true }).click();
await f.page.getByLabel('Source dataset JSON', { exact: true }).setInputFiles({
name: 'reviewed-synthetic-source.json',
mimeType: 'application/json',
buffer: Buffer.from(JSON.stringify(source)),
});
const previewingDataset = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/datasets/canonical/preview')
);
await f.page.getByRole('button', { name: 'Preview dataset', exact: true }).click();
const previewedDataset = await previewingDataset;
expect(previewedDataset.status()).toBe(200);
expect(previewedDataset.request().postDataJSON()).toEqual({ input: source });
const preview = (await previewedDataset.json()) as {
preparation: CanonicalDatasetPreparation;
};
expect(preview.preparation.manifest).toEqual(retained);
expect(preview.preparation.hash).toBe(retained.hash);
expect(preview.preparation.available).toBe(true);
// Exercise real HTTP JSON consumption above the former web-server 1 MiB cap.
// Whitespace changes transport size without changing the economic oracle.
const largePreview = await f.page.evaluate(async input => {
const body = JSON.stringify({ input }) + ' '.repeat(1_048_576);
const response = await fetch('/api/v2/datasets/canonical/preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
});
return {
bytes: new TextEncoder().encode(body).byteLength,
status: response.status,
cacheControl: response.headers.get('Cache-Control'),
result: await response.json(),
};
}, source);
expect(largePreview.bytes).toBeGreaterThan(1_048_576);
expect(largePreview.status).toBe(200);
expect(largePreview.cacheControl).toBe('no-store');
expect(largePreview.result).toEqual(preview);
await visible(f.page, `Dataset hash: ${retained.hash}`);
const calendarDetails = f.page
.getByRole('region', { name: 'Prepared dataset metadata', exact: true })
.getByText(/^Calendar:/);
await calendarDetails.waitFor();
expect(await calendarDetails.textContent()).toContain(
`Revision: ${retained.calendars[0]!.revision}`
);
expect(await preparationCounts()).toEqual({ datasets: 0, runs: 0, dispatch: 0 });
expect(await f.request(`/api/v2/backtests/${backtestId}`)).toEqual(templateBeforePreparation);
const retainingDataset = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/datasets/canonical/retain')
);
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click();
const retainedDataset = await retainingDataset;
expect(retainedDataset.status()).toBe(200);
const retainedRequest = retainedDataset.request().postDataJSON();
expect(retainedRequest).toEqual({ input: source, expectedHash: retained.hash });
expect(await retainedDataset.json()).toEqual(preview);
// Exact replay is safe after a lost response: one immutable row, no new jobs.
expect(await f.request('/api/v2/datasets/canonical/retain', 'POST', retainedRequest)).toEqual(
preview
);
expect(await preparationCounts()).toEqual({ datasets: 1, runs: 0, dispatch: 0 });
expect(await f.request(`/api/v2/backtests/${backtestId}`)).toEqual(templateBeforePreparation);
expect(
(await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [retained.hash]))
.rows[0].payload
).toEqual(oracle.dataset);
await until(
async () =>
(await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()) ===
retained.hash,
'retained source dataset selected in canonical setup'
);
expect(await f.page.getByLabel('Initial capital (USD)', { exact: true }).inputValue()).toBe(
'10000'
);
await visible(f.page, new Date(retained.bounds.tradeStart).toISOString());
await visible(f.page, new Date(retained.bounds.tradeEnd).toISOString());
await f.page.getByLabel('Initial capital (USD)', { exact: true }).fill('10000');

View file

@ -0,0 +1,882 @@
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 type {
CanonicalDatasetCatalogEntry,
CanonicalDatasetPreparation,
} from '@stock-bot/stock-config/canonical-research';
import type {
StrategyParameterSchema,
StrategyRecord,
StrategyVersionPackage,
StrategyVersionSummary,
} from '@stock-bot/types';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import type { CreateBacktestRequest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
import { datasetInput } from '../fixtures/historical-v2/dataset';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT', 'ResizeObserver'] as const;
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
let createRoot: typeof import('react-dom/client').createRoot;
let router: typeof import('react-router-dom');
let CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup;
let DatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation').DatasetPreparation;
let parseDatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').parseDatasetPreparation;
function confirmWith(value: () => boolean) {
Object.defineProperty(browser, 'confirm', { configurable: true, writable: true, value });
}
let root: Root | undefined;
let host: HTMLDivElement;
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: 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;
method: string;
body: unknown;
signal: AbortSignal | null | undefined;
settled: boolean;
};
const requests: Pending[] = [];
function request(path: string, method = 'POST') {
const found = requests.find(
item => item.path === path && item.method === method && !item.settled
);
if (!found) {
throw new Error(
`No pending ${method} ${path}: ${JSON.stringify(requests.map(item => [item.path, item.method, item.settled]))}`
);
}
return found;
}
function reply(item: Pending, body: unknown, status = 200) {
item.settled = true;
item.resolve(Response.json(body, { status }));
}
function fail(item: Pending) {
item.settled = true;
item.reject(new Error('Response lost'));
}
async function flush(action: () => void = () => {}) {
await act(async () => {
action();
await Promise.resolve();
});
}
function button(label: string) {
const found = [...host.querySelectorAll('button')].find(
item => item.textContent?.trim() === label
);
if (!found) {
throw new Error(`Missing ${label}: ${host.textContent}`);
}
return found;
}
function click(label: string) {
button(label).click();
}
function field(label: string) {
const found = host.querySelector(`[aria-label="${label}"]`) as
| HTMLInputElement
| HTMLSelectElement
| null;
if (!found) {
throw new Error(`Missing ${label}`);
}
return found;
}
function edit(label: string, value: string) {
const input = field(label);
Object.getOwnPropertyDescriptor(
input.tagName === 'SELECT'
? browser.HTMLSelectElement.prototype
: browser.HTMLInputElement.prototype,
'value'
)!.set!.call(input, value);
input.dispatchEvent(
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
bubbles: true,
}) as unknown as Event
);
}
function upload(value: unknown = datasetInput(), name = 'source.json', read?: Promise<string>) {
const file = new browser.File([typeof value === 'string' ? value : JSON.stringify(value)], name, {
type: 'application/json',
});
if (read) {
Object.defineProperty(file, 'text', { value: () => read });
}
Object.defineProperty(field('Source dataset JSON'), 'files', {
configurable: true,
value: [file],
});
field('Source dataset JSON').dispatchEvent(
new browser.Event('change', { bubbles: true }) as unknown as Event
);
}
async function mount(element: ReactElement) {
root = createRoot(host);
await flush(() => root!.render(createElement(router.MemoryRouter, null, element)));
}
const previewPath = '/api/v2/datasets/canonical/preview';
const retainPath = '/api/v2/datasets/canonical/retain';
const dataset = createDatasetV2(datasetInput());
const preparation: CanonicalDatasetPreparation = {
version: 'canonical-dataset-preparation/v1',
hash: dataset.manifest.hash,
manifest: dataset.manifest,
available: true,
reason: null,
};
const entry: CanonicalDatasetCatalogEntry = {
hash: preparation.hash,
manifest: preparation.manifest,
available: true,
reason: null,
createdAt: '2026-01-01T00:00:00Z',
};
let retained: { hash: string; available: boolean }[] = [];
let states: { busy: boolean; blocking: boolean }[] = [];
const panelProps = () => ({
disabled: false,
begin: () => true,
onRetained: (hash: string, available: boolean) => retained.push({ hash, available }),
onStateChange: (value: { busy: boolean; blocking: boolean }) => states.push(value),
});
async function mountPanel() {
await mount(createElement(DatasetPreparation, panelProps()));
}
async function preview(value: CanonicalDatasetPreparation = preparation) {
await flush(() => upload());
await flush(() => click('Preview dataset'));
await flush(() => reply(request(previewPath), { preparation: value }));
}
const family = (id = 'family', extra: Partial<StrategyRecord> = {}): StrategyRecord => ({
id,
name: `Strategy ${id}`,
description: 'Reviewed fixture',
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
...extra,
});
const schema: StrategyParameterSchema = {
version: 1,
type: 'object',
additionalProperties: false,
required: [],
properties: {
fastPeriod: { type: 'integer', minimum: 1, default: 5 },
slowPeriod: { type: 'integer', minimum: 2, default: 15 },
},
};
const pkg = (
content = 'globalThis.CATALOG_MUST_NOT_EXECUTE = true; <img src=x onerror=alert(1)>'
): StrategyVersionPackage => ({
version: 1,
program: {
strategyId: 'fixture',
strategyVersion: 'v1',
apiVersion: 'canonical-ts/v1',
checkpointVersion: 'fixture/v1',
},
artifact: {
format: 'esm-bundle/v1',
entryExport: 'createFixture',
content,
sha256: 'a'.repeat(64),
},
dependencyLock: { format: 'bun-lock/v1', content: 'lock', sha256: 'b'.repeat(64) },
parameterSchema: schema,
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
});
const version = (
id = 'version-one',
extra: Partial<StrategyVersionSummary> = {}
): StrategyVersionSummary => {
const full = pkg();
const { content: _artifact, ...artifact } = full.artifact;
const { content: _lock, ...dependencyLock } = full.dependencyLock;
return {
id,
strategyId: 'family',
ordinal: 1,
parentVersionId: null,
createdBy: 'operator',
origin: 'builtin',
createdAt: '2026-01-01',
package: { ...full, artifact, dependencyLock },
reviewStatus: 'approved',
runnable: false,
reason: 'Execution unavailable',
...extra,
};
};
const definition = {
id: 'definition',
name: 'Catalog fixture',
strategy: 'catalog',
strategyVersionId: 'version-one',
strategyParameters: { fastPeriod: 5, slowPeriod: 15 },
symbols: ['AAPL.US'],
startDate: '2024-01-01',
endDate: '2024-03-01',
initialCapital: 100000,
config: {},
archivedAt: null,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
};
async function selected(archived = false) {
await flush(() => {
reply(request('/api/v2/strategies', 'GET'), { strategies: [family('family', { archived })] });
reply(request('/api/v2/strategy-versions/version-one', 'GET'), {
version: version(),
reviews: [],
});
});
await flush(() =>
reply(request('/api/v2/strategies/family', 'GET'), { strategy: family('family', { archived }) })
);
await flush(() =>
reply(request('/api/v2/strategies/family/versions', 'GET'), { versions: [version()] })
);
}
beforeAll(async () => {
for (const [key, value] of Object.entries({
window: browser,
document: browser.document,
IS_REACT_ACT_ENVIRONMENT: true,
ResizeObserver: browser.ResizeObserver,
})) {
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
({ createRoot } = await import('react-dom/client'));
router = await import('react-router-dom');
({ CanonicalSetup } = await import(
'../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup'
));
({ DatasetPreparation } = await import(
'../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation'
));
({ parseDatasetPreparation } = await import(
'../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'
));
});
beforeEach(() => {
requests.length = 0;
retained = [];
states = [];
host = browser.document.createElement('div') as unknown as HTMLDivElement;
browser.document.body.append(host as never);
confirmWith(() => true);
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => {
const item: Pending = {
...deferred<Response>(),
path: new URL(String(url)).pathname,
method: init?.method ?? 'GET',
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
signal: init?.signal,
settled: false,
};
requests.push(item);
return item.promise;
}) as unknown as typeof browser.fetch;
});
afterEach(async () => {
if (root) {
await flush(() => root!.unmount());
}
root = undefined;
host.remove();
});
afterAll(async () => {
await browser.happyDOM.close();
for (const key of keys) {
const value = originals.get(key);
if (value) {
Object.defineProperty(globalThis, key, value);
} else {
delete (globalThis as Record<string, unknown>)[key];
}
}
});
async function readySetup(
onSave: (value: CreateBacktestRequest) => Promise<void>,
onClose?: () => void
) {
await mount(createElement(CanonicalSetup, { backtest: definition, onSave, onClose }));
await selected();
await flush(() => reply(request('/api/v2/datasets/canonical', 'GET'), { datasets: [entry] }));
await flush(() => edit('Canonical dataset', entry.hash));
await flush(() =>
reply(request(`/api/v2/datasets/canonical/${entry.hash}`, 'GET'), { dataset: entry })
);
await flush(() => click('Validate parameters'));
await flush(() =>
reply(request('/api/v2/strategy-versions/version-one/validate'), {
parameters: definition.strategyParameters,
runnable: false,
reason: 'Execution gated',
})
);
expect(button('Save canonical setup').disabled).toBe(false);
}
describe('source preparation decoder', () => {
test('accepts complete declared metadata unchanged and direct null lineage', () => {
expect(parseDatasetPreparation(preparation)).toEqual(preparation);
});
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
const mutations: {
name: string;
change: (value: Mutable<CanonicalDatasetPreparation>) => unknown;
}[] = [
{ name: 'wrong version', change: v => Object.assign(v, { version: 'future' }) },
{ name: 'hash differs', change: v => (v.hash = 'b'.repeat(64)) },
{
name: 'invalid hash',
change: v => {
v.hash = 'invalid';
v.manifest.hash = 'invalid';
},
},
{ name: 'unknown descriptor field', change: v => Object.assign(v, { attested: true }) },
{
name: 'unknown manifest field',
change: v => Object.assign(v.manifest, { certificate: 'not retained' }),
},
{
name: 'unknown nested field',
change: v => Object.assign(v.manifest.series[0]!, { certificate: true }),
},
{ name: 'non-source lineage', change: v => (v.manifest.parentDatasetHash = 'a'.repeat(64)) },
{
name: 'missing session revision',
change: v => Reflect.deleteProperty(v.manifest.calendars[0]!, 'revision'),
},
{ name: 'invalid date', change: v => (v.manifest.calendars[0]!.startDate = '2024-02-31') },
{
name: 'out of Date range',
change: v => (v.manifest.bounds.tradeEnd = 8_640_000_000_000_001),
},
{ name: 'empty session', change: v => (v.manifest.calendars[0]!.sessions = []) },
{ name: 'unmatched calendar', change: v => (v.manifest.series[0]!.calendarId = 'other') },
{
name: 'unmatched execution series',
change: v => (v.manifest.executionSeries[0]!.seriesId = 'other'),
},
{
name: 'eligible disabled contradiction',
change: v => {
v.available = false;
v.reason = 'No';
},
},
{
name: 'exploratory enabled contradiction',
change: v => (v.manifest.eligibility = 'exploratory'),
},
{ name: 'available reason contradiction', change: v => (v.reason = 'No') },
{ name: 'zero bar count', change: v => (v.manifest.barCount = 0) },
];
for (const { name, change } of mutations) {
test(`rejects ${name}`, () => {
const value = structuredClone(preparation) as Mutable<CanonicalDatasetPreparation>;
change(value);
expect(() => parseDatasetPreparation(value)).toThrow();
});
}
test('rejects retained identity different from captured hash', () =>
expect(() => parseDatasetPreparation(preparation, 'c'.repeat(64))).toThrow());
});
describe('explicit source preparation', () => {
test('initial render is lazy and empty; all actions are non-submit buttons', async () => {
await mountPanel();
expect(requests).toHaveLength(0);
expect(host.textContent).toContain('No source export selected.');
expect(button('Preview dataset').disabled).toBe(true);
expect(button('Retain dataset').disabled).toBe(true);
expect(host.querySelector('form')).toBeNull();
expect([...host.querySelectorAll('button')].every(item => item.type === 'button')).toBe(true);
});
test('previews only explicit source, renders declared metadata and preserves unknown publication delay limitation', async () => {
await mountPanel();
await flush(() => upload());
await flush(() => {
click('Preview dataset');
click('Preview dataset');
});
expect(requests).toHaveLength(1);
expect(request(previewPath).body).toEqual({ input: datasetInput() });
expect(host.textContent).toContain('Previewing dataset...');
expect(retained).toHaveLength(0);
await flush(() => reply(request(previewPath), { preparation }));
for (const text of [
preparation.hash,
'A.US / 1d',
'Adjustment: raw',
'Timestamp: session-date',
'Availability: interval-end-assumption',
'actual publication delay is not verified',
'America/New_York',
'test-sessions-2024-v1',
'test-action-coverage-v1',
'test-universe-v1',
'Sessions: 3',
'3 bars',
'2024-03-11T13:30:00.000Z',
'not independent provider certification',
]) {
expect(host.textContent).toContain(text);
}
expect(JSON.parse(host.querySelector('pre')!.textContent!)).toEqual(preparation.manifest);
expect(requests.some(item => item.path === retainPath)).toBe(false);
expect(states.at(-1)).toEqual({ busy: false, blocking: true });
});
test('invalid JSON is recoverable without POST or invented metadata', async () => {
await mountPanel();
await flush(() => upload('{invalid'));
expect(host.textContent).toContain('Could not read source JSON');
expect(requests).toHaveLength(0);
expect(button('Preview dataset').disabled).toBe(true);
await flush(() => upload());
await flush(() => click('Preview dataset'));
expect(request(previewPath).body).toEqual({ input: datasetInput() });
});
test('unreadable file leaves actionable error', async () => {
await mountPanel();
const reading = deferred<string>();
await flush(() => upload({}, 'bad.json', reading.promise));
expect(host.textContent).toContain('Reading source JSON...');
await flush(() => reading.reject(new Error('read denied')));
expect(host.textContent).toContain('read denied');
expect(button('Retain dataset').disabled).toBe(true);
});
test('latest file read wins even when older read completes late', async () => {
await mountPanel();
const reading = deferred<string>();
await flush(() => upload({}, 'old.json', reading.promise));
await flush(() => upload(datasetInput(), 'new.json'));
await flush(() => reading.resolve('{"wrong":"source"}'));
expect(host.textContent).toContain('new.json');
expect(host.textContent).not.toContain('old.json');
await flush(() => click('Preview dataset'));
expect(request(previewPath).body).toEqual({ input: datasetInput() });
});
test('file replacement invalidates preview and fences ignored abort response', async () => {
await mountPanel();
await flush(() => upload());
await flush(() => click('Preview dataset'));
const old = request(previewPath);
await flush(() => upload({ metadata: 'different' }, 'next.json'));
expect(old.signal?.aborted).toBe(true);
await flush(() => reply(old, { preparation }));
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
expect(button('Retain dataset').disabled).toBe(true);
await flush(() => click('Preview dataset'));
expect(request(previewPath).body).toEqual({ input: { metadata: 'different' } });
});
test('clear cancels pending preview and same-event stale Retain cannot submit', async () => {
await mountPanel();
await preview();
await flush(() => {
click('Clear source preparation');
click('Retain dataset');
});
expect(requests.filter(item => item.path === retainPath)).toHaveLength(0);
expect(host.textContent).toContain('No source export selected.');
await flush(() => upload());
await flush(() => click('Preview dataset'));
const old = request(previewPath);
await flush(() => click('Clear source preparation'));
await flush(() => reply(old, { preparation }));
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
});
test('preview errors and malformed envelopes never enable retention', async () => {
await mountPanel();
await flush(() => upload());
await flush(() => click('Preview dataset'));
await flush(() => reply(request(previewPath), { error: 'Metadata incomplete' }, 400));
expect(host.textContent).toContain('Metadata incomplete');
await flush(() => click('Preview dataset'));
await flush(() =>
reply(request(previewPath), { preparation: { ...preparation, manifest: null } })
);
expect(host.textContent).toContain('could not be verified');
expect(button('Retain dataset').disabled).toBe(true);
});
test('lost retain response keeps exact input/hash; duplicate clicks and synchronous clear cannot discard intent', async () => {
await mountPanel();
await preview();
let prompts = 0;
confirmWith(() => {
prompts++;
return true;
});
await flush(() => {
click('Retain dataset');
click('Retain dataset');
click('Clear source preparation');
});
expect(prompts).toBe(0);
const first = request(retainPath);
expect(first.body).toEqual({ input: datasetInput(), expectedHash: preparation.hash });
expect(requests.filter(item => item.path === retainPath)).toHaveLength(1);
expect(field('Source dataset JSON').disabled).toBe(true);
await flush(() => fail(first));
expect(host.textContent).toContain('exact original input and hash are preserved');
confirmWith(() => false);
await flush(() => click('Clear source preparation'));
await flush(() => upload({ not: 'the original' }));
await flush(() => click('Retry retaining same dataset'));
expect(request(retainPath).body).toEqual(first.body);
await flush(() => reply(request(retainPath), { preparation }));
expect(retained).toEqual([{ hash: preparation.hash, available: true }]);
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
expect(button('Retain dataset').disabled).toBe(true);
});
for (const status of [400, 409]) {
test(`definitive ${status} rejects without ambiguous retry and preserves input for new preview`, async () => {
await mountPanel();
await preview();
await flush(() => click('Retain dataset'));
await flush(() => reply(request(retainPath), { error: 'Hash or input rejected' }, status));
expect(host.textContent).toContain('Preview again or choose a corrected source export.');
expect(host.textContent).not.toContain('may already have succeeded');
expect(button('Preview dataset').disabled).toBe(false);
expect(button('Retain dataset').disabled).toBe(true);
expect(field('Source dataset JSON').disabled).toBe(false);
await flush(() => click('Preview dataset'));
expect(request(previewPath).body).toEqual({ input: datasetInput() });
expect(retained).toHaveLength(0);
});
}
for (const mode of [
'server error',
'wrong hash',
'changed metadata',
'unknown metadata',
] as const) {
test(`retention ${mode} remains unconfirmed with same retry`, async () => {
await mountPanel();
await preview();
await flush(() => click('Retain dataset'));
const first = request(retainPath);
const changed = structuredClone(preparation);
if (mode === 'wrong hash') {
Object.assign(changed, {
hash: 'b'.repeat(64),
manifest: { ...changed.manifest, hash: 'b'.repeat(64) },
});
}
if (mode === 'changed metadata') {
Object.assign(changed.manifest, { limitations: ['changed'] });
}
await flush(() =>
reply(
first,
mode === 'server error'
? { error: 'Storage unavailable' }
: {
preparation: mode === 'unknown metadata' ? { ...changed, unknown: true } : changed,
},
mode === 'server error' ? 503 : 200
)
);
expect(retained).toHaveLength(0);
expect(host.textContent).toContain('may already have succeeded');
await flush(() => click('Retry retaining same dataset'));
expect(request(retainPath).body).toEqual(first.body);
});
}
test('valid unavailable data can be retained without selection and remains clearly unavailable', async () => {
await mountPanel();
const value: CanonicalDatasetPreparation = {
...preparation,
manifest: {
...preparation.manifest,
eligibility: 'exploratory',
limitations: ['Source coverage unknown'],
universe: { ...preparation.manifest.universe, selection: 'unknown', asOf: null },
},
available: false,
reason: 'Requires point-in-time universe',
};
await preview(value);
expect(button('Retain dataset').disabled).toBe(false);
expect(host.textContent).toContain('As of: Unknown');
await flush(() => click('Retain dataset'));
await flush(() => reply(request(retainPath), { preparation: value }));
expect(retained).toEqual([{ hash: preparation.hash, available: false }]);
expect(host.textContent).toContain('existing selection is unchanged');
expect(states.at(-1)).toEqual({ busy: false, blocking: true });
});
test('unmount fences late retain and file reads without callbacks', async () => {
await mountPanel();
await preview();
await flush(() => click('Retain dataset'));
const old = request(retainPath);
await flush(() => root!.unmount());
root = undefined;
await flush(() => reply(old, { preparation }));
expect(old.signal?.aborted).toBe(true);
expect(retained).toHaveLength(0);
});
test('unmount while reading a file ignores late content', async () => {
await mountPanel();
const reading = deferred<string>();
await flush(() => upload({}, 'late.json', reading.promise));
await flush(() => root!.unmount());
root = undefined;
await flush(() => reading.resolve(JSON.stringify(datasetInput())));
expect(requests).toHaveLength(0);
expect(retained).toHaveLength(0);
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
});
test('preserves explicit delayed availability and renders known corporate actions as unavailable evidence', async () => {
const sourceInput = datasetInput();
const source = {
...sourceInput,
metadata: {
...sourceInput.metadata,
series: sourceInput.metadata.series.map(item => ({
...item,
availability: 'explicit' as const,
})),
corporateActions: sourceInput.metadata.corporateActions.map(item => ({
...item,
status: 'known-actions' as const,
actions: [
{
kind: 'split' as const,
reference: 'declared-split-17',
effectiveAt: sourceInput.metadata.bounds.tradeStart,
},
],
})),
},
bars: sourceInput.bars.map((bar, index) => ({
...bar,
availableAt: sourceInput.metadata.calendars[0]!.sessions[index]!.close + 30_000,
})),
};
const preparedDataset = createDatasetV2(source);
const value = {
...preparation,
hash: preparedDataset.manifest.hash,
manifest: preparedDataset.manifest,
available: false,
reason: 'Known actions are unsupported for execution',
};
await mountPanel();
await flush(() => upload(source));
await flush(() => click('Preview dataset'));
expect(request(previewPath).body).toEqual({ input: source });
await flush(() => reply(request(previewPath), { preparation: value }));
expect(host.textContent).toContain('Availability: explicit');
expect(host.textContent).toContain('declared-split-17');
expect(host.textContent).toContain('known-actions');
expect(host.textContent).toContain('Unavailable for canonical setup');
expect(host.textContent).not.toContain('Availability is explicitly assumed');
await flush(() => click('Retain dataset'));
expect(request(retainPath).body).toEqual({ input: source, expectedHash: value.hash });
});
test('disabled panel cannot read source or issue requests', async () => {
await mount(createElement(DatasetPreparation, { ...panelProps(), disabled: true }));
await flush(() => upload());
expect(requests).toHaveLength(0);
expect(host.textContent).not.toContain('Selected export');
expect(button('Preview dataset').disabled).toBe(true);
});
});
describe('canonical setup coordination', () => {
test('source workflow has no nested form, preserves all settings, selects only after retention/lookup, and never autosaves', async () => {
const sourceInput = datasetInput();
const replacementInput = {
...sourceInput,
metadata: {
...sourceInput.metadata,
series: sourceInput.metadata.series.map(series => ({
...series,
source: { ...series.source, revision: 'corrected-export-v2' },
})),
},
};
const replacementDataset = createDatasetV2(replacementInput);
const replacement = {
...preparation,
hash: replacementDataset.manifest.hash,
manifest: replacementDataset.manifest,
};
const replacementEntry = { ...entry, hash: replacement.hash, manifest: replacement.manifest };
const saves: CreateBacktestRequest[] = [];
await readySetup(async value => {
saves.push(value);
});
await flush(() => {
edit('Backtest name', 'My edited draft');
edit('Initial capital (USD)', '12345');
edit('Fee rate', '0.002');
edit('fastPeriod', '3');
});
await flush(() => click('Validate parameters'));
await flush(() =>
reply(request('/api/v2/strategy-versions/version-one/validate'), {
parameters: { fastPeriod: 3, slowPeriod: 15 },
runnable: false,
reason: 'gated',
})
);
expect(host.querySelectorAll('form')).toHaveLength(1);
await flush(() => upload(replacementInput));
expect(button('Save canonical setup').disabled).toBe(true);
await flush(() => click('Preview dataset'));
await flush(() => reply(request(previewPath), { preparation: replacement }));
expect(field('Canonical dataset').value).toBe(entry.hash);
expect(saves).toHaveLength(0);
await flush(() => click('Retain dataset'));
expect(field('Canonical dataset').value).toBe(entry.hash);
await flush(() => reply(request(retainPath), { preparation: replacement }));
expect(field('Canonical dataset').value).toBe(replacement.hash);
expect(field('Backtest name').value).toBe('My edited draft');
expect(field('Initial capital (USD)').value).toBe('12345');
expect(field('Fee rate').value).toBe('0.002');
expect(field('fastPeriod').value).toBe('3');
expect(saves).toHaveLength(0);
expect(button('Save canonical setup').disabled).toBe(true);
await flush(() => {
reply(request('/api/v2/datasets/canonical', 'GET'), { datasets: [entry, replacementEntry] });
reply(request(`/api/v2/datasets/canonical/${replacement.hash}`, 'GET'), {
dataset: replacementEntry,
});
});
expect(button('Save canonical setup').disabled).toBe(false);
await flush(() => click('Save canonical setup'));
expect(saves).toHaveLength(1);
expect(saves[0]).toMatchObject({
name: 'My edited draft',
initialCapital: 12345,
strategyParameters: { fastPeriod: 3, slowPeriod: 15 },
config: { datasetHash: replacement.hash, canonical: { feeRate: '0.00200000' } },
});
});
test('same-event file read then submit cannot save or close while preparation is active', async () => {
let saves = 0,
closes = 0;
await readySetup(
async () => {
saves++;
},
() => {
closes++;
}
);
const reading = deferred<string>();
await flush(() => {
upload({}, 'pending.json', reading.promise);
host
.querySelector('form')!
.dispatchEvent(
new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event
);
click('Back to draft settings');
});
expect(saves).toBe(0);
expect(closes).toBe(0);
await flush(() => reading.resolve(JSON.stringify(datasetInput())));
expect(button('Save canonical setup').disabled).toBe(true);
confirmWith(() => false);
await flush(() => click('Back to draft settings'));
expect(closes).toBe(0);
await flush(() => click('Clear source preparation'));
expect(button('Save canonical setup').disabled).toBe(false);
});
test('same-event parent save blocks file loading until save completes', async () => {
const saving = deferred<void>();
let saves = 0;
await readySetup(async () => {
saves++;
await saving.promise;
});
await flush(() => {
click('Save canonical setup');
upload();
});
expect(saves).toBe(1);
expect(host.textContent).not.toContain('Selected export');
expect(field('Source dataset JSON').disabled).toBe(true);
await flush(() => saving.resolve());
expect(field('Source dataset JSON').disabled).toBe(false);
});
for (const newId of [definition.id, 'other-backtest']) {
test(`parent ${newId} change fences retained result and resets preparation`, async () => {
const onSave = async () => {};
await readySetup(onSave);
await preview();
await flush(() => click('Retain dataset'));
const old = request(retainPath);
await flush(() =>
root!.render(
createElement(
router.MemoryRouter,
null,
createElement(CanonicalSetup, {
backtest: { ...definition, id: newId, name: 'Restored source' },
onSave,
})
)
)
);
await flush(() => reply(old, { preparation }));
expect(field('Backtest name').value).toBe('Restored source');
expect(field('Canonical dataset').value).toBe('');
expect(host.textContent).toContain('No source export selected.');
expect(host.textContent).not.toContain('Dataset retained.');
expect(
requests.filter(item => item.path === `/api/v2/datasets/canonical/${entry.hash}`)
).toHaveLength(1);
});
}
test('unavailable retention preserves previous selected hash and disabled Save until explicit clear', async () => {
await readySetup(async () => {});
const unavailable = {
...preparation,
hash: 'd'.repeat(64),
manifest: {
...preparation.manifest,
hash: 'd'.repeat(64),
eligibility: 'ineligible' as const,
},
available: false,
reason: 'Execution unsupported',
};
await preview(unavailable);
await flush(() => click('Retain dataset'));
await flush(() => reply(request(retainPath), { preparation: unavailable }));
expect(field('Canonical dataset').value).toBe(entry.hash);
expect(button('Save canonical setup').disabled).toBe(true);
await flush(() => {
reply(request('/api/v2/datasets/canonical', 'GET'), { datasets: [entry] });
reply(request(`/api/v2/datasets/canonical/${entry.hash}`, 'GET'), { dataset: entry });
});
expect(button('Save canonical setup').disabled).toBe(true);
await flush(() => click('Clear source preparation'));
expect(button('Save canonical setup').disabled).toBe(false);
});
});

View file

@ -0,0 +1,394 @@
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 type { IServiceContainer } from '@stock-bot/services';
import type { HistoricalDatasetInputV2 } from '@stock-bot/types';
import {
NativeReplaySession,
prepareReplayLoad,
runReplayConformance,
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
import {
createDatasetV2,
validateDatasetV2,
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { retainResearchDataset } from '../../apps/stock/orchestrator/src/data/retained-research-dataset';
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
import { readCanonicalDataset } from '../../apps/stock/web-api/src/services/canonical-research.service';
import {
previewDatasetPreparation,
retainDatasetPreparation,
} from '../../apps/stock/web-api/src/services/dataset-preparation.service';
import { retainResearchDataset as cliRetain } from '../../scripts/import-research-dataset';
import { datasetInput } from '../fixtures/historical-v2/dataset';
import { nativeReplayFixture } from '../fixtures/native-replay';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('dataset-source-preparation-test');
const tokens = {
admin: 'source-preparation-admin-fixture-123456789',
read: 'source-preparation-read-fixture-1234567890',
service: 'source-preparation-service-fixture-12345678',
};
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
const source = () => structuredClone(datasetInput()) as Mutable<HistoricalDatasetInputV2>;
function at<T>(values: readonly T[], index = 0): T {
const value = values[index];
if (value === undefined) {
throw new Error('Missing fixture item');
}
return value;
}
function fixture(
query: (
sql: string,
values?: unknown[]
) => Promise<{ rows: Record<string, unknown>[] }> = async () => {
throw new Error('Preview/rejected request reached storage');
}
) {
const database = { query: mock(query) };
const app = new Hono();
createHttpSecurity({
adminToken: tokens.admin,
serviceToken: tokens.service,
readToken: tokens.read,
environment: 'test',
hostname: '127.0.0.1',
browserSessions: true,
}).mount(app);
app.route(
'/',
createDatasetRoutes({ postgres: database, logger } as unknown as IServiceContainer)
);
const request = (
operation: 'preview' | 'retain',
body: unknown,
headers: Record<string, string> = { Authorization: `Bearer ${tokens.admin}` }
) =>
app.request(`/api/v2/datasets/canonical/${operation}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify(body),
});
return { app, database, request };
}
describe('explicit source-export preparation', () => {
test('preview is pure, stable under normalized permutation and preserves declared evidence without mutating input', async () => {
const f = fixture();
const input = source(),
before = structuredClone(input);
const reply = await f.request('preview', { input });
expect(reply.status).toBe(200);
expect(reply.headers.get('Cache-Control')).toBe('no-store');
const expected = previewDatasetPreparation({ input });
expect(await reply.json()).toEqual({ preparation: expected });
expect(expected).toMatchObject({
version: 'canonical-dataset-preparation/v1',
available: true,
reason: null,
});
expect(expected.manifest.series).toEqual(input.metadata.series);
expect(expected.manifest.calendars).toEqual(input.metadata.calendars);
expect(expected.manifest.universe).toEqual(input.metadata.universe);
expect(expected.manifest.corporateActions).toEqual(input.metadata.corporateActions);
expect(expected.manifest.parentDatasetHash).toBeNull();
expect(expected.manifest.limitations.some(value => value.includes('interval end'))).toBe(true);
expect(input).toEqual(before);
input.bars.reverse();
at(input.metadata.calendars).sessions.reverse();
const permuted = structuredClone(input);
expect(previewDatasetPreparation({ input })).toEqual(expected);
expect(input).toEqual(permuted);
expect(f.database.query).not.toHaveBeenCalled();
});
test('complete strict source validation rejects missing metadata, bad declarations, duplicate/invalid observations with actionable safe diagnostics', async () => {
const f = fixture();
const invalid: unknown[] = [
null,
{},
{ bars: source().bars },
{ metadata: source().metadata },
{ ...source(), extra: 'not permitted' },
];
const mutations: Array<(value: Mutable<HistoricalDatasetInputV2>) => void> = [
value => {
at(value.metadata.calendars).revision = '';
},
value => {
at(value.metadata.calendars).timeZone = 'private-invalid-timezone';
},
value => {
value.metadata.corporateActions = [];
},
value => {
at(value.metadata.series).source.revision = '';
},
value => {
at(value.metadata.series).availability = 'explicit';
},
value => {
value.bars.push({ ...at(value.bars) });
},
value => {
at(value.bars).high = 1;
},
value => {
at(value.bars).volume = -1;
},
value => {
at(value.bars).timestamp = '2024-03-09';
},
];
for (const change of mutations) {
const input = source();
change(input);
invalid.push(input);
}
for (const input of invalid) {
const response = await f.request('preview', { input });
expect(response.status).toBe(400);
expect(response.headers.get('Cache-Control')).toBe('no-store');
expect(await response.text()).not.toContain('private-invalid-timezone');
}
const missing = await f.request('preview', { input: { bars: [] } });
expect(await missing.text()).toContain('metadata');
const duplicate = source();
duplicate.bars.push({ ...at(duplicate.bars) });
expect(await (await f.request('preview', { input: duplicate })).text()).toContain(
'Duplicate or conflicting'
);
expect(f.database.query).not.toHaveBeenCalled();
});
test('preview availability exactly matches the existing workbench gate for valid exploratory, adjusted, known-action and multiasset datasets', async () => {
const variants: Array<(value: Mutable<HistoricalDatasetInputV2>) => void> = [
value => {
value.metadata.universe.selection = 'unknown';
value.metadata.universe.asOf = null;
},
value => {
at(value.metadata.corporateActions).status = 'unknown';
},
value => {
at(value.metadata.series).adjustment = 'provider-adjusted';
},
value => {
const coverage = at(value.metadata.corporateActions);
coverage.status = 'known-actions';
coverage.actions.push({
effectiveAt: value.metadata.bounds.tradeStart,
kind: 'split',
reference: 'operator-declared-action',
});
},
value => {
value.metadata.series.push({
...at(value.metadata.series),
id: 'B.US:daily:raw',
instrumentId: 'B.US',
});
value.metadata.executionSeries.push({ instrumentId: 'B.US', seriesId: 'B.US:daily:raw' });
value.metadata.universe.instrumentIds.push('B.US');
value.metadata.corporateActions.push({
...at(value.metadata.corporateActions),
instrumentId: 'B.US',
});
value.bars.push(...value.bars.map(bar => ({ ...bar, seriesId: 'B.US:daily:raw' })));
},
];
for (const mutate of variants) {
const input = source();
mutate(input);
const prepared = previewDatasetPreparation({ input });
expect(prepared.available).toBe(false);
expect(prepared.manifest).toEqual(createDatasetV2(input).manifest);
await expect(
readCanonicalDataset(
{ query: async () => ({ rows: [{ payload: createDatasetV2(input) }] }) },
prepared.hash
)
).rejects.toThrow(prepared.reason ?? 'missing reason');
const stored = new Map<string, unknown>();
const retained = await retainDatasetPreparation(
{
async query(sql, values) {
if (sql.startsWith('INSERT')) {
stored.set(String(values?.[0]), JSON.parse(String(values?.[1])));
return { rows: [] };
}
return { rows: [{ payload: stored.get(String(values?.[0])) }] };
},
},
{ input, expectedHash: prepared.hash }
);
expect(retained).toEqual(prepared);
}
});
test('retained explicit delay and missing VWAP survive normalization; native decisions cannot observe unpublished bars', async () => {
const f = nativeReplayFixture(5),
manifest = f.dataset.manifest;
const delayedAt = f.start + 2.5 * f.minute;
const input: HistoricalDatasetInputV2 = {
metadata: {
calendars: manifest.calendars,
series: manifest.series,
executionSeries: manifest.executionSeries,
bounds: manifest.bounds,
universe: manifest.universe,
corporateActions: manifest.corporateActions,
},
bars: f.dataset.bars.map(bar => ({
seriesId: bar.seriesId,
timestamp: bar.intervalStart,
sourceSequence: bar.sourceSequence,
availableAt: bar.sourceSequence === 0 ? delayedAt : bar.availableAt,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
})),
};
let stored: unknown;
const prepared = previewDatasetPreparation({ input });
await retainDatasetPreparation(
{
async query(sql, values) {
if (sql.startsWith('INSERT')) {
stored = JSON.parse(String(values?.[1]));
return { rows: [] };
}
return { rows: [{ payload: stored }] };
},
},
{ input, expectedHash: prepared.hash }
);
const retained = validateDatasetV2(stored);
expect(retained.bars.find(bar => bar.sourceSequence === 0)?.availableAt).toBe(delayedAt);
expect(retained.bars.every(bar => bar.vwap === null)).toBe(true);
expect(retained.manifest.series).toEqual(manifest.series);
const decisions: Array<{ at: number; sequence: number[] }> = [];
runReplayConformance(
new NativeReplaySession(prepareReplayLoad(retained, f.config)),
(_owner, context, observations) => {
expect(observations.every(bar => bar.available_at <= context.barrier.at)).toBe(true);
decisions.push({
at: context.barrier.at,
sequence: observations.map(bar => bar.source_sequence),
});
return { mode: 'target', targets: [] };
}
);
expect(decisions.some(decision => decision.at < delayedAt)).toBe(true);
expect(
decisions
.filter(decision => decision.at < delayedAt)
.every(decision => !decision.sequence.includes(0))
).toBe(true);
expect(
decisions.some(decision => decision.at >= delayedAt && decision.sequence.includes(0))
).toBe(true);
});
test('strict bodies, malformed JSON and hash drift reject before any write; errors are not cacheable', async () => {
const f = fixture(),
input = source(),
expectedHash = previewDatasetPreparation({ input }).hash;
for (const [operation, body] of [
['preview', {}],
['preview', { input, extra: true }],
['preview', { input, expectedHash }],
['retain', { input }],
['retain', { input, expectedHash: expectedHash.toUpperCase() }],
['retain', { input, expectedHash, extra: true }],
['retain', { input: null, expectedHash }],
] as const) {
const response = await f.request(operation, body);
expect(response.status).toBe(400);
expect(response.headers.get('Cache-Control')).toBe('no-store');
}
const mismatch = await f.request('retain', { input, expectedHash: '0'.repeat(64) });
expect(mismatch.status).toBe(409);
expect(mismatch.headers.get('Cache-Control')).toBe('no-store');
const malformed = await f.app.request('/api/v2/datasets/canonical/preview', {
method: 'POST',
headers: { Authorization: `Bearer ${tokens.admin}`, 'Content-Type': 'application/json' },
body: '{',
});
expect(malformed.status).toBe(400);
expect(f.database.query).not.toHaveBeenCalled();
});
test('storage exceptions and corrupt conflicting content fail as sanitized 500, never input errors or success', async () => {
const input = source(),
expectedHash = previewDatasetPreparation({ input }).hash;
for (const query of [
async () => {
throw new Error('private-storage-details');
},
async () => ({ rows: [{ payload: { private: 'private-storage-details' } }] }),
async () => ({ rows: [] }),
]) {
const response = await fixture(query).request('retain', { input, expectedHash });
expect(response.status).toBe(500);
expect(response.headers.get('Cache-Control')).toBe('no-store');
expect(await response.text()).not.toContain('private-storage-details');
}
});
test('existing mounted global auth rejects read tokens and protects browser mutations with trusted Origin', async () => {
const input = source(),
expectedHash = previewDatasetPreparation({ input }).hash;
const stored = createDatasetV2(input);
const f = fixture(async () => ({ rows: [{ payload: stored }] }));
for (const operation of ['preview', 'retain'] as const) {
const body = operation === 'preview' ? { input } : { input, expectedHash };
expect((await f.request(operation, body, {})).status).toBe(401);
expect(
(await f.request(operation, body, { Authorization: `Bearer ${tokens.read}` })).status
).toBe(403);
}
const login = await f.app.request('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: 'http://localhost' },
body: JSON.stringify({ token: tokens.admin }),
});
expect(login.status).toBe(200);
const cookie = login.headers.get('Set-Cookie')?.split(';')[0];
if (!cookie) {
throw new Error('Missing authenticated browser session');
}
for (const operation of ['preview', 'retain'] as const) {
const body = operation === 'preview' ? { input } : { input, expectedHash };
expect((await f.request(operation, body, { Cookie: cookie })).status).toBe(403);
expect(
(await f.request(operation, body, { Cookie: cookie, Origin: 'https://foreign.invalid' }))
.status
).toBe(403);
}
expect(f.database.query).not.toHaveBeenCalled();
expect(
(await f.request('preview', { input }, { Cookie: cookie, Origin: 'http://localhost' })).status
).toBe(200);
expect(f.database.query).not.toHaveBeenCalled();
expect(
(
await f.request(
'retain',
{ input, expectedHash },
{ Cookie: cookie, Origin: 'http://localhost' }
)
).status
).toBe(200);
expect(f.database.query).toHaveBeenCalledTimes(2);
});
test('existing CLI imports reexport the same retained custody helper without executing the CLI', () => {
expect(cliRetain).toBe(retainResearchDataset);
});
});

View file

@ -0,0 +1,307 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import {
createDatasetV2,
validateDatasetV2,
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
import { readCanonicalDataset } from '../../apps/stock/web-api/src/services/canonical-research.service';
import { previewDatasetPreparation } from '../../apps/stock/web-api/src/services/dataset-preparation.service';
import { datasetInput } from '../fixtures/historical-v2/dataset';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('source-preparation-postgres');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: Array<() => Promise<void>> = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
function at<T>(values: readonly T[], index = 0): T {
const value = values[index];
if (value === undefined) {
throw new Error('Missing fixture item');
}
return value;
}
async function fixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
max: 4,
application_name: schema,
options: `-c search_path=${schema} -c statement_timeout=10000`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
for (const name of [
'06-create-backtest-tables.sql',
'08-create-runs-table.sql',
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'12-historical-datasets.sql',
'14-backtest-submission.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
'20-research-workspace.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
);
}
await pool.query(`INSERT INTO backtests(name,strategy,symbols,start_date,end_date,initial_capital,config)
VALUES('untouched legacy draft','sma-crossover','["A.US"]','2024-03-01','2024-04-01',1000,'{"fastPeriod":2,"slowPeriod":3}')`);
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
let queryCount = 0;
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', {
value: async (sql: string, values?: unknown[]) => {
queryCount++;
return pool.query(sql, values);
},
});
const routes = new Hono().route('/', createDatasetRoutes({ postgres, logger }));
const post = (operation: 'preview' | 'retain', body: unknown) =>
routes.request(`/api/v2/datasets/canonical/${operation}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const snapshot = async (includeDatasets = true) => {
const tables = (
await pool.query<{ tablename: string }>(
'SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename',
[schema]
)
).rows;
const rows: Record<string, unknown> = {};
for (const { tablename } of tables) {
if (includeDatasets || tablename !== 'backtest_datasets') {
rows[tablename] = (
await pool.query(
`SELECT to_jsonb(t) AS row FROM "${tablename}" t ORDER BY to_jsonb(t)::text`
)
).rows;
}
}
return rows;
};
const defaults = async () =>
(
await pool.query(
`SELECT table_name,column_name,column_default FROM information_schema.columns WHERE table_schema=$1 ORDER BY table_name,column_name`,
[schema]
)
).rows;
return {
pool,
schema,
post,
routes,
snapshot,
defaults,
get queryCount() {
return queryCount;
},
};
}
describe.skipIf(!url)('source-export preparation with retained PostgreSQL custody', () => {
test('preview, invalid input and drift write nothing; retain only adds exact normalized dataset, leaving runs/outbox/templates/schema defaults untouched', async () => {
const f = await fixture(),
input = datasetInput();
const before = await f.snapshot(),
defaults = await f.defaults();
const preview = await f.post('preview', { input });
expect(preview.status).toBe(200);
expect(f.queryCount).toBe(0);
const prepared = previewDatasetPreparation({ input });
expect(await preview.json()).toEqual({ preparation: prepared });
expect((await f.post('retain', { input, expectedHash: '0'.repeat(64) })).status).toBe(409);
expect((await f.post('retain', { input: {}, expectedHash: prepared.hash })).status).toBe(400);
expect(f.queryCount).toBe(0);
expect(await f.snapshot()).toEqual(before);
const retained = await f.post('retain', { input, expectedHash: prepared.hash });
expect(retained.status).toBe(200);
expect(await retained.json()).toEqual({ preparation: prepared });
const stored = at((await f.pool.query('SELECT hash,payload FROM backtest_datasets')).rows);
expect(stored.hash).toBe(prepared.hash);
expect(stored.payload).toEqual(createDatasetV2(input));
expect(validateDatasetV2(stored.payload).bars.map(bar => bar.vwap)).toEqual([null, 101, null]);
const { backtest_datasets: _datasets, ...unchanged } = before;
expect(await f.snapshot(false)).toEqual(unchanged);
expect(await f.defaults()).toEqual(defaults);
expect((await f.pool.query('SELECT count(*) AS n FROM runs')).rows).toEqual([{ n: '0' }]);
expect((await f.pool.query('SELECT count(*) AS n FROM backtest_dispatch')).rows).toEqual([
{ n: '0' },
]);
const found = await f.routes.request(`/api/v2/datasets/canonical/${prepared.hash}`);
expect(found.status).toBe(200);
expect((await found.json()).dataset).toMatchObject({
hash: prepared.hash,
manifest: prepared.manifest,
available: true,
reason: null,
});
});
test('concurrent and repeated exact retention is content idempotent with one frozen row and unchanged created_at', async () => {
const f = await fixture(),
input = datasetInput();
const expected = previewDatasetPreparation({ input });
const body = { input, expectedHash: expected.hash };
const replies = await Promise.all(Array.from({ length: 6 }, () => f.post('retain', body)));
for (const reply of replies) {
expect(reply.status).toBe(200);
expect(await reply.json()).toEqual({ preparation: expected });
}
const before = (await f.pool.query('SELECT * FROM backtest_datasets')).rows;
expect(before).toHaveLength(1);
const repeat = await f.post('retain', body);
expect(repeat.status).toBe(200);
expect(await repeat.json()).toEqual({ preparation: expected });
const permuted = { ...input, bars: [...input.bars].reverse() };
expect((await f.post('retain', { input: permuted, expectedHash: expected.hash })).status).toBe(
200
);
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toEqual(before);
await expect(
f.pool.query('UPDATE backtest_datasets SET payload=$1 WHERE hash=$2', [
{ corrupt: true },
expected.hash,
])
).rejects.toThrow();
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toEqual(before);
});
test('valid unavailable source evidence may be retained but remains rejected by the existing picker and execution gate', async () => {
const f = await fixture(),
original = datasetInput();
const input = {
...original,
metadata: {
...original.metadata,
universe: { ...original.metadata.universe, selection: 'unknown' as const, asOf: null },
},
};
const prepared = previewDatasetPreparation({ input });
expect(prepared.available).toBe(false);
expect(prepared.manifest.eligibility).toBe('exploratory');
expect((await f.post('retain', { input, expectedHash: prepared.hash })).status).toBe(200);
expect(
validateDatasetV2(
at((await f.pool.query('SELECT payload FROM backtest_datasets')).rows).payload
).manifest
).toEqual(prepared.manifest);
const lookup = await f.routes.request(`/api/v2/datasets/canonical/${prepared.hash}`);
expect((await lookup.json()).dataset).toMatchObject({
available: false,
reason: prepared.reason,
});
await expect(readCanonicalDataset(f.pool, prepared.hash)).rejects.toThrow(
prepared.reason ?? 'missing reason'
);
expect((await f.pool.query('SELECT count(*) AS n FROM runs')).rows).toEqual([{ n: '0' }]);
});
test('a conflicting retained row with structurally valid but hash-corrupted bars fails full readback as sanitized500 and is never overwritten', async () => {
const f = await fixture(),
input = datasetInput(),
dataset = createDatasetV2(input);
const corrupt = {
...dataset,
bars: dataset.bars.map((bar, index) => (index === 0 ? { ...bar, close: 106 } : bar)),
};
expect(corrupt).not.toEqual(dataset);
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [
dataset.manifest.hash,
corrupt,
]);
const before = await f.snapshot();
const response = await f.post('retain', { input, expectedHash: dataset.manifest.hash });
expect(response.status).toBe(500);
expect(response.headers.get('Cache-Control')).toBe('no-store');
expect(await response.json()).toEqual({ error: 'Source dataset retention unavailable' });
expect(await f.snapshot()).toEqual(before);
await expect(readCanonicalDataset(f.pool, dataset.manifest.hash)).rejects.toThrow(
'content validation'
);
});
test('existing --file CLI retains the same v2 identity and safely repeats against the web-prepared row', 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[]) => {
const child = Bun.spawn(
[process.execPath, 'run', 'scripts/import-research-dataset.ts', ...args],
{
cwd: new URL('../../', import.meta.url).pathname,
env: { ...process.env, RESEARCH_DATASET_DATABASE_URL: connection.toString() },
stdout: 'pipe',
stderr: 'pipe',
}
);
const [code, out, err] = await Promise.all([
child.exited,
new Response(child.stdout).text(),
new Response(child.stderr).text(),
]);
return { code, out, err };
};
expect((await f.post('retain', { input, expectedHash: dataset.manifest.hash })).status).toBe(
200
);
const before = await f.snapshot();
const cli = await execute(['--file', file]);
expect(cli.code).toBe(0);
expect(JSON.parse(cli.out)).toEqual({
hash: dataset.manifest.hash,
barCount: dataset.manifest.barCount,
eligibility: dataset.manifest.eligibility,
limitations: dataset.manifest.limitations,
});
expect(await f.snapshot()).toEqual(before);
const flags = await execute(['--source-hash', dataset.manifest.hash]);
expect(flags.code).toBe(1);
expect(flags.err).toContain('Usage:');
await writeFile(file, JSON.stringify(input));
expect((await execute(['--file', file])).code).toBe(1);
expect(await f.snapshot()).toEqual(before);
});
});