refactor: share research domain and simplify application workflows

This commit is contained in:
Boki 2026-10-26 15:29:43 -04:00
parent 805a9f8fd4
commit 8c39ccf7ea
58 changed files with 3805 additions and 3081 deletions

View file

@ -5,29 +5,10 @@
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
import type {
Backtest,
CreateBacktestRequest,
ResearchRunResult,
Run,
} from '../services/backtestApiV2';
/** Object identity is the ownership token for one status/result request chain. */
interface RunSelection {
id: string;
backtestId: string | null;
controller: AbortController;
timer?: ReturnType<typeof setTimeout>;
request?: Promise<void>;
refreshRequested: boolean;
results: ResearchRunResult | null;
}
const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status);
const messageOf = (error: unknown, fallback: string) =>
error instanceof Error ? error.message : fallback;
import { backtestApiV2 } from '../services/backtestApiV2';
import type { Backtest, CreateBacktestRequest, Run } from '../services/backtestApiV2';
import { messageOf, useRunMonitoring } from './useRunMonitoring';
import { useRunSubmission } from './useRunSubmission';
/**
* Connects BacktestDetailPageV2 to backtestApiV2. Template loading, run monitoring
@ -37,32 +18,14 @@ const messageOf = (error: unknown, fallback: string) =>
export function useBacktestV2() {
const [backtest, setBacktest] = useState<Backtest | null>(null);
const [runs, setRuns] = useState<Run[]>([]);
const [currentRun, setCurrentRun] = useState<Run | null>(null);
const [runResults, setRunResults] = useState<ResearchRunResult | null>(null);
const [isBacktestLoading, setIsBacktestLoading] = useState(false);
const [isRunLoading, setIsRunLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [runError, setRunError] = useState<string | null>(null);
const [submissionError, setSubmissionError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [cancelRequested, setCancelRequested] = useState(false);
// Generations reject late responses even when an earlier request cannot be
// aborted. The selection generation also prevents submission from taking the
// user away from a different run they selected while admission was pending.
const mounted = useRef(true);
const backtestGeneration = useRef(0);
const loadedBacktestId = useRef<string | null>(null);
const selectionGeneration = useRef(0);
// The intent survives an ambiguous response and configuration edits. Only an
// acknowledged submission (or leaving this definition) releases its key.
const submission = useRef<{
backtestId: string;
key: string;
body: { speedMultiplier: number | null };
pending: boolean;
} | null>(null);
const selection = useRef<RunSelection | null>(null);
const cancellation = useRef<RunSelection | null>(null);
const [capabilityRetry, setCapabilityRetry] = useState(0);
const [capabilityState, setCapabilityState] = useState<{
definition: Backtest;
@ -119,172 +82,36 @@ export function useBacktestV2() {
catalog && !backtest?.archivedAt && !capabilityError && canonicalCapability === null;
const refreshCanonicalCapability = useCallback(() => setCapabilityRetry(value => value + 1), []);
const isSelected = useCallback(
(selected: RunSelection) =>
mounted.current &&
selection.current === selected &&
selected.backtestId === loadedBacktestId.current,
[]
);
/** Stop browser observation only; cancelling server execution is cancelRun's job. */
const stopMonitoring = useCallback(() => {
selectionGeneration.current++;
const selected = selection.current;
selection.current = null;
cancellation.current = null;
if (selected) {
clearTimeout(selected.timer);
selected.controller.abort();
}
}, []);
// A selection owns one request chain (status, then results) and one timer.
// Polls, websocket invalidations and cancel acknowledgements all use this path.
const refreshSelection = useCallback(
function refresh(selected: RunSelection): Promise<void> {
if (!isSelected(selected)) {
return Promise.resolve();
}
if (selected.request) {
selected.refreshRequested = true;
return selected.request;
}
clearTimeout(selected.timer);
let monitorAgain = true;
selected.request = (async () => {
try {
const run = await backtestApiV2.getRun(selected.id, selected.controller.signal);
if (!isSelected(selected)) {
return;
}
if (
run.id !== selected.id ||
(selected.backtestId !== null && run.backtestId !== selected.backtestId)
) {
monitorAgain = false;
selected.refreshRequested = false;
selected.results = null;
setCurrentRun(null);
setRunResults(null);
throw new Error('Received a run for a different backtest or run selection');
}
setCurrentRun(run);
setRuns(previous =>
previous.some(item => item.id === run.id)
? previous.map(item => (item.id === run.id ? run : item))
: [run, ...previous]
);
setRunError(null);
monitorAgain = isActive(run);
if (!monitorAgain) {
cancellation.current = null;
setCancelRequested(false);
} else if (run.cancelRequested) {
setCancelRequested(true);
}
if (run.status === 'completed') {
if (!selected.results) {
const results = await backtestApiV2.getRunResults(
selected.id,
selected.controller.signal
);
if (!isSelected(selected)) {
return;
}
if (
results &&
(results.runId !== selected.id || results.backtestId !== run.backtestId)
) {
selected.refreshRequested = false;
throw new Error('Received results for a different backtest or run');
}
selected.results = results;
setRunResults(results);
}
} else {
selected.results = null;
setRunResults(null);
}
} catch (err) {
if (!isSelected(selected)) {
return;
}
setRunError(
err instanceof RunResultsUnavailableError
? null
: messageOf(err, 'Failed to refresh run')
);
} finally {
if (isSelected(selected)) {
selected.request = undefined;
setIsRunLoading(false);
if (selected.refreshRequested) {
selected.refreshRequested = false;
void refresh(selected);
} else if (monitorAgain) {
selected.timer = setTimeout(() => void refresh(selected), 1000);
}
}
}
})();
return selected.request;
},
[isSelected]
);
const refreshRun = useCallback(
(runId?: string) => {
const selected = selection.current;
return selected && (!runId || selected.id === runId)
? refreshSelection(selected)
: Promise.resolve();
},
[refreshSelection]
);
/** Reopening a run reads its recorded state; it never submits another backtest. */
const selectRun = useCallback(
(runId: string | undefined) => {
if (
runId &&
selection.current?.id === runId &&
selection.current.backtestId === loadedBacktestId.current
) {
return refreshSelection(selection.current);
}
stopMonitoring();
setCurrentRun(null);
setRunResults(null);
setRunError(null);
setCancelRequested(false);
setIsRunLoading(Boolean(runId));
if (!runId) {
return Promise.resolve();
}
const selected: RunSelection = {
id: runId,
backtestId: loadedBacktestId.current,
controller: new AbortController(),
refreshRequested: false,
results: null,
};
selection.current = selected;
return refreshSelection(selected);
},
[refreshSelection, stopMonitoring]
);
const {
currentRun,
runResults,
isRunLoading,
runError,
cancelRequested,
selection,
selectionGeneration,
stopMonitoring,
refreshRun,
selectRun,
cancelRun,
} = useRunMonitoring({ mounted, loadedBacktestId, setRuns });
const { createRun, submissionError, isSubmitting, hasPendingSubmission, resetSubmission } =
useRunSubmission({
backtest,
loadedBacktestId,
mounted,
selectionGeneration,
catalog,
canonicalCapability,
capabilityError,
setRuns,
});
const loadBacktest = useCallback(
async (id: string) => {
const generation = ++backtestGeneration.current;
if (loadedBacktestId.current !== id) {
submission.current = null;
setSubmissionError(null);
setIsSubmitting(false);
resetSubmission();
// Parent-only route changes do not rerun the page's runId effect. Fence
// the old request chain and validate the same selection against its new parent.
loadedBacktestId.current = id;
@ -325,7 +152,7 @@ export function useBacktestV2() {
}
}
},
[selectRun]
[selectRun, resetSubmission]
);
const createBacktest = useCallback(
@ -337,9 +164,7 @@ export function useBacktestV2() {
const created = await backtestApiV2.createBacktest(request);
if (mounted.current && generation === backtestGeneration.current) {
loadedBacktestId.current = created.id;
submission.current = null;
setSubmissionError(null);
setIsSubmitting(false);
resetSubmission();
setBacktest(created);
setRuns([]);
await selectRun(undefined);
@ -356,7 +181,7 @@ export function useBacktestV2() {
}
}
},
[selectRun]
[selectRun, resetSubmission]
);
const updateBacktest = useCallback(
@ -395,9 +220,7 @@ export function useBacktestV2() {
await backtestApiV2.deleteBacktest(id);
if (mounted.current && generation === backtestGeneration.current) {
loadedBacktestId.current = null;
submission.current = null;
setSubmissionError(null);
setIsSubmitting(false);
resetSubmission();
setBacktest(null);
setRuns([]);
await selectRun(undefined);
@ -413,7 +236,7 @@ export function useBacktestV2() {
}
}
},
[selectRun]
[selectRun, resetSubmission]
);
const setBacktestArchived = useCallback(async (id: string, archived: boolean) => {
@ -437,103 +260,6 @@ export function useBacktestV2() {
}
}, []);
/**
* Retain the same key/body after an ambiguous response so Retry can recover
* the accepted run. This receipt is in memory for this mounted hook; it is not
* a persistent browser recovery journal. New admissions recheck eligibility;
* receipt retries recover the original run before current eligibility checks.
*/
const createRun = useCallback(
async (_speedMultiplier: number | null = null) => {
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
return undefined;
}
if (backtest.archivedAt && !submission.current) {
setSubmissionError('Restore this archived backtest before starting a new run.');
return undefined;
}
if (catalog && !canonicalCapability?.available && !submission.current) {
setSubmissionError(
capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason
);
return undefined;
}
if (!catalog && !submission.current) {
setSubmissionError(
'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.'
);
return undefined;
}
const intent = (submission.current ??= {
backtestId: backtest.id,
key: crypto.randomUUID(),
body: { speedMultiplier: null },
pending: false,
});
intent.pending = true;
const selectedGeneration = selectionGeneration.current;
const ownsSubmission = () => mounted.current && submission.current === intent;
const ownsSelection = () =>
ownsSubmission() && selectionGeneration.current === selectedGeneration;
setIsSubmitting(true);
setSubmissionError(null);
try {
const created = await backtestApiV2.createRun(intent.backtestId, intent.body, intent.key);
if (!ownsSubmission()) {
return undefined;
}
const selected = ownsSelection();
submission.current = null;
setIsSubmitting(false);
if (!selected) {
return undefined;
}
setRuns(previous => [created, ...previous.filter(run => run.id !== created.id)]);
return created;
} catch (err) {
if (ownsSubmission()) {
setSubmissionError(messageOf(err, 'Failed to submit run'));
}
return undefined;
} finally {
intent.pending = false;
if (ownsSubmission()) {
setIsSubmitting(false);
}
}
},
[backtest, catalog, canonicalCapability, capabilityError]
);
/** Record a cancellation request, then monitor until the server reports a terminal state. */
const cancelRun = useCallback(async () => {
const selected = selection.current;
if (
!selected ||
!currentRun ||
currentRun.id !== selected.id ||
!isActive(currentRun) ||
cancellation.current === selected
) {
return;
}
cancellation.current = selected;
setCancelRequested(true);
setRunError(null);
try {
await backtestApiV2.cancelRun(selected.id, selected.controller.signal);
if (isSelected(selected)) {
await refreshSelection(selected);
}
} catch (err) {
if (isSelected(selected)) {
cancellation.current = null;
setCancelRequested(Boolean(currentRun.cancelRequested));
setRunError(messageOf(err, 'Failed to request cancellation'));
}
}
}, [currentRun, isSelected, refreshSelection]);
useEffect(() => {
mounted.current = true;
return () => {
@ -556,7 +282,7 @@ export function useBacktestV2() {
error: runError ?? error,
submissionError,
isSubmitting,
hasPendingSubmission: submission.current !== null,
hasPendingSubmission,
cancelRequested,
loadBacktest,
createBacktest,

View file

@ -0,0 +1,250 @@
import {
useCallback,
useRef,
useState,
type Dispatch,
type MutableRefObject,
type SetStateAction,
} from 'react';
import {
backtestApiV2,
RunResultsUnavailableError,
type ResearchRunResult,
type Run,
} from '../services/backtestApiV2';
/** Object identity is the ownership token for one status/result request chain. */
export interface RunSelection {
id: string;
backtestId: string | null;
controller: AbortController;
timer?: ReturnType<typeof setTimeout>;
request?: Promise<void>;
refreshRequested: boolean;
results: ResearchRunResult | null;
}
const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status);
export const messageOf = (error: unknown, fallback: string) =>
error instanceof Error ? error.message : fallback;
/** One selection owns status, results, polling, refresh and cancellation. */
export function useRunMonitoring({
mounted,
loadedBacktestId,
setRuns,
}: {
mounted: MutableRefObject<boolean>;
loadedBacktestId: MutableRefObject<string | null>;
setRuns: Dispatch<SetStateAction<Run[]>>;
}) {
const [currentRun, setCurrentRun] = useState<Run | null>(null);
const [runResults, setRunResults] = useState<ResearchRunResult | null>(null);
const [isRunLoading, setIsRunLoading] = useState(false);
const [runError, setRunError] = useState<string | null>(null);
const [cancelRequested, setCancelRequested] = useState(false);
const selectionGeneration = useRef(0);
const selection = useRef<RunSelection | null>(null);
const cancellation = useRef<RunSelection | null>(null);
const isSelected = useCallback(
(selected: RunSelection) =>
mounted.current &&
selection.current === selected &&
selected.backtestId === loadedBacktestId.current,
[]
);
/** Stop browser observation only; cancelling server execution is cancelRun's job. */
const stopMonitoring = useCallback(() => {
selectionGeneration.current++;
const selected = selection.current;
selection.current = null;
cancellation.current = null;
if (selected) {
clearTimeout(selected.timer);
selected.controller.abort();
}
}, []);
// A selection owns one request chain (status, then results) and one timer.
// Polls, websocket invalidations and cancel acknowledgements all use this path.
const refreshSelection = useCallback(
function refresh(selected: RunSelection): Promise<void> {
if (!isSelected(selected)) {
return Promise.resolve();
}
if (selected.request) {
selected.refreshRequested = true;
return selected.request;
}
clearTimeout(selected.timer);
let monitorAgain = true;
selected.request = (async () => {
try {
const run = await backtestApiV2.getRun(selected.id, selected.controller.signal);
if (!isSelected(selected)) {
return;
}
if (
run.id !== selected.id ||
(selected.backtestId !== null && run.backtestId !== selected.backtestId)
) {
monitorAgain = false;
selected.refreshRequested = false;
selected.results = null;
setCurrentRun(null);
setRunResults(null);
throw new Error('Received a run for a different backtest or run selection');
}
setCurrentRun(run);
setRuns(previous =>
previous.some(item => item.id === run.id)
? previous.map(item => (item.id === run.id ? run : item))
: [run, ...previous]
);
setRunError(null);
monitorAgain = isActive(run);
if (!monitorAgain) {
cancellation.current = null;
setCancelRequested(false);
} else if (run.cancelRequested) {
setCancelRequested(true);
}
if (run.status === 'completed') {
if (!selected.results) {
const results = await backtestApiV2.getRunResults(
selected.id,
selected.controller.signal
);
if (!isSelected(selected)) {
return;
}
if (
results &&
(results.runId !== selected.id || results.backtestId !== run.backtestId)
) {
selected.refreshRequested = false;
throw new Error('Received results for a different backtest or run');
}
selected.results = results;
setRunResults(results);
}
} else {
selected.results = null;
setRunResults(null);
}
} catch (err) {
if (!isSelected(selected)) {
return;
}
setRunError(
err instanceof RunResultsUnavailableError
? null
: messageOf(err, 'Failed to refresh run')
);
} finally {
if (isSelected(selected)) {
selected.request = undefined;
setIsRunLoading(false);
if (selected.refreshRequested) {
selected.refreshRequested = false;
void refresh(selected);
} else if (monitorAgain) {
selected.timer = setTimeout(() => void refresh(selected), 1000);
}
}
}
})();
return selected.request;
},
[isSelected]
);
const refreshRun = useCallback(
(runId?: string) => {
const selected = selection.current;
return selected && (!runId || selected.id === runId)
? refreshSelection(selected)
: Promise.resolve();
},
[refreshSelection]
);
/** Reopening a run reads its recorded state; it never submits another backtest. */
const selectRun = useCallback(
(runId: string | undefined) => {
if (
runId &&
selection.current?.id === runId &&
selection.current.backtestId === loadedBacktestId.current
) {
return refreshSelection(selection.current);
}
stopMonitoring();
setCurrentRun(null);
setRunResults(null);
setRunError(null);
setCancelRequested(false);
setIsRunLoading(Boolean(runId));
if (!runId) {
return Promise.resolve();
}
const selected: RunSelection = {
id: runId,
backtestId: loadedBacktestId.current,
controller: new AbortController(),
refreshRequested: false,
results: null,
};
selection.current = selected;
return refreshSelection(selected);
},
[refreshSelection, stopMonitoring]
);
/** Record a cancellation request, then monitor until the server reports a terminal state. */
const cancelRun = useCallback(async () => {
const selected = selection.current;
if (
!selected ||
!currentRun ||
currentRun.id !== selected.id ||
!isActive(currentRun) ||
cancellation.current === selected
) {
return;
}
cancellation.current = selected;
setCancelRequested(true);
setRunError(null);
try {
await backtestApiV2.cancelRun(selected.id, selected.controller.signal);
if (isSelected(selected)) {
await refreshSelection(selected);
}
} catch (err) {
if (isSelected(selected)) {
cancellation.current = null;
setCancelRequested(Boolean(currentRun.cancelRequested));
setRunError(messageOf(err, 'Failed to request cancellation'));
}
}
}, [currentRun, isSelected, refreshSelection]);
return {
currentRun,
runResults,
isRunLoading,
runError,
cancelRequested,
selection,
selectionGeneration,
stopMonitoring,
refreshRun,
selectRun,
cancelRun,
};
}

View file

@ -0,0 +1,123 @@
import {
useCallback,
useRef,
useState,
type Dispatch,
type MutableRefObject,
type SetStateAction,
} from 'react';
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2';
import { messageOf } from './useRunMonitoring';
export function useRunSubmission({
backtest,
loadedBacktestId,
mounted,
selectionGeneration,
catalog,
canonicalCapability,
capabilityError,
setRuns,
}: {
backtest: Backtest | null;
loadedBacktestId: MutableRefObject<string | null>;
mounted: MutableRefObject<boolean>;
selectionGeneration: MutableRefObject<number>;
catalog: boolean;
canonicalCapability: CanonicalRunCapability | null;
capabilityError: string | null;
setRuns: Dispatch<SetStateAction<Run[]>>;
}) {
const [submissionError, setSubmissionError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
// The intent survives an ambiguous response and configuration edits. Only an
// acknowledged submission (or leaving this definition) releases its key.
const submission = useRef<{
backtestId: string;
key: string;
body: { speedMultiplier: number | null };
pending: boolean;
} | null>(null);
/**
* Retain the same key/body after an ambiguous response so Retry can recover
* the accepted run. This receipt is in memory for this mounted hook; it is not
* a persistent browser recovery journal. New admissions recheck eligibility;
* receipt retries recover the original run before current eligibility checks.
*/
const createRun = useCallback(
async (_speedMultiplier: number | null = null) => {
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
return undefined;
}
if (backtest.archivedAt && !submission.current) {
setSubmissionError('Restore this archived backtest before starting a new run.');
return undefined;
}
if (catalog && !canonicalCapability?.available && !submission.current) {
setSubmissionError(
capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason
);
return undefined;
}
if (!catalog && !submission.current) {
setSubmissionError(
'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.'
);
return undefined;
}
const intent = (submission.current ??= {
backtestId: backtest.id,
key: crypto.randomUUID(),
body: { speedMultiplier: null },
pending: false,
});
intent.pending = true;
const selectedGeneration = selectionGeneration.current;
const ownsSubmission = () => mounted.current && submission.current === intent;
const ownsSelection = () =>
ownsSubmission() && selectionGeneration.current === selectedGeneration;
setIsSubmitting(true);
setSubmissionError(null);
try {
const created = await backtestApiV2.createRun(intent.backtestId, intent.body, intent.key);
if (!ownsSubmission()) {
return undefined;
}
const selected = ownsSelection();
submission.current = null;
setIsSubmitting(false);
if (!selected) {
return undefined;
}
setRuns(previous => [created, ...previous.filter(run => run.id !== created.id)]);
return created;
} catch (err) {
if (ownsSubmission()) {
setSubmissionError(messageOf(err, 'Failed to submit run'));
}
return undefined;
} finally {
intent.pending = false;
if (ownsSubmission()) {
setIsSubmitting(false);
}
}
},
[backtest, catalog, canonicalCapability, capabilityError]
);
const resetSubmission = useCallback(() => {
submission.current = null;
setSubmissionError(null);
setIsSubmitting(false);
}, []);
return {
createRun,
submissionError,
isSubmitting,
hasPendingSubmission: submission.current !== null,
resetSubmission,
};
}

View file

@ -1,4 +1,8 @@
import { z } from 'zod';
import {
datasetUnavailableReason,
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 type {
@ -113,112 +117,7 @@ const hashOrNull = (value: unknown) =>
const preparationText = z.string().min(1);
const preparationHash = z.string().regex(/^[a-f0-9]{64}$/);
const preparationInstant = z.number().int().nonnegative().max(8_640_000_000_000_000);
const preparationDay = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.refine(
value =>
Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value
);
const preparationManifest = z
.object({
version: z.literal(2),
hash: preparationHash,
normalizationRevision: z.literal('historical-normalization-v2'),
parentDatasetHash: z.null(),
volumePolicy: z.literal('reported'),
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
intradayPolicy: z.literal('full-duration-session-contained'),
eligibility: z.enum(['eligible', 'exploratory', 'ineligible']),
limitations: z.array(preparationText),
barCount: z.number().int().positive().safe(),
calendars: z
.array(
z
.object({
id: preparationText,
venue: preparationText,
timeZone: preparationText,
source: preparationText,
revision: preparationText,
startDate: preparationDay,
endDate: preparationDay,
sessions: z
.array(
z
.object({
date: preparationDay,
open: preparationInstant,
close: preparationInstant,
})
.strict()
.refine(value => value.open < value.close)
)
.min(1),
})
.strict()
)
.min(1),
series: z
.array(
z
.object({
id: preparationText,
instrumentId: preparationText,
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
calendarId: preparationText,
venue: preparationText,
source: z.object({ provider: preparationText, revision: preparationText }).strict(),
timestamp: z.enum(['session-date', 'interval-start', 'interval-end']),
availability: z.enum(['explicit', 'interval-end-assumption']),
adjustment: z.enum(['raw', 'provider-adjusted']),
})
.strict()
)
.min(1),
executionSeries: z
.array(z.object({ instrumentId: preparationText, seriesId: preparationText }).strict())
.min(1),
bounds: z
.object({
warmupStart: preparationInstant,
tradeStart: preparationInstant,
tradeEnd: preparationInstant,
})
.strict()
.refine(value => value.warmupStart <= value.tradeStart && value.tradeStart < value.tradeEnd),
universe: z
.object({
selection: z.enum(['point-in-time', 'current-constituents', 'unknown']),
asOf: preparationInstant.nullable(),
revision: preparationText,
instrumentIds: z.array(preparationText).min(1),
})
.strict(),
corporateActions: z
.array(
z
.object({
instrumentId: preparationText,
status: z.enum(['unknown', 'action-free', 'known-actions']),
start: preparationInstant,
end: preparationInstant,
revision: preparationText,
actions: z.array(
z
.object({
effectiveAt: preparationInstant,
kind: z.enum(['split', 'dividend', 'other']),
reference: preparationText,
})
.strict()
),
})
.strict()
)
.min(1),
})
.strict();
const preparationManifest = preparationManifestSchema;
const datasetPreparationSchema = z
.object({
version: z.literal('canonical-dataset-preparation/v1'),
@ -234,11 +133,7 @@ export function parseDatasetPreparation(
): CanonicalDatasetPreparation {
const value = datasetPreparationSchema.parse(raw),
manifest = value.manifest;
const available =
manifest.eligibility === 'eligible' &&
manifest.executionSeries.length === 1 &&
manifest.series.length === 1 &&
manifest.universe.instrumentIds.length === 1;
const available = datasetUnavailableReason(manifest) === null;
if (
value.hash !== manifest.hash ||
(expectedHash !== undefined && value.hash !== expectedHash) ||