From 67ab30cb7a578591262cb0218fa9f6a135924c7f Mon Sep 17 00:00:00 2001
From: Boki
Date: Sat, 24 Oct 2026 11:23:45 -0400
Subject: [PATCH] feat(research): preview chronological validation inputs and
windows
---
apps/stock/config/package.json | 4 +
.../src/contracts/chronological-validation.ts | 75 +++
.../src/data/historical-dataset-v2.ts | 40 ++
.../web-api/src/routes/experiments.routes.ts | 5 +
.../services/canonical-research.service.ts | 30 +-
.../src/services/canonical-risk-clock.ts | 30 +
.../src/services/experiments.service.ts | 10 +
.../src/services/validation-preview.ts | 177 +++++
.../ChronologicalValidationPreflight.tsx | 373 +++++++++++
.../components/ExperimentEditor.tsx | 20 +-
.../services/chronologicalValidationApi.ts | 158 +++++
.../experiments/services/experimentApi.ts | 6 +-
docs/development/ROADMAP.md | 18 +-
docs/development/backlog/README.md | 6 +-
docs/development/backlog/manifest.json | 154 ++++-
docs/development/backlog/tasks/R06.md | 4 +-
docs/development/backlog/tasks/R07.md | 2 +-
docs/development/backlog/tasks/R08.md | 16 +
test/e2e/workbench.test.ts | 130 ++++
test/fixtures/chronological-validation.ts | 43 ++
.../chronological-validation-api.test.ts | 137 ++++
.../chronological-validation-native.test.ts | 156 +++++
.../chronological-validation-ui.test.tsx | 621 ++++++++++++++++++
.../chronological-validation.test.ts | 423 ++++++++++++
.../postgres/chronological-validation.test.ts | 333 ++++++++++
25 files changed, 2917 insertions(+), 54 deletions(-)
create mode 100644 apps/stock/config/src/contracts/chronological-validation.ts
create mode 100644 apps/stock/web-api/src/services/canonical-risk-clock.ts
create mode 100644 apps/stock/web-api/src/services/validation-preview.ts
create mode 100644 apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx
create mode 100644 apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts
create mode 100644 test/fixtures/chronological-validation.ts
create mode 100644 test/integration/chronological-validation-api.test.ts
create mode 100644 test/integration/chronological-validation-native.test.ts
create mode 100644 test/integration/chronological-validation-ui.test.tsx
create mode 100644 test/integration/chronological-validation.test.ts
create mode 100644 test/postgres/chronological-validation.test.ts
diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json
index 881c32fa..769dc0c5 100644
--- a/apps/stock/config/package.json
+++ b/apps/stock/config/package.json
@@ -32,6 +32,10 @@
"./experiments": {
"types": "./dist/contracts/experiments.d.ts",
"default": "./dist/contracts/experiments.js"
+ },
+ "./chronological-validation": {
+ "types": "./dist/contracts/chronological-validation.d.ts",
+ "default": "./dist/contracts/chronological-validation.js"
}
},
"scripts": {
diff --git a/apps/stock/config/src/contracts/chronological-validation.ts b/apps/stock/config/src/contracts/chronological-validation.ts
new file mode 100644
index 00000000..3cd4f239
--- /dev/null
+++ b/apps/stock/config/src/contracts/chronological-validation.ts
@@ -0,0 +1,75 @@
+/** Prepared inputs only: this contract does not admit runs or certify out-of-sample evidence. */
+import { z } from 'zod';
+import type { HistoricalDatasetManifestV2 } from '@stock-bot/types';
+import type { CanonicalRunRequest } from './canonical-research';
+import { experimentInputSchema, type ExperimentPreview } from './experiments';
+
+const instant = z.number().int().nonnegative().max(8_640_000_000_000_000);
+export const validationWindowSchema = z
+ .object({ warmupStart: instant, tradeStart: instant, tradeEnd: instant })
+ .strict()
+ .refine(value => value.warmupStart < value.tradeStart && value.tradeStart < value.tradeEnd, {
+ message: 'Each window requires warmupStart < tradeStart < tradeEnd',
+ });
+export const chronologicalValidationInputSchema = experimentInputSchema.extend({
+ recipe: z
+ .object({
+ version: z.literal(1),
+ train: validationWindowSchema,
+ validation: validationWindowSchema,
+ test: validationWindowSchema,
+ /** Fitted models and nonzero prediction horizons need a future fit/purge contract. */
+ labelHorizonMs: z.literal(0),
+ })
+ .strict()
+ .refine(
+ value =>
+ value.train.tradeEnd <= value.validation.tradeStart &&
+ value.validation.tradeEnd <= value.test.tradeStart,
+ { message: 'Evaluation windows must be chronological and nonoverlapping' }
+ ),
+});
+export type ChronologicalValidationInput = z.infer;
+export type ValidationPhase = 'train' | 'validation' | 'test';
+export interface ValidationPartitionPreview {
+ phase: ValidationPhase;
+ dataset: HistoricalDatasetManifestV2;
+ /** Preview identity only. A later durable admission must allocate run/account identities. */
+ request: CanonicalRunRequest;
+ counts: {
+ totalBars: number;
+ availableWarmup: number;
+ admittedWarmup: number;
+ ignoredLateWarmup: number;
+ availableEvaluation: number;
+ terminalAtEnd: number;
+ unavailableAtEnd: number;
+ };
+ /** Maximum required history over every candidate, measured in admitted observations. */
+ requiredWarmup: number;
+ warnings: string[];
+}
+export const chronologicalValidationPolicy = {
+ selection: {
+ phase: 'train',
+ metric: 'totalReturn',
+ direction: 'maximize',
+ tieBreak: 'candidate-index',
+ requireAllCandidates: true,
+ },
+ validationRole: 'diagnostic-only',
+ testRole: 'holdout-only',
+ reset: 'initial-capital-empty-positions',
+ model: 'deterministic-unfitted',
+ readiness: 'input-checks-only',
+} as const;
+export interface ChronologicalValidationPreview {
+ version: 'chronological-validation-preview/v1';
+ execution: 'preview-only';
+ previewHash: string;
+ input: ChronologicalValidationInput;
+ /** Source lineage lives here; dataset parentDatasetHash retains its legacy-v1 meaning. */
+ source: ExperimentPreview;
+ policy: typeof chronologicalValidationPolicy;
+ partitions: [ValidationPartitionPreview, ValidationPartitionPreview, ValidationPartitionPreview];
+}
diff --git a/apps/stock/orchestrator/src/data/historical-dataset-v2.ts b/apps/stock/orchestrator/src/data/historical-dataset-v2.ts
index 0d091be7..a82a16d6 100644
--- a/apps/stock/orchestrator/src/data/historical-dataset-v2.ts
+++ b/apps/stock/orchestrator/src/data/historical-dataset-v2.ts
@@ -554,6 +554,46 @@ export function validateDatasetV2(input: unknown): HistoricalDatasetV2 {
return dataset;
}
+/** Exact retained v2 interval slice. V2 lineage belongs to the caller's manifest;
+ * parentDatasetHash continues to describe only the original legacy-v1 conversion. */
+export function sliceDatasetV2(
+ input: unknown,
+ boundsInput: HistoricalDatasetMetadataV2['bounds']
+): HistoricalDatasetV2 {
+ const source = validateDatasetV2(input);
+ const bounds = metadataSchema.shape.bounds.parse(boundsInput);
+ if (
+ bounds.warmupStart < source.manifest.bounds.warmupStart ||
+ bounds.tradeStart < source.manifest.bounds.tradeStart ||
+ bounds.tradeEnd > source.manifest.bounds.tradeEnd
+ ) {
+ throw new Error('Slice bounds must remain within the source warmup and evaluation bounds');
+ }
+ for (const boundary of [bounds.warmupStart, bounds.tradeStart, bounds.tradeEnd]) {
+ if (source.bars.some(bar => bar.intervalStart < boundary && boundary < bar.intervalEnd)) {
+ throw new Error('Slice boundaries cannot cut through a retained bar interval');
+ }
+ }
+ const {
+ version: _version,
+ hash: _hash,
+ normalizationRevision: _revision,
+ parentDatasetHash,
+ volumePolicy: _volume,
+ qualityPolicy: _quality,
+ intradayPolicy: _intraday,
+ eligibility: _eligibility,
+ limitations: _limitations,
+ barCount: _count,
+ ...rawMetadata
+ } = source.manifest;
+ const metadata = parseMetadata({ ...rawMetadata, bounds });
+ const bars = source.bars.filter(
+ bar => bar.intervalStart >= bounds.warmupStart && bar.intervalEnd <= bounds.tradeEnd
+ );
+ return finish(metadata, validateBars(metadata, bars), parentDatasetHash);
+}
+
/** Unknown coverage remains exploratory; this assertion does not certify economic correctness. */
export function assertDatasetV2Executable(input: unknown): HistoricalDatasetV2 {
const dataset = validateDatasetV2(input);
diff --git a/apps/stock/web-api/src/routes/experiments.routes.ts b/apps/stock/web-api/src/routes/experiments.routes.ts
index ec7065ec..6972ed5e 100644
--- a/apps/stock/web-api/src/routes/experiments.routes.ts
+++ b/apps/stock/web-api/src/routes/experiments.routes.ts
@@ -12,6 +12,7 @@ import {
} from '../services/experiment-input';
import { parseExperimentRetry } from '../services/experiment-retry';
import { ExperimentsService } from '../services/experiments.service';
+import { parseChronologicalValidation } from '../services/validation-preview';
/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */
export function createExperimentRoutes(container: IServiceContainer) {
@@ -42,6 +43,10 @@ export function createExperimentRoutes(container: IServiceContainer) {
throw new ExperimentError(400, 'Invalid JSON request');
}
};
+ app.post('/api/v2/experiments/validation/preview', async c => {
+ const input = parseChronologicalValidation(await body(c.req.raw));
+ return c.json({ preview: await service.previewValidation(input) });
+ });
app.post('/api/v2/experiments/preview', async c => {
const input = parseExperimentInput(await body(c.req.raw));
return c.json({ preview: await service.preview(input) });
diff --git a/apps/stock/web-api/src/services/canonical-research.service.ts b/apps/stock/web-api/src/services/canonical-research.service.ts
index 2b087281..a6e01309 100644
--- a/apps/stock/web-api/src/services/canonical-research.service.ts
+++ b/apps/stock/web-api/src/services/canonical-research.service.ts
@@ -16,6 +16,7 @@ import {
} from '@stock-bot/types';
import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build';
import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
+import { canonicalRiskSessionClock } from './canonical-risk-clock';
import type { DatasetCatalogQuery } from './dataset-catalog.service';
import { StrategyCatalogService } from './strategy-catalog.service';
@@ -179,27 +180,8 @@ export async function admitCanonicalRequest(
template.strategyVersionId,
client
);
- const { settings, dataset, execution, series, initial } = await validateCanonicalSetup(
- client,
- template
- );
- const calendar = dataset.manifest.calendars.find(item => item.id === series.calendarId);
- if (!calendar) {
- return invalid('Retained dataset is missing its execution calendar');
- }
- const { warmupStart, tradeEnd } = dataset.manifest.bounds;
- const initialSession = calendar.sessions.filter(session => session.open <= warmupStart).at(-1);
- if (!initialSession) {
- return invalid('Retained calendar needs an account-session opening at or before warmup start');
- }
- // The account resets at this retained calendar's opens. This declared clock is
- // distinct from venue order expiry; its identity and every boundary are frozen.
- const riskSession = (session: typeof initialSession) => ({
- calendarId: calendar.id,
- calendarRevision: calendar.revision,
- sessionId: session.date,
- startsAt: session.open,
- });
+ const { settings, dataset, execution, initial } = await validateCanonicalSetup(client, template);
+ const clock = canonicalRiskSessionClock(dataset);
const ownerId = `strategy:${template.strategyVersionId}`;
const selection = builtinStrategySelectionSchema.parse({
strategyId: pkg.program.strategyId,
@@ -237,7 +219,7 @@ export async function admitCanonicalRequest(
reserveOwnerId: 'reserve',
ownerIds: [ownerId],
initialCapital: initial,
- riskSession: riskSession(initialSession),
+ riskSession: clock.riskSession,
},
feeRate: settings.feeRate,
maxOrderQuantity: settings.maxOrderQuantity,
@@ -257,9 +239,7 @@ export async function admitCanonicalRequest(
participation_rate: settings.participationRate,
cadence: [{ owner_id: ownerId, series_ids: [execution.seriesId] }],
allow_exploratory: false,
- risk_boundaries: calendar.sessions
- .filter(session => session.open > warmupStart && session.open <= tradeEnd)
- .map(riskSession),
+ risk_boundaries: clock.riskBoundaries,
},
analyticsPolicy: {
version: 1,
diff --git a/apps/stock/web-api/src/services/canonical-risk-clock.ts b/apps/stock/web-api/src/services/canonical-risk-clock.ts
new file mode 100644
index 00000000..dd02b858
--- /dev/null
+++ b/apps/stock/web-api/src/services/canonical-risk-clock.ts
@@ -0,0 +1,30 @@
+import { HistoricalDataRequestError, type HistoricalDatasetV2 } from '@stock-bot/types';
+
+/** The account clock is retained calendar data, independent of venue order expiry. */
+export function canonicalRiskSessionClock(dataset: HistoricalDatasetV2) {
+ const execution = dataset.manifest.executionSeries[0];
+ const series = dataset.manifest.series.find(item => item.id === execution?.seriesId);
+ const calendar = dataset.manifest.calendars.find(item => item.id === series?.calendarId);
+ if (!calendar) {
+ throw new HistoricalDataRequestError('Retained dataset is missing its execution calendar');
+ }
+ const { warmupStart, tradeEnd } = dataset.manifest.bounds;
+ const initialSession = calendar.sessions.filter(session => session.open <= warmupStart).at(-1);
+ if (!initialSession) {
+ throw new HistoricalDataRequestError(
+ 'Retained calendar needs an account-session opening at or before warmup start'
+ );
+ }
+ const riskSession = (session: typeof initialSession) => ({
+ calendarId: calendar.id,
+ calendarRevision: calendar.revision,
+ sessionId: session.date,
+ startsAt: session.open,
+ });
+ return {
+ riskSession: riskSession(initialSession),
+ riskBoundaries: calendar.sessions
+ .filter(session => session.open > warmupStart && session.open <= tradeEnd)
+ .map(riskSession),
+ };
+}
diff --git a/apps/stock/web-api/src/services/experiments.service.ts b/apps/stock/web-api/src/services/experiments.service.ts
index 18f87d58..d299da10 100644
--- a/apps/stock/web-api/src/services/experiments.service.ts
+++ b/apps/stock/web-api/src/services/experiments.service.ts
@@ -30,6 +30,7 @@ import {
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
import { StrategyCatalogError } from './strategy-catalog.service';
+import { parseChronologicalValidation, prepareChronologicalValidation } from './validation-preview';
interface Query {
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
@@ -108,6 +109,15 @@ export class ExperimentsService {
const input = parseExperimentInput(raw);
return this.database.transaction(client => this.lockedPreview(client, input));
}
+ async previewValidation(raw: unknown) {
+ const input = parseChronologicalValidation(raw);
+ const { recipe: _recipe, ...sourceInput } = input;
+ return this.database.transaction(async client => {
+ const source = await this.lockedPreview(client, sourceInput);
+ const dataset = await readCanonicalDataset(client, source.request.datasetHash);
+ return prepareChronologicalValidation(input, source, dataset).preview;
+ });
+ }
private async lockedPreview(
client: PoolClient,
input: ExperimentInput
diff --git a/apps/stock/web-api/src/services/validation-preview.ts b/apps/stock/web-api/src/services/validation-preview.ts
new file mode 100644
index 00000000..4de91a08
--- /dev/null
+++ b/apps/stock/web-api/src/services/validation-preview.ts
@@ -0,0 +1,177 @@
+import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
+import {
+ chronologicalValidationInputSchema,
+ chronologicalValidationPolicy,
+ type ChronologicalValidationInput,
+ type ChronologicalValidationPreview,
+ type ValidationPartitionPreview,
+ type ValidationPhase,
+} from '@stock-bot/stock-config/chronological-validation';
+import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
+import {
+ assertStrategyJsonText,
+ builtinStrategySelectionSchema,
+ canonicalStrategyJson,
+} from '@stock-bot/stock-config/strategy';
+import type { HistoricalDatasetV2 } from '@stock-bot/types';
+import {
+ sliceDatasetV2,
+ validateDatasetV2,
+} from '../../../orchestrator/src/data/historical-dataset-v2';
+import { canonicalRiskSessionClock } from './canonical-risk-clock';
+import { ExperimentError, experimentHash, retainedExperimentPreview } from './experiment-input';
+
+export function parseChronologicalValidation(input: unknown): ChronologicalValidationInput {
+ try {
+ assertStrategyJsonText(input);
+ return chronologicalValidationInputSchema.parse(input);
+ } catch (error) {
+ throw new ExperimentError(
+ 400,
+ `Invalid chronological validation input: ${error instanceof Error ? error.message : 'validation failed'}`
+ );
+ }
+}
+function requiredHistory(source: ExperimentPreview): number {
+ return Math.max(
+ ...source.candidates.map(candidate => {
+ const selection = builtinStrategySelectionSchema.parse({
+ ...source.request.strategy.selection,
+ parameters: candidate.parameters,
+ });
+ if (selection.strategyId === 'sma_crossover') {
+ return selection.parameters.slowPeriod + 1;
+ }
+ const p = selection.parameters;
+ return Math.max(
+ p.lookbackPeriod,
+ p.trendPeriod,
+ p.momentumPeriod + 1,
+ p.volatilityPeriod + 1
+ );
+ })
+ );
+}
+/** Prepares data and request identities only. It neither executes nor chooses a candidate. */
+export function prepareChronologicalValidation(
+ raw: ChronologicalValidationInput,
+ sourcePreview: ExperimentPreview,
+ sourceDataset: HistoricalDatasetV2
+): {
+ preview: ChronologicalValidationPreview;
+ datasets: Record;
+} {
+ const input = parseChronologicalValidation(raw);
+ const source = retainedExperimentPreview(sourcePreview);
+ const dataset = validateDatasetV2(sourceDataset);
+ const { recipe: _recipe, ...sourceInput } = input;
+ if (
+ canonicalStrategyJson(source.input) !== canonicalStrategyJson(sourceInput) ||
+ source.request.datasetHash !== dataset.manifest.hash ||
+ canonicalStrategyJson(source.dataset) !== canonicalStrategyJson(dataset.manifest)
+ ) {
+ throw new Error('Validation source input or retained dataset identity mismatch');
+ }
+ if (
+ dataset.manifest.eligibility !== 'eligible' ||
+ dataset.manifest.series.length !== 1 ||
+ dataset.manifest.executionSeries.length !== 1 ||
+ dataset.manifest.universe.instrumentIds.length !== 1
+ ) {
+ throw new ExperimentError(
+ 409,
+ 'Validation requires one eligible retained execution asset and series'
+ );
+ }
+ const requiredWarmup = requiredHistory(source);
+ const datasets = {} as Record;
+ const phases = ['train', 'validation', 'test'] as const;
+ const partitions = phases.map(phase => {
+ let partition;
+ try {
+ partition = sliceDatasetV2(dataset, input.recipe[phase]);
+ } catch (error) {
+ throw new ExperimentError(
+ 400,
+ `${phase}: ${error instanceof Error ? error.message : 'invalid slice'}`
+ );
+ }
+ datasets[phase] = partition;
+ const { tradeStart, tradeEnd } = partition.manifest.bounds;
+ const warmup = partition.bars.filter(bar => bar.availableAt < tradeStart);
+ let previous: { eventTime: number; sourceSequence: number } | undefined;
+ let admittedWarmup = 0;
+ for (const bar of warmup) {
+ if (
+ previous &&
+ (bar.eventTime < previous.eventTime ||
+ (bar.eventTime === previous.eventTime && bar.sourceSequence <= previous.sourceSequence))
+ ) {
+ continue;
+ }
+ previous = bar;
+ admittedWarmup++;
+ }
+ const counts = {
+ totalBars: partition.bars.length,
+ availableWarmup: warmup.length,
+ admittedWarmup,
+ ignoredLateWarmup: warmup.length - admittedWarmup,
+ availableEvaluation: partition.bars.filter(
+ bar => bar.availableAt >= tradeStart && bar.availableAt < tradeEnd
+ ).length,
+ terminalAtEnd: partition.bars.filter(bar => bar.availableAt === tradeEnd).length,
+ unavailableAtEnd: partition.bars.filter(bar => bar.availableAt > tradeEnd).length,
+ };
+ if (counts.admittedWarmup < requiredWarmup) {
+ throw new ExperimentError(
+ 400,
+ `${phase}: ${counts.admittedWarmup} admitted warmup observations; ${requiredWarmup} required across the candidate grid (${counts.availableWarmup} available, ${counts.ignoredLateWarmup} ignored late)`
+ );
+ }
+ if (counts.availableEvaluation === 0) {
+ throw new ExperimentError(
+ 400,
+ `${phase}: no observations are available inside the evaluation window`
+ );
+ }
+ const warnings: string[] = [];
+ if (counts.unavailableAtEnd) {
+ warnings.push(
+ `${counts.unavailableAtEnd} completed-bar observations arrive after the evaluation end and cannot inform decisions or terminal marks`
+ );
+ }
+ if (counts.ignoredLateWarmup) {
+ warnings.push(
+ `${counts.ignoredLateWarmup} late warmup observations are ignored by the retained strategy ordering`
+ );
+ }
+ if (counts.availableEvaluation < requiredWarmup) {
+ warnings.push(
+ `Only ${counts.availableEvaluation} evaluation observations; input readiness does not establish statistical adequacy`
+ );
+ }
+ const clock = canonicalRiskSessionClock(partition);
+ const request = structuredClone(source.request);
+ request.datasetHash = partition.manifest.hash;
+ request.policy.matching.risk.ledger.riskSession = clock.riskSession;
+ request.policy.risk_boundaries = clock.riskBoundaries;
+ return {
+ phase,
+ dataset: partition.manifest,
+ request: canonicalRunRequestSchema.parse(request),
+ counts,
+ requiredWarmup,
+ warnings,
+ } satisfies ValidationPartitionPreview;
+ }) as [ValidationPartitionPreview, ValidationPartitionPreview, ValidationPartitionPreview];
+ const manifest = {
+ version: 'chronological-validation-preview/v1' as const,
+ execution: 'preview-only' as const,
+ input,
+ source,
+ policy: chronologicalValidationPolicy,
+ partitions,
+ };
+ return { preview: { ...manifest, previewHash: experimentHash(manifest) }, datasets };
+}
diff --git a/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx b/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx
new file mode 100644
index 00000000..d6364583
--- /dev/null
+++ b/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx
@@ -0,0 +1,373 @@
+import { useEffect, useRef, useState } from 'react';
+import { z } from 'zod';
+import {
+ chronologicalValidationInputSchema,
+ type ValidationPhase,
+} from '@stock-bot/stock-config/chronological-validation';
+import { Button } from '@/components/ui/Button';
+import {
+ chronologicalValidationApi,
+ type ChronologicalValidationPreviewView,
+} from '../services/chronologicalValidationApi';
+
+const phases = ['train', 'validation', 'test'] as const;
+const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
+const labels = {
+ warmupStart: 'warmup start',
+ tradeStart: 'trading start',
+ tradeEnd: 'trading end',
+};
+const phaseLabels = { train: 'Train', validation: 'Validation', test: 'Test' };
+type Windows = Record>;
+const empty = (): Windows => ({
+ train: { warmupStart: '', tradeStart: '', tradeEnd: '' },
+ validation: { warmupStart: '', tradeStart: '', tradeEnd: '' },
+ test: { warmupStart: '', tradeStart: '', tradeEnd: '' },
+});
+const fieldClass =
+ 'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
+function parseInstant(raw: string, label: string) {
+ const text = raw.trim();
+ const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/.exec(text);
+ const value = Date.parse(text);
+ if (
+ !match ||
+ !Number.isFinite(value) ||
+ new Date(value).toISOString() !== `${match[1]}.${(match[2] ?? '').padEnd(3, '0')}Z`
+ ) {
+ throw new Error(
+ `${label} must be a real UTC instant ending in Z, for example 2024-01-01T09:00:00Z.`
+ );
+ }
+ return value;
+}
+const message = (cause: unknown) =>
+ cause instanceof z.ZodError
+ ? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
+ : cause instanceof Error
+ ? cause.message
+ : 'Could not prepare chronological validation inputs';
+
+export function ChronologicalValidationPreflight({
+ backtestId,
+ name,
+ grid,
+ disabled,
+ eligible,
+ onDirty,
+}: {
+ backtestId: string;
+ name: string;
+ grid: string;
+ disabled: boolean;
+ eligible: boolean;
+ onDirty: (dirty: boolean) => void;
+}) {
+ const [windows, setWindows] = useState(empty);
+ const [prepared, setPrepared] = useState<{
+ identity: string;
+ preview: ChronologicalValidationPreviewView;
+ } | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState('');
+ const generation = useRef(0);
+ const request = useRef(null);
+ const pending = useRef(false);
+ const alive = useRef(false);
+ const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible });
+ const currentIdentity = useRef(identity);
+ currentIdentity.current = identity;
+ const preview = prepared?.identity === identity ? prepared.preview : null;
+ const dirty = phases.some(phase => fields.some(field => windows[phase][field] !== ''));
+ useEffect(() => {
+ onDirty(dirty);
+ }, [dirty, onDirty]);
+ useEffect(() => {
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ generation.current++;
+ request.current?.abort();
+ };
+ }, []);
+ useEffect(() => {
+ generation.current++;
+ request.current?.abort();
+ pending.current = false;
+ setPrepared(null);
+ setLoading(false);
+ setError('');
+ }, [identity]);
+ const edit = (phase: ValidationPhase, field: (typeof fields)[number], value: string) => {
+ if (disabled) {
+ return;
+ }
+ generation.current++;
+ request.current?.abort();
+ setWindows(previous => ({ ...previous, [phase]: { ...previous[phase], [field]: value } }));
+ };
+ const prepare = async () => {
+ if (disabled || !eligible || pending.current) {
+ return;
+ }
+ const captured = identity;
+ const revision = ++generation.current;
+ request.current?.abort();
+ const controller = new AbortController();
+ request.current = controller;
+ pending.current = true;
+ setPrepared(null);
+ setError('');
+ setLoading(true);
+ try {
+ const bounds = (phase: ValidationPhase) =>
+ Object.fromEntries(
+ fields.map(field => [
+ field,
+ parseInstant(windows[phase][field], `${phaseLabels[phase]} ${labels[field]} (UTC)`),
+ ])
+ );
+ const input = chronologicalValidationInputSchema.parse({
+ backtestId,
+ name,
+ grid: JSON.parse(grid),
+ recipe: {
+ version: 1,
+ train: bounds('train'),
+ validation: bounds('validation'),
+ test: bounds('test'),
+ labelHorizonMs: 0,
+ },
+ });
+ const value = await chronologicalValidationApi.preview(input, controller.signal);
+ if (
+ alive.current &&
+ revision === generation.current &&
+ captured === currentIdentity.current
+ ) {
+ setPrepared({ identity: captured, preview: value });
+ }
+ } catch (cause) {
+ if (
+ alive.current &&
+ revision === generation.current &&
+ captured === currentIdentity.current
+ ) {
+ setError(message(cause));
+ }
+ } finally {
+ if (
+ alive.current &&
+ revision === generation.current &&
+ captured === currentIdentity.current
+ ) {
+ pending.current = false;
+ setLoading(false);
+ }
+ }
+ };
+ return (
+
+ Chronological validation preflight
+
+ Preview only. No datasets, experiments or runs are saved. Staged execution and immutable
+ reports are not available yet.
+
+
+ Uses the saved backtest, experiment name and parameter grid above. Enter explicit UTC
+ instants ending in Z; no local-time conversion or automatic date split is applied. Trading
+ windows exclude their end instant. Warmup may overlap earlier phases.
+
+
+ {phases.map(phase => (
+
+ {phaseLabels[phase]} window
+ {fields.map(field => (
+
+ {phaseLabels[phase]} {labels[field]} (UTC)
+ edit(phase, field, event.target.value)}
+ />
+
+ ))}
+
+ ))}
+
+ {disabled && (
+
+ Resolve or explicitly release the ordinary sweep submission before preparing chronological
+ inputs.
+
+ )}
+ void prepare()}
+ >
+ Preview chronological validation
+
+ {loading && Preparing chronological validation preview...
}
+ {error && (
+
+ {error}
+
+ )}
+ {!preview && !loading && !error && (
+
+ No chronological preview prepared for the current inputs.
+
+ )}
+ {preview && (
+
+
+ {preview.source.candidates.length} parameter candidates checked for input requirements.
+ No candidate has been selected or evaluated.
+
+
+
+
Source dataset
+ {preview.source.request.datasetHash}
+
+
+
Strategy version
+ {preview.source.request.strategy.versionId}
+
+
+
Initial capital / owner budget (USD)
+
+ {preview.source.request.policy.matching.risk.ledger.initialCapital} /{' '}
+ {preview.source.request.strategy.selection.ownerBudget}
+
+
+
+
Seed
+ {preview.source.request.strategy.selection.seed}
+
+
+
+ Planned selection: maximize train total return; ties use ascending candidate index.
+ Every train candidate must complete with a comparable, finite score before selection.
+ Validation is diagnostic only; test is holdout only. Neither may retune the selected
+ parameters.
+
+
+ Each phase resets to the same initial capital and empty positions, with warmed
+ indicators. Capital, costs, risk rules and seed stay unchanged. These are independent
+ reset segments, not a continuous portfolio equity curve.
+
+
+ Input checks only. Warmup sufficiency is not evidence of profitability or statistical
+ adequacy. Only deterministic, unfitted strategies with zero label horizon are supported.
+
+
+ {preview.partitions.map(part => (
+
+ {phaseLabels[part.phase]} partition
+
+
+
Prepared dataset hash
+ {part.dataset.hash}
+
+
+
Warmup start (UTC)
+ {new Date(part.dataset.bounds.warmupStart).toISOString()}
+
+
+
Trading start (UTC)
+ {new Date(part.dataset.bounds.tradeStart).toISOString()}
+
+
+
Trading end (UTC, exclusive)
+ {new Date(part.dataset.bounds.tradeEnd).toISOString()}
+
+
+
Total retained bars
+ {part.counts.totalBars}
+
+
+
Available before trading
+ {part.counts.availableWarmup}
+
+
+
Admitted warmup / required warmup
+
+ {part.counts.admittedWarmup} / {part.requiredWarmup}
+
+
+
+
Ignored late warmup observations
+ {part.counts.ignoredLateWarmup}
+
+
+
Available during evaluation
+ {part.counts.availableEvaluation}
+
+
+
Available exactly at end (terminal mark only)
+ {part.counts.terminalAtEnd}
+
+
+
Completed observations unavailable at end
+ {part.counts.unavailableAtEnd}
+
+
+ {part.warnings.map((warning, index) => (
+ {warning}
+ ))}
+
+ ))}
+
+
+
+ Exact chronological preview inputs and policies
+
+
+ {JSON.stringify(
+ {
+ previewHash: preview.previewHash,
+ input: preview.input,
+ policy: preview.policy,
+ sourcePreviewHash: preview.source.previewHash,
+ sourceDataset: preview.source.dataset,
+ strategyVersion: preview.source.request.strategy.versionId,
+ reviewId: preview.source.request.strategy.reviewId,
+ artifactHash: preview.source.request.strategy.package.artifact.sha256,
+ dependencyLockHash: preview.source.request.strategy.package.dependencyLock.sha256,
+ parameters: preview.source.candidates,
+ analyticsPolicy: preview.source.request.analyticsPolicy,
+ financialPolicy: preview.source.request.policy,
+ build: preview.source.request.build,
+ partitions: preview.partitions.map(part => ({
+ phase: part.phase,
+ dataset: part.dataset,
+ counts: part.counts,
+ requiredWarmup: part.requiredWarmup,
+ initialRiskSession: part.request.policy.matching.risk.ledger.riskSession,
+ riskBoundaries: part.request.policy.risk_boundaries,
+ })),
+ },
+ null,
+ 2
+ )}
+
+
+
+ )}
+
+ );
+}
diff --git a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx
index fefb84fa..eea5809f 100644
--- a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx
+++ b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx
@@ -14,6 +14,7 @@ import {
ExperimentApiError,
type ExperimentPreviewView,
} from '../services/experimentApi';
+import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
import { ExperimentInputs } from './ExperimentInputs';
const fieldClass =
@@ -63,7 +64,11 @@ export function ExperimentEditor({
const [error, setError] = useState('');
const [submitting, setSubmitting] = useState(false);
const [ambiguous, setAmbiguous] = useState(false);
- const dirty = hasIntent || Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
+ const [validationDirty, setValidationDirty] = useState(false);
+ const dirty =
+ hasIntent ||
+ validationDirty ||
+ Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
useUnsavedWarning(dirty);
useEffect(() => {
onDirty(dirty);
@@ -286,6 +291,11 @@ export function ExperimentEditor({
the unchanged parameters once. Maximum {MAX_EXPERIMENT_TRIALS} trials per experiment; this
does not promise concurrent execution.
+ Ordinary parameter sweep
+
+ Ordinary submission uses the template's retained window. Chronological preflight below does
+ not change or execute this sweep.
+
)}
+ item.id === backtestId)}
+ onDirty={setValidationDirty}
+ />
);
}
diff --git a/apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts
new file mode 100644
index 00000000..6f6381f5
--- /dev/null
+++ b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts
@@ -0,0 +1,158 @@
+import { z } from 'zod';
+import {
+ chronologicalValidationInputSchema,
+ chronologicalValidationPolicy,
+ type ChronologicalValidationInput,
+ type ChronologicalValidationPreview,
+ type ValidationPartitionPreview,
+} from '@stock-bot/stock-config/chronological-validation';
+import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
+import { API_BASE_URL, apiFetch } from '@/lib/api';
+import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
+
+export type ValidationPartitionView = Omit & {
+ dataset: ExperimentPreviewView['dataset'];
+};
+export type ChronologicalValidationPreviewView = Omit<
+ ChronologicalValidationPreview,
+ 'source' | 'partitions'
+> & {
+ source: ExperimentPreviewView;
+ partitions: [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
+};
+const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
+const counts = z.object({
+ totalBars: counter,
+ availableWarmup: counter,
+ admittedWarmup: counter,
+ ignoredLateWarmup: counter,
+ availableEvaluation: counter,
+ terminalAtEnd: counter,
+ unavailableAtEnd: counter,
+});
+const partition = z.object({
+ phase: z.enum(['train', 'validation', 'test']),
+ dataset: z.unknown(),
+ request: z.unknown(),
+ counts,
+ requiredWarmup: counter.positive(),
+ warnings: z.array(z.string()),
+});
+const prepared = z.object({
+ version: z.literal('chronological-validation-preview/v1'),
+ execution: z.literal('preview-only'),
+ previewHash: z.string().regex(/^[a-f0-9]{64}$/),
+ input: chronologicalValidationInputSchema,
+ source: z.unknown(),
+ policy: z.unknown(),
+ partitions: z.tuple([partition, partition, partition]),
+});
+const same = (left: unknown, right: unknown) =>
+ canonicalStrategyJson(left) === canonicalStrategyJson(right);
+const invalid = () =>
+ new Error(
+ 'The chronological validation preview could not be verified. Preview the current inputs again.'
+ );
+
+function parsePreview(
+ body: unknown,
+ input: ChronologicalValidationInput
+): ChronologicalValidationPreviewView {
+ const value = prepared.parse(z.object({ preview: z.unknown() }).parse(body).preview);
+ const source = parseExperimentPreview(value.source);
+ const { recipe: _recipe, ...sourceInput } = input;
+ if (
+ !same(value.input, input) ||
+ !same(source.input, sourceInput) ||
+ !same(value.policy, chronologicalValidationPolicy)
+ ) {
+ throw invalid();
+ }
+ const phases = ['train', 'validation', 'test'] as const;
+ const partitions = value.partitions.map((part, index): ValidationPartitionView => {
+ const phase = phases[index];
+ if (!phase || part.phase !== phase) {
+ throw invalid();
+ }
+ const decoded = parseExperimentPreview({
+ ...source,
+ dataset: part.dataset,
+ request: part.request,
+ });
+ const { request, dataset } = decoded;
+ const expected = {
+ ...source.request,
+ datasetHash: dataset.hash,
+ policy: {
+ ...source.request.policy,
+ risk_boundaries: request.policy.risk_boundaries,
+ matching: {
+ ...source.request.policy.matching,
+ risk: {
+ ...source.request.policy.matching.risk,
+ ledger: {
+ ...source.request.policy.matching.risk.ledger,
+ riskSession: request.policy.matching.risk.ledger.riskSession,
+ },
+ },
+ },
+ },
+ };
+ const measured = part.counts;
+ const metadata = (manifest: ExperimentPreviewView['dataset']) => {
+ const { hash: _hash, bounds: _bounds, barCount: _barCount, ...retained } = manifest;
+ return retained;
+ };
+ if (
+ !same(request, expected) ||
+ !same(dataset.bounds, input.recipe[phase]) ||
+ !same(metadata(dataset), metadata(source.dataset)) ||
+ measured.totalBars !== dataset.barCount ||
+ dataset.bounds.warmupStart < source.dataset.bounds.warmupStart ||
+ dataset.bounds.tradeStart < source.dataset.bounds.tradeStart ||
+ dataset.bounds.tradeEnd > source.dataset.bounds.tradeEnd ||
+ measured.totalBars !==
+ measured.availableWarmup +
+ measured.availableEvaluation +
+ measured.terminalAtEnd +
+ measured.unavailableAtEnd ||
+ measured.availableWarmup !== measured.admittedWarmup + measured.ignoredLateWarmup ||
+ measured.admittedWarmup < part.requiredWarmup ||
+ measured.availableEvaluation === 0
+ ) {
+ throw invalid();
+ }
+ return { ...part, phase, request, dataset };
+ }) as [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
+ return { ...value, source, policy: chronologicalValidationPolicy, partitions };
+}
+export const chronologicalValidationApi = {
+ async preview(
+ input: ChronologicalValidationInput,
+ signal?: AbortSignal
+ ): Promise {
+ const response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/validation/preview`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(input),
+ signal,
+ });
+ const body: unknown = await response.json().catch(() => null);
+ if (!response.ok) {
+ const error = z.object({ error: z.string() }).safeParse(body);
+ throw new Error(
+ error.success
+ ? error.data.error
+ : `Chronological validation preview failed (${response.status})`
+ );
+ }
+ try {
+ if (response.status !== 200) {
+ throw invalid();
+ }
+ return parsePreview(body, input);
+ } catch {
+ throw invalid();
+ }
+ },
+};
diff --git a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts
index c505bb46..84490735 100644
--- a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts
+++ b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts
@@ -165,7 +165,7 @@ function parseSummary(value: unknown): ExperimentSummary {
}
return parsed;
}
-function parsePreview(value: unknown): ExperimentPreviewView {
+export function parseExperimentPreview(value: unknown): ExperimentPreviewView {
const parsed = preview.parse(value);
if (
parsed.input.backtestId !== parsed.request.backtestId ||
@@ -188,7 +188,7 @@ function parsePreview(value: unknown): ExperimentPreviewView {
function parseDetail(value: unknown): ExperimentDetailView {
const parsed = detail.parse(value);
parseSummary(parsed);
- const retained = parsePreview(parsed.preview);
+ const retained = parseExperimentPreview(parsed.preview);
if (
parsed.backtestId !== retained.input.backtestId ||
parsed.name !== retained.input.name ||
@@ -345,7 +345,7 @@ export const experimentApi = {
),
preview: (input: ExperimentInput, signal?: AbortSignal) =>
request('/preview', { ...json(input), signal }, 200, body => {
- const value = parsePreview(envelope(body, 'preview'));
+ const value = parseExperimentPreview(envelope(body, 'preview'));
if (!same(value.input, input)) {
throw invalid();
}
diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md
index 0898b129..564947e4 100644
--- a/docs/development/ROADMAP.md
+++ b/docs/development/ROADMAP.md
@@ -1,8 +1,8 @@
# Revised development roadmap
-**First twenty-seven waves committed; failed-trial retries are validated and await commit.** The experiment workbench is committed as `6f64ef6`. **34 of 45 scheduled tasks are fully committed (76% by count)**; R06 now satisfies its retained-input acceptance and is in review. R07 retry/history controls are validated, while broader comparison work and full R05 remain partial. Next after acceptance: R08 chronological validation. Performance work remains paused.
+**First twenty-eight waves committed; R08 chronological preflight is validated and awaits commit.** Retry work is committed as `b373410`; **35 of 45 scheduled tasks are fully committed (78% by count)**. The new workbench input check verifies exact train/validation/test slices, warmup and independent account clocks. Full R08 remains incomplete until durable phase execution, selection and reports; R05/R07 remain partial. Performance work stays paused.
-Authorization update: the owner requested “commit and start”. The first R06/R07 experiment workbench is committed as `6f64ef6`; **34/45 scheduled tasks are fully committed**, plus these partial components. This continuation adds failed-trial retry receipts, diagnostic preservation, fencing and UI history using existing durable runs/outbox. Full R05 and broader R07 work remain partial. Performance stays paused; new-wave commits, pushes, PRs and trading/default-engine operations are outside this continuation's scope.
+Authorization update: the owner requested “commit and continue”. R06 is complete and committed as `b373410`; R08 now starts with an explicitly partial, read-only preflight foundation. No performance work, new-wave commits/pushes/PRs, SQL admission changes, candidate execution or trading/default activation are included.
## Strategy and review outcome
@@ -613,3 +613,17 @@ Validation passed: `bun run check` (93 tooling, 43 utility, 44 calculation, 738
The release addon remains `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103`. Both disposable fixture containers were stopped; development services were untouched. Worktrees and logs remain under `/tmp/stock-bot-wave28.AqRnN8/`.
Next after acceptance/commit: **R08 bounded chronological selection and reset-segment validation**. Freeze train/validation/test windows and selection rules before execution, retain all tried candidates and distinguish reset segments from continuous portfolio performance. No performance work, standalone/bulk retries, candidate execution, multi-asset/default/paper/live activation, AI execution, new-wave commit, push or PR occurred.
+
+## Twenty-ninth-wave handoff — 2026-10-24
+
+The owner accepted R06 retries, committed as `b373410`; 35/45 scheduled tasks are fully committed. R08's first preflight component is implemented, independently reviewed and validated, but uncommitted. Full R08 and the existing R05/R07 exclusions remain incomplete.
+
+- **Prepared chronological inputs:** The existing experiment editor accepts explicit UTC train/validation/test windows and previews their exact retained slices, candidate-wide warmup requirements, original policies and reset-account assumptions. Invalid or stale input never becomes a prepared result. Ordinary sweep submission remains separately labelled.
+- **Point-in-time correctness:** Slices preserve original bars, availability, sequences, VWAP and legacy conversion provenance. They reject cut bars, out-of-range/overlapping evaluation windows and insufficient usable warmup. Each phase reuses the existing calendar clock logic while keeping capital, risk, costs, strategy and seed unchanged. Completed observations are distinguished from execution opens.
+- **Honest scope:** Preview creates no datasets, experiments, runs, reports or selected winner. Its fixed future protocol selects from complete training evidence only; validation/test cannot retune. Staged execution and immutable evidence are still unavailable. No financial simulation, SQL admission or dispatcher behavior changed.
+
+All gates passed: `bun run check` (93 tooling, 43 utility, 44 calculation, 786 integration and 150 Rust tests; four existing manual Rust tests ignored); full PostgreSQL/Redis (194 tests /1655 assertions); Chromium (12 workflows /306 assertions); strict test types, scoped lint, formatting and whitespace checks. Two native regressions prove fresh independent account/state and unchanged earlier economics after modifying the test suffix. The browser workflow proves preview/rejection/invalidation/reload with no database effects. Exact 19-file source hashes, review evidence and logs are in `manifest.json` → `twenty_ninth_wave_validation`.
+
+The release addon remains `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103`. Both disposable fixture containers were stopped; worktrees/logs remain under `/tmp/stock-bot-wave29.kK85O1/`. Existing warnings remain; development data/services were untouched.
+
+Next after acceptance/commit: **R08 immutable recipe and staged admission**. Freeze windows and selection rules before execution, retain all training candidates, then atomically freeze the winner before validation/test admission. Extend existing one-dataset admission/retry assumptions explicitly; do not add another scheduler. R09 stays blocked, and performance/default/trading/AI activation remains excluded. No new-wave commit, push or PR occurred.
diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md
index e270a530..7d6a1d09 100644
--- a/docs/development/backlog/README.md
+++ b/docs/development/backlog/README.md
@@ -1,6 +1,6 @@
# Canonical development backlog
-**First twenty-seven waves committed; failed-trial retries are validated and await commit.** The experiment workbench is committed as `6f64ef6`. **34 of 45 scheduled tasks are fully committed (76% by count)**; R06 now satisfies its retained-input acceptance and is in review. R07 retry/history controls are validated, while broader comparison work and full R05 remain partial. Next after acceptance: R08 chronological validation. Performance work remains paused.
+**First twenty-eight waves committed; R08 chronological preflight is validated and awaits commit.** Retry work is committed as `b373410`; **35 of 45 scheduled tasks are fully committed (78% by count)**. The new workbench input check verifies exact train/validation/test slices, warmup and independent account clocks. Full R08 remains incomplete until durable phase execution, selection and reports; R05/R07 remain partial. Performance work stays paused.
## One source of truth
@@ -77,9 +77,9 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / done | R01, R10, ADR-006 | — | Full-stack research product / M |
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / done | R03, W02, ADR-006 | W04 | Full-stack research product / M |
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
-| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / review (validated, uncommitted) | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M |
+| [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 (component) | R06 component API pinned; release after integration, ADR-006 | W04 | Full-stack research product / M |
-| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / blocked | R06, ADR-006 | — | Quantitative research integrity / M |
+| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / in_progress (preflight validated) | R06, ADR-006 | — | Quantitative research integrity / M |
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, 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 |
diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json
index d73e4e7c..59cf9358 100644
--- a/docs/development/backlog/manifest.json
+++ b/docs/development/backlog/manifest.json
@@ -1,14 +1,14 @@
{
"schema_version": 1,
- "plan_revision": "2026-10-24.60",
+ "plan_revision": "2026-10-24.62",
"repository_base": "b7aeca4",
- "plan_status": "twenty_eighth_wave_validated_awaiting_commit",
+ "plan_status": "twenty_ninth_wave_validated_awaiting_commit",
"execution_authorized": true,
"execution_scope": {
- "authorized_by": "User: commit and start after wave27 named safe failed-trial retries; prior slice committed6f64ef6",
- "tasks": ["R06", "R07"],
+ "authorized_by": "User: commit and continue after validated R06 retry handoff recommended R08 chronological validation; retry work committed b373410",
+ "tasks": ["R08"],
"permissions": [
- "Failed canonical experiment trial retry with immutable diagnostic receipts, SQL fencing and focused history/retry controls; isolated implementation/review and full validation"
+ "R08 preflight foundation: verified chronological dataset windows, prepared reset-account requests and input-only web preview; isolated implementation/review and full validation"
],
"excluded": [
"performance_profiling_or_optimization",
@@ -23,7 +23,10 @@
"multi_asset_activation",
"AI_execution_or_credentials",
"historical_binary_provisioning",
- "cross_experiment_ranking"
+ "cross_experiment_ranking",
+ "durable_validation_admission",
+ "validation_selection_or_performance_claims",
+ "validation_report_persistence"
],
"pending_policy_decisions": [
"ADR-007",
@@ -1334,7 +1337,7 @@
"epic": "E6",
"priority": "P1",
"severity": "High",
- "status": "review",
+ "status": "done",
"dependencies": ["R01", "R10", "F08", "S02", "D01", "W03", "C06", "R12"],
"decision_dependencies": ["ADR-006"],
"task_file": "backlog/tasks/R06.md",
@@ -1346,10 +1349,10 @@
"assignment": "/root",
"branch": null,
"pull_request": null,
- "completed_commit": null,
+ "completed_commit": "b373410320e987ddce1ee8dd5e8a691cf183d527",
"blocker": null,
"release_gates": [],
- "integration_state": "validated_uncommitted",
+ "integration_state": "validated_committed",
"integration_base": "6f64ef62ba233b293ea1374c753bd0b467703792",
"worktree": "/home/boki/repos/stock-bot",
"execution_component": "Failed-trial retry with immutable diagnostic history",
@@ -1363,7 +1366,7 @@
],
"reviewed_by": "/root/r04_review",
"verification_reference": "ROADMAP.md#twenty-eighth-wave-handoff--2026-10-24",
- "review_notes": "Retained-input experiment and retry acceptance complete; independently reviewed and all integrated gates passed. Awaiting owner acceptance/commit before downstream readiness changes.",
+ "review_notes": "Retained-input experiment/retry acceptance verified and owner accepted; committed b373410. Broader R05 cutover remains separate.",
"implementation_slices": [
{
"owner": "/root/r12_backend",
@@ -1398,7 +1401,7 @@
"completed_commit": null,
"blocker": null,
"release_gates": ["W04"],
- "integration_state": "component_validated_uncommitted",
+ "integration_state": "partial_validated_committed",
"integration_base": "6f64ef62ba233b293ea1374c753bd0b467703792",
"worktree": "/home/boki/repos/stock-bot",
"execution_component": "Per-trial retry controls and retained history",
@@ -1418,7 +1421,7 @@
"scope": "Shared DTO, migration allowlist/old fixtures, actual native browser workflow, integrated gates and planning"
}
],
- "partial_commit": "6f64ef62ba233b293ea1374c753bd0b467703792"
+ "partial_commit": "b373410320e987ddce1ee8dd5e8a691cf183d527"
},
{
"id": "R08",
@@ -1426,7 +1429,7 @@
"epic": "E6",
"priority": "P1",
"severity": "High",
- "status": "blocked",
+ "status": "in_progress",
"dependencies": ["R06"],
"decision_dependencies": ["ADR-006"],
"task_file": "backlog/tasks/R08.md",
@@ -1435,12 +1438,39 @@
"specialization": "Quantitative research integrity",
"write_locks": ["validation-contract", "sql-migrations"],
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
- "assignment": null,
+ "assignment": "/root",
"branch": null,
"pull_request": null,
"completed_commit": null,
"blocker": null,
- "release_gates": []
+ "release_gates": [],
+ "integration_state": "component_validated_uncommitted",
+ "integration_base": "b373410320e987ddce1ee8dd5e8a691cf183d527",
+ "worktree": "/home/boki/repos/stock-bot",
+ "execution_component": "Chronological validation preflight and exact dataset slicing",
+ "component_exclusions": [
+ "durable experiment/phase admission and immutable selection/report",
+ "walk-forward aggregation and cost-sensitivity execution"
+ ],
+ "reviewed_by": "/root/r04_review",
+ "verification_reference": "ROADMAP.md#twenty-ninth-wave-handoff--2026-10-24",
+ "review_notes": "Preflight foundation independently reviewed and all integrated gates passed. Full task stays in progress: no durable recipe/admission, selection, report, walk-forward or cost-sensitivity execution yet.",
+ "implementation_slices": [
+ {
+ "owner": "/root/r12_backend",
+ "worktree": "/tmp/stock-bot-wave29.kK85O1/backend",
+ "scope": "Exact v2 slice export, prepared phase requests and extracted unchanged risk clock, authenticated preview API and pure/API/PostgreSQL regressions"
+ },
+ {
+ "owner": "/root/r12_frontend",
+ "worktree": "/tmp/stock-bot-wave29.kK85O1/frontend",
+ "scope": "Explicit UTC preflight panel/client and interaction tests; ordinary sweep remains distinct"
+ },
+ {
+ "owner": "/root",
+ "scope": "Shared DTO/export, native reset/suffix regression, actual browser no-write workflow, full integration and planning"
+ }
+ ]
},
{
"id": "R09",
@@ -6684,7 +6714,7 @@
"Original input/review snapshot remains immutable; fresh retry requires current approval and records its receipt separately. Existing lifetime automatic recovery budget remains unchanged."
],
"twenty_eighth_wave_validation": {
- "state": "validated_uncommitted",
+ "state": "validated_committed",
"scope": "R06 retained-input experiment acceptance complete; R07 retry/history component complete, broader task partial",
"artifacts": "/tmp/stock-bot-wave28.AqRnN8",
"source_archive": "/tmp/stock-bot-wave28.AqRnN8/validated-source.tar.gz",
@@ -6765,6 +6795,96 @@
"Chromium only; existing bundle-size/Rust warnings and four manual Rust test exclusions remain. Initial focused SQL test parameter-type fixture error was corrected before the frozen 11/101 suite; final integrated gates passed on their first run."
],
"cleanup": "Both exact --rm disposable PostgreSQL/Redis fixture containers stopped successfully. 27 authored source/test files archived and hashed; isolated worktrees/logs retained. Development/production services and data untouched.",
- "next": "Accept/commit this R06 retry completion, then start R08 bounded chronological parameter selection and reset-segment validation on the accepted retained-input experiment foundation. Pin explicit training/validation/test/warmup boundaries and selection rule before execution; preserve all candidate evidence and label reset-segment results honestly. Keep performance paused and R05/R07/AI/multi-asset/default activation gates intact."
+ "next": "Accept/commit this R06 retry completion, then start R08 bounded chronological parameter selection and reset-segment validation on the accepted retained-input experiment foundation. Pin explicit training/validation/test/warmup boundaries and selection rule before execution; preserve all candidate evidence and label reset-segment results honestly. Keep performance paused and R05/R07/AI/multi-asset/default activation gates intact.",
+ "completed_commit": "b373410320e987ddce1ee8dd5e8a691cf183d527"
+ },
+ "twenty_ninth_wave": ["R08"],
+ "twenty_ninth_wave_base": "b373410320e987ddce1ee8dd5e8a691cf183d527",
+ "twenty_ninth_wave_notes": [
+ "Explicitly partial preflight: prepared input checks are not frozen experiments/reports or OOS evidence; no new SQL/admission/queue/engine semantics.",
+ "Existing one-dataset experiment and retry contracts require a later coordinated staged admission branch; first validate exact slices, availability-aware warmup and phase account clocks.",
+ "Future fixed selection protocol: every train candidate must have a comparable finite totalReturn; maximize then tie by original candidate.index. Validation and test assess only that frozen winner."
+ ],
+ "twenty_ninth_wave_validation": {
+ "state": "component_validated_uncommitted",
+ "scope": "R08 read-only chronological preflight foundation; full R08 remains in_progress and R09 blocked",
+ "integration_base": "b373410320e987ddce1ee8dd5e8a691cf183d527",
+ "log_directory": "/tmp/stock-bot-wave29.kK85O1",
+ "source_archive": "/tmp/stock-bot-wave29.kK85O1/validated-source.tar.gz",
+ "source_files": {
+ "apps/stock/config/package.json": "8113f4137acc8303540319431e196ac40a52413698ff85b6940a1367d7c2317c",
+ "apps/stock/config/src/contracts/chronological-validation.ts": "3dfa61b02e95d29d12d1f1077c2c4fd2ade32606188fc9188dc380c6ab963122",
+ "apps/stock/orchestrator/src/data/historical-dataset-v2.ts": "f76516192c213ce206a0869298b349572cc6ee375892c4b7af834b567dd76a32",
+ "apps/stock/web-api/src/routes/experiments.routes.ts": "154dae18a156609ecdcb7d6d8153ad032109a21fab00d4934e49df3dc57562e6",
+ "apps/stock/web-api/src/services/canonical-research.service.ts": "95a1638bc6e30cfedca37b6eb0515ebcaf042214a8ad2550447e9bfb0eec3564",
+ "apps/stock/web-api/src/services/canonical-risk-clock.ts": "3df138ffa327aca9c1bd1f4cf3fb9b4a20e7fc1f0d5ebd908184dd15bbbc4c4b",
+ "apps/stock/web-api/src/services/experiments.service.ts": "86839986119642dd3886aefd011564860c226738b36eabf724633592e8229b2a",
+ "apps/stock/web-api/src/services/validation-preview.ts": "8d09ff2ba19eb6fdace30a4936f77d10fe30fc06af8935d133d1d4c3a2bf34d0",
+ "apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx": "684a1bfedb068f4c54fe26872ded053039b4e1670b4e91b0841b5d92512b3192",
+ "apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx": "03778008549386acbec221d510555bf251d6db3e4ecf26fe7532a567ec9b8454",
+ "apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts": "4a189d11658aba2450fe556b9ca401c2b07849df0e03328d35810e2220d4d9f9",
+ "apps/stock/web-app/src/features/experiments/services/experimentApi.ts": "a45619f25c9ecc59a30ad576398aecc57efd458e23e04621a98baf438a4e1159",
+ "test/e2e/workbench.test.ts": "b52302ccec7c4d90c4f06483f70927d825ee7565787ed3c9be38fd32dbf7303e",
+ "test/fixtures/chronological-validation.ts": "44dd7ca82cf102e202d3fdc835961ff74c33cf846a9f523c998ff8db831d9e9d",
+ "test/integration/chronological-validation-api.test.ts": "e8e360ff187b075dec16277d4f35c03db29f83c6c438c345632d3d711a8dd49a",
+ "test/integration/chronological-validation-native.test.ts": "822bdca6aac5b33219f6a3b68d45eaa5efe4151b4d103a8a8e31e70864d2c258",
+ "test/integration/chronological-validation-ui.test.tsx": "debdb04c07e68b6c5212f70d19b5f93abf352a535ec432d4f8ebe226adbf760b",
+ "test/integration/chronological-validation.test.ts": "15dce3033886c919f8e4f458fc6c9b9ce45c445dd667130bcd72a312315bcf0c",
+ "test/postgres/chronological-validation.test.ts": "d13a1749defdbd2a67c3f74af195fc3872b81985671d38062ba2a3b5a4066859"
+ },
+ "checks": [
+ {
+ "command": "CARGO_BUILD_JOBS=2 bun run check",
+ "log": "/tmp/stock-bot-wave29.kK85O1/check.log",
+ "outcome": "All repository gates passed: build/source/contracts/secrets/lint; 93 tooling, 43 utility, 44 calculation, 786 integration and 150 Rust tests, zero failures. Four existing manual Rust tests ignored."
+ },
+ {
+ "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:postgres",
+ "log": "/tmp/stock-bot-wave29.kK85O1/postgres.log",
+ "outcome": "194 tests / 1655 assertions passed across 22 files. New four-test preflight suite proves unchanged full-table snapshots/no writes, one-connection transactions, current approval/archive gates, ordinary policy preservation and missing/corrupt-input handling."
+ },
+ {
+ "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:e2e",
+ "log": "/tmp/stock-bot-wave29.kK85O1/e2e.log",
+ "outcome": "12 Chromium workflows / 306 assertions passed. New flow prepares three explicit windows, inspects exact inputs/hash, rejects insufficient warmup, invalidates on bounds/name edits and confirms no datasets/experiments/runs/outbox/results/template writes through retry/reload. All 11 previous workflows passed."
+ },
+ {
+ "command": "bun test test/integration/chronological-validation-native.test.ts",
+ "log": "/tmp/stock-bot-wave29.kK85O1/native-focused.log",
+ "outcome": "Two native regressions /371 assertions passed in isolated backend worktree and are included in full integration totals. All phases start with original cash, no positions/orders and fresh strategy state; warmup cannot decide/fill. Changing only test suffix prices leaves earlier slice requests, decisions and native results unchanged."
+ },
+ {
+ "command": "bunx tsc --project /tmp/stock-bot-wave29.kK85O1/tests-tsconfig.json --noEmit",
+ "log": "/tmp/stock-bot-wave29.kK85O1/integrated-test-types-final.log",
+ "outcome": "Strict new tests/browser/dependent source types passed. Initial root test dynamic-index assertion needed an as-const tuple; final fix changes only types, not runtime values."
+ },
+ {
+ "command": "bunx eslint --max-warnings 0; bunx prettier --check ; git diff --check",
+ "log": "/tmp/stock-bot-wave29.kK85O1/integrated-test-lint.log",
+ "outcome": "Scoped test lint, changed-file formatting and whitespace checks passed; final planning metadata separately formatted and validated."
+ },
+ {
+ "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release",
+ "log": "/tmp/stock-bot-wave29.kK85O1/native-release.log",
+ "outcome": "Release native addon restored before PostgreSQL/Chromium gates; SHA256 ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103 unchanged. No Rust, runner, dispatcher or SQL changes."
+ }
+ ],
+ "reviews": [
+ {
+ "reviewer": "/root/r04_review",
+ "scope": "All 14 backend/frontend overlay file hashes, root precise observation-label delta, native tests/fixture, browser test and partial-scope planning",
+ "outcome": "Accepted without remaining blockers. Independently ran backend pure/API 13 tests /161 assertions and frontend 33/125; reviewed author PG 4/46 and root native 2/371 evidence. Root completed combined gates. Frontend changed one label after overlay review to distinguish completed observations from execution opens."
+ }
+ ],
+ "limitations": [
+ "Prepared inputs are non-durable. POST /api/v2/experiments/validation/preview writes no datasets, experiments, runs or reports and performs no strategy selection or financial execution. UI provides no validation submit/save control.",
+ "Current approved retained deterministic built-ins, one eligible asset/series and installed build only. Zero label horizon; trainable/nonzero-horizon models reject. Ordinary sweeps remain a separate existing workflow.",
+ "Warmup readiness counts usable observations, not profitability or statistical adequacy. Completed observations available exactly at tradeEnd may terminal-mark only; later arrivals cannot inform decisions/terminal marks. Existing open execution semantics remain unchanged.",
+ "Future fixed protocol is all-candidate finite comparable training totalReturn, maximizing then tying by original candidate index; validation/test assess the same locked winner. That selection is declared but not executed or durably frozen in this slice.",
+ "Durable recipes, staged admission, write-once selection/report, holdout access history, walk-forward/reset-series reporting and cost sensitivity remain R08 acceptance work; R09 stays blocked. R05/R07 remain partial.",
+ "No performance measurements/optimization, new scheduler/simulator, candidate code, multi-asset/default/paper/live/AI activation, new-wave commit, push or PR. Chromium only; existing bundle-size/Rust warnings remain."
+ ],
+ "cleanup": "Both exact --rm disposable PostgreSQL/Redis containers stopped successfully. Nineteen source/test files archived and hashed; worktrees and logs retained. Development/production services and data untouched.",
+ "next": "After acceptance/commit, continue R08 with immutable experiment-owned recipe and a coordinated guarded admission branch. Freeze all windows/source/phase inputs and selection policy before training; commit the write-once complete-training winner before admitting the same winner to validation/test. Extend existing one-dataset admission/retry/result assumptions explicitly, preserve normal experiments and recovery, and persist immutable evidence. Do not call preflight OOS validation or release R09 prematurely; performance remains paused."
}
}
diff --git a/docs/development/backlog/tasks/R06.md b/docs/development/backlog/tasks/R06.md
index 11468329..9ca4987d 100644
--- a/docs/development/backlog/tasks/R06.md
+++ b/docs/development/backlog/tasks/R06.md
@@ -93,6 +93,6 @@ Lock order is parent → experiment → run → strategy family. Atomic acceptan
### Validated retry handoff
-R06's retained-input acceptance is complete and independently reviewed; status is `review` / `validated_uncommitted`. Existing bounded expansion/cancellation/compact comparison behavior is preserved. Full repository gates, PostgreSQL (190 tests / 1609 assertions) and Chromium (11 workflows / 285 assertions) passed. Exact source hashes and logs: `manifest.json` → `twenty_eighth_wave_validation`.
+R06's retained-input acceptance is complete and independently reviewed; owner accepted and committed it as `b373410` (`done` / `validated_committed`). Existing bounded expansion/cancellation/compact comparison behavior is preserved. Full repository gates, PostgreSQL (190 tests / 1609 assertions) and Chromium (11 workflows / 285 assertions) passed. Exact source hashes and logs: `manifest.json` → `twenty_eighth_wave_validation`.
-The retry suite proves exact failure snapshots, duplicate/stale intent handling, lifetime counter monotonicity, rollback, old-attempt fencing, Redis recovery, current original-version approval and actual Rust completion with one result. SQL23 adds guards only to experiment retry semantics; ordinary run lifecycle behavior remains intact. No engine or dispatcher changes were required. Downstream R08 remains blocked until acceptance/commit; broader R05 cutover is still separate.
+The retry suite proves exact failure snapshots, duplicate/stale intent handling, lifetime counter monotonicity, rollback, old-attempt fencing, Redis recovery, current original-version approval and actual Rust completion with one result. SQL23 adds guards only to experiment retry semantics; ordinary run lifecycle behavior remains intact. No engine or dispatcher changes were required. R08 is released from this prerequisite by acceptance/commit; broader R05 cutover is still separate.
diff --git a/docs/development/backlog/tasks/R07.md b/docs/development/backlog/tasks/R07.md
index ada7fb71..e2bb5941 100644
--- a/docs/development/backlog/tasks/R07.md
+++ b/docs/development/backlog/tasks/R07.md
@@ -85,6 +85,6 @@ The first experiment UI component is committed as `6f64ef6`. Add per-trial faile
### Validated retry controls handoff
-The retry/history component is independently reviewed and `component_validated_uncommitted`. The actual Chromium workflow retries a failed canonical trial, verifies the original immutable inputs despite template edits, replays the accepted receipt after completion and reopens saved failure history and the native result. Interaction tests cover uncertain responses, stale refresh/route responses, cancellation coordination, null/history/error states and explicit discard/new intent. Exact logs and hashes: `manifest.json` → `twenty_eighth_wave_validation`.
+The retry/history component is independently reviewed and committed as `b373410`; full R07 remains partial. The actual Chromium workflow retries a failed canonical trial, verifies the original immutable inputs despite template edits, replays the accepted receipt after completion and reopens saved failure history and the native result. Interaction tests cover uncertain responses, stale refresh/route responses, cancellation coordination, null/history/error states and explicit discard/new intent. Exact logs and hashes: `manifest.json` → `twenty_eighth_wave_validation`.
Full R07 remains in progress for broader cross-experiment comparison and table measurements. All performance work stays paused. No new finance, statistics or result-ranking logic was added.
diff --git a/docs/development/backlog/tasks/R08.md b/docs/development/backlog/tasks/R08.md
index 3cdcfc05..97e63901 100644
--- a/docs/development/backlog/tasks/R08.md
+++ b/docs/development/backlog/tasks/R08.md
@@ -68,3 +68,19 @@ Keep migrations additive and previous results readable. Do not add a switch that
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
+
+## Authorized first component — 2026-10-24
+
+R06 is accepted/committed as `b373410`. Begin with a read-only chronological preflight using the existing approved canonical template, bounded grid and retained source dataset. POST `/api/v2/experiments/validation/preview` prepares explicit train/validation/test slices, availability-aware warmup diagnostics, exact source/phase hashes and reset-account requests. The existing experiment editor exposes this input check without a submit/save control.
+
+The fixed future selection protocol maximizes every candidate's finite comparable training total return, breaking ties by original candidate index. Failed/missing/incomparable/null candidates block later selection. Validation and test assess that same winner; neither retunes. Only deterministic unfitted built-ins and zero label horizon are supported. Warmup can overlap prior phases; evaluation intervals cannot overlap. No financial policy is recalculated; only dataset identity and calendar-derived risk-session clocks change per phase.
+
+This component is explicitly **prepared input, not durable experiment evidence**. It writes no datasets, runs, experiments or reports and performs no selection or holdout execution. Existing SQL22/23 require one dataset per experiment; changing that admission/retry contract belongs to the next coordinated durable slice. Full R08 remains incomplete until frozen recipe, selection gating, reports, reset-segment validation and cost-sensitivity acceptance are met. No findings/regime integration or performance work is included.
+
+### Validated preflight handoff
+
+The first component is independently reviewed and `component_validated_uncommitted`; full R08 remains `in_progress`. Exact bars and legacy conversion provenance survive slicing; immediate source lineage stays in the outer preview. Warmup diagnostics respect actual availability and retained strategy ordering, including observations at/after the evaluation end. Existing account-clock calculation is reused for each phase without changing financial policy.
+
+Full repository checks passed (786 integration /150 Rust tests), PostgreSQL (194 tests /1655 assertions), Chromium (12 workflows /306 assertions), strict test types, lint and formatting. Native regressions prove independent initial cash/positions/state, no warmup orders/fills and earlier-phase invariance to a changed test suffix. Browser/database tests prove preview makes no retained-data/job/template writes. Hashes and logs: `manifest.json` → `twenty_ninth_wave_validation`.
+
+Next: immutable experiment-owned recipe and guarded staged admission, with all candidate training evidence complete before a write-once winner selection and validation/test admission. Existing ordinary experiment/retry behavior must remain intact. This preflight does not satisfy immutable report reopening, holdout access history, walk-forward aggregation or cost-sensitivity execution; R09 remains blocked.
diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts
index f67b3e3d..f0485ea8 100644
--- a/test/e2e/workbench.test.ts
+++ b/test/e2e/workbench.test.ts
@@ -5,6 +5,7 @@ import {
canonicalResearchSettingsSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
+import type { ChronologicalValidationPreview } from '@stock-bot/stock-config/chronological-validation';
import type {
ExperimentDetail,
ExperimentPreview,
@@ -14,6 +15,7 @@ import type {
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
+import { chronologicalDataset } from '../fixtures/chronological-validation';
import {
fixture as createFixture,
createInBrowser,
@@ -36,6 +38,134 @@ afterAll(async () => {
});
const fixture = (native = false) => createFixture(browser, native);
+test('chronological_preflight_checks_explicit_windows_without_admitting_or_saving_work_browser', async () => {
+ const f = await fixture(true);
+ f.page.on('dialog', dialog => void dialog.accept());
+ try {
+ const { dataset, recipe, start, minute } = chronologicalDataset();
+ await retainResearchDataset(f.pool, dataset);
+ const selected = (await f.seedCatalog()).find(
+ item => item.package.program.strategyId === 'sma_crossover'
+ )!;
+ await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', {
+ decision: 'approve',
+ reason: 'Reviewed canonical chronological preflight fixture',
+ });
+ const backtest = await f.request('/api/v2/backtests', 'POST', {
+ name: 'Chronological preflight template',
+ strategy: 'catalog',
+ strategyVersionId: selected.id,
+ strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
+ symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
+ startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
+ endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
+ initialCapital: 10000,
+ config: {
+ datasetHash: dataset.manifest.hash,
+ dataFrequency: dataset.manifest.series[0]!.interval,
+ canonical: canonicalSettings,
+ },
+ autoStart: false,
+ });
+ const evidence = async () =>
+ (
+ await f.pool.query(
+ `SELECT (SELECT count(*) FROM backtest_datasets) AS datasets,
+ (SELECT count(*) FROM research_experiments) AS experiments,
+ (SELECT count(*) FROM runs) AS runs,
+ (SELECT count(*) FROM backtest_dispatch) AS dispatch,
+ (SELECT count(*) FROM backtest_results) AS results,
+ (SELECT row_to_json(b) FROM backtests b WHERE id=$1) AS template`,
+ [backtest.id]
+ )
+ ).rows[0];
+ const before = await evidence();
+ await f.login();
+ await f.page.goto(`${f.origin}/experiments?backtestId=${backtest.id}`);
+ await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
+ await f.page.getByLabel('Experiment name', { exact: true }).fill('Chronological input check');
+ await f.page.getByLabel('Parameter grid').fill('{"fastPeriod":[1,2]}');
+ for (const phase of ['Train', 'Validation', 'Test'] as const) {
+ const window = recipe[phase.toLowerCase() as 'train' | 'validation' | 'test'];
+ await f.page
+ .getByLabel(`${phase} warmup start (UTC)`, { exact: true })
+ .fill(new Date(window.warmupStart).toISOString());
+ await f.page
+ .getByLabel(`${phase} trading start (UTC)`, { exact: true })
+ .fill(new Date(window.tradeStart).toISOString());
+ await f.page
+ .getByLabel(`${phase} trading end (UTC)`, { exact: true })
+ .fill(new Date(window.tradeEnd).toISOString());
+ }
+ const prepare = async () => {
+ const reply = f.page.waitForResponse(response =>
+ response.url().endsWith('/api/v2/experiments/validation/preview')
+ );
+ await f.page
+ .getByRole('button', { name: 'Preview chronological validation', exact: true })
+ .click();
+ return reply;
+ };
+ const response = await prepare();
+ expect(response.status()).toBe(200);
+ const { preview } = (await response.json()) as { preview: ChronologicalValidationPreview };
+ expect(response.request().postDataJSON().recipe).toEqual(recipe);
+ expect(preview.execution).toBe('preview-only');
+ expect(preview.source.dataset.hash).toBe(dataset.manifest.hash);
+ expect(preview.partitions.map(partition => partition.phase)).toEqual([
+ 'train',
+ 'validation',
+ 'test',
+ ]);
+ expect(preview.source.candidates).toHaveLength(2);
+ const preparedInputs = f.page.getByRole('region', {
+ name: 'Prepared chronological inputs',
+ exact: true,
+ });
+ await visible(f.page, 'Exact chronological preview inputs and policies');
+ await f.page
+ .getByText('Exact chronological preview inputs and policies', { exact: true })
+ .click();
+ expect(await preparedInputs.locator('pre').textContent()).toContain(preview.previewHash);
+ await visible(f.page, /No datasets, experiments or runs are saved/);
+ for (const partition of preview.partitions) {
+ await visible(f.page, partition.dataset.hash);
+ expect(partition.requiredWarmup).toBe(4);
+ }
+ expect(await evidence()).toEqual(before);
+ // Structurally valid bounds with too few available warmup observations reject explicitly.
+ await f.page
+ .getByLabel('Train warmup start (UTC)', { exact: true })
+ .fill(new Date(start + 4 * minute).toISOString());
+ expect(await preparedInputs.count()).toBe(0);
+ const invalid = await prepare();
+ expect(invalid.status()).toBe(400);
+ const failure = (await invalid.json()) as { error: string };
+ await visible(f.page, failure.error);
+ await f.page
+ .getByLabel('Train warmup start (UTC)', { exact: true })
+ .fill(new Date(recipe.train.warmupStart).toISOString());
+ const repeated = await prepare();
+ expect(repeated.status()).toBe(200);
+ expect((await repeated.json()).preview.previewHash).toBe(preview.previewHash);
+ await visible(f.page, 'Exact chronological preview inputs and policies');
+ await f.page
+ .getByText('Exact chronological preview inputs and policies', { exact: true })
+ .click();
+ expect(await preparedInputs.locator('pre').textContent()).toContain(preview.previewHash);
+ await f.page.getByLabel('Experiment name', { exact: true }).fill('Changed input');
+ expect(await preparedInputs.count()).toBe(0);
+ await f.page.reload();
+ await visible(f.page, /No experiments yet/);
+ expect(await preparedInputs.count()).toBe(0);
+ expect(await evidence()).toEqual(before);
+ expect(f.historicalDataReads).toEqual([]);
+ expect(f.unexpectedNetwork).toEqual([]);
+ } finally {
+ await f.close();
+ }
+});
+
test('failed_experiment_trial_retry_preserves_history_and_reopens_native_result_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
diff --git a/test/fixtures/chronological-validation.ts b/test/fixtures/chronological-validation.ts
new file mode 100644
index 00000000..776c41fc
--- /dev/null
+++ b/test/fixtures/chronological-validation.ts
@@ -0,0 +1,43 @@
+import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
+import { nativeReplayFixture } from './native-replay';
+
+/** Three explicit windows; a later suffix can change without changing earlier observations. */
+export function chronologicalDataset(testSuffixPrice?: number) {
+ const fixture = nativeReplayFixture(36);
+ const { calendars, series, executionSeries, bounds, universe, corporateActions } =
+ fixture.dataset.manifest;
+ const closes = [3, 2, 1, 4, 5, 1, 1, 3, 6, 2, 1, 4];
+ const dataset = createDatasetV2({
+ metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
+ bars: fixture.dataset.bars.map((bar, index) => {
+ const close =
+ index >= 28 && testSuffixPrice !== undefined
+ ? testSuffixPrice + index
+ : closes[index % closes.length]!;
+ const open = index === 0 ? 3 : closes[(index - 1) % closes.length]!;
+ return {
+ seriesId: bar.seriesId,
+ timestamp: bar.intervalStart,
+ availableAt: bar.availableAt,
+ sourceSequence: bar.sourceSequence,
+ open,
+ close,
+ high: Math.max(open, close),
+ low: Math.min(open, close),
+ volume: 1000,
+ };
+ }),
+ });
+ const at = (step: number) => fixture.start + step * fixture.minute;
+ return {
+ ...fixture,
+ dataset,
+ recipe: {
+ version: 1 as const,
+ labelHorizonMs: 0 as const,
+ train: { warmupStart: at(0), tradeStart: at(6), tradeEnd: at(12) },
+ validation: { warmupStart: at(10), tradeStart: at(16), tradeEnd: at(24) },
+ test: { warmupStart: at(22), tradeStart: at(28), tradeEnd: at(36) },
+ },
+ };
+}
diff --git a/test/integration/chronological-validation-api.test.ts b/test/integration/chronological-validation-api.test.ts
new file mode 100644
index 00000000..fd7334e0
--- /dev/null
+++ b/test/integration/chronological-validation-api.test.ts
@@ -0,0 +1,137 @@
+import { randomUUID } from 'node:crypto';
+import { describe, expect, mock, test } from 'bun:test';
+import { Hono } from 'hono';
+import { z } from 'zod';
+import { createHttpSecurity } from '@stock-bot/di';
+import type { IServiceContainer } from '@stock-bot/services';
+import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
+import { chronologicalDataset } from '../fixtures/chronological-validation';
+
+const tokens = {
+ operator: 'validation-admin-fixture-not-a-real-secret-1234',
+ service: 'validation-service-fixture-not-a-real-secret-1234',
+ read: 'validation-read-fixture-not-a-real-secret-1234',
+};
+const input = {
+ backtestId: randomUUID(),
+ name: 'Validation preview',
+ grid: { fastPeriod: [1, 2] },
+ recipe: chronologicalDataset().recipe,
+};
+type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record[] }>;
+function fixture(
+ mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
+ query: Query = async () => ({ rows: [] })
+) {
+ const client = { query: mock(query) };
+ const database = {
+ ...client,
+ transaction: mock(async (work: (client: { query: Query }) => Promise) => work(client)),
+ };
+ const app = new Hono();
+ if (mode !== 'absent') {
+ createHttpSecurity({
+ adminToken: tokens.operator,
+ serviceToken: tokens.service,
+ readToken: tokens.read,
+ environment: 'test',
+ hostname: '127.0.0.1',
+ disabled: mode === 'disabled',
+ }).mount(app);
+ }
+ app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer));
+ return {
+ database,
+ request(body: string, role?: keyof typeof tokens) {
+ return app.request('/api/v2/experiments/validation/preview', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
+ },
+ body,
+ });
+ },
+ };
+}
+
+describe('chronological validation HTTP boundary', () => {
+ test('verified credentials are mandatory even for disabled development auth; read roles cannot prepare', async () => {
+ for (const mode of ['enabled', 'disabled', 'absent'] as const) {
+ const f = fixture(mode);
+ expect((await f.request(JSON.stringify(input))).status).toBe(401);
+ expect(f.database.transaction.mock.calls).toHaveLength(0);
+ }
+ const f = fixture();
+ expect((await f.request(JSON.stringify(input), 'read')).status).toBe(403);
+ expect(f.database.transaction.mock.calls).toHaveLength(0);
+ });
+ test('malformed bodies, raw reserved keys, nonzero labels, fitted models and implicit windows reject before storage', async () => {
+ for (const body of [
+ '{',
+ '[]',
+ 'null',
+ JSON.stringify({ ...input, backtestId: 'invalid' }),
+ JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }),
+ JSON.stringify({ ...input, modelArtifacts: ['fit'] }),
+ JSON.stringify({ ...input, recipe: { ...input.recipe, labelHorizonMs: 1 } }),
+ JSON.stringify({ ...input, recipe: { ...input.recipe, embargoMs: 0 } }),
+ JSON.stringify({
+ ...input,
+ recipe: {
+ ...input.recipe,
+ train: { ...input.recipe.train, tradeStart: '2024-01-01T09:06:00Z' },
+ },
+ }),
+ JSON.stringify({
+ ...input,
+ recipe: {
+ ...input.recipe,
+ train: { ...input.recipe.train, warmupStart: input.recipe.train.tradeStart },
+ },
+ }),
+ JSON.stringify({
+ ...input,
+ recipe: {
+ ...input.recipe,
+ validation: { ...input.recipe.validation, tradeStart: input.recipe.train.tradeEnd - 1 },
+ },
+ }),
+ JSON.stringify(input).replace('"fastPeriod":[1,2]', '"__proto__":[1]'),
+ ]) {
+ const f = fixture();
+ const response = await f.request(body, 'operator');
+ expect(response.status).toBe(400);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(f.database.query.mock.calls).toHaveLength(0);
+ expect(f.database.transaction.mock.calls).toHaveLength(0);
+ }
+ });
+ test('operator and service requests bind the preview method without requiring a receipt; missing and archived are distinct', async () => {
+ for (const role of ['operator', 'service'] as const) {
+ const f = fixture('enabled', async (sql, values) => {
+ expect(sql).toBe('SELECT * FROM backtests WHERE id=$1 FOR UPDATE');
+ expect(values).toEqual([input.backtestId]);
+ return { rows: [] };
+ });
+ const response = await f.request(JSON.stringify(input), role);
+ expect(response.status).toBe(404);
+ expect(await response.json()).toEqual({ error: 'Backtest not found' });
+ expect(f.database.transaction.mock.calls).toHaveLength(1);
+ }
+ const f = fixture('enabled', async () => ({
+ rows: [{ id: input.backtestId, archived_at: new Date() }],
+ }));
+ expect((await f.request(JSON.stringify(input), 'operator')).status).toBe(409);
+ });
+ test('unexpected storage and internal schema failures remain sanitized server errors, never invalid user input', async () => {
+ for (const error of [new Error('secret database connection detail'), new z.ZodError([])]) {
+ const f = fixture('enabled', async () => {
+ throw error;
+ });
+ const response = await f.request(JSON.stringify(input), 'operator');
+ expect(response.status).toBe(500);
+ expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
+ }
+ });
+});
diff --git a/test/integration/chronological-validation-native.test.ts b/test/integration/chronological-validation-native.test.ts
new file mode 100644
index 00000000..076bfb44
--- /dev/null
+++ b/test/integration/chronological-validation-native.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, test } from 'bun:test';
+import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
+import type { ChronologicalValidationInput } from '@stock-bot/stock-config/chronological-validation';
+import { parseFinancialDecimal } from '@stock-bot/types';
+import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
+import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
+import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
+import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
+import {
+ buildExperimentPreview,
+ PREVIEW_RUN_ID,
+} from '../../apps/stock/web-api/src/services/experiment-input';
+import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview';
+import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
+import { chronologicalDataset } from '../fixtures/chronological-validation';
+
+const versionId = '00000000-0000-4000-8000-000000000021';
+const backtestId = '00000000-0000-4000-8000-000000000022';
+let packages: ReturnType | undefined;
+async function prepared(testSuffixPrice?: number) {
+ const fixture = chronologicalDataset(testSuffixPrice);
+ const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
+ const policy = structuredClone(fixture.config);
+ const ownerId = `strategy:${versionId}`;
+ policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
+ policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
+ policy.matching.risk.ledger.ownerIds = [ownerId];
+ policy.matching.owners = [{ ownerId, mode: 'Target' }];
+ policy.cadence = [{ owner_id: ownerId, series_ids: ['X0.US:1m'] }];
+ const clock = canonicalRiskSessionClock(fixture.dataset);
+ policy.matching.risk.ledger.riskSession = clock.riskSession;
+ policy.risk_boundaries = clock.riskBoundaries;
+ const request = canonicalRunRequestSchema.parse({
+ kind: 'canonical-research/v1',
+ runId: PREVIEW_RUN_ID,
+ backtestId,
+ name: 'Chronological fixture',
+ strategy: {
+ familyId: '00000000-0000-4000-8000-000000000023',
+ versionId,
+ origin: 'builtin',
+ reviewId: '00000000-0000-4000-8000-000000000024',
+ package: pkg,
+ selection: {
+ strategyId: pkg.program.strategyId,
+ strategyVersion: pkg.program.strategyVersion,
+ ownerId,
+ seed: 42,
+ instrumentId: 'X0.US',
+ seriesId: 'X0.US:1m',
+ ownerBudget: '40',
+ parameters: { fastPeriod: 2, slowPeriod: 3 },
+ },
+ },
+ datasetHash: fixture.dataset.manifest.hash,
+ policy,
+ analyticsPolicy: {
+ version: 1,
+ periodsPerYear: 252,
+ annualRiskFreeRate: 0,
+ benchmark: null,
+ },
+ build: {
+ version: 1,
+ workerSha256: 'a'.repeat(64),
+ engineWrapperSha256: 'b'.repeat(64),
+ engineBinarySha256: 'c'.repeat(64),
+ dependencyLockSha256: 'd'.repeat(64),
+ runtime: 'bun',
+ runtimeVersion: Bun.version,
+ platform: process.platform,
+ arch: process.arch,
+ },
+ modelArtifacts: [],
+ });
+ const input: ChronologicalValidationInput = {
+ backtestId,
+ name: 'Three-window input check',
+ grid: { fastPeriod: [1, 2] },
+ recipe: fixture.recipe,
+ };
+ const { recipe: _recipe, ...experimentInput } = input;
+ const source = buildExperimentPreview(experimentInput, request, fixture.dataset.manifest);
+ const original = JSON.stringify({ source, dataset: fixture.dataset });
+ const preparation = prepareChronologicalValidation(input, source, fixture.dataset);
+ expect(JSON.stringify({ source, dataset: fixture.dataset })).toBe(original);
+ return preparation;
+}
+
+type Prepared = Awaited>;
+function execute(preparation: Prepared, index: number) {
+ const partition = preparation.preview.partitions[index]!;
+ const strategy = createBuiltinStrategy(partition.request.strategy.selection);
+ let decisions = 0;
+ const run = runStrategyReplay(
+ prepareReplayLoad(preparation.datasets[partition.phase], partition.request.policy),
+ [
+ {
+ ...strategy,
+ decide(context) {
+ expect(context.now).toBeGreaterThanOrEqual(partition.dataset.bounds.tradeStart);
+ expect(context.now).toBeLessThan(partition.dataset.bounds.tradeEnd);
+ expect(context.observations.every(bar => bar.available_at <= context.now)).toBe(true);
+ if (decisions++ === 0) {
+ expect(context.portfolio.portfolio.cash).toBe(parseFinancialDecimal('10000'));
+ expect(context.positions).toEqual([]);
+ expect(context.portfolio.orders).toEqual([]);
+ expect(context.state).toEqual(strategy.initialState);
+ }
+ return strategy.decide(context);
+ },
+ },
+ ],
+ { resultFormat: 'report', eventBudget: 3 }
+ );
+ expect(decisions).toBeGreaterThan(0);
+ expect(run.result.reporting.initialEquity).toBe(parseFinancialDecimal('10000'));
+ expect(run.result.projection.fills.length).toBeGreaterThan(0);
+ for (const fill of run.result.projection.fills) {
+ expect(fill.eventTime).toBeGreaterThanOrEqual(partition.dataset.bounds.tradeStart);
+ expect(fill.eventTime).toBeLessThan(partition.dataset.bounds.tradeEnd);
+ }
+ return run;
+}
+
+describe('chronological preflight slices on the authoritative native engine', () => {
+ test('each phase independently starts with initial cash, empty positions and fresh state; warmup cannot trade', async () => {
+ const preparation = await prepared();
+ expect(preparation.preview.execution).toBe('preview-only');
+ for (const index of [0, 1, 2]) {
+ const first = execute(preparation, index);
+ const repeated = execute(preparation, index);
+ expect(repeated.result).toEqual(first.result);
+ expect(repeated.diagnostics).toEqual(first.diagnostics);
+ }
+ });
+
+ test('changing only the test suffix cannot change training or validation inputs, native economics or decisions', async () => {
+ const before = await prepared();
+ const after = await prepared(1000);
+ expect(after.preview.previewHash).not.toBe(before.preview.previewHash);
+ expect(after.preview.source.dataset.hash).not.toBe(before.preview.source.dataset.hash);
+ expect(after.preview.partitions[2].dataset.hash).not.toBe(
+ before.preview.partitions[2].dataset.hash
+ );
+ for (const index of [0, 1] as const) {
+ const phase = before.preview.partitions[index]!.phase;
+ expect(after.preview.partitions[index]).toEqual(before.preview.partitions[index]);
+ expect(after.datasets[phase]).toEqual(before.datasets[phase]);
+ const original = execute(before, index);
+ const changed = execute(after, index);
+ expect(changed.result).toEqual(original.result);
+ expect(changed.diagnostics).toEqual(original.diagnostics);
+ }
+ });
+});
diff --git a/test/integration/chronological-validation-ui.test.tsx b/test/integration/chronological-validation-ui.test.tsx
new file mode 100644
index 00000000..e281ad44
--- /dev/null
+++ b/test/integration/chronological-validation-ui.test.tsx
@@ -0,0 +1,621 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { GlobalWindow } from 'happy-dom';
+import { act, createElement } from 'react';
+import type { Root } from 'react-dom/client';
+import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
+import {
+ chronologicalValidationPolicy,
+ type ChronologicalValidationInput,
+ type ChronologicalValidationPreview,
+} from '@stock-bot/stock-config/chronological-validation';
+import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
+import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
+import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
+import { nativeReplayFixture } from '../fixtures/native-replay';
+
+const browser = new GlobalWindow({ url: 'http://localhost:5173' });
+const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] 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 ExperimentListPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentListPage;
+let root: Root | undefined;
+let host: HTMLDivElement;
+let navigate: ReturnType;
+let location = '';
+const backtestId = '11111111-1111-4111-8111-111111111111';
+const otherBacktestId = '22222222-2222-4222-8222-222222222222';
+const versionId = '55555555-5555-4555-8555-555555555555';
+const endpoint = '/api/v2/experiments/validation/preview';
+function deferred() {
+ let resolve!: (value: T) => void;
+ let reject!: (cause: Error) => void;
+ const promise = new Promise((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+}
+type Pending = ReturnType> & {
+ path: string;
+ method: string;
+ body: unknown;
+ headers: Headers;
+ settled: boolean;
+ signal?: AbortSignal | null;
+ credentials?: RequestCredentials;
+};
+const requests: Pending[] = [];
+function request(path: string, method = 'GET') {
+ const found = requests.find(
+ item => item.path === path && item.method === method && !item.settled
+ );
+ if (!found) {
+ throw new Error(`Missing ${method} ${path}`);
+ }
+ return found;
+}
+function reply(item: Pending, value: unknown, status = 200) {
+ item.settled = true;
+ item.resolve(Response.json(value, { status }));
+}
+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 button ${label}: ${host.textContent}`);
+ }
+ return found;
+}
+function field(label: string) {
+ const found = [...host.querySelectorAll('label')]
+ .find(
+ item => item.firstChild?.textContent?.trim() === label || item.textContent?.trim() === label
+ )
+ ?.querySelector('input,select,textarea');
+ if (!found) {
+ throw new Error(`Missing field ${label}`);
+ }
+ return found as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
+}
+function change(label: string, value: string) {
+ const input = field(label);
+ const prototype =
+ input.tagName === 'SELECT'
+ ? browser.HTMLSelectElement.prototype
+ : input.tagName === 'TEXTAREA'
+ ? browser.HTMLTextAreaElement.prototype
+ : browser.HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
+ input.dispatchEvent(
+ new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
+ bubbles: true,
+ }) as unknown as Event
+ );
+}
+function Probe() {
+ navigate = router.useNavigate();
+ location = router.useLocation().pathname + router.useLocation().search;
+ return null;
+}
+const template = (id = backtestId): Backtest => ({
+ id,
+ name: `Template ${id}`,
+ strategy: 'sma',
+ strategyVersionId: versionId,
+ symbols: ['X0.US'],
+ startDate: '2024-01-01',
+ endDate: '2024-01-02',
+ initialCapital: 100,
+ config: { canonical: {}, datasetHash: 'a'.repeat(64) },
+ archivedAt: null,
+ createdAt: '2026-10-24',
+ updatedAt: '2026-10-24',
+});
+function sourcePreview(count = 2, parent = backtestId): ExperimentPreview {
+ const owner = `strategy:${versionId}`;
+ const { config, dataset } = nativeReplayFixture(60, 1, [owner]);
+ const previewId = '00000000-0000-4000-8000-000000000001';
+ config.matching.risk.ledger.sessionId = previewId;
+ config.matching.risk.ledger.accountId = `research:${previewId}`;
+ const builtin = builtinCatalogDescriptors[0]!;
+ const candidates = Array.from({ length: count }, (_, index) => ({
+ index,
+ trialKey: String(index + 1).padStart(64, '0'),
+ parameters: { fastPeriod: index + 2, slowPeriod: 20 },
+ }));
+ return {
+ version: 'research-experiment-preview/v1',
+ previewHash: 'e'.repeat(64),
+ input: {
+ backtestId: parent,
+ name: 'Trend study',
+ grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) },
+ },
+ dataset: dataset.manifest,
+ candidates,
+ request: canonicalRunRequestSchema.parse({
+ kind: 'canonical-research/v1',
+ runId: previewId,
+ backtestId: parent,
+ name: 'Frozen template name',
+ strategy: {
+ familyId: '66666666-6666-4666-8666-666666666666',
+ versionId,
+ origin: 'builtin',
+ reviewId: '88888888-8888-4888-8888-888888888888',
+ package: {
+ version: 1,
+ program: builtin.program,
+ parameterSchema: builtin.parameterSchema,
+ artifact: {
+ format: 'esm-bundle/v1',
+ entryExport: builtin.entryExport,
+ content: 'Never execute fixture code',
+ sha256: 'a'.repeat(64),
+ },
+ dependencyLock: {
+ format: 'bun-lock/v1',
+ content: 'Retained lock',
+ sha256: 'b'.repeat(64),
+ },
+ source: { revision: 'c'.repeat(40), dirty: false },
+ build: { tool: 'bun', version: '1.2.17', target: 'browser' },
+ },
+ selection: {
+ strategyId: builtin.program.strategyId,
+ strategyVersion: builtin.program.strategyVersion,
+ ownerId: owner,
+ seed: 17,
+ instrumentId: 'X0.US',
+ seriesId: 'X0.US:1m',
+ ownerBudget: '100',
+ parameters: { fastPeriod: 2, slowPeriod: 20 },
+ },
+ },
+ datasetHash: dataset.manifest.hash,
+ policy: config,
+ analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
+ build: {
+ version: 1,
+ workerSha256: 'a'.repeat(64),
+ engineWrapperSha256: 'b'.repeat(64),
+ engineBinarySha256: 'c'.repeat(64),
+ dependencyLockSha256: 'd'.repeat(64),
+ runtime: 'bun',
+ runtimeVersion: '1.2.17',
+ platform: 'linux',
+ arch: 'x64',
+ },
+ modelArtifacts: [],
+ }),
+ };
+}
+
+function prepared(): ChronologicalValidationPreview {
+ const source = sourcePreview();
+ const start = source.dataset.bounds.warmupStart;
+ const minute = 60000;
+ const bounds = (offset: number) => ({
+ warmupStart: start + offset * minute,
+ tradeStart: start + (offset + 22) * minute,
+ tradeEnd: start + (offset + 30) * minute,
+ });
+ const input: ChronologicalValidationInput = {
+ ...source.input,
+ recipe: {
+ version: 1,
+ train: bounds(0),
+ validation: bounds(10),
+ test: bounds(20),
+ labelHorizonMs: 0,
+ },
+ };
+ const phases = ['train', 'validation', 'test'] as const;
+ const partitions = phases.map((phase, index) => {
+ const dataset = {
+ ...structuredClone(source.dataset),
+ hash: ['a', 'b', 'c'][index]!.repeat(64),
+ bounds: input.recipe[phase],
+ barCount: 30,
+ };
+ const request = { ...structuredClone(source.request), datasetHash: dataset.hash };
+ return {
+ phase,
+ dataset,
+ request,
+ counts: {
+ totalBars: 30,
+ availableWarmup: 21,
+ admittedWarmup: 21,
+ ignoredLateWarmup: 0,
+ availableEvaluation: 8,
+ terminalAtEnd: 1,
+ unavailableAtEnd: 0,
+ },
+ requiredWarmup: 21,
+ warnings: ['Input history sufficiency does not establish statistical adequacy.'],
+ };
+ }) as ChronologicalValidationPreview['partitions'];
+ return {
+ version: 'chronological-validation-preview/v1',
+ execution: 'preview-only',
+ previewHash: 'f'.repeat(64),
+ input,
+ source,
+ policy: chronologicalValidationPolicy,
+ partitions,
+ };
+}
+async function mount() {
+ root ??= createRoot(host);
+ await flush(() =>
+ root!.render(
+ createElement(
+ router.MemoryRouter,
+ { initialEntries: [`/experiments?backtestId=${backtestId}`] },
+ createElement(ExperimentListPage),
+ createElement(Probe)
+ )
+ )
+ );
+ await flush(() => {
+ reply(request('/api/v2/backtests?limit=50&offset=0'), [template(), template(otherBacktestId)]);
+ reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [] });
+ });
+}
+async function fill(value = prepared()) {
+ await mount();
+ await flush(() => {
+ change('Experiment name', value.input.name);
+ change('Parameter grid (JSON)', JSON.stringify(value.input.grid));
+ for (const phase of ['train', 'validation', 'test'] as const) {
+ const label = phase[0]!.toUpperCase() + phase.slice(1);
+ change(
+ `${label} warmup start (UTC)`,
+ new Date(value.input.recipe[phase].warmupStart).toISOString()
+ );
+ change(
+ `${label} trading start (UTC)`,
+ new Date(value.input.recipe[phase].tradeStart).toISOString()
+ );
+ change(
+ `${label} trading end (UTC)`,
+ new Date(value.input.recipe[phase].tradeEnd).toISOString()
+ );
+ }
+ });
+ return value;
+}
+async function ready(value = prepared()) {
+ await fill(value);
+ await flush(() => button('Preview chronological validation').click());
+ await flush(() => reply(request(endpoint, 'POST'), { preview: value }));
+ return value;
+}
+beforeAll(async () => {
+ for (const [key, value] of Object.entries({
+ window: browser,
+ document: browser.document,
+ Event: browser.Event,
+ ResizeObserver: browser.ResizeObserver,
+ IS_REACT_ACT_ENVIRONMENT: true,
+ })) {
+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
+ }
+ ({ createRoot } = await import('react-dom/client'));
+ router = await import('react-router-dom');
+ ({ ExperimentListPage } = await import('../../apps/stock/web-app/src/features/experiments'));
+});
+beforeEach(() => {
+ requests.length = 0;
+ location = '';
+ host = browser.document.createElement('div') as unknown as HTMLDivElement;
+ browser.document.body.append(host as never);
+ Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
+ Object.defineProperty(browser, 'fetch', {
+ configurable: true,
+ value: (input: unknown, init?: RequestInit) => {
+ const url = new URL(String(input));
+ const item: Pending = {
+ ...deferred(),
+ path: url.pathname + url.search,
+ method: init?.method ?? 'GET',
+ body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
+ headers: new Headers(init?.headers),
+ signal: init?.signal,
+ credentials: init?.credentials,
+ settled: false,
+ };
+ requests.push(item);
+ return item.promise; // Ignore abort so generation/identity fencing is exercised.
+ },
+ });
+});
+afterEach(async () => {
+ if (root) {
+ await flush(() => root!.unmount());
+ }
+ root = undefined;
+ host.remove();
+});
+afterAll(async () => {
+ await browser.happyDOM.close();
+ for (const key of keys) {
+ const old = originals.get(key);
+ if (old) {
+ Object.defineProperty(globalThis, key, old);
+ } else {
+ Reflect.deleteProperty(globalThis, key);
+ }
+ }
+});
+
+describe('chronological validation preflight', () => {
+ test('explicit UTC preparation sends only read-only preview and displays all phase assumptions and counts', async () => {
+ const value = await fill();
+ expect(host.textContent).toContain('No chronological preview prepared');
+ expect(host.textContent).toContain(
+ 'Preview only. No datasets, experiments or runs are saved. Staged execution and immutable reports are not available yet.'
+ );
+ expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
+ await flush(() => {
+ button('Preview chronological validation').click();
+ button('Preview chronological validation').click();
+ });
+ expect(host.textContent).toContain('Preparing chronological validation preview...');
+ const post = request(endpoint, 'POST');
+ expect(post.body).toEqual(value.input);
+ expect(post.headers.has('Idempotency-Key')).toBe(false);
+ expect(post.credentials).toBe('include');
+ expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
+ await flush(() => reply(post, { preview: value }));
+ expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).not.toBeNull();
+ expect(host.textContent).toContain('2 parameter candidates checked');
+ expect(host.textContent).toContain('No candidate has been selected or evaluated.');
+ expect(host.textContent).toContain('maximize train total return');
+ expect(host.textContent).toContain('Validation is diagnostic only; test is holdout only');
+ expect(host.textContent).toContain('independent reset segments');
+ for (const phase of ['Train', 'Validation', 'Test']) {
+ const card = host.querySelector(`[aria-label="${phase} partition"]`)!;
+ expect(card.textContent).toContain('21 / 21');
+ expect(card.textContent).toContain('Available exactly at end (terminal mark only)');
+ expect(card.textContent).toContain('Input history sufficiency');
+ }
+ expect(
+ host
+ .querySelector('[aria-label="Chronological validation preflight"]')!
+ .querySelectorAll('button')
+ ).toHaveLength(1);
+ expect(host.textContent).not.toContain('Confirm experiment');
+ expect(location).toBe(`/experiments?backtestId=${backtestId}`);
+ });
+ test.each([
+ 'Experiment name',
+ 'Parameter grid (JSON)',
+ 'Saved backtest',
+ 'Train trading end (UTC)',
+ ])(
+ '%s changes invalidate visible and pending previews without automatically reposting',
+ async label => {
+ const value = await ready();
+ await flush(() => button('Preview chronological validation').click());
+ const old = request(endpoint, 'POST');
+ const next =
+ label === 'Experiment name'
+ ? 'Changed'
+ : label === 'Parameter grid (JSON)'
+ ? '{}'
+ : label === 'Saved backtest'
+ ? otherBacktestId
+ : '2024-01-01T09:29:00Z';
+ await flush(() => change(label, next));
+ expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
+ expect(old.signal?.aborted).toBe(true);
+ await flush(() => reply(old, { preview: value }));
+ expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
+ expect(requests.filter(item => item.path === endpoint)).toHaveLength(2);
+ }
+ );
+ test.each([
+ '2024-01-01T09:00:00',
+ '2024-01-01T09:00:00+00:00',
+ '2024-02-30T09:00:00Z',
+ '2024-01-01T09:00:00.0001Z',
+ '',
+ ])('rejects ambiguous or invalid UTC value %s before any request', async text => {
+ await fill();
+ await flush(() => change('Train warmup start (UTC)', text));
+ await flush(() => button('Preview chronological validation').click());
+ expect(host.textContent).toContain('must be a real UTC instant ending in Z');
+ expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
+ });
+ test('chronology and invalid grid reject locally, including overlapping evaluation windows', async () => {
+ await fill();
+ await flush(() => change('Validation trading start (UTC)', '2024-01-01T09:29:00Z'));
+ await flush(() => button('Preview chronological validation').click());
+ expect(host.textContent).toContain('chronological and nonoverlapping');
+ expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
+ await flush(() => {
+ change('Validation trading start (UTC)', '2024-01-01T09:32:00Z');
+ change('Parameter grid (JSON)', '{"__proto__":[1]}');
+ });
+ await flush(() => button('Preview chronological validation').click());
+ expect(host.textContent).toContain('Invalid parameter name');
+ expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
+ });
+ test.each([400, 401, 404, 409, 500])(
+ 'HTTP %s has a visible retryable error and never admits a sweep',
+ async status => {
+ const value = await fill();
+ await flush(() => button('Preview chronological validation').click());
+ await flush(() =>
+ reply(
+ request(endpoint, 'POST'),
+ { error: 'Train has insufficient admitted warmup: 4 of 21 observations' },
+ status
+ )
+ );
+ expect(host.textContent).toContain('Train has insufficient admitted warmup');
+ expect(button('Preview chronological validation').disabled).toBe(false);
+ expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
+ await flush(() => button('Preview chronological validation').click());
+ await flush(() => reply(request(endpoint, 'POST'), { preview: value }));
+ expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).not.toBeNull();
+ expect(
+ requests.filter(item => item.method === 'POST').every(item => item.path === endpoint)
+ ).toBe(true);
+ }
+ );
+ test.each([
+ 'wrong-parent',
+ 'wrong-name',
+ 'wrong-grid',
+ 'wrong-policy',
+ 'phase-order',
+ 'phase-bounds',
+ 'changed-finance',
+ 'changed-metadata',
+ 'count-mismatch',
+ 'manifest-count',
+ 'missing-terminal',
+ 'invalid-warmup',
+ 'partial',
+ ] as const)('malformed %s response fails closed', async kind => {
+ const value = await fill();
+ await flush(() => button('Preview chronological validation').click());
+ const invalid = structuredClone(value);
+ if (kind === 'wrong-parent') {
+ invalid.source.input.backtestId = otherBacktestId;
+ }
+ if (kind === 'wrong-name') {
+ invalid.source.input.name = 'Different';
+ }
+ if (kind === 'wrong-grid') {
+ invalid.source.input.grid = {};
+ }
+ if (kind === 'wrong-policy') {
+ (invalid.policy.selection as unknown as Record).metric = 'sharpeRatio';
+ }
+ if (kind === 'phase-order') {
+ invalid.partitions.reverse();
+ }
+ if (kind === 'phase-bounds') {
+ invalid.partitions[0].dataset = {
+ ...invalid.partitions[0].dataset,
+ bounds: {
+ ...invalid.partitions[0].dataset.bounds,
+ tradeEnd: value.input.recipe.train.tradeEnd - 60000,
+ },
+ };
+ }
+ if (kind === 'changed-finance') {
+ invalid.partitions[0].request.policy.matching.risk.maxDailyLoss = '123.00000000' as never;
+ }
+ if (kind === 'changed-metadata') {
+ invalid.partitions[0].dataset = {
+ ...invalid.partitions[0].dataset,
+ series: invalid.partitions[0].dataset.series.map(item => ({ ...item, interval: '5m' })),
+ };
+ }
+ if (kind === 'count-mismatch') {
+ invalid.partitions[0].counts.totalBars = 99;
+ }
+ if (kind === 'manifest-count') {
+ invalid.partitions[0].dataset = { ...invalid.partitions[0].dataset, barCount: 99 };
+ }
+ if (kind === 'missing-terminal') {
+ delete (invalid.partitions[0].counts as Partial<(typeof invalid.partitions)[0]['counts']>)
+ .terminalAtEnd;
+ }
+ if (kind === 'invalid-warmup') {
+ invalid.partitions[0].requiredWarmup = 22;
+ }
+ await flush(() =>
+ reply(
+ request(endpoint, 'POST'),
+ kind === 'partial' ? { preview: { previewHash: value.previewHash } } : { preview: invalid }
+ )
+ );
+ expect(host.textContent).toContain('could not be verified');
+ expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
+ });
+ test('network loss and stale route responses are recoverable without creating records', async () => {
+ const value = await fill();
+ await flush(() => button('Preview chronological validation').click());
+ const post = request(endpoint, 'POST');
+ await flush(() => {
+ post.settled = true;
+ post.reject(new Error('Connection lost'));
+ });
+ expect(host.textContent).toContain('Connection lost');
+ await flush(() => button('Preview chronological validation').click());
+ const stale = request(endpoint, 'POST');
+ await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
+ await flush(() => reply(stale, { preview: value }));
+ expect(location).toBe(`/experiments?backtestId=${otherBacktestId}`);
+ expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
+ expect(field('Train warmup start (UTC)').value).toBe('');
+ });
+ test('ordinary unresolved submission disables and invalidates preflight without changing its exact sweep body', async () => {
+ const value = await fill();
+ await flush(() => button('Preview chronological validation').click());
+ const stale = request(endpoint, 'POST');
+ await flush(() => button('Preview experiment').click());
+ await flush(() =>
+ reply(request('/api/v2/experiments/preview', 'POST'), { preview: value.source })
+ );
+ await flush(() => button('Confirm experiment').click());
+ const ordinary = request('/api/v2/experiments', 'POST');
+ expect(ordinary.body).toEqual({ ...value.source.input, previewHash: value.source.previewHash });
+ expect(ordinary.headers.has('Idempotency-Key')).toBe(true);
+ await flush(() => {
+ ordinary.settled = true;
+ ordinary.reject(new Error('Lost ordinary receipt'));
+ });
+ await flush(() => reply(stale, { preview: value }));
+ expect(button('Preview chronological validation').disabled).toBe(true);
+ expect(field('Train warmup start (UTC)').closest('fieldset')!.disabled).toBe(true);
+ expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
+ expect(host.textContent).toContain(
+ 'Resolve or explicitly release the ordinary sweep submission'
+ );
+ await flush(() => button('Start new experiment').click());
+ expect(button('Preview chronological validation').disabled).toBe(false);
+ expect(field('Train warmup start (UTC)').value).toBe(
+ new Date(value.input.recipe.train.warmupStart).toISOString()
+ );
+ expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
+ });
+ test('window-only draft participates in the existing owned-navigation discard guard', async () => {
+ await mount();
+ await flush(() => change('Train warmup start (UTC)', '2024-01-01T09:00:00Z'));
+ Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
+ await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click());
+ expect(location).toBe(`/experiments?backtestId=${backtestId}`);
+ expect(field('Train warmup start (UTC)').value).toBe('2024-01-01T09:00:00Z');
+ });
+ test('delayed observations remain explicit and tiny evaluation warnings are not performance evidence', async () => {
+ const value = prepared();
+ value.partitions[2].counts.availableEvaluation = 1;
+ value.partitions[2].counts.unavailableAtEnd = 7;
+ value.partitions[2].warnings = [
+ 'Only one evaluation observation is available.',
+ 'Seven delayed observations remain unavailable at the end.',
+ ];
+ await ready(value);
+ const card = host.querySelector('[aria-label="Test partition"]')!;
+ expect(card.textContent).toContain('Only one evaluation observation');
+ expect(card.textContent).toContain('Seven delayed observations');
+ expect(host.textContent).toContain(
+ 'Warmup sufficiency is not evidence of profitability or statistical adequacy'
+ );
+ });
+});
diff --git a/test/integration/chronological-validation.test.ts b/test/integration/chronological-validation.test.ts
new file mode 100644
index 00000000..b3325f78
--- /dev/null
+++ b/test/integration/chronological-validation.test.ts
@@ -0,0 +1,423 @@
+import { createHash } from 'node:crypto';
+import { describe, expect, test } from 'bun:test';
+import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
+import type { ChronologicalValidationInput } from '@stock-bot/stock-config/chronological-validation';
+import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
+import type {
+ HistoricalDataset,
+ HistoricalDatasetInputV2,
+ HistoricalDatasetV2,
+} from '@stock-bot/types';
+import {
+ convertDatasetV1ToV2,
+ createDatasetV2,
+ sliceDatasetV2,
+ validateDatasetV2,
+} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
+import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
+import {
+ buildExperimentPreview,
+ PREVIEW_RUN_ID,
+} from '../../apps/stock/web-api/src/services/experiment-input';
+import {
+ parseChronologicalValidation,
+ prepareChronologicalValidation,
+} from '../../apps/stock/web-api/src/services/validation-preview';
+import { chronologicalDataset } from '../fixtures/chronological-validation';
+import { datasetInput } from '../fixtures/historical-v2/dataset';
+import { nativeReplayFixture } from '../fixtures/native-replay';
+
+const backtestId = '10000000-0000-4000-8000-000000000001';
+const versionId = '20000000-0000-4000-8000-000000000001';
+const owner = `strategy:${versionId}`;
+const input = (): ChronologicalValidationInput => ({
+ backtestId,
+ name: 'Chronological input checks',
+ grid: { fastPeriod: [1, 2], slowPeriod: [3] },
+ recipe: chronologicalDataset().recipe,
+});
+function source(
+ dataset: HistoricalDatasetV2,
+ raw = input(),
+ meanParameters?: Record
+) {
+ const { recipe: _recipe, ...experiment } = raw;
+ const descriptor = builtinCatalogDescriptors[meanParameters ? 1 : 0]!;
+ const policy = structuredClone(nativeReplayFixture(36, 1, [owner]).config);
+ const clock = canonicalRiskSessionClock(dataset);
+ policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
+ policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
+ policy.matching.risk.ledger.riskSession = clock.riskSession;
+ policy.risk_boundaries = clock.riskBoundaries;
+ const request = canonicalRunRequestSchema.parse({
+ kind: 'canonical-research/v1',
+ runId: PREVIEW_RUN_ID,
+ backtestId,
+ name: 'Template',
+ strategy: {
+ familyId: '30000000-0000-4000-8000-000000000001',
+ versionId,
+ origin: 'builtin',
+ reviewId: '40000000-0000-4000-8000-000000000001',
+ package: {
+ version: 1,
+ program: descriptor.program,
+ parameterSchema: descriptor.parameterSchema,
+ artifact: {
+ format: 'esm-bundle/v1',
+ entryExport: descriptor.entryExport,
+ content: 'fixture',
+ sha256: 'a'.repeat(64),
+ },
+ dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
+ source: { revision: 'c'.repeat(40), dirty: false },
+ build: { tool: 'bun', version: 'fixture', target: 'browser' },
+ },
+ selection: {
+ strategyId: descriptor.program.strategyId,
+ strategyVersion: descriptor.program.strategyVersion,
+ ownerId: owner,
+ seed: 42,
+ instrumentId: 'X0.US',
+ seriesId: 'X0.US:1m',
+ ownerBudget: '40',
+ parameters: meanParameters ?? { fastPeriod: 2, slowPeriod: 3 },
+ },
+ },
+ datasetHash: dataset.manifest.hash,
+ policy,
+ analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
+ build: {
+ version: 1,
+ workerSha256: 'a'.repeat(64),
+ engineWrapperSha256: 'b'.repeat(64),
+ engineBinarySha256: 'c'.repeat(64),
+ dependencyLockSha256: 'd'.repeat(64),
+ runtime: 'bun',
+ runtimeVersion: 'fixture',
+ platform: 'linux',
+ arch: 'x64',
+ },
+ modelArtifacts: [],
+ });
+ return buildExperimentPreview(experiment, request, dataset.manifest);
+}
+function providerInput(dataset: HistoricalDatasetV2): HistoricalDatasetInputV2 {
+ const { calendars, series, executionSeries, bounds, universe, corporateActions } =
+ dataset.manifest;
+ return {
+ metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
+ bars: dataset.bars.map(
+ ({
+ seriesId,
+ intervalStart,
+ availableAt,
+ sourceSequence,
+ open,
+ high,
+ low,
+ close,
+ volume,
+ vwap,
+ }) => ({
+ seriesId,
+ timestamp: intervalStart,
+ availableAt,
+ sourceSequence,
+ open,
+ high,
+ low,
+ close,
+ volume,
+ vwap,
+ })
+ ),
+ };
+}
+function changedAvailability(delays: Record) {
+ const fixture = chronologicalDataset();
+ const raw = providerInput(fixture.dataset);
+ return createDatasetV2({
+ ...raw,
+ bars: raw.bars.map((bar, index) => ({
+ ...bar,
+ availableAt: fixture.start + (delays[index] ?? index + 1) * fixture.minute,
+ })),
+ });
+}
+
+describe('chronological validation input preparation', () => {
+ test('exact slices retain observations and all provenance without mutating the source or financial policy', () => {
+ const dataset = chronologicalDataset().dataset,
+ raw = input(),
+ preview = source(dataset, raw);
+ const before = structuredClone({ dataset, preview, raw });
+ const result = prepareChronologicalValidation(raw, preview, dataset);
+ expect(prepareChronologicalValidation(raw, preview, dataset)).toEqual(result);
+ expect({ dataset, preview, raw }).toEqual(before);
+ expect(result.preview.execution).toBe('preview-only');
+ expect(result.preview.policy).toMatchObject({
+ selection: { phase: 'train', metric: 'totalReturn', requireAllCandidates: true },
+ reset: 'initial-capital-empty-positions',
+ });
+ for (const phase of ['train', 'validation', 'test'] as const) {
+ const slice = result.datasets[phase],
+ partition = result.preview.partitions.find(p => p.phase === phase)!;
+ expect(validateDatasetV2(slice)).toEqual(slice);
+ expect(slice.bars).toEqual(
+ dataset.bars.filter(
+ b =>
+ b.intervalStart >= raw.recipe[phase].warmupStart &&
+ b.intervalEnd <= raw.recipe[phase].tradeEnd
+ )
+ );
+ expect(slice.manifest.parentDatasetHash).toBeNull();
+ for (const key of [
+ 'calendars',
+ 'series',
+ 'executionSeries',
+ 'universe',
+ 'corporateActions',
+ ] as const) {
+ expect(slice.manifest[key]).toEqual(dataset.manifest[key]);
+ }
+ const expected = structuredClone(preview.request),
+ clock = canonicalRiskSessionClock(slice);
+ expected.datasetHash = slice.manifest.hash;
+ expected.policy.matching.risk.ledger.riskSession = clock.riskSession;
+ expected.policy.risk_boundaries = clock.riskBoundaries;
+ expect(partition.request).toEqual(expected);
+ expect(partition.counts.terminalAtEnd).toBe(1);
+ const c = partition.counts;
+ expect(c.availableWarmup + c.availableEvaluation + c.terminalAtEnd + c.unavailableAtEnd).toBe(
+ c.totalBars
+ );
+ }
+ });
+ test('direct slice rejects out-of-source bounds, invalid ordering and every bar-cut boundary', () => {
+ const dataset = chronologicalDataset().dataset,
+ bounds = input().recipe.train;
+ for (const changed of [
+ { ...bounds, warmupStart: bounds.warmupStart - 1 },
+ { ...bounds, tradeStart: dataset.manifest.bounds.tradeStart - 1 },
+ { ...bounds, tradeEnd: dataset.manifest.bounds.tradeEnd + 1 },
+ { ...bounds, warmupStart: bounds.tradeStart + 60_000 },
+ { ...bounds, tradeStart: bounds.tradeEnd },
+ { ...bounds, tradeEnd: bounds.tradeStart - 60_000 },
+ ...(['warmupStart', 'tradeStart', 'tradeEnd'] as const).map(key => ({
+ ...bounds,
+ [key]: bounds[key] + 1,
+ })),
+ ]) {
+ expect(() => sliceDatasetV2(dataset, changed)).toThrow();
+ }
+ });
+ test('later test suffix cannot change earlier datasets, requests or counts; full source identity still changes', () => {
+ const raw = input(),
+ first = chronologicalDataset().dataset,
+ changed = chronologicalDataset(900).dataset;
+ const before = prepareChronologicalValidation(raw, source(first, raw), first);
+ const after = prepareChronologicalValidation(raw, source(changed, raw), changed);
+ expect(after.preview.previewHash).not.toBe(before.preview.previewHash);
+ expect(after.datasets.train).toEqual(before.datasets.train);
+ expect(after.datasets.validation).toEqual(before.datasets.validation);
+ expect(after.preview.partitions.slice(0, 2)).toEqual(before.preview.partitions.slice(0, 2));
+ expect(after.datasets.test.manifest.hash).not.toBe(before.datasets.test.manifest.hash);
+ });
+ test('availability, terminal-only and ignored late warmup counts reflect arrival order without dropping delayed bars', () => {
+ const raw = input(),
+ dataset = changedAvailability({ 0: 5, 10: 13 });
+ const result = prepareChronologicalValidation(raw, source(dataset, raw), dataset);
+ expect(result.preview.partitions[0].counts).toEqual({
+ totalBars: 12,
+ availableWarmup: 5,
+ admittedWarmup: 4,
+ ignoredLateWarmup: 1,
+ availableEvaluation: 5,
+ terminalAtEnd: 1,
+ unavailableAtEnd: 1,
+ });
+ expect(result.datasets.train.bars).toHaveLength(12);
+ expect(result.preview.partitions[0].warnings).toHaveLength(2);
+ const insufficient = changedAvailability({ 0: 5, 1: 5 });
+ expect(() =>
+ prepareChronologicalValidation(raw, source(insufficient, raw), insufficient)
+ ).toThrow('3 admitted warmup');
+ const unavailable = changedAvailability(
+ Object.fromEntries(Array.from({ length: 6 }, (_, i) => [i + 5, 13]))
+ );
+ expect(() =>
+ prepareChronologicalValidation(raw, source(unavailable, raw), unavailable)
+ ).toThrow('no observations');
+ });
+ test('SMA readiness uses the largest candidate period and rejects warmup at the exact trading start', () => {
+ const dataset = chronologicalDataset().dataset;
+ const ready = { ...input(), grid: { fastPeriod: [1], slowPeriod: [3, 4] } };
+ expect(
+ prepareChronologicalValidation(ready, source(dataset, ready), dataset).preview.partitions[0]
+ .requiredWarmup
+ ).toBe(5);
+ const insufficient = { ...ready, grid: { fastPeriod: [1], slowPeriod: [3, 5] } };
+ expect(() =>
+ prepareChronologicalValidation(insufficient, source(dataset, insufficient), dataset)
+ ).toThrow('5 admitted warmup observations; 6 required');
+ });
+ test('mean reversion readiness covers trend, lookback and both return-history periods across the grid', () => {
+ const dataset = chronologicalDataset().dataset;
+ const parameters = {
+ lookbackPeriod: 2,
+ trendPeriod: 3,
+ momentumPeriod: 1,
+ volatilityPeriod: 2,
+ entryZScore: 2,
+ exitZScore: 1,
+ minTrendReturn: 0,
+ minMomentumReturn: 0,
+ maxVolatility: 1,
+ minNotionalVolume: '0',
+ regimeFilter: 'volatility',
+ };
+ for (const [grid, required] of [
+ [{ trendPeriod: [3, 5] }, 5],
+ [{ momentumPeriod: [1, 4] }, 5],
+ [{ volatilityPeriod: [2, 4] }, 5],
+ [{ lookbackPeriod: [2, 3], trendPeriod: [4] }, 4],
+ ] as const) {
+ const raw = parseChronologicalValidation({ ...input(), grid });
+ expect(
+ prepareChronologicalValidation(raw, source(dataset, raw, parameters), dataset).preview
+ .partitions[0].requiredWarmup
+ ).toBe(required);
+ }
+ for (const grid of [
+ { trendPeriod: [6] },
+ { momentumPeriod: [5] },
+ { volatilityPeriod: [5] },
+ { lookbackPeriod: [6], trendPeriod: [7] },
+ ]) {
+ const raw = parseChronologicalValidation({ ...input(), grid });
+ expect(() =>
+ prepareChronologicalValidation(raw, source(dataset, raw, parameters), dataset)
+ ).toThrow('admitted warmup');
+ }
+ });
+ test('sparse calendar gaps remain sparse and each segment receives the exact original clock inclusivity', () => {
+ const fixture = nativeReplayFixture(1208),
+ dataset = fixture.dataset;
+ const sessions = dataset.manifest.calendars[0]!.sessions;
+ const raw = input();
+ raw.recipe.train = {
+ warmupStart: sessions[0]!.open,
+ tradeStart: sessions[0]!.open + 6 * fixture.minute,
+ tradeEnd: sessions[1]!.open,
+ };
+ raw.recipe.validation = {
+ warmupStart: sessions[1]!.open,
+ tradeStart: sessions[1]!.open + 6 * fixture.minute,
+ tradeEnd: sessions[2]!.open,
+ };
+ raw.recipe.test = {
+ warmupStart: sessions[2]!.open,
+ tradeStart: sessions[2]!.open + 6 * fixture.minute,
+ tradeEnd: dataset.manifest.bounds.tradeEnd,
+ };
+ const result = prepareChronologicalValidation(raw, source(dataset, raw), dataset);
+ expect(result.datasets.train.bars).toHaveLength(600);
+ expect(result.datasets.validation.bars).toHaveLength(600);
+ expect(result.datasets.test.bars).toHaveLength(8);
+ const expected = (i: number) => ({
+ calendarId: 'fixture-calendar',
+ calendarRevision: '1',
+ sessionId: sessions[i]!.date,
+ startsAt: sessions[i]!.open,
+ });
+ expect(canonicalRiskSessionClock(dataset)).toEqual({
+ riskSession: expected(0),
+ riskBoundaries: [expected(1), expected(2)],
+ });
+ for (const [index, partition] of result.preview.partitions.entries()) {
+ expect(partition.request.policy.matching.risk.ledger.riskSession).toEqual(expected(index));
+ expect(partition.request.policy.risk_boundaries).toEqual(
+ index < 2 ? [expected(index + 1)] : []
+ );
+ }
+ expect(result.preview.partitions[2].warnings).toContain(
+ 'Only 2 evaluation observations; input readiness does not establish statistical adequacy'
+ );
+ });
+ test('v1 conversion lineage and null VWAP provenance survive slicing without inventing v2 ancestry', () => {
+ const fixture = datasetInput();
+ const bars = fixture.bars.map(row => ({
+ symbol: 'A.US',
+ timestamp: Date.parse(String(row.timestamp)),
+ open: row.open,
+ high: row.high,
+ low: row.low,
+ close: row.close,
+ volume: row.volume,
+ vwap: 101,
+ }));
+ const manifest = {
+ version: 1 as const,
+ instruments: [{ id: 'A.US', symbol: 'A', exchange: 'US' }],
+ startDate: '2024-03-08T00:00:00.000Z',
+ endDate: '2024-11-30T00:00:00.000Z',
+ interval: '1d',
+ policy: { adjustment: 'raw' as const, timestamp: 'utc-session-date' as const },
+ volumePolicy: 'reported' as const,
+ qualityPolicy: 'reject-invalid-no-interpolation' as const,
+ sources: [
+ { instrumentId: 'A.US', provider: 'eod' as const, revision: 'historical-normalization-v1' },
+ ],
+ barCount: bars.length,
+ };
+ const legacy: HistoricalDataset = {
+ manifest: {
+ ...manifest,
+ hash: createHash('sha256').update(JSON.stringify({ manifest, bars })).digest('hex'),
+ },
+ bars,
+ };
+ const converted = convertDatasetV1ToV2(legacy, fixture.metadata);
+ const bounds = {
+ ...converted.manifest.bounds,
+ tradeEnd: fixture.metadata.calendars[0]!.sessions[1]!.close,
+ };
+ const slice = sliceDatasetV2(converted, bounds);
+ expect(slice.manifest.parentDatasetHash).toBe(legacy.manifest.hash);
+ expect(slice.manifest.parentDatasetHash).not.toBe(converted.manifest.hash);
+ expect(slice.bars.every(b => b.vwap === null)).toBe(true);
+ expect(slice.manifest.limitations).toEqual(converted.manifest.limitations);
+ expect(validateDatasetV2(slice)).toEqual(slice);
+ });
+ test('corrupt source identities fail closed and strict recipe forbids fitting, labels, overlap and unknown fields', () => {
+ const dataset = chronologicalDataset().dataset,
+ raw = input(),
+ preview = source(dataset, raw);
+ expect(() =>
+ prepareChronologicalValidation({ ...raw, name: 'other' }, preview, dataset)
+ ).toThrow('identity mismatch');
+ const bad = structuredClone(preview);
+ bad.candidates[0]!.parameters = {};
+ expect(() => prepareChronologicalValidation(raw, bad, dataset)).toThrow('integrity');
+ for (const recipe of [
+ { ...raw.recipe, labelHorizonMs: 1 },
+ { ...raw.recipe, fit: true },
+ {
+ ...raw.recipe,
+ validation: { ...raw.recipe.validation, tradeStart: raw.recipe.train.tradeEnd - 1 },
+ },
+ { ...raw.recipe, train: { ...raw.recipe.train, warmupStart: raw.recipe.train.tradeStart } },
+ ]) {
+ expect(() => parseChronologicalValidation({ ...raw, recipe })).toThrow(
+ 'Invalid chronological'
+ );
+ }
+ expect(() => parseChronologicalValidation({ ...raw, modelArtifacts: [] })).toThrow();
+ const tooMany = {
+ ...raw,
+ grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1), slowPeriod: [199] },
+ };
+ expect(() => source(dataset, tooMany)).toThrow('at most');
+ });
+});
diff --git a/test/postgres/chronological-validation.test.ts b/test/postgres/chronological-validation.test.ts
new file mode 100644
index 00000000..ba826ad3
--- /dev/null
+++ b/test/postgres/chronological-validation.test.ts
@@ -0,0 +1,333 @@
+import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { afterEach, describe, expect, test } from 'bun:test';
+import { Hono } from 'hono';
+import { Pool, type PoolClient } from 'pg';
+import { createHttpSecurity } from '@stock-bot/di';
+import { getLogger, setLoggerConfig } from '@stock-bot/logger';
+import { PostgreSQLClient } from '@stock-bot/postgres';
+import type {
+ ChronologicalValidationInput,
+ ChronologicalValidationPreview,
+} from '@stock-bot/stock-config/chronological-validation';
+import { parseFinancialDecimal } from '@stock-bot/types';
+import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
+import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
+import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
+import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
+import { retainResearchDataset } from '../../scripts/import-research-dataset';
+import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
+import { canonicalSettings } from '../fixtures/canonical-research';
+import { chronologicalDataset } from '../fixtures/chronological-validation';
+
+setLoggerConfig({ logLevel: 'fatal', logConsole: false });
+const logger = getLogger('chronological-validation');
+const url = process.env.PIPELINE_TEST_DATABASE_URL;
+const cleanup: (() => Promise)[] = [];
+let packages: ReturnType | undefined;
+const tokens = {
+ operator: 'chronological-operator-fixture-not-a-real-secret-1234',
+ service: 'chronological-service-fixture-not-a-real-secret-1234',
+};
+afterEach(async () => {
+ for (const close of cleanup.splice(0).reverse()) {
+ await close();
+ }
+});
+async function fixture() {
+ if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
+ throw new Error('Disposable safety database required');
+ }
+ const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', '');
+ const admin = new Pool({ connectionString: url });
+ await admin.query(`CREATE SCHEMA ${schema}`);
+ // A single connection detects accidental nested pool reads while the admission lock is held.
+ const pool = new Pool({
+ connectionString: url,
+ application_name: schema,
+ max: 1,
+ 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',
+ '07-fix-execution-time-type.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',
+ '21-run-reproduction.sql',
+ '22-experiments.sql',
+ '23-experiment-retries.sql',
+ ]) {
+ await pool.query(
+ readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
+ );
+ }
+ const postgres = new PostgreSQLClient(
+ { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
+ logger
+ );
+ Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
+ Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
+ const container = { postgres, logger },
+ api = new BacktestServiceV2(container),
+ experiments = new ExperimentsService(container),
+ catalog = new StrategyCatalogService(container);
+ const version = await catalog.seedBuiltin(
+ 'Validation SMA',
+ (await (packages ??= packageBuiltinStrategies()))[0]!,
+ 'seed'
+ );
+ const data = chronologicalDataset(),
+ dataset = data.dataset;
+ await retainResearchDataset(pool, dataset);
+ const draft = await api.createBacktest(
+ {
+ name: 'Validation template',
+ strategy: 'catalog',
+ strategyVersionId: version.id,
+ strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
+ symbols: ['X0.US'],
+ startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
+ endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
+ initialCapital: 10000,
+ config: {
+ datasetHash: dataset.manifest.hash,
+ dataFrequency: '1m',
+ canonical: canonicalSettings,
+ },
+ },
+ { autoStart: false }
+ );
+ const input: ChronologicalValidationInput = {
+ backtestId: draft.id,
+ name: 'Three explicit windows',
+ grid: { fastPeriod: [1, 2], slowPeriod: [3] },
+ recipe: data.recipe,
+ };
+ const app = new Hono();
+ createHttpSecurity({
+ adminToken: tokens.operator,
+ serviceToken: tokens.service,
+ environment: 'test',
+ hostname: '127.0.0.1',
+ }).mount(app);
+ app.route('/', createExperimentRoutes(container));
+ const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') =>
+ app.request('/api/v2/experiments/validation/preview', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` },
+ body: JSON.stringify(raw),
+ });
+ const review = async (decision: 'approve' | 'revoke' = 'approve') => {
+ await catalog.reviewVersion(
+ version.id,
+ { decision, reason: 'Disposable validation proof' },
+ 'operator'
+ );
+ return (await catalog.getVersionReviews(version.id)).at(-1)!;
+ };
+ const snapshot = async () => {
+ const tables = (
+ await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [
+ schema,
+ ])
+ ).rows;
+ const rows: Record = {};
+ for (const { tablename } of tables) {
+ const quoted = '"' + String(tablename).replaceAll('"', '""') + '"';
+ rows[String(tablename)] = (
+ await pool.query(
+ `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t`
+ )
+ ).rows[0].rows;
+ }
+ return rows;
+ };
+ return {
+ pool,
+ postgres,
+ experiments,
+ catalog,
+ version,
+ draft,
+ dataset,
+ input,
+ request,
+ review,
+ snapshot,
+ };
+}
+
+describe.skipIf(!url)('chronological validation PostgreSQL preflight', () => {
+ test('real approved retained preview uses one transaction/connection, writes no tables and leaves ordinary economic policy unchanged', async () => {
+ const f = await fixture(),
+ review = await f.review(),
+ before = await f.snapshot();
+ const observed: string[] = [],
+ transaction = f.postgres.transaction.bind(f.postgres);
+ Object.defineProperty(f.postgres, 'transaction', {
+ value: (work: (client: PoolClient) => Promise) =>
+ transaction(client =>
+ work(
+ new Proxy(client, {
+ get(target, property) {
+ if (property === 'query') {
+ return (sql: string, values?: unknown[]) => {
+ observed.push(sql);
+ return target.query(sql, values);
+ };
+ }
+ const value = Reflect.get(target, property);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ })
+ )
+ ),
+ });
+ const response = await f.request();
+ expect(response.status).toBe(200);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ const { preview } = (await response.json()) as { preview: ChronologicalValidationPreview };
+ expect(preview.source.request.strategy.reviewId).toBe(review.id);
+ expect(preview.source.dataset).toEqual(f.dataset.manifest);
+ expect(preview.execution).toBe('preview-only');
+ expect(preview.source.candidates).toHaveLength(2);
+ expect(preview.partitions.map(p => p.phase)).toEqual(['train', 'validation', 'test']);
+ expect(preview.source.request.build.engineBinarySha256).toMatch(/^[a-f0-9]{64}$/);
+ expect(observed.length).toBeGreaterThan(0);
+ expect(observed.every(sql => sql.trimStart().startsWith('SELECT'))).toBe(true);
+ expect(observed[0]).toContain('FROM backtests WHERE id=$1 FOR UPDATE');
+ expect(observed[1]).toContain('FOR UPDATE OF s');
+ expect(await f.snapshot()).toEqual(before);
+ const ordinary = await f.experiments.preview({
+ backtestId: f.draft.id,
+ name: f.input.name,
+ grid: f.input.grid,
+ });
+ expect(preview.source).toEqual(ordinary);
+ expect(ordinary.request.policy.matching.risk).toEqual({
+ ledger: {
+ version: 1,
+ sessionId: ordinary.request.runId,
+ accountId: `research:${ordinary.request.runId}`,
+ baseCurrency: 'USD',
+ reserveOwnerId: 'reserve',
+ ownerIds: [`strategy:${f.version.id}`],
+ initialCapital: parseFinancialDecimal('10000'),
+ riskSession: {
+ calendarId: 'fixture-calendar',
+ calendarRevision: '1',
+ sessionId: '2024-01-01',
+ startsAt: f.dataset.manifest.bounds.warmupStart,
+ },
+ },
+ feeRate: parseFinancialDecimal(canonicalSettings.feeRate),
+ maxOrderQuantity: parseFinancialDecimal(canonicalSettings.maxOrderQuantity),
+ maxPositionQuantity: parseFinancialDecimal(canonicalSettings.maxPositionQuantity),
+ maxSymbolExposure: parseFinancialDecimal(canonicalSettings.maxSymbolExposure),
+ maxGrossExposure: parseFinancialDecimal(canonicalSettings.maxGrossExposure),
+ maxDailyLoss: parseFinancialDecimal(canonicalSettings.maxDailyLoss),
+ maxDrawdownAmount: parseFinancialDecimal(canonicalSettings.maxDrawdownAmount),
+ maxMarkAgeMs: canonicalSettings.maxMarkAgeMs,
+ });
+ expect(ordinary.request.policy.risk_boundaries).toEqual([]);
+ expect(await (await f.request(f.input, 'service')).json()).toEqual({ preview });
+ expect(await f.snapshot()).toEqual(before);
+ }, 30_000);
+ test('current approval, family/template availability and exact saved dataset remain authoritative', async () => {
+ const f = await fixture();
+ expect((await f.request()).status).toBe(409);
+ const first = await f.review(),
+ initial = (await (await f.request()).json()) as { preview: ChronologicalValidationPreview };
+ expect(initial.preview.source.request.strategy.reviewId).toBe(first.id);
+ await f.review('revoke');
+ expect((await f.request()).status).toBe(409);
+ const latest = await f.review(),
+ newer = (await (await f.request()).json()) as { preview: ChronologicalValidationPreview };
+ expect(newer.preview.source.request.strategy.reviewId).toBe(latest.id);
+ expect(newer.preview.previewHash).not.toBe(initial.preview.previewHash);
+ expect(newer.preview.partitions.map(p => p.dataset.hash)).toEqual(
+ initial.preview.partitions.map(p => p.dataset.hash)
+ );
+ await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
+ f.version.strategyId,
+ ]);
+ const archivedFamily = await f.snapshot();
+ expect((await f.request()).status).toBe(409);
+ expect(await f.snapshot()).toEqual(archivedFamily);
+ await f.pool.query('UPDATE strategies SET archived_at=NULL WHERE id=$1', [
+ f.version.strategyId,
+ ]);
+ await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
+ expect((await f.request()).status).toBe(409);
+ expect((await f.request({ ...f.input, backtestId: randomUUID() })).status).toBe(404);
+ expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
+ }, 30_000);
+ test('recipe cuts, insufficient candidate history and invalid or excessive grids reject without persistence', async () => {
+ const f = await fixture();
+ await f.review();
+ const before = await f.snapshot();
+ for (const raw of [
+ {
+ ...f.input,
+ recipe: {
+ ...f.input.recipe,
+ train: { ...f.input.recipe.train, tradeStart: f.input.recipe.train.tradeStart + 1 },
+ },
+ },
+ {
+ ...f.input,
+ recipe: {
+ ...f.input.recipe,
+ train: {
+ ...f.input.recipe.train,
+ warmupStart: f.input.recipe.train.warmupStart - 60_000,
+ },
+ },
+ },
+ { ...f.input, grid: { fastPeriod: [1], slowPeriod: [5] } },
+ { ...f.input, grid: { unknown: [1] } },
+ { ...f.input, grid: { fastPeriod: [1, 1] } },
+ {
+ ...f.input,
+ grid: {
+ fastPeriod: Array.from({ length: 11 }, (_, i) => i + 1),
+ slowPeriod: Array.from({ length: 10 }, (_, i) => i + 20),
+ },
+ },
+ ]) {
+ const response = await f.request(raw);
+ expect(response.status).toBe(400);
+ expect(await f.snapshot()).toEqual(before);
+ }
+ }, 30_000);
+ test('missing or corrupt retained input is unavailable, arbitrary storage failures remain sanitized500', async () => {
+ const f = await fixture();
+ await f.review();
+ await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER');
+ await f.pool.query(
+ "UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,close}','999') WHERE hash=$1",
+ [f.dataset.manifest.hash]
+ );
+ const corrupt = await f.snapshot();
+ expect((await f.request()).status).toBe(409);
+ expect(await f.snapshot()).toEqual(corrupt);
+ await f.pool.query('DELETE FROM backtest_datasets WHERE hash=$1', [f.dataset.manifest.hash]);
+ expect((await f.request()).status).toBe(409);
+ await f.pool.query('ALTER TABLE backtest_datasets RENAME TO unavailable_datasets');
+ const response = await f.request();
+ expect(response.status).toBe(500);
+ expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
+ }, 30_000);
+});