diff --git a/apps/stock/config/src/contracts/canonical-research.ts b/apps/stock/config/src/contracts/canonical-research.ts
index d644ffaa..2610cf9c 100644
--- a/apps/stock/config/src/contracts/canonical-research.ts
+++ b/apps/stock/config/src/contracts/canonical-research.ts
@@ -7,6 +7,7 @@ import type {
FinancialDecimal,
HistoricalDatasetInputV2,
HistoricalDatasetManifestV2,
+ HistoricalDatasetMetadataV2,
} from '@stock-bot/types';
import { parseFinancialDecimal } from '@stock-bot/types';
import { builtinStrategySelectionSchema } from './builtin-strategy';
@@ -214,8 +215,23 @@ export interface CanonicalDatasetPreparation {
reason: string | null;
}
-/** One materialized storage read; retention must use this input without requerying. */
+/** Intersections only: declarations are supplied by the caller, never inferred from source bars. */
+export function declaredStoredSourceWindows(metadata: HistoricalDatasetMetadataV2) {
+ const series = metadata.series[0];
+ const calendar = metadata.calendars.find(item => item.id === series?.calendarId);
+ return (calendar?.sessions ?? [])
+ .map(session => ({
+ date: session.date,
+ start: Math.max(session.open, metadata.bounds.warmupStart),
+ end: Math.min(session.close, metadata.bounds.tradeEnd),
+ }))
+ .filter(window => window.start < window.end)
+ .sort((left, right) => left.start - right.start);
+}
+
+/** Materialized source capture; retention must use this input without requerying. */
export interface CanonicalStoredSourcePreparation {
+ selection?: 'declared-sessions';
input: HistoricalDatasetInputV2;
preparation: CanonicalDatasetPreparation;
}
diff --git a/apps/stock/web-api/src/services/stored-dataset-preparation.ts b/apps/stock/web-api/src/services/stored-dataset-preparation.ts
index 90220e58..27a07999 100644
--- a/apps/stock/web-api/src/services/stored-dataset-preparation.ts
+++ b/apps/stock/web-api/src/services/stored-dataset-preparation.ts
@@ -1,6 +1,9 @@
import { z } from 'zod';
import { parseHistoricalDatasetMetadataV2 } from '@stock-bot/research/datasets';
-import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research';
+import {
+ declaredStoredSourceWindows,
+ type CanonicalStoredSourcePreparation,
+} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetInputV2, HistoricalDatasetMetadataV2 } from '@stock-bot/types';
import {
HistoricalStorageError,
@@ -16,7 +19,9 @@ export class StoredDatasetPreparationError extends Error {
super(message);
}
}
-const bodySchema = z.object({ metadata: z.unknown() }).strict();
+const bodySchema = z
+ .object({ metadata: z.unknown(), selection: z.literal('declared-sessions').optional() })
+ .strict();
function freeze(value: T): T {
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
Object.values(value).forEach(freeze);
@@ -24,10 +29,16 @@ function freeze(value: T): T {
}
return value;
}
-function metadataFromBody(body: unknown): HistoricalDatasetMetadataV2 {
+function metadataFromBody(body: unknown): {
+ metadata: HistoricalDatasetMetadataV2;
+ selection?: 'declared-sessions';
+} {
try {
const parsed = bodySchema.parse(body);
- return freeze(parseHistoricalDatasetMetadataV2(parsed.metadata));
+ return {
+ metadata: freeze(parseHistoricalDatasetMetadataV2(parsed.metadata)),
+ ...(parsed.selection ? { selection: parsed.selection } : {}),
+ };
} catch (error) {
const path = error instanceof z.ZodError ? error.issues[0]?.path.join('.') : undefined;
throw new StoredDatasetPreparationError(
@@ -39,14 +50,14 @@ function metadataFromBody(body: unknown): HistoricalDatasetMetadataV2 {
}
}
-/** Materialize one explicit stored EOD query. Captured bytes, not this mutable query, are retained. */
+/** Capture the explicit range or declared session windows. Retention never repeats these reads. */
export async function prepareStoredDataset(
body: unknown,
storage: Pick,
signal: AbortSignal
): Promise {
signal.throwIfAborted();
- const metadata = metadataFromBody(body);
+ const { metadata, selection } = metadataFromBody(body);
const series = metadata.series[0];
if (
!series ||
@@ -64,60 +75,79 @@ export async function prepareStoredDataset(
'Stored source supports one EOD raw 1m/5m/1h series with interval-start timestamps and declared interval-end-assumption availability'
);
}
- let rows;
- try {
- rows = await storage.getHistoricalBars(
- series.instrumentId,
- new Date(metadata.bounds.warmupStart),
- new Date(metadata.bounds.tradeEnd),
- series.interval,
- { adjustment: 'raw', timestamp: 'utc-instant' },
- signal,
- 'eod'
+ const windows =
+ selection === 'declared-sessions'
+ ? declaredStoredSourceWindows(metadata)
+ : [{ start: metadata.bounds.warmupStart, end: metadata.bounds.tradeEnd }];
+ if (!windows.length) {
+ throw new StoredDatasetPreparationError(
+ 422,
+ 'No declared sessions intersect the requested bounds'
);
- } catch (error) {
+ }
+ const captured: Array<
+ Omit & {
+ timestamp: number;
+ }
+ > = [];
+ for (const window of windows) {
signal.throwIfAborted();
- if (error instanceof HistoricalStorageError && error.code === 'missing-range') {
+ let rows;
+ try {
+ rows = await storage.getHistoricalBars(
+ series.instrumentId,
+ new Date(window.start),
+ new Date(window.end),
+ series.interval,
+ { adjustment: 'raw', timestamp: 'utc-instant' },
+ signal,
+ 'eod'
+ );
+ } catch (error) {
+ signal.throwIfAborted();
+ if (error instanceof HistoricalStorageError && error.code === 'missing-range') {
+ throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range');
+ }
+ if (error instanceof HistoricalStorageError && error.code === 'provider-unavailable') {
+ throw new StoredDatasetPreparationError(503, 'EOD historical storage is unavailable');
+ }
+ throw error;
+ }
+ signal.throwIfAborted();
+ if (!rows.length) {
throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range');
}
- if (error instanceof HistoricalStorageError && error.code === 'provider-unavailable') {
- throw new StoredDatasetPreparationError(503, 'EOD historical storage is unavailable');
- }
- throw error;
- }
- signal.throwIfAborted();
- if (!rows.length) {
- throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range');
- }
- for (const row of rows) {
- if (
- row.symbol !== series.instrumentId ||
- row.source !== 'eod' ||
- row.interpolated === true ||
- !(row.timestamp instanceof Date) ||
- !Number.isSafeInteger(row.timestamp.getTime()) ||
- row.timestamp.getTime() < metadata.bounds.warmupStart ||
- row.timestamp.getTime() >= metadata.bounds.tradeEnd
- ) {
- throw new Error('Stored source returned inconsistent bar identity or range');
- }
- }
- const input: HistoricalDatasetInputV2 = freeze({
- metadata,
- // Ordinal is deterministic adapter ordering, not a vendor publication sequence.
- bars: [...rows]
- .sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime())
- .map((row, sourceSequence) => ({
+ for (const row of rows) {
+ if (
+ row.symbol !== series.instrumentId ||
+ row.source !== 'eod' ||
+ row.interpolated === true ||
+ !(row.timestamp instanceof Date) ||
+ !Number.isSafeInteger(row.timestamp.getTime()) ||
+ row.timestamp.getTime() < window.start ||
+ row.timestamp.getTime() >= window.end
+ ) {
+ throw new Error('Stored source returned inconsistent bar identity or range');
+ }
+ // Snapshot scalars now: a subsequent asynchronous read may reuse mutable adapter rows.
+ captured.push({
seriesId: series.id,
timestamp: row.timestamp.getTime(),
- sourceSequence,
open: row.open,
high: row.high,
low: row.low,
close: row.close,
volume: row.volume,
...(row.vwap === undefined ? {} : { vwap: row.vwap }),
- })),
+ });
+ }
+ }
+ const input: HistoricalDatasetInputV2 = freeze({
+ metadata,
+ // Ordinal is deterministic adapter ordering, not a vendor publication sequence.
+ bars: captured
+ .sort((a, b) => a.timestamp - b.timestamp)
+ .map((row, sourceSequence) => ({ ...row, sourceSequence })),
});
let preparation;
try {
@@ -132,5 +162,5 @@ export async function prepareStoredDataset(
throw error;
}
signal.throwIfAborted();
- return freeze({ input, preparation });
+ return freeze({ input, preparation, ...(selection ? { selection } : {}) });
}
diff --git a/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx b/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx
index 2c0d23aa..f4b97216 100644
--- a/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx
+++ b/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx
@@ -2,7 +2,11 @@ import { useEffect, useRef, useState } from 'react';
import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
-import { backtestApiV2, DatasetPreparationRequestError } from '../services/backtestApiV2';
+import {
+ backtestApiV2,
+ DatasetPreparationRequestError,
+ storedSourceSessionScope,
+} from '../services/backtestApiV2';
import { StoredSourceInspector } from './StoredSourceInspector';
export interface DatasetPreparationState {
@@ -19,7 +23,7 @@ interface Retention {
input: unknown;
preview: CanonicalDatasetPreparation;
}
-type InputMode = 'export' | 'stored-eod';
+type InputMode = 'export' | 'stored-eod' | 'stored-eod-sessions';
const instant = (value: number) => new Date(value).toISOString();
export function DatasetPreparation({ disabled, begin, onStateChange, onRetained }: Props) {
const [mode, setMode] = useState('export');
@@ -71,7 +75,7 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
};
const changeMode = (next: string) => {
if (
- (next !== 'export' && next !== 'stored-eod') ||
+ (next !== 'export' && next !== 'stored-eod' && next !== 'stored-eod-sessions') ||
next === modeRef.current ||
disabled ||
captured.current ||
@@ -147,8 +151,12 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
state(true, true);
try {
const result =
- selectedMode === 'stored-eod'
- ? await backtestApiV2.previewStoredDataset(selectedSource.value, abort.signal)
+ selectedMode !== 'export'
+ ? await backtestApiV2.previewStoredDataset(
+ selectedSource.value,
+ abort.signal,
+ selectedMode === 'stored-eod-sessions' ? 'declared-sessions' : undefined
+ )
: {
input: selectedSource.value,
preparation: await backtestApiV2.previewDataset(selectedSource.value, abort.signal),
@@ -239,6 +247,8 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
}
}
};
+ const sessionWindows =
+ mode === 'stored-eod-sessions' && input ? storedSourceSessionScope(input.value) : null;
return (
@@ -258,9 +268,10 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
>
Source export
Stored EOD intraday bars
+ Stored EOD — declared sessions only
- {mode === 'stored-eod' && (
+ {mode !== 'export' && (
Load one EOD instrument from existing storage using raw 1m, 5m or 1h interval-start bars.
Supply complete metadata with interval-end-assumption availability. Source sequence is a
@@ -269,7 +280,7 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
uses that captured snapshot without querying storage again.
)}
- {mode === 'stored-eod' && (
+ {mode !== 'export' && (
)}
@@ -292,6 +303,29 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
Selected {mode === 'export' ? 'export' : 'metadata'}: {input.filename}
)}
+ {mode === 'stored-eod-sessions' && (
+
+
+ Reads only the declared calendar sessions intersecting warmup start through trading end.
+ Rows outside those explicit windows are not requested. Invalid or empty selected
+ sessions fail preparation; bars are never shortened to fit. This does not verify the
+ calendar or establish gap-free coverage.
+
+ {sessionWindows === null ? (
+ Supply complete single-series metadata to view the declared UTC query windows.
+ ) : sessionWindows.length === 0 ? (
+ No declared sessions intersect the requested bounds.
+ ) : (
+
+ {sessionWindows.map(window => (
+
+ {window.date}: {instant(window.start)} — {instant(window.end)} (end exclusive)
+
+ ))}
+
+ )}
+
+ )}
{phase && (
{phase === 'reading'
@@ -353,10 +387,11 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
)}
{preview && (
- {mode === 'stored-eod' && (
+ {mode !== 'export' && (
- Stored source: EOD · Query bounds (UTC, end exclusive):{' '}
- {instant(preview.manifest.bounds.warmupStart)} —{' '}
+ Stored source: EOD ·{' '}
+ {mode === 'stored-eod-sessions' ? 'Declared sessions within bounds' : 'Query bounds'}{' '}
+ (UTC, end exclusive): {instant(preview.manifest.bounds.warmupStart)} —{' '}
{instant(preview.manifest.bounds.tradeEnd)}
)}
diff --git a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts
index c9026275..82690a2d 100644
--- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts
+++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts
@@ -4,7 +4,10 @@ import {
preparationManifestSchema,
} from '@stock-bot/research/dataset-contracts';
import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution';
-import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
+import {
+ canonicalRunRequestSchema,
+ declaredStoredSourceWindows,
+} from '@stock-bot/stock-config/canonical-research';
import type {
CanonicalDatasetCatalogEntry,
CanonicalDatasetPreparation,
@@ -218,14 +221,29 @@ function metadataIdentity(value: PreparationMetadata) {
.sort((a, b) => compareText(a.instrumentId, b.instrumentId)),
});
}
+/** Preview caller declarations only; the server still validates the complete metadata and bars. */
+export function storedSourceSessionScope(raw: unknown) {
+ const parsed = preparationMetadata.safeParse(raw);
+ return parsed.success && parsed.data.series.length === 1
+ ? declaredStoredSourceWindows(parsed.data)
+ : null;
+}
export function parseStoredDatasetPreparation(
raw: unknown,
- suppliedMetadata: unknown
+ suppliedMetadata: unknown,
+ selection?: CanonicalStoredSourcePreparation['selection']
): CanonicalStoredSourcePreparation {
const envelope = z
- .object({ input: storedSourceInput, preparation: z.unknown() })
+ .object({
+ input: storedSourceInput,
+ preparation: z.unknown(),
+ selection: z.literal('declared-sessions').optional(),
+ })
.strict()
.parse(raw);
+ if (envelope.selection !== selection) {
+ throw new Error('The stored source response does not match the requested selection.');
+ }
const preparation = parseDatasetPreparation(envelope.preparation);
const expected = preparationMetadata.parse(suppliedMetadata);
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
@@ -268,7 +286,7 @@ export function parseStoredDatasetPreparation(
) {
throw new Error('The stored source response does not match its metadata and prepared dataset.');
}
- return { input, preparation };
+ return { input, preparation, ...(selection ? { selection } : {}) };
}
export class DatasetPreparationRequestError extends Error {
constructor(
@@ -317,12 +335,13 @@ export const backtestApiV2 = {
prepareDatasetRequest({ input, expectedHash }, signal),
async previewStoredDataset(
metadata: unknown,
- signal?: AbortSignal
+ signal?: AbortSignal,
+ selection?: CanonicalStoredSourcePreparation['selection']
): Promise {
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical/stored-source`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ metadata }),
+ body: JSON.stringify({ metadata, ...(selection ? { selection } : {}) }),
signal,
});
if (!response.ok) {
@@ -332,7 +351,7 @@ export const backtestApiV2 = {
if (response.status !== 200) {
throw new Error('Unexpected stored source status');
}
- return parseStoredDatasetPreparation(await response.json(), metadata);
+ return parseStoredDatasetPreparation(await response.json(), metadata, selection);
} catch {
throw new Error('The stored source response could not be verified.');
}
diff --git a/docs/backtest-datasets.md b/docs/backtest-datasets.md
index af6d343d..2146c9fd 100644
--- a/docs/backtest-datasets.md
+++ b/docs/backtest-datasets.md
@@ -63,6 +63,33 @@ Historical Bun 1.2.17 sample, recorded before removal of the size-limit machiner
Results vary with machine load and garbage collection. This optional diagnostic remains
available; it does not impose input limits or change v1 content identity.
+## Stored EOD preparation across declared sessions (v2)
+
+In backtest **Settings → Prepare dataset from source export**, choose **Stored EOD —
+declared sessions only** and upload the complete v2 metadata JSON. The panel displays
+the selected series' declared session windows, clipped to the warmup/evaluation bounds,
+in UTC. Preview reads these windows sequentially; retain saves the captured input and
+hash without querying the mutable source again.
+The reads are not an atomic database snapshot; the captured rows define the retained
+dataset. Cancellation prevents subsequent reads/results but does not interrupt an
+already dispatched Mongo query.
+
+The existing API opts in explicitly:
+
+```json
+{ "metadata": { "...": "complete v2 metadata" }, "selection": "declared-sessions" }
+```
+
+Send this to `POST /api/v2/datasets/canonical/stored-source`. The response echoes
+`selection` alongside `input` and `preparation`; retain uses that exact `input` and
+`preparation.hash`. Omitting `selection` preserves the continuous-range query.
+
+Empty selected sessions, invalid selected rows, duplicates and bars crossing a session
+boundary fail preparation. Rows outside the declared windows are never read. Sessions,
+corporate-action coverage and source timing remain explicit operator declarations:
+successful preparation does not certify them or establish gap-free data. The source
+inspector diagnoses its own selected range independently of these capture windows.
+
## Verification
`bun run check` includes complete-range reads without row caps, acceptance beyond the
diff --git a/docs/development/backlog/tasks/RP03.md b/docs/development/backlog/tasks/RP03.md
index 80ac9522..e628a11e 100644
--- a/docs/development/backlog/tasks/RP03.md
+++ b/docs/development/backlog/tasks/RP03.md
@@ -15,3 +15,5 @@ Likely files/locks: `apps/stock/config/src/contracts/canonical-research.ts`, `ap
Acceptance/tests: unchanged default query/output; two sessions with an intervening invalid close marker succeed only in explicit session mode; selected null/OHLC/identity/duplicate errors and missing sessions fail; per-window out-of-range adapter results fail; DST, early close and clipped bounds use declared instants; partial bars fail; metadata/earlier-row mutation cannot affect captured results; abort prevents later reads; repeated same capture has the same v2 hash; wrong response mode and late replies fail; retention retry never rereads. Extend the real browser preparation workflow. Validate a read-only actual stored multi-session preview against exact selected source rows; no new research execution is required.
Gates: focused regressions, types/strict lint, full repository check, relevant disposable PostgreSQL retention tests and Chromium workbench. Independent backend/frontend acceptance before completion. Risk: hiding source defects outside incorrectly declared sessions or implying gap-free data; declarations remain explicit and unverified by the UI.
+
+Accepted October 27, 2026: explicit session-window capture and its web workflow are implemented with unchanged default behavior and dataset identity rules. Independent backend/frontend reviewers accepted. Root passed the full repository check, 14 relevant PostgreSQL tests and all 20 Chromium scenarios. Actual read-only AAPL October 1–2 preparation captured 156 unchanged bars with identical repeated hashes; the continuous query still rejects its interior null-volume marker. No real dataset retention or research run was performed. [Combined evidence](../../real-data-research.md) records scope, hashes and limitations; [usage](../../../backtest-datasets.md#stored-eod-preparation-across-declared-sessions-v2) explains the explicit selection.
diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts
index c8e9c0e5..1e3a49ef 100644
--- a/test/e2e/workbench.test.ts
+++ b/test/e2e/workbench.test.ts
@@ -2351,6 +2351,127 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
}
});
+test('declared_session_source_browser_captures_two_windows_and_retains_without_requery', async () => {
+ const f = await fixture();
+ try {
+ await f.login();
+ const { id, dataset } = await createCanonicalInBrowser(f, 'Declared session preparation');
+ const { calendars, series, executionSeries, bounds, universe, corporateActions } =
+ dataset.manifest;
+ const start = bounds.warmupStart;
+ const end = dataset.bars.at(-1)!.intervalEnd;
+ const day = 86_400_000;
+ const metadata = {
+ calendars: calendars.map(calendar => ({
+ ...calendar,
+ endDate: new Date(end + 2 * day).toISOString().slice(0, 10),
+ sessions: [
+ { date: new Date(start).toISOString().slice(0, 10), open: start, close: end },
+ {
+ date: new Date(start + day).toISOString().slice(0, 10),
+ open: start + day,
+ close: end + day,
+ },
+ ],
+ })),
+ series: series.map(value => ({
+ ...value,
+ source: { provider: 'eod', revision: 'declared-two-session-browser-fixture' },
+ availability: 'interval-end-assumption',
+ })),
+ executionSeries,
+ bounds: { ...bounds, tradeEnd: end + day },
+ universe,
+ corporateActions: corporateActions.map(value => ({ ...value, end: end + day })),
+ };
+ const firstRows = dataset.bars.map(bar => ({
+ eodSearchCode: 'X0.US',
+ symbol: 'X0',
+ exchange: 'US',
+ timestamp: bar.intervalStart / 1000,
+ open: bar.open,
+ high: bar.high,
+ low: bar.low,
+ close: bar.close,
+ volume: bar.volume,
+ }));
+ f.setStoredEodBars('eodIntraday1M', [
+ ...firstRows,
+ { ...firstRows[0]!, timestamp: end / 1000, volume: -1 },
+ ...firstRows.map(row => ({ ...row, timestamp: row.timestamp + day / 1000 })),
+ ]);
+ const before = await f.request(`/api/v2/backtests/${id}`);
+ await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
+ await f.page.getByText('Prepare dataset from source export', { exact: true }).click();
+ await f.page.getByLabel('Dataset input', { exact: true }).selectOption('stored-eod-sessions');
+ await f.page.getByLabel('Source metadata JSON', { exact: true }).setInputFiles({
+ name: 'two-declared-sessions.json',
+ mimeType: 'application/json',
+ buffer: Buffer.from(JSON.stringify(metadata)),
+ });
+ const windows = f.page.getByRole('list', { name: 'Declared UTC query windows', exact: true });
+ await windows.waitFor({ state: 'visible' });
+ expect(await windows.getByRole('listitem').count()).toBe(2);
+ for (const offset of [0, day]) {
+ expect(await windows.textContent()).toContain(new Date(start + offset).toISOString());
+ expect(await windows.textContent()).toContain(new Date(end + offset).toISOString());
+ }
+ const previewing = f.page.waitForResponse(response =>
+ response.url().endsWith('/api/v2/datasets/canonical/stored-source')
+ );
+ await f.page.getByRole('button', { name: 'Preview dataset', exact: true }).click();
+ const response = await previewing;
+ expect(response.status()).toBe(200);
+ expect(response.request().postDataJSON()).toEqual({ metadata, selection: 'declared-sessions' });
+ const captured = (await response.json()) as CanonicalStoredSourcePreparation;
+ expect(captured.selection).toBe('declared-sessions');
+ expect(captured.input.bars).toHaveLength(2 * firstRows.length);
+ expect(f.storedSourceReads).toEqual(
+ [start, start + day].map(windowStart => ({
+ collection: 'eodIntraday1M',
+ filter: {
+ eodSearchCode: 'X0.US',
+ timestamp: { $gte: windowStart / 1000, $lt: (windowStart + end - start) / 1000 },
+ },
+ }))
+ );
+ await visible(f.page, `Dataset hash: ${captured.preparation.hash}`);
+ f.setStoredEodBars('eodIntraday1M', []);
+ const retaining = f.page.waitForResponse(result =>
+ result.url().endsWith('/api/v2/datasets/canonical/retain')
+ );
+ await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click();
+ const retained = await retaining;
+ expect(retained.status()).toBe(200);
+ expect(retained.request().postDataJSON()).toEqual({
+ input: captured.input,
+ expectedHash: captured.preparation.hash,
+ });
+ await until(
+ async () =>
+ (await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()) ===
+ captured.preparation.hash,
+ 'declared-session snapshot selection'
+ );
+ expect(f.storedSourceReads).toHaveLength(2);
+ expect(
+ (
+ await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
+ captured.preparation.hash,
+ ])
+ ).rows[0].payload
+ ).toEqual(createDatasetV2(captured.input));
+ expect(await f.request(`/api/v2/backtests/${id}`)).toEqual(before);
+ expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
+ expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
+ 0
+ );
+ expect(f.unexpectedNetwork).toEqual([]);
+ } finally {
+ await f.close();
+ }
+});
+
test('stored_source_inspection_browser_keeps_utc_scope_and_research_state_unchanged', async () => {
const f = await fixture();
try {
diff --git a/test/integration/dataset-source-preparation-ui.test.tsx b/test/integration/dataset-source-preparation-ui.test.tsx
index 91ffd860..3ac94552 100644
--- a/test/integration/dataset-source-preparation-ui.test.tsx
+++ b/test/integration/dataset-source-preparation-ui.test.tsx
@@ -119,7 +119,7 @@ function upload(value: unknown = datasetInput(), name = 'source.json', read?: Pr
Object.defineProperty(file, 'text', { value: () => read });
}
const label =
- field('Dataset input').value === 'stored-eod' ? 'Source metadata JSON' : 'Source dataset JSON';
+ field('Dataset input').value !== 'export' ? 'Source metadata JSON' : 'Source dataset JSON';
Object.defineProperty(field(label), 'files', {
configurable: true,
value: [file],
@@ -1326,3 +1326,168 @@ describe('stored source panel', () => {
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
});
});
+
+function declaredSessionFixture(): CanonicalStoredSourcePreparation {
+ const offset = 86400000;
+ const metadata: HistoricalDatasetMetadataV2 = {
+ ...storedMetadata,
+ bounds: { ...storedMetadata.bounds, tradeEnd: storedMetadata.bounds.tradeEnd + offset },
+ calendars: storedMetadata.calendars.map(calendar => ({
+ ...calendar,
+ endDate: '2024-03-13',
+ sessions: [
+ ...calendar.sessions,
+ ...calendar.sessions.map(session => ({
+ date: '2024-03-12',
+ open: session.open + offset,
+ close: session.close + offset,
+ })),
+ ],
+ })),
+ corporateActions: storedMetadata.corporateActions.map(coverage => ({
+ ...coverage,
+ end: coverage.end + offset,
+ })),
+ };
+ const input = {
+ metadata,
+ bars: [
+ ...stored.input.bars,
+ ...stored.input.bars.map(bar => ({ ...bar, timestamp: Number(bar.timestamp) + offset })),
+ ].map((bar, sourceSequence) => ({ ...bar, sourceSequence })),
+ };
+ const normalized = createDatasetV2(input);
+ return {
+ input,
+ selection: 'declared-sessions',
+ preparation: {
+ ...stored.preparation,
+ hash: normalized.manifest.hash,
+ manifest: normalized.manifest,
+ },
+ };
+}
+
+describe('declared-session stored preparation contract and panel', () => {
+ test('requires the exact requested selection echo while keeping the default response unchanged', () => {
+ const sessions = declaredSessionFixture();
+ expect(
+ parseStoredDatasetPreparation(sessions, sessions.input.metadata, 'declared-sessions')
+ ).toEqual(sessions);
+ expect(parseStoredDatasetPreparation(stored, storedMetadata)).toEqual(stored);
+ for (const selection of [undefined, null, 'continuous', false]) {
+ expect(() =>
+ parseStoredDatasetPreparation(
+ { ...sessions, selection },
+ sessions.input.metadata,
+ 'declared-sessions'
+ )
+ ).toThrow();
+ }
+ expect(() => parseStoredDatasetPreparation(sessions, sessions.input.metadata)).toThrow();
+ });
+
+ test('shows declared UTC windows, captures explicit session mode and retries retention without rereading', async () => {
+ const sessions = declaredSessionFixture();
+ await mountPanel();
+ await flush(() => edit('Dataset input', 'stored-eod-sessions'));
+ expect(requests).toHaveLength(0);
+ expect(host.textContent).toContain('does not verify the calendar');
+ await flush(() => upload(sessions.input.metadata, 'sessions.json'));
+ const windows = host.querySelector('[aria-label="Declared UTC query windows"]');
+ expect(windows?.textContent).toContain('2024-03-11T13:30:00.000Z');
+ expect(windows?.textContent).toContain('2024-03-11T20:00:00.000Z');
+ expect(windows?.textContent).toContain('2024-03-12T13:30:00.000Z');
+ expect(windows?.textContent).toContain('2024-03-12T20:00:00.000Z');
+ expect(requests).toHaveLength(0);
+ await flush(() => click('Preview dataset'));
+ expect(request(storedPath).body).toEqual({
+ metadata: sessions.input.metadata,
+ selection: 'declared-sessions',
+ });
+ await flush(() => reply(request(storedPath), sessions));
+ expect(host.textContent).toContain('Declared sessions within bounds');
+ await flush(() => click('Retain dataset'));
+ const first = request(retainPath);
+ expect(first.body).toEqual({ input: sessions.input, expectedHash: sessions.preparation.hash });
+ await flush(() => fail(first));
+ expect(field('Dataset input').disabled).toBe(true);
+ expect(field('Source metadata JSON').disabled).toBe(true);
+ await flush(() => edit('Dataset input', 'stored-eod'));
+ expect(field('Dataset input').value).toBe('stored-eod-sessions');
+ await flush(() => click('Retry retaining same dataset'));
+ expect(request(retainPath).body).toEqual(first.body);
+ expect(requests.filter(value => value.path === storedPath)).toHaveLength(1);
+ await flush(() => reply(request(retainPath), { preparation: sessions.preparation }));
+ expect(retained).toEqual([{ hash: sessions.preparation.hash, available: true }]);
+ });
+
+ test('missing or wrong echoed mode fails closed and preserves metadata for retry', async () => {
+ const sessions = declaredSessionFixture();
+ await mountPanel();
+ await flush(() => edit('Dataset input', 'stored-eod-sessions'));
+ await flush(() => upload(sessions.input.metadata));
+ for (const selection of [undefined, 'continuous']) {
+ await flush(() => click('Preview dataset'));
+ await flush(() => reply(request(storedPath), { ...sessions, selection }));
+ expect(button('Retain dataset').disabled).toBe(true);
+ expect(host.querySelector('[role="alert"]')?.textContent).toContain('could not be verified');
+ expect(host.textContent).toContain('Selected metadata: source.json');
+ expect(button('Preview dataset').disabled).toBe(false);
+ }
+ });
+
+ test('switching between stored modes cancels the old preview and late replies cannot restore it', async () => {
+ const sessions = declaredSessionFixture();
+ await mountPanel();
+ await flush(() => edit('Dataset input', 'stored-eod-sessions'));
+ await flush(() => upload(sessions.input.metadata));
+ await flush(() => click('Preview dataset'));
+ const old = request(storedPath);
+ await flush(() => edit('Dataset input', 'stored-eod'));
+ expect(old.signal?.aborted).toBe(true);
+ await flush(() => reply(old, sessions));
+ expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
+ expect(host.querySelector('[aria-label="Declared session selection"]')).toBeNull();
+ expect(button('Retain dataset').disabled).toBe(true);
+ await flush(() => upload(storedMetadata));
+ await flush(() => click('Preview dataset'));
+ expect(request(storedPath).body).toEqual({ metadata: storedMetadata });
+ await flush(() => reply(request(storedPath), stored));
+ expect(button('Retain dataset').disabled).toBe(false);
+ });
+
+ test('clipped windows and an empty intersection are displayed without starting a source read', async () => {
+ const sessions = declaredSessionFixture();
+ const metadata = sessions.input.metadata;
+ await mountPanel();
+ await flush(() => edit('Dataset input', 'stored-eod-sessions'));
+ await flush(() =>
+ upload({
+ ...metadata,
+ bounds: {
+ ...metadata.bounds,
+ warmupStart: metadata.bounds.warmupStart + 300000,
+ tradeStart: metadata.bounds.warmupStart + 300000,
+ tradeEnd: metadata.bounds.tradeEnd - 300000,
+ },
+ })
+ );
+ const windows = host.querySelector('[aria-label="Declared UTC query windows"]');
+ expect(windows?.textContent).toContain('2024-03-11T13:35:00.000Z');
+ expect(windows?.textContent).toContain('2024-03-12T19:55:00.000Z');
+ await flush(() =>
+ upload({
+ ...metadata,
+ bounds: {
+ warmupStart: Date.parse('2024-03-11T20:00:00Z'),
+ tradeStart: Date.parse('2024-03-11T21:00:00Z'),
+ tradeEnd: Date.parse('2024-03-12T13:30:00Z'),
+ },
+ })
+ );
+ expect(host.textContent).toContain('No declared sessions intersect the requested bounds');
+ expect(requests).toHaveLength(0);
+ expect(button('Retain dataset').disabled).toBe(true);
+ });
+});
diff --git a/test/integration/stored-dataset-preparation.test.ts b/test/integration/stored-dataset-preparation.test.ts
index 0b3bf520..29657f5b 100644
--- a/test/integration/stored-dataset-preparation.test.ts
+++ b/test/integration/stored-dataset-preparation.test.ts
@@ -470,3 +470,261 @@ describe('stored EOD preparation', () => {
expect(f.read).toHaveBeenCalledTimes(1);
});
});
+
+function sessionSource() {
+ const input = source('5m');
+ const calendar = at(input.metadata.calendars);
+ const first = at(calendar.sessions);
+ first.close = input.metadata.bounds.tradeEnd;
+ const offset = 86400000;
+ const second = {
+ date: new Date(first.open + offset).toISOString().slice(0, 10),
+ open: first.open + offset,
+ close: first.close + offset,
+ };
+ calendar.sessions.push(second);
+ calendar.endDate = new Date(second.close + offset).toISOString().slice(0, 10);
+ input.metadata.bounds.tradeEnd = second.close;
+ at(input.metadata.corporateActions).end = second.close;
+ return {
+ ...input,
+ rows: [
+ ...input.rows,
+ ...input.rows.map(row => ({ ...row, timestamp: row.timestamp + offset / 1000 })),
+ ],
+ sessions: [first, second],
+ };
+}
+function filterRows(rows: Row[]) {
+ return async (_collection: string, filter: Record) => {
+ const range = filter.timestamp as { $gte: number; $lt: number };
+ return rows.filter(row => row.timestamp >= range.$gte && row.timestamp < range.$lt);
+ };
+}
+
+describe('explicit declared-session stored preparation', () => {
+ const selection = 'declared-sessions' as const;
+ test('only explicit mode selects sessions, excluding an invalid close marker without post-filtering source rows', async () => {
+ const input = sessionSource();
+ const marker = {
+ ...at(input.rows),
+ timestamp: at(input.sessions).close / 1000,
+ volume: null as unknown as number,
+ };
+ const rows = [...input.rows, marker];
+ const regular = fixture(filterRows(rows));
+ expect((await regular.request({ metadata: input.metadata })).status).toBe(500);
+ expect(regular.read).toHaveBeenCalledTimes(1);
+ const selected = fixture(filterRows(rows));
+ const response = await selected.request({ metadata: input.metadata, selection });
+ expect(response.status).toBe(200);
+ const captured = await response.json();
+ expect(captured.selection).toBe(selection);
+ expect(captured.input.bars.map((bar: { timestamp: number }) => bar.timestamp)).toEqual(
+ input.rows.map(row => row.timestamp * 1000)
+ );
+ expect(
+ captured.input.bars.map((bar: { sourceSequence: number }) => bar.sourceSequence)
+ ).toEqual([0, 1, 2, 3, 4, 5]);
+ expect(selected.read.mock.calls.map(call => call[1].timestamp)).toEqual(
+ input.sessions.map(session => ({ $gte: session.open / 1000, $lt: session.close / 1000 }))
+ );
+ expect(selected.query).not.toHaveBeenCalled();
+ expect(selected.questdb.query).not.toHaveBeenCalled();
+ const repeated = await (await selected.request({ metadata: input.metadata, selection })).json();
+ expect(repeated.preparation.hash).toBe(captured.preparation.hash);
+ expect(captured.preparation).toEqual(previewDatasetPreparation({ input: captured.input }));
+ expect(rows).toContain(marker);
+ expect(marker.volume).toBeNull();
+ });
+
+ test('missing and invalid selected sessions fail the entire capture, including later failures', async () => {
+ for (const defect of ['missing', 'null-volume', 'ohlc', 'identity', 'duplicate'] as const) {
+ const input = sessionSource();
+ const last = at(input.rows, 3);
+ if (defect === 'missing') {
+ input.rows.splice(3);
+ }
+ if (defect === 'null-volume') {
+ last.volume = null as unknown as number;
+ }
+ if (defect === 'ohlc') {
+ last.high = last.low - 1;
+ }
+ if (defect === 'identity') {
+ last.symbol = 'WRONG';
+ }
+ if (defect === 'duplicate') {
+ input.rows.push({ ...last });
+ }
+ const f = fixture(filterRows(input.rows));
+ const response = await f.request({ metadata: input.metadata, selection });
+ expect(response.status).toBe(defect === 'missing' ? 404 : 500);
+ expect(await response.json()).not.toHaveProperty('input');
+ expect(f.read).toHaveBeenCalledTimes(2);
+ expect(f.query).not.toHaveBeenCalled();
+ }
+ });
+
+ test('empty intersections and unsupported selection reject before any source read', async () => {
+ const input = sessionSource();
+ const f = fixture();
+ input.metadata.bounds.warmupStart = at(input.sessions).close;
+ input.metadata.bounds.tradeStart = at(input.sessions).close;
+ input.metadata.bounds.tradeEnd = at(input.sessions, 1).open;
+ expect((await f.request({ metadata: input.metadata, selection })).status).toBe(422);
+ expect((await f.request({ metadata: input.metadata, selection: 'regular-hours' })).status).toBe(
+ 400
+ );
+ expect((await f.request({ metadata: input.metadata, selection: null })).status).toBe(400);
+ expect(f.read).not.toHaveBeenCalled();
+ });
+
+ test('declared DST instants, early close and clipped bounds are exact; sparse nonempty sessions remain allowed', async () => {
+ const input = sessionSource();
+ const calendar = at(input.metadata.calendars);
+ calendar.timeZone = 'America/New_York';
+ calendar.startDate = '2024-03-08';
+ calendar.endDate = '2024-03-12';
+ calendar.sessions = [
+ {
+ date: '2024-03-08',
+ open: Date.parse('2024-03-08T14:30:00Z'),
+ close: Date.parse('2024-03-08T18:00:00Z'),
+ },
+ {
+ date: '2024-03-11',
+ open: Date.parse('2024-03-11T13:30:00Z'),
+ close: Date.parse('2024-03-11T20:00:00Z'),
+ },
+ ];
+ input.metadata.bounds = {
+ warmupStart: Date.parse('2024-03-08T14:35:00Z'),
+ tradeStart: Date.parse('2024-03-08T14:40:00Z'),
+ tradeEnd: Date.parse('2024-03-11T13:40:00Z'),
+ };
+ at(input.metadata.corporateActions).start = input.metadata.bounds.warmupStart;
+ at(input.metadata.corporateActions).end = input.metadata.bounds.tradeEnd;
+ input.metadata.universe.asOf = input.metadata.bounds.warmupStart;
+ const rows = [
+ { ...at(input.rows), timestamp: input.metadata.bounds.warmupStart / 1000 },
+ { ...at(input.rows), timestamp: Date.parse('2024-03-11T13:30:00Z') / 1000 },
+ ];
+ const f = fixture(filterRows(rows));
+ const response = await f.request({ metadata: input.metadata, selection });
+ expect(response.status).toBe(200);
+ expect(f.read.mock.calls.map(call => call[1].timestamp)).toEqual([
+ {
+ $gte: Date.parse('2024-03-08T14:35:00Z') / 1000,
+ $lt: Date.parse('2024-03-08T18:00:00Z') / 1000,
+ },
+ {
+ $gte: Date.parse('2024-03-11T13:30:00Z') / 1000,
+ $lt: Date.parse('2024-03-11T13:40:00Z') / 1000,
+ },
+ ]);
+ expect((await response.json()).input.bars).toHaveLength(2);
+ });
+
+ test('a selected bar crossing session close or clipped trading end is rejected rather than shortened or dropped', async () => {
+ for (const boundary of ['close', 'tradeEnd'] as const) {
+ const input = sessionSource();
+ if (boundary === 'close') {
+ at(at(input.metadata.calendars).sessions).close -= 30000;
+ } else {
+ input.metadata.bounds.tradeEnd -= 30000;
+ }
+ const f = fixture(filterRows(input.rows));
+ const response = await f.request({ metadata: input.metadata, selection });
+ expect(response.status).toBe(422);
+ expect(await response.json()).not.toHaveProperty('input');
+ expect(f.read.mock.calls[0]?.[1].timestamp).toEqual({
+ $gte: at(input.sessions).open / 1000,
+ $lt: at(input.sessions).close / 1000,
+ });
+ }
+ });
+
+ test('each adapter response must belong to its own session and empty responses cannot be skipped', async () => {
+ const input = sessionSource();
+ const base = fixture(filterRows(input.rows));
+ const bars = await base.storage.getHistoricalBars(
+ 'X0.US',
+ new Date(input.metadata.bounds.warmupStart),
+ new Date(input.metadata.bounds.tradeEnd),
+ '5m',
+ { adjustment: 'raw', timestamp: 'utc-instant' },
+ undefined,
+ 'eod'
+ );
+ const wrong = mock(async () => [at(bars, 3)]);
+ await expect(
+ prepareStoredDataset(
+ { metadata: input.metadata, selection },
+ { getHistoricalBars: wrong },
+ new AbortController().signal
+ )
+ ).rejects.toThrow('inconsistent bar identity or range');
+ expect(wrong).toHaveBeenCalledTimes(1);
+ await expect(
+ prepareStoredDataset(
+ { metadata: input.metadata, selection },
+ { getHistoricalBars: async () => [] },
+ new AbortController().signal
+ )
+ ).rejects.toMatchObject({ status: 404 });
+ });
+
+ test('metadata and earlier rows are captured before subsequent reads can mutate them', async () => {
+ const input = sessionSource();
+ const base = fixture(filterRows(input.rows));
+ const bars = await base.storage.getHistoricalBars(
+ 'X0.US',
+ new Date(input.metadata.bounds.warmupStart),
+ new Date(input.metadata.bounds.tradeEnd),
+ '5m',
+ { adjustment: 'raw', timestamp: 'utc-instant' },
+ undefined,
+ 'eod'
+ );
+ const expected = structuredClone(input.metadata);
+ const firstTimestamp = at(bars).timestamp.getTime();
+ let calls = 0;
+ const read = mock(async () => {
+ calls++;
+ if (calls === 1) {
+ return bars.slice(0, 3);
+ }
+ at(bars).timestamp.setTime(0);
+ at(bars).close = 999;
+ at(input.metadata.calendars).sessions = [];
+ await Promise.resolve();
+ return bars.slice(3);
+ });
+ const result = await prepareStoredDataset(
+ { metadata: input.metadata, selection },
+ { getHistoricalBars: read },
+ new AbortController().signal
+ );
+ expect(result.input.metadata).toEqual(expected);
+ expect(at(result.input.bars).timestamp).toBe(firstTimestamp);
+ expect(at(result.input.bars).close).toBe(11);
+ expect(result.preparation).toEqual(previewDatasetPreparation({ input: result.input }));
+ expect(Object.isFrozen(at(result.input.bars))).toBe(true);
+ });
+
+ test('cancellation after one read prevents every later session read', async () => {
+ const input = sessionSource();
+ const controller = new AbortController();
+ const f = fixture(async (_collection, filter) => {
+ const rows = await filterRows(input.rows)('', filter);
+ controller.abort();
+ return rows;
+ });
+ expect(
+ (await f.request({ metadata: input.metadata, selection }, controller.signal)).status
+ ).toBe(499);
+ expect(f.read).toHaveBeenCalledTimes(1);
+ expect(f.query).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/postgres/stored-dataset-preparation.test.ts b/test/postgres/stored-dataset-preparation.test.ts
index 657814e4..b79d7408 100644
--- a/test/postgres/stored-dataset-preparation.test.ts
+++ b/test/postgres/stored-dataset-preparation.test.ts
@@ -60,7 +60,7 @@ function source() {
}));
return { metadata, rows };
}
-async function fixture() {
+async function fixture(input = source(), scopedReads = false) {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
@@ -116,12 +116,17 @@ async function fixture() {
return pool.query(sql, values);
},
});
- const input = source();
let reads = 0;
const mongodb = {
- async find() {
+ async find(_collection: string, filter: { timestamp: { $gte: number; $lt: number } }) {
reads++;
- return structuredClone(input.rows);
+ return structuredClone(
+ scopedReads
+ ? input.rows.filter(
+ row => row.timestamp >= filter.timestamp.$gte && row.timestamp < filter.timestamp.$lt
+ )
+ : input.rows
+ );
},
} as unknown as MongoDBClient;
const routes = new Hono().route('/', createDatasetRoutes({ postgres, mongodb, logger }));
@@ -175,6 +180,61 @@ async function fixture() {
}
describe.skipIf(!url)('stored source materialization and immutable retention on PostgreSQL', () => {
+ test('declared sessions retain captured rows across an invalid intervening close marker without further source reads', async () => {
+ const input = source();
+ const first = input.metadata.bounds.warmupStart;
+ const day = 86_400_000;
+ const close = first + 180_000;
+ const originals = structuredClone(input.rows);
+ input.metadata = {
+ ...input.metadata,
+ calendars: input.metadata.calendars.map(calendar => ({
+ ...calendar,
+ endDate: '2024-01-03',
+ sessions: [
+ { date: '2024-01-01', open: first, close },
+ { date: '2024-01-02', open: first + day, close: close + day },
+ ],
+ })),
+ bounds: { ...input.metadata.bounds, tradeEnd: close + day },
+ corporateActions: input.metadata.corporateActions.map(coverage => ({
+ ...coverage,
+ end: close + day,
+ })),
+ };
+ input.rows = [
+ ...originals,
+ { ...at(originals), timestamp: close / 1000, volume: -1 },
+ ...originals.map(row => ({ ...row, timestamp: row.timestamp + day / 1000 })),
+ ];
+ const f = await fixture(input, true);
+ const before = await f.snapshot();
+ expect((await f.post('stored-source', { metadata: input.metadata })).status).toBe(500);
+ const response = await f.post('stored-source', {
+ metadata: input.metadata,
+ selection: 'declared-sessions',
+ });
+ expect(response.status).toBe(200);
+ const captured = (await response.json()) as CanonicalStoredSourcePreparation;
+ expect(captured.selection).toBe('declared-sessions');
+ expect(captured.input.bars).toHaveLength(6);
+ expect(captured.input.bars.map(bar => bar.sourceSequence)).toEqual([0, 1, 2, 3, 4, 5]);
+ expect(f.reads).toBe(3);
+ expect(await f.snapshot()).toEqual(before);
+ const expected = createDatasetV2(captured.input);
+ const retainBody = { input: captured.input, expectedHash: expected.manifest.hash };
+ input.rows.splice(0);
+ for (let attempt = 0; attempt < 2; attempt++) {
+ expect((await f.post('retain', retainBody)).status).toBe(200);
+ }
+ expect(f.reads).toBe(3);
+ const rows = (await f.pool.query('SELECT payload FROM backtest_datasets')).rows;
+ expect(rows).toHaveLength(1);
+ expect(validateDatasetV2(at(rows).payload)).toEqual(expected);
+ const { backtest_datasets: _datasets, ...unchangedBefore } = before;
+ expect(await f.snapshot(false)).toEqual(unchangedBefore);
+ });
+
test('source read writes nothing; edits after capture cannot change exact retention/retry, and a fresh read has a different identity', async () => {
const f = await fixture();
const before = await f.snapshot(),