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

@ -1,51 +1,21 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { z } from 'zod';
import {
costSensitivityInputSchema,
type CostScenario,
type CostSensitivitySubmission,
} from '@stock-bot/stock-config/cost-sensitivity';
import {
experimentInputSchema,
MAX_EXPERIMENT_TRIALS,
type ExperimentSubmission,
} from '@stock-bot/stock-config/experiments';
import { type CostScenario } from '@stock-bot/stock-config/cost-sensitivity';
import { MAX_EXPERIMENT_TRIALS } from '@stock-bot/stock-config/experiments';
import { Button } from '@/components/ui/Button';
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
import {
StrategySelection,
type CatalogSelection,
} from '@/features/strategies/components/StrategySelection';
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
import {
experimentApi,
ExperimentApiError,
type WorkbenchExperimentPreviewView,
} from '../services/experimentApi';
import { useExperimentSubmission } from '../hooks/useExperimentSubmission';
import { useExperimentTemplates } from '../hooks/useExperimentTemplates';
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
import { ExperimentInputs } from './ExperimentInputs';
import { WalkForwardPreflight } from './WalkForwardPreflight';
const fieldClass =
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
const message = (cause: unknown) =>
cause instanceof z.ZodError
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
: cause instanceof Error
? cause.message
: 'Could not prepare the experiment';
const canonical = (value: Backtest) =>
value &&
typeof value.id === 'string' &&
typeof value.name === 'string' &&
!value.archivedAt &&
value.strategyVersionId &&
value.config &&
typeof value.config.canonical === 'object' &&
value.config.canonical !== null &&
typeof value.config.datasetHash === 'string';
export function ExperimentEditor({
initialBacktestId,
onDirty,
@ -54,47 +24,9 @@ export function ExperimentEditor({
onDirty: (dirty: boolean) => void;
}) {
const navigate = useNavigate();
const alive = useRef(false);
const generation = useRef(0);
const previewRevision = useRef<number | null>(null);
const previewRequest = useRef<AbortController | null>(null);
const pending = useRef(false);
type Intent =
| { kind: 'parameters'; body: ExperimentSubmission; key: string }
| { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string };
const intent = useRef<Intent | null>(null);
const [mode, setMode] = useState<'parameters' | 'cost-sensitivity'>('parameters');
const modeRef = useRef(mode);
const [scenarios, setScenarios] = useState<CostScenario[]>([{ feeRate: '', slippageRate: '' }]);
const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null);
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>(
null
);
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
if (
(owner !== 'ordinary' && modeRef.current === 'cost-sensitivity') ||
(submissionOwner.current && submissionOwner.current !== owner)
) {
return false;
}
submissionOwner.current = owner;
setLockedBy(owner);
if (owner !== 'ordinary') {
generation.current++;
previewRequest.current?.abort();
previewRevision.current = null;
setPreview(null);
setPreviewLoading(false);
}
return true;
}, []);
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
if (submissionOwner.current === owner) {
submissionOwner.current = null;
setLockedBy(null);
}
}, []);
const [hasIntent, setHasIntent] = useState(false);
const [backtestId, setBacktestId] = useState(initialBacktestId);
const [name, setName] = useState('');
const [grid, setGrid] = useState('{}');
@ -111,19 +43,38 @@ export function ExperimentEditor({
parameters: candidateSelection.strategyParameters ?? {},
}
: undefined;
const [backtests, setBacktests] = useState<Backtest[]>([]);
const [templateLoading, setTemplateLoading] = useState(true);
const [templateError, setTemplateError] = useState('');
const [templateReload, setTemplateReload] = useState(0);
const [limit, setLimit] = useState(50);
const [moreTemplates, setMoreTemplates] = useState(false);
const [preview, setPreview] = useState<WorkbenchExperimentPreviewView | null>(null);
const [previewLoading, setPreviewLoading] = useState(false);
const [error, setError] = useState('');
const [submitting, setSubmitting] = useState(false);
const [ambiguous, setAmbiguous] = useState(false);
const [validationDirty, setValidationDirty] = useState(false);
const [walkForwardDirty, setWalkForwardDirty] = useState(false);
const { backtests, templateLoading, templateError, setTemplateReload, moreTemplates, setLimit } =
useExperimentTemplates(initialBacktestId);
const {
submissionOwner,
lockedBy,
claimSubmission,
releaseSubmission,
preview,
previewLoading,
error,
hasIntent,
submitting,
ambiguous,
invalidate,
prepare,
submit,
newIntent,
} = useExperimentSubmission({
backtestId,
name,
grid,
modeRef,
scenarios,
candidate,
candidateRevision,
renderedCandidateRevision,
useCandidate,
candidateValid,
onAccepted: id => navigate(`/experiments/${encodeURIComponent(id)}`),
});
const dirty =
hasIntent ||
validationDirty ||
@ -141,183 +92,7 @@ export function ExperimentEditor({
useEffect(() => {
onDirty(dirty);
}, [dirty, onDirty]);
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
generation.current++;
previewRequest.current?.abort();
};
}, []);
useEffect(() => {
let current = true;
const controller = new AbortController();
setTemplateLoading(true);
setTemplateError('');
void (async () => {
const rows = await backtestApiV2.listBacktests(limit, 0, false, controller.signal);
if (!Array.isArray(rows)) {
throw new Error('The saved backtest list could not be read');
}
const selected =
initialBacktestId && !rows.some(item => item?.id === initialBacktestId)
? await backtestApiV2.getBacktest(initialBacktestId)
: null;
if (current) {
setMoreTemplates(rows.length === limit);
setBacktests((selected ? [...rows, selected] : rows).filter(canonical));
}
})()
.catch(cause => {
if (current) {
setTemplateError(message(cause));
}
})
.finally(() => {
if (current) {
setTemplateLoading(false);
}
});
return () => {
current = false;
controller.abort();
};
}, [initialBacktestId, templateReload, limit]);
const invalidate = (change: () => void) => {
if (submissionOwner.current) {
return;
}
generation.current++;
previewRequest.current?.abort();
previewRevision.current = null;
setPreview(null);
setPreviewLoading(false);
setError('');
change();
};
const prepare = async () => {
if (
submissionOwner.current ||
previewLoading ||
candidateRevision.current !== renderedCandidateRevision ||
(useCandidate && !candidateValid)
) {
return;
}
const current = ++generation.current;
previewRequest.current?.abort();
const controller = new AbortController();
previewRequest.current = controller;
previewRevision.current = null;
setPreview(null);
setError('');
setPreviewLoading(true);
try {
const value =
modeRef.current === 'cost-sensitivity'
? await experimentApi.costPreview(
costSensitivityInputSchema.parse({
backtestId,
name,
scenarios,
...(candidate ? { candidate } : {}),
}),
controller.signal
)
: await experimentApi.preview(
experimentInputSchema.parse({
backtestId,
name,
grid: JSON.parse(grid),
...(candidate ? { candidate } : {}),
}),
controller.signal
);
if (alive.current && current === generation.current) {
previewRevision.current = current;
setPreview(value);
}
} catch (cause) {
if (alive.current && current === generation.current) {
setError(message(cause));
}
} finally {
if (alive.current && current === generation.current) {
setPreviewLoading(false);
}
}
};
const submit = async () => {
if (
pending.current ||
(!intent.current && (!preview || previewRevision.current !== generation.current)) ||
!claimSubmission('ordinary')
) {
return;
}
if (!intent.current) {
if (!preview) {
return;
}
intent.current =
preview.version === 'cost-sensitivity-preview/v1'
? {
kind: 'cost-sensitivity',
key: crypto.randomUUID(),
body: { ...preview.input, previewHash: preview.previewHash },
}
: {
kind: 'parameters',
key: crypto.randomUUID(),
body: { ...preview.input, previewHash: preview.previewHash },
};
}
const captured = intent.current;
pending.current = true;
setHasIntent(true);
setSubmitting(true);
setError('');
try {
const accepted =
captured.kind === 'cost-sensitivity'
? await experimentApi.costSubmit(captured.body, captured.key)
: await experimentApi.create(captured.body, captured.key);
if (alive.current) {
intent.current = null;
setHasIntent(false);
releaseSubmission('ordinary');
navigate(`/experiments/${encodeURIComponent(accepted.id)}`);
}
} catch (cause) {
if (alive.current) {
setError(message(cause));
setAmbiguous(!(cause instanceof ExperimentApiError) || cause.ambiguous);
}
} finally {
pending.current = false;
if (alive.current) {
setSubmitting(false);
}
}
};
const newIntent = () => {
if (
pending.current ||
!window.confirm(
'Release this submission? If its response was lost, it may already exist. Check the experiment list before creating another.'
)
) {
return;
}
intent.current = null;
setHasIntent(false);
releaseSubmission('ordinary');
setAmbiguous(false);
previewRevision.current = null;
setPreview(null);
setError('');
};
return (
<section
aria-label="Create experiment"

View file

@ -0,0 +1,252 @@
import { useCallback, useEffect, useRef, useState, type MutableRefObject } from 'react';
import { z } from 'zod';
import {
costSensitivityInputSchema,
type CostScenario,
type CostSensitivitySubmission,
} from '@stock-bot/stock-config/cost-sensitivity';
import {
experimentInputSchema,
type ExperimentSubmission,
} from '@stock-bot/stock-config/experiments';
import type { StrategyParameterValue } from '@stock-bot/types';
import {
experimentApi,
ExperimentApiError,
type WorkbenchExperimentPreviewView,
} from '../services/experimentApi';
interface Inputs {
backtestId: string;
name: string;
grid: string;
modeRef: MutableRefObject<'parameters' | 'cost-sensitivity'>;
scenarios: CostScenario[];
candidate: { versionId: string; parameters: Record<string, StrategyParameterValue> } | undefined;
candidateRevision: MutableRefObject<number>;
renderedCandidateRevision: number;
useCandidate: boolean;
candidateValid: boolean;
onAccepted: (id: string) => void;
}
export const message = (cause: unknown) =>
cause instanceof z.ZodError
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
: cause instanceof Error
? cause.message
: 'Could not prepare the experiment';
/** One coordinator owns all submission modes and ordinary receipt recovery. */
export function useExperimentSubmission({
backtestId,
name,
grid,
modeRef,
scenarios,
candidate,
candidateRevision,
renderedCandidateRevision,
useCandidate,
candidateValid,
onAccepted,
}: Inputs) {
const alive = useRef(false);
const generation = useRef(0);
const previewRevision = useRef<number | null>(null);
const previewRequest = useRef<AbortController | null>(null);
const pending = useRef(false);
type Intent =
| { kind: 'parameters'; body: ExperimentSubmission; key: string }
| { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string };
const intent = useRef<Intent | null>(null);
const [preview, setPreview] = useState<WorkbenchExperimentPreviewView | null>(null);
const [previewLoading, setPreviewLoading] = useState(false);
const [error, setError] = useState('');
const [phase, setPhase] = useState<'idle' | 'submitting' | 'uncertain' | 'rejected'>('idle');
const hasIntent = phase !== 'idle';
const submitting = phase === 'submitting';
const ambiguous = phase === 'uncertain';
const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null);
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>(
null
);
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
if (
(owner !== 'ordinary' && modeRef.current === 'cost-sensitivity') ||
(submissionOwner.current && submissionOwner.current !== owner)
) {
return false;
}
submissionOwner.current = owner;
setLockedBy(owner);
if (owner !== 'ordinary') {
generation.current++;
previewRequest.current?.abort();
previewRevision.current = null;
setPreview(null);
setPreviewLoading(false);
}
return true;
}, []);
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
if (submissionOwner.current === owner) {
submissionOwner.current = null;
setLockedBy(null);
}
}, []);
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
generation.current++;
previewRequest.current?.abort();
};
}, []);
const invalidate = (change: () => void) => {
if (submissionOwner.current) {
return;
}
generation.current++;
previewRequest.current?.abort();
previewRevision.current = null;
setPreview(null);
setPreviewLoading(false);
setError('');
change();
};
const prepare = async () => {
if (
submissionOwner.current ||
previewLoading ||
candidateRevision.current !== renderedCandidateRevision ||
(useCandidate && !candidateValid)
) {
return;
}
const current = ++generation.current;
previewRequest.current?.abort();
const controller = new AbortController();
previewRequest.current = controller;
previewRevision.current = null;
setPreview(null);
setError('');
setPreviewLoading(true);
try {
const value =
modeRef.current === 'cost-sensitivity'
? await experimentApi.costPreview(
costSensitivityInputSchema.parse({
backtestId,
name,
scenarios,
...(candidate ? { candidate } : {}),
}),
controller.signal
)
: await experimentApi.preview(
experimentInputSchema.parse({
backtestId,
name,
grid: JSON.parse(grid),
...(candidate ? { candidate } : {}),
}),
controller.signal
);
if (alive.current && current === generation.current) {
previewRevision.current = current;
setPreview(value);
}
} catch (cause) {
if (alive.current && current === generation.current) {
setError(message(cause));
}
} finally {
if (alive.current && current === generation.current) {
setPreviewLoading(false);
}
}
};
const submit = async () => {
if (
pending.current ||
(!intent.current && (!preview || previewRevision.current !== generation.current)) ||
!claimSubmission('ordinary')
) {
return;
}
if (!intent.current) {
if (!preview) {
return;
}
intent.current =
preview.version === 'cost-sensitivity-preview/v1'
? {
kind: 'cost-sensitivity',
key: crypto.randomUUID(),
body: { ...preview.input, previewHash: preview.previewHash },
}
: {
kind: 'parameters',
key: crypto.randomUUID(),
body: { ...preview.input, previewHash: preview.previewHash },
};
}
const captured = intent.current;
pending.current = true;
setPhase('submitting');
setError('');
try {
const accepted =
captured.kind === 'cost-sensitivity'
? await experimentApi.costSubmit(captured.body, captured.key)
: await experimentApi.create(captured.body, captured.key);
if (alive.current) {
intent.current = null;
setPhase('idle');
releaseSubmission('ordinary');
onAccepted(accepted.id);
}
} catch (cause) {
if (alive.current) {
setError(message(cause));
setPhase(
!(cause instanceof ExperimentApiError) || cause.ambiguous ? 'uncertain' : 'rejected'
);
}
} finally {
pending.current = false;
}
};
const newIntent = () => {
if (
pending.current ||
!window.confirm(
'Release this submission? If its response was lost, it may already exist. Check the experiment list before creating another.'
)
) {
return;
}
intent.current = null;
setPhase('idle');
releaseSubmission('ordinary');
previewRevision.current = null;
setPreview(null);
setError('');
};
return {
submissionOwner,
lockedBy,
claimSubmission,
releaseSubmission,
preview,
previewLoading,
error,
hasIntent,
submitting,
ambiguous,
invalidate,
prepare,
submit,
newIntent,
};
}

View file

@ -0,0 +1,59 @@
import { useEffect, useState } from 'react';
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
import { message } from './useExperimentSubmission';
const canonical = (value: Backtest) =>
value &&
typeof value.id === 'string' &&
typeof value.name === 'string' &&
!value.archivedAt &&
value.strategyVersionId &&
value.config &&
typeof value.config.canonical === 'object' &&
value.config.canonical !== null &&
typeof value.config.datasetHash === 'string';
export function useExperimentTemplates(initialBacktestId: string) {
const [backtests, setBacktests] = useState<Backtest[]>([]);
const [templateLoading, setTemplateLoading] = useState(true);
const [templateError, setTemplateError] = useState('');
const [templateReload, setTemplateReload] = useState(0);
const [limit, setLimit] = useState(50);
const [moreTemplates, setMoreTemplates] = useState(false);
useEffect(() => {
let current = true;
const controller = new AbortController();
setTemplateLoading(true);
setTemplateError('');
void (async () => {
const rows = await backtestApiV2.listBacktests(limit, 0, false, controller.signal);
if (!Array.isArray(rows)) {
throw new Error('The saved backtest list could not be read');
}
const selected =
initialBacktestId && !rows.some(item => item?.id === initialBacktestId)
? await backtestApiV2.getBacktest(initialBacktestId)
: null;
if (current) {
setMoreTemplates(rows.length === limit);
setBacktests((selected ? [...rows, selected] : rows).filter(canonical));
}
})()
.catch(cause => {
if (current) {
setTemplateError(message(cause));
}
})
.finally(() => {
if (current) {
setTemplateLoading(false);
}
});
return () => {
current = false;
controller.abort();
};
}, [initialBacktestId, templateReload, limit]);
return { backtests, templateLoading, templateError, setTemplateReload, moreTemplates, setLimit };
}

View file

@ -15,7 +15,8 @@ import {
validationSummarySchema as summary,
ValidationApiError,
} from '@stock-bot/stock-config/research-responses';
import { API_BASE_URL, apiFetch } from '@/lib/api';
import { API_BASE_URL } from '@/lib/api';
import { requestJson } from '@/lib/requestJson';
export {
parseValidationDetail,
@ -26,41 +27,20 @@ export {
export type { ValidationResultEvidence };
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
async function request<T>(
function request<T>(
path: string,
init: RequestInit,
status: number,
parse: (body: unknown) => T
): Promise<T> {
let response: Response;
try {
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init);
} catch (cause) {
if (init.signal?.aborted) {
throw cause;
}
throw new ValidationApiError(
'The validation response was lost. Retry the same request to recover its receipt.',
null
);
}
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
const error = z.object({ error: z.string() }).safeParse(body);
throw new ValidationApiError(
error.success ? error.data.error : `Validation request failed (${response.status})`,
response.status
);
}
try {
if (response.status !== status) {
throw invalid();
}
return parse(body);
} catch {
throw invalid();
}
return requestJson(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init, status, parse, {
create: (message, code) => new ValidationApiError(message, code),
invalid,
lostMessage: 'The validation response was lost. Retry the same request to recover its receipt.',
failureLabel: 'Validation request failed',
});
}
const post = (body: unknown, key?: string): RequestInit => ({
method: 'POST',
body: JSON.stringify(body),

View file

@ -23,7 +23,8 @@ import {
sameExperimentInput as same,
type ExperimentRetryTarget,
} from '@stock-bot/stock-config/research-responses';
import { API_BASE_URL, apiFetch } from '@/lib/api';
import { API_BASE_URL } from '@/lib/api';
import { requestJson } from '@/lib/requestJson';
export {
ExperimentApiError,
@ -41,41 +42,21 @@ export {
type WorkbenchExperimentPreviewView,
} from '@stock-bot/stock-config/research-responses';
async function request<T>(
function request<T>(
path: string,
init: RequestInit,
expectedStatus: number,
status: number,
parse: (body: unknown) => T
): Promise<T> {
let response: Response;
try {
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments${path}`, init);
} catch (cause) {
if (init.signal?.aborted) {
throw cause;
}
throw new ExperimentApiError(
return requestJson(`${API_BASE_URL}/api/v2/experiments${path}`, init, status, parse, {
create: (message, code) => new ExperimentApiError(message, code),
invalid,
lostMessage:
'The experiment response was lost. Retry the same submission to check whether it was accepted.',
null
);
}
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
const parsed = z.object({ error: z.string() }).safeParse(body);
throw new ExperimentApiError(
parsed.success ? parsed.data.error : `Experiment request failed (${response.status})`,
response.status
);
}
try {
if (response.status !== expectedStatus) {
throw invalid();
}
return parse(body);
} catch {
throw invalid();
}
failureLabel: 'Experiment request failed',
});
}
const envelope = (body: unknown, field: string): unknown =>
z.record(z.unknown()).parse(body)[field];
const json = (body: unknown): RequestInit => ({

View file

@ -16,7 +16,8 @@ import {
type WalkForwardSubmission,
type WalkForwardSummary,
} from '@stock-bot/stock-config/walk-forward';
import { API_BASE_URL, apiFetch } from '@/lib/api';
import { API_BASE_URL } from '@/lib/api';
import { requestJson } from '@/lib/requestJson';
export {
WalkForwardApiError,
@ -27,41 +28,27 @@ export {
} from '@stock-bot/stock-config/research-responses';
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
async function request<T>(
function request<T>(
path: string,
init: RequestInit,
status: number,
parse: (body: unknown) => T
): Promise<T> {
let response: Response;
try {
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/walk-forward${path}`, init);
} catch (cause) {
if (init.signal?.aborted) {
throw cause;
return requestJson(
`${API_BASE_URL}/api/v2/experiments/walk-forward${path}`,
init,
status,
parse,
{
create: (message, code) => new WalkForwardApiError(message, code),
invalid,
lostMessage:
'The walk-forward response was lost. Retry the same request to recover its receipt.',
failureLabel: 'Walk-forward request failed',
}
throw new WalkForwardApiError(
'The walk-forward response was lost. Retry the same request to recover its receipt.',
null
);
}
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
const error = z.object({ error: z.string() }).safeParse(body);
throw new WalkForwardApiError(
error.success ? error.data.error : `Walk-forward request failed (${response.status})`,
response.status
);
}
try {
if (response.status !== status) {
throw invalid();
}
return parse(body);
} catch {
throw invalid();
}
);
}
const post = (body: unknown, key?: string): RequestInit => ({
method: 'POST',
body: JSON.stringify(body),