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

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

View file

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

View file

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

View file

@ -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<string, unknown>) => {
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();
});
});

View file

@ -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(),