fix(research): reuse older and known-hash datasets (RP05)
This commit is contained in:
parent
5319bd1bb2
commit
6d549542a9
5 changed files with 680 additions and 51 deletions
|
|
@ -278,6 +278,15 @@ export function CanonicalSetup({
|
|||
const [catalogError, setCatalogError] = useState<string | null>(null);
|
||||
const [datasetError, setDatasetError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [detailRetry, setDetailRetry] = useState(0);
|
||||
const [knownHash, setKnownHash] = useState('');
|
||||
const [knownHashError, setKnownHashError] = useState<string | null>(null);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const nextOffset = useRef(0);
|
||||
const catalogRequest = useRef<AbortController | null>(null);
|
||||
const datasetRequest = useRef<AbortController | null>(null);
|
||||
const selectedHash = useRef(hash);
|
||||
const invalidHashDraft = useRef(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
|
|
@ -307,6 +316,10 @@ export function CanonicalSetup({
|
|||
return;
|
||||
}
|
||||
authoritative.current = backtest;
|
||||
catalogRequest.current?.abort();
|
||||
datasetRequest.current?.abort();
|
||||
setDataset(null);
|
||||
invalidHashDraft.current = false;
|
||||
setName(backtest.name);
|
||||
setCapital(String(backtest.initialCapital));
|
||||
setRaw(initialPolicy(backtest));
|
||||
|
|
@ -316,6 +329,13 @@ export function CanonicalSetup({
|
|||
? backtest.config.datasetHash
|
||||
: ''
|
||||
);
|
||||
selectedHash.current =
|
||||
typeof backtest.config.canonical === 'object' &&
|
||||
typeof backtest.config.datasetHash === 'string'
|
||||
? backtest.config.datasetHash
|
||||
: '';
|
||||
setKnownHash('');
|
||||
setKnownHashError(null);
|
||||
setSelection({
|
||||
strategyVersionId: backtest.strategyVersionId,
|
||||
strategyParameters: backtest.strategyParameters,
|
||||
|
|
@ -327,31 +347,53 @@ export function CanonicalSetup({
|
|||
setDirty(false);
|
||||
setError(null);
|
||||
}, [backtest]);
|
||||
useEffect(() => {
|
||||
const loadCatalog = useCallback(async (offset: number, replace = false) => {
|
||||
if (!replace && catalogRequest.current) {
|
||||
return;
|
||||
}
|
||||
catalogRequest.current?.abort();
|
||||
const controller = new AbortController();
|
||||
catalogRequest.current = controller;
|
||||
setCatalogLoading(true);
|
||||
setCatalogError(null);
|
||||
void backtestApiV2
|
||||
.listCanonicalDatasets(controller.signal)
|
||||
.then(entries => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalog(entries);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [retry]);
|
||||
if (replace) {
|
||||
nextOffset.current = 0;
|
||||
setCatalog([]);
|
||||
setHasMore(false);
|
||||
}
|
||||
try {
|
||||
const entries = await backtestApiV2.listCanonicalDatasets(50, offset, controller.signal);
|
||||
if (!controller.signal.aborted && active.current) {
|
||||
setCatalog(previous => [
|
||||
...new Map(
|
||||
[...(replace ? [] : previous), ...entries].map(entry => [entry.hash, entry])
|
||||
).values(),
|
||||
]);
|
||||
nextOffset.current = offset + entries.length;
|
||||
setHasMore(entries.length === 50);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted && active.current) {
|
||||
setCatalogError(
|
||||
cause instanceof Error ? cause.message : 'Could not load canonical datasets'
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!controller.signal.aborted && active.current) {
|
||||
catalogRequest.current = null;
|
||||
setCatalogLoading(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
void loadCatalog(0, true);
|
||||
return () => {
|
||||
catalogRequest.current?.abort();
|
||||
};
|
||||
}, [retry, epoch, loadCatalog]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
datasetRequest.current = controller;
|
||||
setDataset(null);
|
||||
setDatasetError(null);
|
||||
setDatasetLoading(Boolean(hash));
|
||||
|
|
@ -359,7 +401,7 @@ export function CanonicalSetup({
|
|||
void backtestApiV2
|
||||
.canonicalDataset(hash, controller.signal)
|
||||
.then(entry => {
|
||||
if (!controller.signal.aborted) {
|
||||
if (!controller.signal.aborted && selectedHash.current === hash && active.current) {
|
||||
if (entry.hash !== hash) {
|
||||
throw new Error('Dataset lookup returned a different hash.');
|
||||
}
|
||||
|
|
@ -367,18 +409,37 @@ export function CanonicalSetup({
|
|||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
if (!controller.signal.aborted && selectedHash.current === hash && active.current) {
|
||||
setDatasetError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
if (!controller.signal.aborted && selectedHash.current === hash && active.current) {
|
||||
setDatasetLoading(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
return () => controller.abort();
|
||||
}, [hash, retry]);
|
||||
}, [hash, retry, detailRetry, epoch]);
|
||||
const chooseHash = (next: string) => {
|
||||
datasetRequest.current?.abort();
|
||||
selectedHash.current = next;
|
||||
setHash(next);
|
||||
setDataset(null);
|
||||
setDatasetError(null);
|
||||
setDatasetLoading(Boolean(next));
|
||||
setKnownHashError(null);
|
||||
invalidHashDraft.current = false;
|
||||
setDetailRetry(value => value + 1);
|
||||
setDirty(true);
|
||||
};
|
||||
const refreshDatasets = () => {
|
||||
catalogRequest.current?.abort();
|
||||
datasetRequest.current?.abort();
|
||||
setDataset(null);
|
||||
setDatasetLoading(Boolean(selectedHash.current));
|
||||
setRetry(value => value + 1);
|
||||
};
|
||||
const parsed = parsePolicy(raw);
|
||||
let selectedFields: ReturnType<typeof canonicalDatasetFields> | undefined;
|
||||
let compatibilityError: string | null = null;
|
||||
|
|
@ -396,6 +457,8 @@ export function CanonicalSetup({
|
|||
name.trim() &&
|
||||
validCapital &&
|
||||
selectedFields &&
|
||||
!datasetLoading &&
|
||||
!knownHashError &&
|
||||
parsed.settings &&
|
||||
selection.strategyVersionId &&
|
||||
strategyValid
|
||||
|
|
@ -405,6 +468,9 @@ export function CanonicalSetup({
|
|||
if (
|
||||
locked ||
|
||||
pending.current ||
|
||||
selectedHash.current !== hash ||
|
||||
invalidHashDraft.current ||
|
||||
datasetRequest.current?.signal.aborted ||
|
||||
preparationRef.current.busy ||
|
||||
preparationRef.current.blocking ||
|
||||
!valid ||
|
||||
|
|
@ -498,11 +564,11 @@ export function CanonicalSetup({
|
|||
aria-label="Canonical dataset"
|
||||
className={fieldClass}
|
||||
value={hash}
|
||||
onChange={event => setHash(event.target.value)}
|
||||
onChange={event => chooseHash(event.target.value)}
|
||||
>
|
||||
<option value="">Select a retained single-asset dataset</option>
|
||||
{hash && !options.some(entry => entry.hash === hash) && (
|
||||
<option value={hash}>{hash} — retained selection</option>
|
||||
<option value={hash}>{hash} — selected hash</option>
|
||||
)}
|
||||
{options.map(entry => (
|
||||
<option key={entry.hash} value={entry.hash} disabled={!entry.available}>
|
||||
|
|
@ -514,32 +580,93 @@ export function CanonicalSetup({
|
|||
))}
|
||||
</select>
|
||||
</label>
|
||||
{catalogLoading && <p role="status">Loading canonical datasets...</p>}
|
||||
{!catalogLoading && !catalogError && !catalog.length && (
|
||||
<p role="status">
|
||||
No canonical datasets are available. Retain an eligible dataset with explicit sessions
|
||||
and availability before configuring a run.
|
||||
</p>
|
||||
)}
|
||||
{datasetLoading && <p role="status">Loading selected canonical dataset...</p>}
|
||||
{[catalogError, datasetError, compatibilityError].filter(Boolean).map((message, index) => (
|
||||
<p key={index} role="alert" className="text-error text-sm">
|
||||
{message}
|
||||
</p>
|
||||
))}
|
||||
{(catalogError || datasetError || compatibilityError) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{hasMore && (
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={catalogLoading}
|
||||
onClick={() => void loadCatalog(nextOffset.current)}
|
||||
>
|
||||
Load more canonical datasets
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className={actionClass} onClick={refreshDatasets}>
|
||||
Refresh canonical datasets
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-2" onChange={event => event.stopPropagation()}>
|
||||
<label className="block text-sm">
|
||||
Retained dataset hash
|
||||
<input
|
||||
aria-label="Retained dataset hash"
|
||||
className={fieldClass}
|
||||
value={knownHash}
|
||||
onChange={event => {
|
||||
setKnownHash(event.target.value);
|
||||
invalidHashDraft.current = false;
|
||||
setKnownHashError(null);
|
||||
}}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
placeholder="64-character retained hash"
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
onClick={() => setRetry(value => value + 1)}
|
||||
onClick={() => {
|
||||
const value = knownHash.trim();
|
||||
if (!/^[a-f0-9]{64}$/.test(value)) {
|
||||
invalidHashDraft.current = true;
|
||||
setKnownHashError(
|
||||
'Enter a retained dataset hash of 64 lowercase hexadecimal characters.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
chooseHash(value);
|
||||
}}
|
||||
>
|
||||
Use dataset hash
|
||||
</button>
|
||||
</div>
|
||||
{catalogLoading && <p role="status">Loading canonical datasets...</p>}
|
||||
{!catalogLoading && !catalogError && !catalog.length && (
|
||||
<p role="status">
|
||||
No canonical datasets are listed. Use a known retained hash or prepare a dataset with
|
||||
explicit sessions and availability.
|
||||
</p>
|
||||
)}
|
||||
{datasetLoading && <p role="status">Loading selected canonical dataset...</p>}
|
||||
{[catalogError, datasetError, compatibilityError, knownHashError]
|
||||
.filter(Boolean)
|
||||
.map((message, index) => (
|
||||
<p key={index} role="alert" className="text-error text-sm">
|
||||
{message}
|
||||
</p>
|
||||
))}
|
||||
{catalogError && (
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={catalogLoading}
|
||||
onClick={() => void loadCatalog(nextOffset.current, nextOffset.current === 0)}
|
||||
>
|
||||
Retry canonical datasets
|
||||
</button>
|
||||
)}
|
||||
{(datasetError || compatibilityError) && (
|
||||
<button type="button" className={actionClass} onClick={() => chooseHash(hash)}>
|
||||
Retry selected dataset
|
||||
</button>
|
||||
)}
|
||||
{hash && !selectedFields && !datasetLoading && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
The selected hash is retained. Saving stays disabled until compatible metadata is
|
||||
available.
|
||||
The selected hash has not been verified for this setup. Saving stays disabled until
|
||||
compatible retained metadata is available.
|
||||
</p>
|
||||
)}
|
||||
{selectedFields && (
|
||||
|
|
@ -585,9 +712,9 @@ export function CanonicalSetup({
|
|||
return;
|
||||
}
|
||||
if (available) {
|
||||
setHash(retainedHash);
|
||||
chooseHash(retainedHash);
|
||||
}
|
||||
setRetry(value => value + 1);
|
||||
refreshDatasets();
|
||||
setDirty(true);
|
||||
}}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
datasetUnavailableReason,
|
||||
manifestSchema,
|
||||
preparationManifestSchema,
|
||||
} from '@stock-bot/research/dataset-contracts';
|
||||
import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution';
|
||||
|
|
@ -161,6 +162,30 @@ export function parseDatasetPreparation(
|
|||
}
|
||||
return value;
|
||||
}
|
||||
const canonicalDatasetEntrySchema = z
|
||||
.object({
|
||||
hash: preparationHash,
|
||||
createdAt: z.string().min(1),
|
||||
manifest: manifestSchema.nullable(),
|
||||
available: z.boolean(),
|
||||
reason: preparationText.nullable(),
|
||||
})
|
||||
.strict()
|
||||
.refine(entry => {
|
||||
const manifest = entry.manifest;
|
||||
return (
|
||||
(entry.available
|
||||
? manifest !== null && entry.reason === null && datasetUnavailableReason(manifest) === null
|
||||
: entry.reason !== null) &&
|
||||
(!manifest ||
|
||||
(manifest.hash === entry.hash &&
|
||||
manifest.bounds.warmupStart <= manifest.bounds.tradeStart &&
|
||||
manifest.bounds.tradeStart < manifest.bounds.tradeEnd &&
|
||||
manifest.calendars.every(calendar =>
|
||||
calendar.sessions.every(session => session.open < session.close)
|
||||
)))
|
||||
);
|
||||
}, 'Invalid canonical dataset descriptor');
|
||||
const preparationMetadata = preparationManifest.pick({
|
||||
calendars: true,
|
||||
series: true,
|
||||
|
|
@ -490,19 +515,44 @@ export const backtestApiV2 = {
|
|||
}
|
||||
return capability;
|
||||
},
|
||||
async listCanonicalDatasets(signal?: AbortSignal): Promise<CanonicalDatasetCatalogEntry[]> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical?limit=50&offset=0`, {
|
||||
signal,
|
||||
});
|
||||
async listCanonicalDatasets(
|
||||
limit = 50,
|
||||
offset = 0,
|
||||
signal?: AbortSignal
|
||||
): Promise<CanonicalDatasetCatalogEntry[]> {
|
||||
if (!Number.isSafeInteger(limit) || limit < 1 || !Number.isSafeInteger(offset) || offset < 0) {
|
||||
throw new Error(
|
||||
'Canonical dataset pagination requires a positive limit and nonnegative offset'
|
||||
);
|
||||
}
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/datasets/canonical?limit=${limit}&offset=${offset}`,
|
||||
{ signal }
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Could not load canonical datasets');
|
||||
}
|
||||
return (await response.json()).datasets;
|
||||
try {
|
||||
const value = z
|
||||
.object({ datasets: canonicalDatasetEntrySchema.array() })
|
||||
.strict()
|
||||
.parse(await response.json());
|
||||
signal?.throwIfAborted();
|
||||
if (response.status !== 200 || value.datasets.length > limit) {
|
||||
throw new Error('Unexpected canonical dataset page');
|
||||
}
|
||||
return value.datasets;
|
||||
} catch {
|
||||
throw new Error('The canonical dataset catalog response could not be verified.');
|
||||
}
|
||||
},
|
||||
async canonicalDataset(
|
||||
hash: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<CanonicalDatasetCatalogEntry> {
|
||||
if (!/^[a-f0-9]{64}$/.test(hash)) {
|
||||
throw new Error('Enter a retained dataset hash of 64 lowercase hexadecimal characters.');
|
||||
}
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/datasets/canonical/${encodeURIComponent(hash)}`,
|
||||
{ signal }
|
||||
|
|
@ -510,7 +560,21 @@ export const backtestApiV2 = {
|
|||
if (!response.ok) {
|
||||
throw await requestError(response, 'Could not load canonical dataset');
|
||||
}
|
||||
return (await response.json()).dataset;
|
||||
try {
|
||||
const value = z
|
||||
.object({ dataset: canonicalDatasetEntrySchema })
|
||||
.strict()
|
||||
.parse(await response.json());
|
||||
signal?.throwIfAborted();
|
||||
if (response.status !== 200 || value.dataset.hash !== hash) {
|
||||
throw new Error('Unexpected canonical dataset identity');
|
||||
}
|
||||
return value.dataset;
|
||||
} catch {
|
||||
throw new Error(
|
||||
'The canonical dataset response could not be verified for the requested hash.'
|
||||
);
|
||||
}
|
||||
},
|
||||
async listDatasets(
|
||||
limit = 50,
|
||||
|
|
|
|||
|
|
@ -11,3 +11,5 @@ Acceptance: choose and save a dataset beyond the first 50; choose an exact known
|
|||
Files/locks: `CanonicalSetup.tsx`, `backtestApiV2.ts`, focused `test/integration/canonical-workbench.test.tsx` (add a focused transport test file if necessary). Root owns the shared browser test and all planning state. Parallel with RP06, which owns only the parent page and its lifecycle tests. Frontend implementation agent; independent transport/UI review.
|
||||
|
||||
Required tests: >50 entries and exact hash; appended page failure/retry and overlapping responses; stale refresh/lookup; unavailable/corrupt/malformed entries including valid converted v2 parent hash; final saved input and no unintended submission. Extend real authenticated browser/database workflow. Run focused tests, application/authored-test types, strict lint, production build; root combined repository and browser gates. Risk: stale data changing selection or falsely accepting malformed metadata; existing server admission remains authoritative.
|
||||
|
||||
Accepted October 27, 2026: pagination, deliberate hash lookup, strict catalog/detail parsing and stale-response fencing are implemented in the existing frontend. Independent review passed 29 workbench tests / 245 assertions plus eight transport probes; implementer combined UI suites passed 119 / 570. Root full repository gate passed. The real browser scenario seeded 52 older immutable snapshots, selected an out-of-page hash, loaded another page, saved and reopened an older dataset with zero runs/dispatch. Its initial test omitted existing parameter validation; after fixing that test sequence, the scenario passed (13 assertions). [Combined evidence](../../real-data-research.md) records exact coverage and limits.
|
||||
|
|
|
|||
|
|
@ -2351,6 +2351,128 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
|
|||
}
|
||||
});
|
||||
|
||||
test('canonical_dataset_browser_reuses_older_pages_and_known_hash_without_new_runs', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
await f.login();
|
||||
const { id, dataset } = await createCanonicalInBrowser(f, 'Retained dataset reuse');
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
dataset.manifest;
|
||||
const snapshots = [];
|
||||
for (let index = 0; index < 52; index++) {
|
||||
const snapshot = createDatasetV2({
|
||||
metadata: {
|
||||
calendars,
|
||||
series: series.map(value => ({
|
||||
...value,
|
||||
source: { ...value.source, revision: `catalog-browser-fixture-${index}` },
|
||||
})),
|
||||
executionSeries,
|
||||
bounds,
|
||||
universe,
|
||||
corporateActions,
|
||||
},
|
||||
bars: dataset.bars.map(bar => ({
|
||||
seriesId: bar.seriesId,
|
||||
timestamp: bar.intervalStart,
|
||||
availableAt: bar.availableAt,
|
||||
sourceSequence: bar.sourceSequence,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
})),
|
||||
});
|
||||
// Set fixture ordering on initial insertion; retained evidence is immutable.
|
||||
await f.pool.query(
|
||||
'INSERT INTO backtest_datasets(hash,payload,created_at) VALUES($1,$2::jsonb,$3)',
|
||||
[
|
||||
snapshot.manifest.hash,
|
||||
JSON.stringify(snapshot),
|
||||
new Date(Date.parse('2020-01-01T00:00:00Z') + index * 60_000),
|
||||
]
|
||||
);
|
||||
await retainResearchDataset(f.pool, snapshot);
|
||||
snapshots.push(snapshot);
|
||||
}
|
||||
const older = snapshots[0]!,
|
||||
known = snapshots[1]!;
|
||||
const before = await f.request(`/api/v2/backtests/${id}`);
|
||||
const listResponses: string[] = [];
|
||||
f.page.on('request', request => {
|
||||
const url = new URL(request.url());
|
||||
if (url.pathname === '/api/v2/datasets/canonical') {
|
||||
listResponses.push(url.search);
|
||||
}
|
||||
});
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
const choice = f.page.getByLabel('Canonical dataset', { exact: true });
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Load more canonical datasets', exact: true })
|
||||
.waitFor();
|
||||
expect(await choice.locator(`option[value="${older.manifest.hash}"]`).count()).toBe(0);
|
||||
expect(await choice.locator(`option[value="${known.manifest.hash}"]`).count()).toBe(0);
|
||||
await f.page.getByLabel('Retained dataset hash', { exact: true }).fill(known.manifest.hash);
|
||||
const lookup = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/api/v2/datasets/canonical/${known.manifest.hash}`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Use dataset hash', exact: true }).click();
|
||||
expect((await lookup).status()).toBe(200);
|
||||
await until(
|
||||
() => choice.inputValue().then(value => value === known.manifest.hash),
|
||||
'known hash selection'
|
||||
);
|
||||
expect(await f.request(`/api/v2/backtests/${id}`)).toEqual(before);
|
||||
await f.page.getByRole('button', { name: 'Load more canonical datasets', exact: true }).click();
|
||||
await choice.locator(`option[value="${older.manifest.hash}"]`).waitFor({ state: 'attached' });
|
||||
expect(listResponses).toContain('?limit=50&offset=50');
|
||||
expect(await choice.inputValue()).toBe(known.manifest.hash);
|
||||
const values = await choice
|
||||
.locator('option')
|
||||
.evaluateAll(options => options.map(option => (option as HTMLOptionElement).value));
|
||||
expect(new Set(values).size).toBe(values.length);
|
||||
await choice.selectOption(older.manifest.hash);
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(f.page, /Parameters validated/);
|
||||
await until(
|
||||
() => f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).isEnabled(),
|
||||
'older dataset verified and ready to save'
|
||||
);
|
||||
const saving = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'PUT' && response.url().endsWith(`/api/v2/backtests/${id}`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).click();
|
||||
const saved = await saving;
|
||||
expect(saved.status()).toBe(200);
|
||||
expect(saved.request().postDataJSON()).toMatchObject({
|
||||
config: { datasetHash: older.manifest.hash },
|
||||
startDate: new Date(bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(bounds.tradeEnd).toISOString(),
|
||||
});
|
||||
await f.page.reload();
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
await until(
|
||||
() => choice.inputValue().then(value => value === older.manifest.hash),
|
||||
'saved older hash reopens outside first catalog page'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(f.page, /Parameters validated/);
|
||||
await until(
|
||||
() => f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).isEnabled(),
|
||||
'reopened retained metadata verified'
|
||||
);
|
||||
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('declared_session_source_browser_captures_two_windows_and_retains_without_requery', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ const keys = ['window', 'document', '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 backtestApiV2: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').backtestApiV2;
|
||||
let CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup;
|
||||
let CanonicalResults: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalResults').CanonicalResults;
|
||||
let RunsListWithMetrics: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics').RunsListWithMetrics;
|
||||
|
|
@ -49,6 +50,8 @@ function deferred<T>() {
|
|||
}
|
||||
type Pending = ReturnType<typeof deferred<Response>> & {
|
||||
path: string;
|
||||
search: string;
|
||||
signal: AbortSignal | null | undefined;
|
||||
method: string;
|
||||
body: unknown;
|
||||
headers: Headers;
|
||||
|
|
@ -230,6 +233,9 @@ beforeAll(async () => {
|
|||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ backtestApiV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'
|
||||
));
|
||||
({ CanonicalSetup } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup'
|
||||
));
|
||||
|
|
@ -260,6 +266,8 @@ beforeEach(() => {
|
|||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: new URL(String(url)).pathname,
|
||||
search: new URL(String(url)).search,
|
||||
signal: init?.signal,
|
||||
method: init?.method ?? 'GET',
|
||||
headers: new Headers(init?.headers),
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
|
|
@ -874,6 +882,7 @@ describe('canonical research workbench', () => {
|
|||
)
|
||||
);
|
||||
await selected();
|
||||
await flush(() => reply(request('/api/v2/datasets/canonical'), { datasets: [entry] }));
|
||||
await flush(() =>
|
||||
reply(stale, {
|
||||
parameters: { fastPeriod: 3, slowPeriod: 15 },
|
||||
|
|
@ -893,6 +902,7 @@ describe('canonical research workbench', () => {
|
|||
)
|
||||
);
|
||||
await selected();
|
||||
await flush(() => reply(request('/api/v2/datasets/canonical'), { datasets: [entry] }));
|
||||
expect(field('fastPeriod').value).toBe('5');
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
await flush(() => edit('Canonical dataset', hash));
|
||||
|
|
@ -1064,3 +1074,307 @@ describe('canonical research workbench', () => {
|
|||
});
|
||||
}
|
||||
});
|
||||
|
||||
const catalogPath = '/api/v2/datasets/canonical';
|
||||
function catalogEntry(
|
||||
index: number,
|
||||
extra: Partial<CanonicalDatasetCatalogEntry> = {}
|
||||
): CanonicalDatasetCatalogEntry {
|
||||
const identity = index.toString(16).padStart(64, '0');
|
||||
return {
|
||||
...entry,
|
||||
hash: identity,
|
||||
manifest: { ...entry.manifest!, hash: identity },
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
async function setupCatalog(entries: CanonicalDatasetCatalogEntry[]) {
|
||||
const saves: CreateBacktestRequest[] = [];
|
||||
await mount(
|
||||
createElement(CanonicalSetup, {
|
||||
backtest: definition,
|
||||
onSave: async value => {
|
||||
saves.push(value);
|
||||
},
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
await validateSelected();
|
||||
await flush(() => reply(request(catalogPath), { datasets: entries }));
|
||||
return saves;
|
||||
}
|
||||
async function useKnownHash(value: string) {
|
||||
await flush(() => edit('Retained dataset hash', value));
|
||||
await flush(() => click('Use dataset hash'));
|
||||
}
|
||||
function optionHashes() {
|
||||
return [...(field('Canonical dataset') as HTMLSelectElement).options]
|
||||
.map(option => option.value)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
describe('retained canonical dataset reuse', () => {
|
||||
test('loads beyond fifty, retries the same failed offset, deduplicates overlaps and saves exact verified bounds', async () => {
|
||||
const entries = Array.from({ length: 53 }, (_, index) => catalogEntry(index + 1));
|
||||
const saves = await setupCatalog(entries.slice(0, 50));
|
||||
await flush(() => edit('Canonical dataset', entries[0]!.hash));
|
||||
await flush(() =>
|
||||
reply(request(`${catalogPath}/${entries[0]!.hash}`), { dataset: entries[0] })
|
||||
);
|
||||
await flush(() => {
|
||||
click('Load more canonical datasets');
|
||||
click('Load more canonical datasets');
|
||||
});
|
||||
const next = request(catalogPath);
|
||||
expect(next.search).toBe('?limit=50&offset=50');
|
||||
expect(requests.filter(item => item.path === catalogPath && !item.settled)).toHaveLength(1);
|
||||
await flush(() => fail(next));
|
||||
expect(optionHashes()).toHaveLength(50);
|
||||
expect(field('Canonical dataset').value).toBe(entries[0]!.hash);
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await flush(() => click('Retry canonical datasets'));
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=50');
|
||||
await flush(() => reply(request(catalogPath), { datasets: entries.slice(49) }));
|
||||
expect(optionHashes()).toHaveLength(53);
|
||||
expect(new Set(optionHashes()).size).toBe(53);
|
||||
expect(
|
||||
[...host.querySelectorAll('button')].some(
|
||||
item => item.textContent === 'Load more canonical datasets'
|
||||
)
|
||||
).toBe(false);
|
||||
const chosen = entries[52]!;
|
||||
await flush(() => edit('Canonical dataset', chosen.hash));
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
await flush(() => click('Save canonical setup'));
|
||||
expect(saves).toHaveLength(1);
|
||||
expect(saves[0]!.config?.datasetHash).toBe(chosen.hash);
|
||||
expect(saves[0]!.startDate).toBe(new Date(chosen.manifest!.bounds.tradeStart).toISOString());
|
||||
expect(saves[0]!.endDate).toBe(new Date(chosen.manifest!.bounds.tradeEnd).toISOString());
|
||||
expect(requests.some(item => item.method === 'POST' && item.path.endsWith('/runs'))).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('explicit known-hash lookup accepts converted lineage; typing and Enter never fetch or submit', async () => {
|
||||
const chosen = catalogEntry(100);
|
||||
chosen.manifest = { ...chosen.manifest!, parentDatasetHash: 'e'.repeat(64) };
|
||||
const saves = await setupCatalog([]);
|
||||
const before = requests.length;
|
||||
await flush(() => edit('Retained dataset hash', chosen.hash));
|
||||
const enter = new browser.KeyboardEvent('keydown', {
|
||||
key: 'Enter',
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await flush(() => {
|
||||
field('Retained dataset hash').dispatchEvent(enter as unknown as Event);
|
||||
});
|
||||
expect(enter.defaultPrevented).toBe(true);
|
||||
expect(requests).toHaveLength(before);
|
||||
expect(saves).toEqual([]);
|
||||
expect(host.textContent).not.toContain('Unsaved canonical setup');
|
||||
await flush(() => click('Use dataset hash'));
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
expect(field('Canonical dataset').value).toBe(chosen.hash);
|
||||
expect(optionHashes()).toEqual([chosen.hash]);
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await flush(() => click('Save canonical setup'));
|
||||
expect(saves[0]!.config?.datasetHash).toBe(chosen.hash);
|
||||
});
|
||||
|
||||
test('malformed hash never fetches and invalid, missing, unavailable or wrong detail cannot authorize saving', async () => {
|
||||
const chosen = catalogEntry(100);
|
||||
const saves = await setupCatalog([chosen]);
|
||||
for (const invalid of ['', 'not-a-hash', 'A'.repeat(64)]) {
|
||||
const before = requests.length;
|
||||
await useKnownHash(invalid);
|
||||
expect(requests).toHaveLength(before);
|
||||
expect(host.textContent).toContain('64 lowercase hexadecimal');
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
}
|
||||
const replies = [
|
||||
{ body: { error: 'Dataset not found' }, status: 404 },
|
||||
{
|
||||
body: {
|
||||
dataset: { ...chosen, available: false, manifest: null, reason: 'Stored bytes invalid' },
|
||||
},
|
||||
status: 200,
|
||||
},
|
||||
{ body: { dataset: catalogEntry(101) }, status: 200 },
|
||||
{ body: { dataset: { ...chosen, available: true, manifest: null } }, status: 200 },
|
||||
{
|
||||
body: { dataset: { ...chosen, manifest: { ...chosen.manifest, executionSeries: null } } },
|
||||
status: 200,
|
||||
},
|
||||
{ body: { wrongEnvelope: chosen }, status: 200 },
|
||||
];
|
||||
for (const item of replies) {
|
||||
await useKnownHash(chosen.hash);
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), item.body, item.status));
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(host.textContent).not.toContain('The selected hash is retained');
|
||||
}
|
||||
await useKnownHash(chosen.hash);
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await flush(() => edit('Retained dataset hash', 'bad'));
|
||||
await flush(() => {
|
||||
click('Use dataset hash');
|
||||
click('Save canonical setup');
|
||||
});
|
||||
expect(saves).toEqual([]);
|
||||
});
|
||||
|
||||
test('late lookups, refresh and unmount cannot replace the current verified hash or authorize a same-event save', async () => {
|
||||
const a = catalogEntry(100),
|
||||
b = catalogEntry(101);
|
||||
const saves = await setupCatalog([]);
|
||||
await useKnownHash(a.hash);
|
||||
const stale = request(`${catalogPath}/${a.hash}`);
|
||||
await useKnownHash(b.hash);
|
||||
expect(stale.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(request(`${catalogPath}/${b.hash}`), { dataset: b }));
|
||||
await flush(() => reply(stale, { dataset: a }));
|
||||
expect(field('Canonical dataset').value).toBe(b.hash);
|
||||
await flush(() => {
|
||||
click('Refresh canonical datasets');
|
||||
click('Save canonical setup');
|
||||
});
|
||||
expect(saves).toEqual([]);
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
expect(field('Canonical dataset').value).toBe(b.hash);
|
||||
await flush(() => reply(request(catalogPath), { datasets: [] }));
|
||||
await flush(() => reply(request(`${catalogPath}/${b.hash}`), { dataset: b }));
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await useKnownHash(a.hash);
|
||||
const pending = request(`${catalogPath}/${a.hash}`);
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
expect(pending.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(pending, { dataset: a }));
|
||||
expect(saves).toEqual([]);
|
||||
});
|
||||
|
||||
test('refresh fences old pages, resets pagination and preserves an off-page selection', async () => {
|
||||
const entries = Array.from({ length: 51 }, (_, index) => catalogEntry(index + 1));
|
||||
await setupCatalog(entries.slice(0, 50));
|
||||
const chosen = entries[0]!;
|
||||
await flush(() => edit('Canonical dataset', chosen.hash));
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
await flush(() => click('Load more canonical datasets'));
|
||||
const old = request(catalogPath);
|
||||
await flush(() => click('Refresh canonical datasets'));
|
||||
expect(old.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(old, { datasets: entries.slice(50) }));
|
||||
expect(optionHashes()).toEqual([chosen.hash]);
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=0');
|
||||
await flush(() => reply(request(catalogPath), { datasets: entries.slice(1, 51) }));
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
expect(field('Canonical dataset').value).toBe(chosen.hash);
|
||||
expect(optionHashes()).toHaveLength(51);
|
||||
await flush(() => click('Load more canonical datasets'));
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=50');
|
||||
});
|
||||
|
||||
test('malformed catalog is recoverable; valid unavailable entries remain visible and disabled', async () => {
|
||||
await setupCatalog([]);
|
||||
for (const malformed of [
|
||||
{ datasets: null },
|
||||
{ datasets: [null] },
|
||||
{ datasets: [{ ...entry, manifest: {} }] },
|
||||
{ entries: [] },
|
||||
]) {
|
||||
await flush(() => click('Refresh canonical datasets'));
|
||||
await flush(() => reply(request(catalogPath), malformed));
|
||||
expect(host.textContent).toContain('catalog response could not be verified');
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
}
|
||||
await flush(() => click('Retry canonical datasets'));
|
||||
const unavailable = {
|
||||
...catalogEntry(99),
|
||||
available: false,
|
||||
manifest: null,
|
||||
reason: 'Retained payload cannot be validated',
|
||||
};
|
||||
await flush(() => reply(request(catalogPath), { datasets: [unavailable] }));
|
||||
const option = [...(field('Canonical dataset') as HTMLSelectElement).options].find(
|
||||
item => item.value === unavailable.hash
|
||||
)!;
|
||||
expect(option.disabled).toBe(true);
|
||||
expect(option.textContent).toContain(unavailable.reason);
|
||||
expect(host.querySelector('[role="alert"]')).toBeNull();
|
||||
});
|
||||
|
||||
test('retention refresh fences an old page and selects newly retained bytes without duplicate choices', async () => {
|
||||
const entries = Array.from({ length: 50 }, (_, index) => catalogEntry(index + 1));
|
||||
await setupCatalog(entries);
|
||||
await flush(() => click('Load more canonical datasets'));
|
||||
const old = request(catalogPath);
|
||||
const retained = nativeReplayFixture(4).dataset;
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
retained.manifest;
|
||||
const input = {
|
||||
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
|
||||
bars: retained.bars.map(bar => ({
|
||||
seriesId: bar.seriesId,
|
||||
timestamp: bar.intervalStart,
|
||||
availableAt: bar.availableAt,
|
||||
sourceSequence: bar.sourceSequence,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
})),
|
||||
};
|
||||
const file = field('Source dataset JSON');
|
||||
Object.defineProperty(file, 'files', {
|
||||
configurable: true,
|
||||
value: [{ name: 'new.json', text: async () => JSON.stringify(input) }],
|
||||
});
|
||||
await flush(() =>
|
||||
file.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event)
|
||||
);
|
||||
await flush(() => click('Preview dataset'));
|
||||
const preparation = {
|
||||
version: 'canonical-dataset-preparation/v1',
|
||||
hash: retained.manifest.hash,
|
||||
manifest: retained.manifest,
|
||||
available: true,
|
||||
reason: null,
|
||||
};
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/datasets/canonical/preview', 'POST'), { preparation })
|
||||
);
|
||||
await flush(() => click('Retain dataset'));
|
||||
await flush(() => reply(request('/api/v2/datasets/canonical/retain', 'POST'), { preparation }));
|
||||
expect(old.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(old, { datasets: [catalogEntry(51)] }));
|
||||
const fresh = {
|
||||
hash: retained.manifest.hash,
|
||||
manifest: retained.manifest,
|
||||
available: true,
|
||||
reason: null,
|
||||
createdAt: entry.createdAt,
|
||||
};
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=0');
|
||||
await flush(() => reply(request(catalogPath), { datasets: [fresh, ...entries.slice(0, 49)] }));
|
||||
await flush(() => reply(request(`${catalogPath}/${fresh.hash}`), { dataset: fresh }));
|
||||
expect(field('Canonical dataset').value).toBe(fresh.hash);
|
||||
expect(optionHashes()).toHaveLength(50);
|
||||
expect(new Set(optionHashes()).size).toBe(50);
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await flush(() => click('Load more canonical datasets'));
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=50');
|
||||
});
|
||||
|
||||
test('transport rejects malformed page arguments and exact-hash requests before network access', async () => {
|
||||
const before = requests.length;
|
||||
await expect(backtestApiV2.listCanonicalDatasets(0, 0)).rejects.toThrow('pagination');
|
||||
await expect(backtestApiV2.listCanonicalDatasets(50, -1)).rejects.toThrow('pagination');
|
||||
await expect(backtestApiV2.canonicalDataset('bad')).rejects.toThrow('64 lowercase hexadecimal');
|
||||
expect(requests).toHaveLength(before);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue