feat(research): compare saved experiments against explicit trials
This commit is contained in:
parent
397cd0e160
commit
46a4f13acd
22 changed files with 3045 additions and 35 deletions
|
|
@ -37,6 +37,10 @@
|
|||
"types": "./dist/contracts/chronological-validation.d.ts",
|
||||
"default": "./dist/contracts/chronological-validation.js"
|
||||
},
|
||||
"./experiment-comparison": {
|
||||
"types": "./dist/contracts/experiment-comparison.d.ts",
|
||||
"default": "./dist/contracts/experiment-comparison.js"
|
||||
},
|
||||
"./cost-sensitivity": {
|
||||
"types": "./dist/contracts/cost-sensitivity.d.ts",
|
||||
"default": "./dist/contracts/cost-sensitivity.js"
|
||||
|
|
|
|||
66
apps/stock/config/src/contracts/experiment-comparison.ts
Normal file
66
apps/stock/config/src/contracts/experiment-comparison.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
/** Read-only comparison of retained inputs and existing scalar result summaries. */
|
||||
import { z } from 'zod';
|
||||
import type { WorkbenchExperimentDetail } from './cost-sensitivity';
|
||||
|
||||
const experimentId = z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(id => id.toLowerCase());
|
||||
export const experimentComparisonInputSchema = z
|
||||
.object({
|
||||
leftId: experimentId,
|
||||
rightId: experimentId,
|
||||
referenceTrialKey: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/)
|
||||
.optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine(input => input.leftId !== input.rightId, {
|
||||
message: 'Select two different experiments',
|
||||
});
|
||||
export type ExperimentComparisonInput = z.infer<typeof experimentComparisonInputSchema>;
|
||||
|
||||
/** Stable order for mismatch explanations; these are conditions, not performance scores. */
|
||||
export const experimentComparisonDimensions = [
|
||||
'dataset',
|
||||
'window',
|
||||
'capital',
|
||||
'costs',
|
||||
'execution',
|
||||
'risk',
|
||||
'clock',
|
||||
'analytics',
|
||||
'seed',
|
||||
'build',
|
||||
'models',
|
||||
] as const;
|
||||
export type ExperimentComparisonDimension = (typeof experimentComparisonDimensions)[number];
|
||||
export interface ExperimentComparisonRow {
|
||||
experimentId: string;
|
||||
trialKey: string;
|
||||
inputCompatibility: 'match' | 'mismatch';
|
||||
differences: ExperimentComparisonDimension[];
|
||||
/** Existing compact provenance/shape checks, not full financial reconciliation. */
|
||||
summaryAvailable: boolean;
|
||||
/** Both saved summaries exist and their input conditions match. */
|
||||
ready: boolean;
|
||||
}
|
||||
export interface ExperimentComparison {
|
||||
version: 'experiment-comparison/v1';
|
||||
policy: 'retained-input-compatibility/v1';
|
||||
selection: Required<ExperimentComparisonInput>;
|
||||
reference: {
|
||||
experimentId: string;
|
||||
trialKey: string;
|
||||
index: number;
|
||||
runId: string | null;
|
||||
summaryAvailable: boolean;
|
||||
diagnostic: string | null;
|
||||
};
|
||||
/** Existing compact result readers; never include full financial/trade/return arrays. */
|
||||
experiments: [WorkbenchExperimentDetail, WorkbenchExperimentDetail];
|
||||
/** Left then right, in each experiment's immutable candidate order. */
|
||||
rows: ExperimentComparisonRow[];
|
||||
limitations: string[];
|
||||
}
|
||||
|
|
@ -211,6 +211,17 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
}
|
||||
return c.json({ experiments: await service.list(filter) });
|
||||
});
|
||||
app.get('/api/v2/experiments/compare', async c => {
|
||||
const params = new URL(c.req.url).searchParams;
|
||||
const seen = new Set<string>();
|
||||
for (const key of params.keys()) {
|
||||
if (seen.has(key) || !['leftId', 'rightId', 'referenceTrialKey'].includes(key)) {
|
||||
throw new ExperimentError(400, 'Unknown or duplicate comparison query parameter');
|
||||
}
|
||||
seen.add(key);
|
||||
}
|
||||
return c.json({ comparison: await service.compare(Object.fromEntries(params)) });
|
||||
});
|
||||
app.get('/api/v2/experiments/:id', async c =>
|
||||
c.json({ experiment: await service.get(experimentId(c.req.param('id'))) })
|
||||
);
|
||||
|
|
|
|||
124
apps/stock/web-api/src/services/experiment-comparison.ts
Normal file
124
apps/stock/web-api/src/services/experiment-comparison.ts
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { WorkbenchExperimentDetail } from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentComparisonDimensions,
|
||||
experimentComparisonInputSchema,
|
||||
type ExperimentComparison,
|
||||
type ExperimentComparisonDimension,
|
||||
type ExperimentComparisonInput,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type { HistoricalDatasetManifestV2 } from '@stock-bot/types';
|
||||
import { workbenchTrialRequest } from './cost-sensitivity-input';
|
||||
import { ExperimentError, PREVIEW_RUN_ID } from './experiment-input';
|
||||
|
||||
export function parseExperimentComparison(raw: unknown): ExperimentComparisonInput {
|
||||
const parsed = experimentComparisonInputSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
throw new ExperimentError(
|
||||
400,
|
||||
'Comparison requires two distinct experiment IDs and an optional reference trial key'
|
||||
);
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
/** Partition the complete parsed replay policy. Only validated admission/owner identities normalize. */
|
||||
export function comparisonConditions(
|
||||
input: CanonicalRunRequest,
|
||||
manifest: HistoricalDatasetManifestV2
|
||||
): Record<ExperimentComparisonDimension, unknown> {
|
||||
const request = canonicalRunRequestSchema.parse(input),
|
||||
policy = structuredClone(request.policy);
|
||||
policy.matching.risk.ledger.sessionId = 'comparison-run';
|
||||
policy.matching.risk.ledger.accountId = 'comparison-account';
|
||||
policy.matching.risk.ledger.ownerIds[0] = 'comparison-owner';
|
||||
at(policy.matching.owners, 0).ownerId = 'comparison-owner';
|
||||
at(policy.cadence, 0).owner_id = 'comparison-owner';
|
||||
const { matching, risk_boundaries, ...policyRemainder } = policy;
|
||||
const { risk, halfSpreadRate, slippageRate, ...matchingRemainder } = matching;
|
||||
const { ledger, feeRate, ...riskRemainder } = risk;
|
||||
const { initialCapital, riskSession, ...ledgerRemainder } = ledger;
|
||||
return {
|
||||
dataset: { manifest, datasetHash: request.datasetHash },
|
||||
window: manifest.bounds,
|
||||
capital: { initialCapital, ownerBudget: request.strategy.selection.ownerBudget },
|
||||
costs: { feeRate, halfSpreadRate, slippageRate },
|
||||
execution: {
|
||||
...policyRemainder,
|
||||
matching: matchingRemainder,
|
||||
instrumentId: request.strategy.selection.instrumentId,
|
||||
seriesId: request.strategy.selection.seriesId,
|
||||
},
|
||||
risk: { ...riskRemainder, ledger: ledgerRemainder },
|
||||
clock: { riskSession, risk_boundaries },
|
||||
analytics: request.analyticsPolicy,
|
||||
seed: request.strategy.selection.seed,
|
||||
build: request.build,
|
||||
models: request.modelArtifacts,
|
||||
};
|
||||
}
|
||||
export function compareExperiments(
|
||||
raw: ExperimentComparisonInput,
|
||||
experiments: [WorkbenchExperimentDetail, WorkbenchExperimentDetail]
|
||||
): ExperimentComparison {
|
||||
const input = parseExperimentComparison(raw),
|
||||
[left, right] = experiments;
|
||||
if (left.id !== input.leftId || right.id !== input.rightId) {
|
||||
throw new Error('Comparison experiment identities do not match the requested pair');
|
||||
}
|
||||
const reference =
|
||||
input.referenceTrialKey === undefined
|
||||
? at(left.trials, 0)
|
||||
: left.trials.find(trial => trial.trialKey === input.referenceTrialKey);
|
||||
if (!reference) {
|
||||
throw new ExperimentError(409, 'Reference trial does not belong to the left experiment');
|
||||
}
|
||||
const conditions = comparisonConditions(
|
||||
workbenchTrialRequest(left.preview, reference, reference.runId ?? PREVIEW_RUN_ID),
|
||||
left.preview.dataset
|
||||
);
|
||||
const rows = experiments.flatMap(experiment =>
|
||||
experiment.trials.map(trial => {
|
||||
const current = comparisonConditions(
|
||||
workbenchTrialRequest(experiment.preview, trial, trial.runId ?? PREVIEW_RUN_ID),
|
||||
experiment.preview.dataset
|
||||
);
|
||||
const differences = experimentComparisonDimensions.filter(
|
||||
dimension =>
|
||||
canonicalStrategyJson(current[dimension]) !== canonicalStrategyJson(conditions[dimension])
|
||||
);
|
||||
return {
|
||||
experimentId: experiment.id,
|
||||
trialKey: trial.trialKey,
|
||||
inputCompatibility: differences.length ? ('mismatch' as const) : ('match' as const),
|
||||
differences,
|
||||
summaryAvailable: trial.comparable,
|
||||
ready: differences.length === 0 && trial.comparable && reference.comparable,
|
||||
};
|
||||
})
|
||||
);
|
||||
return {
|
||||
version: 'experiment-comparison/v1',
|
||||
policy: 'retained-input-compatibility/v1',
|
||||
selection: { ...input, referenceTrialKey: reference.trialKey },
|
||||
reference: {
|
||||
experimentId: left.id,
|
||||
trialKey: reference.trialKey,
|
||||
index: reference.index,
|
||||
runId: reference.runId,
|
||||
summaryAvailable: reference.comparable,
|
||||
diagnostic: reference.diagnostic,
|
||||
},
|
||||
experiments,
|
||||
rows,
|
||||
limitations: [
|
||||
'Matching settings and saved scalar summaries do not establish economic equivalence, full financial reconciliation, independence, statistical significance or out-of-sample validity.',
|
||||
'Summary availability uses existing compact provenance and shape checks. Open the exact run for deeper retained-result validation.',
|
||||
'Strategy implementations and parameters may differ. Rows preserve original candidate order; no ranking or preferred candidate is implied.',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
|
@ -27,6 +27,7 @@ import {
|
|||
retainedWorkbenchPreview,
|
||||
workbenchTrialRequest,
|
||||
} from './cost-sensitivity-input';
|
||||
import { compareExperiments, parseExperimentComparison } from './experiment-comparison';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
|
|
@ -319,6 +320,30 @@ export class ExperimentsService {
|
|||
);
|
||||
return rows.rows.map(summary);
|
||||
}
|
||||
async compare(raw: unknown) {
|
||||
const input = parseExperimentComparison(raw);
|
||||
return this.database.transaction(async client => {
|
||||
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
const rows = (
|
||||
await client.query(
|
||||
'SELECT id,validation_phase FROM research_experiments WHERE id=ANY($1::uuid[])',
|
||||
[[input.leftId, input.rightId]]
|
||||
)
|
||||
).rows;
|
||||
if (rows.length !== 2) {
|
||||
throw new ExperimentError(404, 'Comparison experiment not found');
|
||||
}
|
||||
if (rows.some(row => row.validation_phase !== null)) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Compare standalone experiments; chronological phases have their own workflow'
|
||||
);
|
||||
}
|
||||
const left = await this.readDetail(client, input.leftId),
|
||||
right = await this.readDetail(client, input.rightId);
|
||||
return compareExperiments(input, [left, right]);
|
||||
});
|
||||
}
|
||||
async get(id: string): Promise<WorkbenchExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.readDetail(this.database, id);
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { DashboardPage } from '@/features/dashboard';
|
|||
import { ExchangesPage } from '@/features/exchanges';
|
||||
import {
|
||||
ChronologicalValidationDetailPage,
|
||||
ExperimentComparisonPage,
|
||||
ExperimentDetailPage,
|
||||
ExperimentListPage,
|
||||
WalkForwardDetailPage,
|
||||
|
|
@ -56,6 +57,7 @@ export function App() {
|
|||
</Route>
|
||||
<Route path="experiments">
|
||||
<Route index element={<ExperimentListPage />} />
|
||||
<Route path="compare" element={<ExperimentComparisonPage />} />
|
||||
<Route
|
||||
path="validation/:validationId"
|
||||
element={<ChronologicalValidationDetailPage />}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,322 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router-dom';
|
||||
import type {
|
||||
ExperimentComparisonDimension,
|
||||
ExperimentComparisonInput,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentInputs } from './components/ExperimentInputs';
|
||||
import { metricText } from './components/trialMetricText';
|
||||
import {
|
||||
experimentComparisonApi,
|
||||
parseComparisonQuery,
|
||||
type ExperimentComparisonView,
|
||||
} from './services/experimentComparisonApi';
|
||||
|
||||
const dimensionLabels: Record<ExperimentComparisonDimension, string> = {
|
||||
dataset: 'Dataset and retained provenance',
|
||||
window: 'Warmup and evaluation window',
|
||||
capital: 'Initial capital and strategy budget',
|
||||
costs: 'Fees, spread or slippage',
|
||||
execution: 'Execution and liquidity settings',
|
||||
risk: 'Portfolio risk limits and ledger settings',
|
||||
clock: 'Account risk-session clock',
|
||||
analytics: 'Metric definitions and analytics settings',
|
||||
seed: 'Random seed',
|
||||
build: 'Engine, worker or runtime build',
|
||||
models: 'Model artifacts',
|
||||
};
|
||||
export function ExperimentComparisonPage() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
let input: ExperimentComparisonInput;
|
||||
try {
|
||||
input = parseComparisonQuery(params);
|
||||
} catch (cause) {
|
||||
return (
|
||||
<div className="space-y-3 p-1">
|
||||
<h1 className="text-lg font-bold">Compare experiments</h1>
|
||||
<p role="alert">{cause instanceof Error ? cause.message : 'Invalid comparison URL'}</p>
|
||||
<Link className="text-primary-500" to="/experiments">
|
||||
Select experiments
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Comparison
|
||||
key={params.toString()}
|
||||
input={input}
|
||||
onReference={key => setParams({ ...input, referenceTrialKey: key })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function Comparison({
|
||||
input,
|
||||
onReference,
|
||||
}: {
|
||||
input: ExperimentComparisonInput;
|
||||
onReference: (key: string) => void;
|
||||
}) {
|
||||
const [value, setValue] = useState<ExperimentComparisonView | null>(null),
|
||||
[loading, setLoading] = useState(true),
|
||||
[error, setError] = useState(''),
|
||||
[reload, setReload] = useState(0);
|
||||
const reading = useRef(true);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
reading.current = true;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
void experimentComparisonApi
|
||||
.get(input, controller.signal)
|
||||
.then(result => {
|
||||
if (current) {
|
||||
setValue(result);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Could not load comparison');
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
reading.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [input.leftId, input.rightId, input.referenceTrialKey, reload]);
|
||||
return (
|
||||
<div className="h-full overflow-auto p-1 space-y-4">
|
||||
<Link className="text-primary-500 text-sm" to="/experiments">
|
||||
All experiments
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-lg font-bold">Compare experiments</h1>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
if (!reading.current) {
|
||||
reading.current = true;
|
||||
setReload(current => current + 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Refresh comparison
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm">
|
||||
Read-only comparison of recorded settings and saved summaries. Matching settings do not
|
||||
establish economic equivalence, full financial reconciliation, independence, statistical
|
||||
significance or out-of-sample validity. No ranking, deltas or aggregate performance are
|
||||
calculated.
|
||||
</p>
|
||||
{loading && <p role="status">Loading comparison...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
{value && ' Showing the last loaded comparison for this same selection.'}
|
||||
</p>
|
||||
)}
|
||||
{value && (
|
||||
<>
|
||||
<label className="block text-sm">
|
||||
Reference trial
|
||||
<select
|
||||
aria-label="Reference trial"
|
||||
className="mt-1 w-full rounded border border-border bg-background p-2"
|
||||
value={value.selection.referenceTrialKey}
|
||||
onChange={event => onReference(event.target.value)}
|
||||
>
|
||||
{value.experiments[0].trials.map(trial => (
|
||||
<option key={trial.trialKey} value={trial.trialKey}>
|
||||
{'costs' in trial
|
||||
? trial.index === 0
|
||||
? 'Baseline'
|
||||
: `Scenario ${trial.index}`
|
||||
: `Trial ${trial.index + 1}`}{' '}
|
||||
· {JSON.stringify(trial.parameters)} · {trial.status}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
Reference comes from {value.experiments[0].name}. Without an explicit URL reference, its
|
||||
frozen first candidate is used; completion status and performance never choose the
|
||||
reference.
|
||||
</p>
|
||||
{!value.reference.summaryAvailable && (
|
||||
<p role="status">
|
||||
Reference saved summary unavailable:{' '}
|
||||
{value.reference.diagnostic ?? 'No comparable saved summary exists for this trial.'}{' '}
|
||||
Settings comparisons and every outcome remain visible.
|
||||
</p>
|
||||
)}
|
||||
<section aria-label="Comparison limitations" className="text-sm space-y-1">
|
||||
{value.limitations.map((text, index) => (
|
||||
<p key={index}>{text}</p>
|
||||
))}
|
||||
</section>
|
||||
{value.experiments.map((experiment, side) => (
|
||||
<section
|
||||
key={experiment.id}
|
||||
aria-label={`${side === 0 ? 'Left' : 'Right'} experiment outcomes`}
|
||||
className="space-y-3"
|
||||
>
|
||||
<h2 className="font-semibold">
|
||||
{side === 0 ? 'Left' : 'Right'}: {experiment.name}
|
||||
</h2>
|
||||
<Link
|
||||
className="text-primary-500 text-sm"
|
||||
to={`/experiments/${encodeURIComponent(experiment.id)}`}
|
||||
>
|
||||
Open {side === 0 ? 'left' : 'right'} experiment
|
||||
</Link>
|
||||
<ExperimentCounts experiment={experiment} />
|
||||
<p className="text-sm break-all">
|
||||
Strategy {experiment.preview.request.strategy.selection.strategyId} · Version{' '}
|
||||
{experiment.strategyVersionId} · Dataset {experiment.datasetHash}
|
||||
</p>
|
||||
<details>
|
||||
<summary className="cursor-pointer">
|
||||
{side === 0 ? 'Left' : 'Right'} frozen inputs
|
||||
</summary>
|
||||
<ExperimentInputs preview={experiment.preview} />
|
||||
</details>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Trial / parameters',
|
||||
'Status',
|
||||
'Effective costs (fractions)',
|
||||
'Input settings',
|
||||
'Saved summary',
|
||||
'Total return (fraction)',
|
||||
'Max drawdown (fraction)',
|
||||
'Sharpe ratio',
|
||||
'Diagnostics / evidence',
|
||||
].map(label => (
|
||||
<th className="p-2 border-b border-border whitespace-nowrap" key={label}>
|
||||
{label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{experiment.trials.map(trial => {
|
||||
const row = value.rows.find(
|
||||
item =>
|
||||
item.experimentId === experiment.id && item.trialKey === trial.trialKey
|
||||
);
|
||||
if (!row) {
|
||||
throw new Error('Verified comparison row is missing');
|
||||
}
|
||||
const matching = experiment.preview.request.policy.matching,
|
||||
costs =
|
||||
'costs' in trial
|
||||
? trial.costs
|
||||
: {
|
||||
feeRate: matching.risk.feeRate,
|
||||
slippageRate: matching.slippageRate,
|
||||
};
|
||||
const reference =
|
||||
experiment.id === value.reference.experimentId &&
|
||||
trial.trialKey === value.reference.trialKey;
|
||||
return (
|
||||
<tr key={trial.trialKey} className="align-top">
|
||||
<td className="p-2 border-b border-border">
|
||||
<p>
|
||||
{'costs' in trial
|
||||
? trial.index === 0
|
||||
? 'Baseline'
|
||||
: `Scenario ${trial.index}`
|
||||
: `Trial ${trial.index + 1}`}
|
||||
{reference ? ' · Reference' : ''}
|
||||
</p>
|
||||
<pre className="whitespace-pre-wrap text-xs">
|
||||
{JSON.stringify(trial.parameters, null, 2)}
|
||||
</pre>
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
<p>{trial.status}</p>
|
||||
<p>
|
||||
{trial.status === 'missing'
|
||||
? 'Expected run missing'
|
||||
: `${trial.progress}% complete`}
|
||||
</p>
|
||||
{trial.cancelRequested && <p>Cancellation requested</p>}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
<p>Fee: {costs.feeRate}</p>
|
||||
<p>Half-spread: {matching.halfSpreadRate}</p>
|
||||
<p>Slippage: {costs.slippageRate}</p>
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
<p>
|
||||
{row.inputCompatibility === 'match'
|
||||
? 'Matching settings'
|
||||
: 'Settings differ'}
|
||||
</p>
|
||||
{row.differences.map(difference => (
|
||||
<p key={difference}>{dimensionLabels[difference]}</p>
|
||||
))}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
<p>
|
||||
{row.summaryAvailable
|
||||
? 'Saved summary available'
|
||||
: (trial.diagnostic ?? 'Saved summary unavailable')}
|
||||
</p>
|
||||
<p>
|
||||
{row.ready
|
||||
? 'Matching settings and both saved summaries available'
|
||||
: 'Comparison evidence not ready'}
|
||||
</p>
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
{metricText(trial, 'totalReturn')}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
{metricText(trial, 'maxDrawdown')}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
{metricText(trial, 'sharpeRatio')}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border min-w-64 space-y-1">
|
||||
{trial.error && <p>{trial.error}</p>}
|
||||
{trial.diagnostic && <p>{trial.diagnostic}</p>}
|
||||
{trial.limitations.map((text, index) => (
|
||||
<p key={index}>{text}</p>
|
||||
))}
|
||||
{trial.runId && (
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/backtests/${encodeURIComponent(experiment.backtestId)}/run/${encodeURIComponent(trial.runId)}`}
|
||||
>
|
||||
Open {side === 0 ? 'left' : 'right'} trial {trial.index + 1} run
|
||||
</Link>
|
||||
)}
|
||||
<p className="break-all text-xs">Trial key {trial.trialKey}</p>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWa
|
|||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentInputs } from './components/ExperimentInputs';
|
||||
import { ExperimentTrialRecovery } from './components/ExperimentTrialRecovery';
|
||||
import { metricText } from './components/trialMetricText';
|
||||
import {
|
||||
experimentApi,
|
||||
type WorkbenchExperimentDetailView as Detail,
|
||||
|
|
@ -15,12 +16,6 @@ export function ExperimentDetailPage() {
|
|||
const { experimentId = '' } = useParams<{ experimentId: string }>();
|
||||
return <ExperimentDetailView key={experimentId} experimentId={experimentId} />;
|
||||
}
|
||||
function metricText(trial: ExperimentTrial, key: keyof NonNullable<ExperimentTrial['metrics']>) {
|
||||
const value = trial.metrics?.[key];
|
||||
return value === null || value === undefined
|
||||
? `Unavailable${trial.unavailable?.[key] ? `: ${trial.unavailable[key]}` : ''}`
|
||||
: String(value);
|
||||
}
|
||||
function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
||||
const alive = useRef(false);
|
||||
const pending = useRef(false);
|
||||
|
|
|
|||
|
|
@ -19,6 +19,10 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
const [error, setError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [leftId, rightId] = selected;
|
||||
const compareUrl =
|
||||
leftId && rightId ? `/experiments/compare?${new URLSearchParams({ leftId, rightId })}` : null;
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
|
|
@ -30,6 +34,7 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
.then(value => {
|
||||
if (current) {
|
||||
setRows(value);
|
||||
setSelected(previous => previous.filter(id => value.some(item => item.id === id)));
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
|
|
@ -87,6 +92,18 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
Refresh experiments
|
||||
</Button>
|
||||
</div>
|
||||
<div className="text-sm space-y-2">
|
||||
<p>Select two experiments in order. The first supplies the reference trial.</p>
|
||||
{compareUrl && !loading && !error ? (
|
||||
<Link className="text-primary-500" to={compareUrl}>
|
||||
Compare selected experiments
|
||||
</Link>
|
||||
) : (
|
||||
<Button variant="outline" size="sm" disabled>
|
||||
Compare selected experiments
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{backtestId && (
|
||||
<p className="text-sm">
|
||||
Showing experiments for the selected backtest.{' '}
|
||||
|
|
@ -104,6 +121,26 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
{!loading && !error && rows.length === 0 && <p>No experiments yet.</p>}
|
||||
{rows.map(item => (
|
||||
<article key={item.id} className="rounded-lg border border-border p-3 space-y-2">
|
||||
<label className="flex gap-2 items-center text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`Select ${item.name} for comparison`}
|
||||
checked={selected.includes(item.id)}
|
||||
disabled={loading || (!selected.includes(item.id) && selected.length === 2)}
|
||||
onChange={() =>
|
||||
setSelected(previous =>
|
||||
previous.includes(item.id)
|
||||
? previous.filter(id => id !== item.id)
|
||||
: previous.length < 2
|
||||
? [...previous, item.id]
|
||||
: previous
|
||||
)
|
||||
}
|
||||
/>
|
||||
{selected.includes(item.id)
|
||||
? `Selected ${selected.indexOf(item.id) + 1}`
|
||||
: 'Select for comparison'}
|
||||
</label>
|
||||
<Link
|
||||
className="font-medium text-primary-500"
|
||||
to={`/experiments/${encodeURIComponent(item.id)}`}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,11 @@
|
|||
import type { ExperimentTrial } from '@stock-bot/stock-config/experiments';
|
||||
|
||||
export function metricText(
|
||||
trial: ExperimentTrial,
|
||||
key: keyof NonNullable<ExperimentTrial['metrics']>
|
||||
) {
|
||||
const value = trial.metrics?.[key];
|
||||
return value === null || value === undefined
|
||||
? `Unavailable${trial.unavailable?.[key] ? `: ${trial.unavailable[key]}` : ''}`
|
||||
: String(value);
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
export { ExperimentListPage } from './ExperimentListPage';
|
||||
export { ExperimentDetailPage } from './ExperimentDetailPage';
|
||||
export { ExperimentComparisonPage } from './ExperimentComparisonPage';
|
||||
export { ChronologicalValidationDetailPage } from './ChronologicalValidationDetailPage';
|
||||
export { WalkForwardDetailPage } from './WalkForwardDetailPage';
|
||||
|
|
|
|||
|
|
@ -0,0 +1,146 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
experimentComparisonDimensions,
|
||||
experimentComparisonInputSchema,
|
||||
type ExperimentComparison,
|
||||
type ExperimentComparisonInput,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseWorkbenchExperimentDetail,
|
||||
type WorkbenchExperimentDetailView,
|
||||
} from './experimentApi';
|
||||
|
||||
export type ExperimentComparisonView = Omit<ExperimentComparison, 'experiments'> & {
|
||||
experiments: [WorkbenchExperimentDetailView, WorkbenchExperimentDetailView];
|
||||
};
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid();
|
||||
const schema = z.object({
|
||||
version: z.literal('experiment-comparison/v1'),
|
||||
policy: z.literal('retained-input-compatibility/v1'),
|
||||
selection: z.object({ leftId: uuid, rightId: uuid, referenceTrialKey: hash }).strict(),
|
||||
reference: z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
index: z.number().int().nonnegative(),
|
||||
runId: uuid.nullable(),
|
||||
summaryAvailable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
}),
|
||||
experiments: z.tuple([z.unknown(), z.unknown()]),
|
||||
rows: z
|
||||
.array(
|
||||
z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
inputCompatibility: z.enum(['match', 'mismatch']),
|
||||
differences: z.array(z.enum(experimentComparisonDimensions)),
|
||||
summaryAvailable: z.boolean(),
|
||||
ready: z.boolean(),
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(200),
|
||||
limitations: z.array(z.string().min(1)).min(1),
|
||||
});
|
||||
const invalid = () =>
|
||||
new Error('The experiment comparison could not be verified. Refresh the same selection.');
|
||||
export function parseComparisonQuery(params: URLSearchParams): ExperimentComparisonInput {
|
||||
const allowed = ['leftId', 'rightId', 'referenceTrialKey'];
|
||||
for (const key of params.keys()) {
|
||||
if (!allowed.includes(key) || params.getAll(key).length !== 1) {
|
||||
throw new Error(
|
||||
'Comparison URL requires two different experiment IDs and at most one reference trial key. Unknown or repeated query fields are not supported.'
|
||||
);
|
||||
}
|
||||
}
|
||||
const result = experimentComparisonInputSchema.safeParse(Object.fromEntries(params));
|
||||
if (!result.success) {
|
||||
throw new Error(
|
||||
'Select two different saved experiments to compare. The URL must contain valid leftId and rightId values and, when supplied, a valid referenceTrialKey.'
|
||||
);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
export function parseExperimentComparison(
|
||||
raw: unknown,
|
||||
input: ExperimentComparisonInput
|
||||
): ExperimentComparisonView {
|
||||
const value = schema.parse(raw),
|
||||
experiments = value.experiments.map(
|
||||
parseWorkbenchExperimentDetail
|
||||
) as ExperimentComparisonView['experiments'];
|
||||
const [left, right] = experiments;
|
||||
const expectedKey = input.referenceTrialKey ?? left.trials[0]?.trialKey;
|
||||
const reference = left.trials.find(trial => trial.trialKey === expectedKey);
|
||||
if (
|
||||
!reference ||
|
||||
left.id !== input.leftId ||
|
||||
right.id !== input.rightId ||
|
||||
value.selection.leftId !== input.leftId ||
|
||||
value.selection.rightId !== input.rightId ||
|
||||
value.selection.referenceTrialKey !== expectedKey ||
|
||||
value.reference.experimentId !== left.id ||
|
||||
value.reference.trialKey !== reference.trialKey ||
|
||||
value.reference.index !== reference.index ||
|
||||
value.reference.runId !== reference.runId ||
|
||||
value.reference.summaryAvailable !== reference.comparable ||
|
||||
value.reference.diagnostic !== reference.diagnostic
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRows = experiments.flatMap(experiment =>
|
||||
experiment.trials.map(trial => ({ experimentId: experiment.id, trial }))
|
||||
);
|
||||
if (value.rows.length !== expectedRows.length) {
|
||||
throw invalid();
|
||||
}
|
||||
value.rows.forEach((row, index) => {
|
||||
const expected = expectedRows[index],
|
||||
order = row.differences.map(key => experimentComparisonDimensions.indexOf(key));
|
||||
if (
|
||||
!expected ||
|
||||
row.experimentId !== expected.experimentId ||
|
||||
row.trialKey !== expected.trial.trialKey ||
|
||||
order.some((position, i) => i > 0 && position <= (order[i - 1] ?? -1)) ||
|
||||
(row.inputCompatibility === 'match') !== (row.differences.length === 0) ||
|
||||
row.summaryAvailable !== expected.trial.comparable ||
|
||||
row.ready !==
|
||||
(row.inputCompatibility === 'match' && row.summaryAvailable && reference.comparable)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
});
|
||||
return { ...value, experiments };
|
||||
}
|
||||
export const experimentComparisonApi = {
|
||||
async get(
|
||||
input: ExperimentComparisonInput,
|
||||
signal?: AbortSignal
|
||||
): Promise<ExperimentComparisonView> {
|
||||
const normalized = experimentComparisonInputSchema.parse(input);
|
||||
const query = new URLSearchParams(normalized);
|
||||
const response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/compare?${query}`, {
|
||||
signal,
|
||||
});
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const message = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new Error(
|
||||
message.success ? message.data.error : `Comparison unavailable (${response.status})`
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (response.status !== 200) {
|
||||
throw invalid();
|
||||
}
|
||||
return parseExperimentComparison(
|
||||
z.object({ comparison: z.unknown() }).parse(body).comparison,
|
||||
normalized
|
||||
);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# Revised development roadmap
|
||||
|
||||
**First thirty-one waves committed; full R08 is validated and awaiting commit.** Walk-forward is committed as `3ed7b98`; **35 of 45 scheduled tasks are fully committed (78% by count), with R08 ready for acceptance**. Fee/slippage diagnostics now reuse the existing experiment workbench. R05/R07 remain partial; performance work stays paused.
|
||||
**First thirty-two waves committed; R07 functional comparison is validated and awaiting commit.** Full R08 is committed as `397cd0e`; **36 of 45 scheduled tasks are fully committed (80% by count)**. R05 remains partial; R07 retains only its paused table measurement after this functional component is accepted.
|
||||
|
||||
Authorization update: the owner requested “commit and continue”. Walk-forward is committed as `3ed7b98`; bounded fee/slippage sensitivity is now implemented and independently validated. No performance work, new-wave commits/pushes/PRs, candidate execution or trading/default activation is included.
|
||||
|
||||
|
|
@ -671,3 +671,15 @@ All repository gates passed: **926 integration /150 Rust** tests, plus 93 toolin
|
|||
Independent reviewer accepted exact backend/frontend eight-file overlays; root composition/browser/migration-chain fixes were independently reviewed. Source archive, 37 file hashes, native identities and logs are recorded in `manifest.json` → `thirty_second_wave_validation`, under `/tmp/stock-bot-wave32.Dg3iwI/`. The release engine was restored before database/browser validation. Both disposable fixture containers were removed after validation; development services remain untouched. New wave is uncommitted; no push, PR or trading operation occurred.
|
||||
|
||||
R08 completion covers deterministic unfitted strategies, explicit zero label horizon, frozen chronological selection, separate reset segments and bounded template cost diagnostics. Unsupported trainable/nonzero-horizon models reject; no purge/fitting framework or global OOS certification is claimed. Next non-performance slice: R07 comparisons across saved experiments with explicit policy/window/cost compatibility. Table measurements stay paused. R09 still also depends on partial R07; do not declare all downstream work ready merely because R08 is validated.
|
||||
|
||||
## Thirty-third wave handoff — 2026-10-24
|
||||
|
||||
R08 was accepted and committed as `397cd0e` at owner request. R07's functional comparison across saved experiments is now implemented and independently reviewed. Select two standalone parameter/cost experiments in click order, compare every candidate against the explicit left reference (default frozen index zero), change that reference and reopen its URL. Failed, cancelled, missing, incompatible and null-metric outcomes remain visible. Effective fee/spread/slippage and exact run links use retained inputs.
|
||||
|
||||
The existing service reads both details on one repeatable read-only snapshot. A small pure helper partitions retained data/window/capital/cost/execution/risk/clock/analytics/seed/build/model inputs, normalizing only the five pinned admission/owner identities. Strategy/version/parameter differences are allowed and shown. Compact summary availability remains separate from matching settings. No financial recalculation, ranking, statistical-validity claim, migration, persistent report or new engine path. Archived/revoked strategies remain historically readable. Review caught and fixed UUID case normalization and an exact selector-label issue before final gates.
|
||||
|
||||
All repository gates passed: **988 integration /150 Rust**, plus 93 tooling, 43 utility and 44 calculation tests, build/types/contracts/lint/secret audit. Final release **PostgreSQL/Redis: 228 tests /2013 assertions**; **Chromium: 16 workflows /500 assertions**. Strict all-authored-test types, scoped lint/format and diff/source/DAG checks pass. Four preexisting Rust cases remain ignored. Native browser proof uses five actual Rust trials and checks saved metrics, changed/archived template, approval revocation, reference changes/reload and exact-run drilldown without creating new work.
|
||||
|
||||
Independent review accepted both six-file overlays plus root contract/route/browser composition; all 17 source hashes and the archive are recorded in `manifest.json` → `thirty_third_wave_validation`, under `/tmp/stock-bot-wave33.c3IAY2/`. The unchanged release engine was restored before final database/browser gates. Both exact disposable containers were removed; development services are untouched. Wave33 remains uncommitted; no push or PR.
|
||||
|
||||
Full R07 remains partial solely because its large-table measurement is explicitly paused and unrun. After accepting/committing this functional component, R09 can consume it without waiting for performance work: record the component commit as a satisfied prerequisite rather than claiming the whole task complete. Next non-performance work is evidence/finding integration over existing R08 validation and cost outputs. R05 provider/default cutover, pending architecture approvals and candidate/AI/multiasset/paper/live activation gates remain unchanged.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**First thirty-one waves committed; full R08 is validated and awaiting commit.** Walk-forward is committed as `3ed7b98`; **35 of 45 scheduled tasks are fully committed (78% by count), with R08 ready for acceptance**. Fee/slippage diagnostics now reuse the existing experiment workbench. R05/R07 remain partial; performance work stays paused.
|
||||
**First thirty-two waves committed; R07 functional comparison is validated and awaiting commit.** Full R08 is committed as `397cd0e`; **36 of 45 scheduled tasks are fully committed (80% by count)**. R05 remains partial; R07 retains only its paused table measurement after this functional component is accepted.
|
||||
|
||||
## One source of truth
|
||||
|
||||
|
|
@ -78,8 +78,8 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / done | R03, W02, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
|
||||
| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / done | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M |
|
||||
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (component) | R06 component API pinned; release after integration, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / review (validated, awaiting commit) | R06, ADR-006 | — | Quantitative research integrity / M |
|
||||
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (functional validated, awaiting commit; measurement paused) | R06, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / done | R06, ADR-006 | — | Quantitative research integrity / M |
|
||||
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M |
|
||||
| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / done | R01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / done | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M |
|
||||
|
|
@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
|
||||
|
||||
R06 is complete and committed as `b373410`; R08's walk-forward component is committed as `3ed7b98`. Bounded cost sensitivity now completes supported R08 implementation, independently validated and awaiting acceptance/commit. Next non-performance work is R07 comparison across saved experiments. R05/R07 remain partial; R09 also depends on R07, and AI/default/trading activation retain their gates. Provider preparation is independent of experiments over retained data; performance work remains paused.
|
||||
R06 is complete (`b373410`), and full supported R08 is committed as `397cd0e`. Wave33 independently validates read-only comparison across saved standalone experiments and awaits commit. R07 functional acceptance does not require resuming its paused table measurement; R09 may consume the accepted functional component after commit. R05 remains partial, and AI/default/trading activation retain their gates.
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-24.68",
|
||||
"plan_revision": "2026-10-24.70",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "thirty_second_wave_validated_awaiting_commit",
|
||||
"plan_status": "thirty_third_wave_functional_validated_awaiting_commit",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "User: commit and continue; accepted walk-forward workflow committed 3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9",
|
||||
"tasks": ["R08"],
|
||||
"authorized_by": "User: commit and continue; accepted full R08 committed 397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963",
|
||||
"tasks": ["R07"],
|
||||
"permissions": [
|
||||
"Complete R08 bounded fee/slippage sensitivity as an existing experiment mode with immutable fixed-template inputs, Rust simulation and integrated web results/retry/reproduction"
|
||||
"Read-only comparisons across two saved standalone experiments, explicit reference trial and preserved native summaries; no rankings or financial recomputation"
|
||||
],
|
||||
"excluded": [
|
||||
"performance_profiling_or_optimization",
|
||||
|
|
@ -1402,24 +1402,29 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": ["W04"],
|
||||
"integration_state": "partial_validated_committed",
|
||||
"integration_base": "6f64ef62ba233b293ea1374c753bd0b467703792",
|
||||
"integration_state": "partial_validated_uncommitted",
|
||||
"integration_base": "397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"execution_component": "Per-trial retry controls and retained history",
|
||||
"component_exclusions": ["cross-experiment comparisons and table performance measurements"],
|
||||
"component_readiness": "Integrated against the validated R06 retry contract. Full R07 still excludes broader cross-experiment comparison and paused table rendering measurements.",
|
||||
"execution_component": "Read-only cross-experiment comparison with explicit reference and retained input compatibility",
|
||||
"component_exclusions": ["Large-table performance measurements remain paused"],
|
||||
"component_readiness": "Cross-experiment comparison is independently reviewed and all root gates pass. Functional acceptance awaits owner commit; only explicitly paused large-table measurement remains outstanding in full R07.",
|
||||
"reviewed_by": "/root/r04_review",
|
||||
"verification_reference": "ROADMAP.md#twenty-eighth-wave-handoff--2026-10-24",
|
||||
"review_notes": "Retry/history controls independently reviewed and all integrated gates passed. Broader comparison and paused table measurements remain outstanding; full task is not complete.",
|
||||
"verification_reference": "ROADMAP.md#thirty-third-wave-handoff--2026-10-24",
|
||||
"review_notes": "Final exact source snapshots accepted. Full repository, PostgreSQL/Redis, Chromium and authored types/lint/format pass. Matching retained inputs is not financial/statistical equivalence; no performance measurement claimed.",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/r12_backend",
|
||||
"worktree": "/tmp/stock-bot-wave33.c3IAY2/backend",
|
||||
"scope": "Pure compatibility helper, repeatable read-only service/API, pure/HTTP/PostgreSQL regressions"
|
||||
},
|
||||
{
|
||||
"owner": "/root/r12_frontend",
|
||||
"worktree": "/tmp/stock-bot-wave28.AqRnN8/frontend",
|
||||
"scope": "Failed-trial review/retry/history UI, frozen intent through refresh and ambiguous responses, interaction regressions"
|
||||
"worktree": "/tmp/stock-bot-wave33.c3IAY2/frontend",
|
||||
"scope": "Saved list selection, strict comparison client/page, focused UI regressions"
|
||||
},
|
||||
{
|
||||
"owner": "/root",
|
||||
"scope": "Shared DTO, migration allowlist/old fixtures, actual native browser workflow, integrated gates and planning"
|
||||
"scope": "Shared DTO/export and route, real native browser acceptance, integrated gates and planning"
|
||||
}
|
||||
],
|
||||
"partial_commit": "b373410320e987ddce1ee8dd5e8a691cf183d527"
|
||||
|
|
@ -1430,7 +1435,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "review",
|
||||
"status": "done",
|
||||
"dependencies": ["R06"],
|
||||
"decision_dependencies": ["ADR-006"],
|
||||
"task_file": "backlog/tasks/R08.md",
|
||||
|
|
@ -1442,10 +1447,10 @@
|
|||
"assignment": "/root",
|
||||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "validated_uncommitted",
|
||||
"integration_state": "validated_committed",
|
||||
"integration_base": "3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"execution_component": "Bounded immutable fee/slippage diagnostics in the existing experiment lifecycle",
|
||||
|
|
@ -1456,7 +1461,7 @@
|
|||
],
|
||||
"reviewed_by": "/root/r04_review",
|
||||
"verification_reference": "ROADMAP.md#thirty-second-wave-handoff--2026-10-24",
|
||||
"review_notes": "Full supported R08 scope independently accepted: chronological preflight, durable fixed-winner validation, repeated reset-segment walk-forward and bounded template cost sensitivity. All root repository/PostgreSQL/Chromium gates pass. Awaiting owner acceptance/commit; unsupported trained/nonzero-horizon models remain explicit refusals, not missing purge infrastructure.",
|
||||
"review_notes": "Full supported R08 scope independently accepted: chronological preflight, durable fixed-winner validation, repeated reset-segment walk-forward and bounded template cost sensitivity. All root repository/PostgreSQL/Chromium gates pass. Accepted and committed at owner request; unsupported trained/nonzero-horizon models remain explicit refusals, not missing purge infrastructure.",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/r12_backend",
|
||||
|
|
@ -1506,7 +1511,8 @@
|
|||
"when": "Saving or linking a research finding is enabled",
|
||||
"tasks": ["R03"]
|
||||
}
|
||||
]
|
||||
],
|
||||
"component_readiness": "After accepted wave33 functional commit, replace whole-R07 prerequisite with a satisfied_component_dependencies record for accepted comparison/sweep/retry UI, retaining R08 dependency. Paused table measurement is not a functional prerequisite; do not mark ready before commit."
|
||||
},
|
||||
{
|
||||
"id": "R10",
|
||||
|
|
@ -7161,8 +7167,8 @@
|
|||
"Performance and candidate/AI/multiasset/default/paper/live activation remain paused or gated."
|
||||
],
|
||||
"thirty_second_wave_validation": {
|
||||
"state": "validated_uncommitted",
|
||||
"scope": "Completes supported R08 implementation; owner acceptance/commit pending. R09 also depends on partial R07.",
|
||||
"state": "committed",
|
||||
"scope": "Completes supported R08 implementation; accepted and committed. R09 still requires R07 functional comparison.",
|
||||
"integration_base": "3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9",
|
||||
"log_directory": "/tmp/stock-bot-wave32.Dg3iwI",
|
||||
"source_archive": "/tmp/stock-bot-wave32.Dg3iwI/validated-source.tar.gz",
|
||||
|
|
@ -7258,6 +7264,100 @@
|
|||
"Performance work stays paused. R07 comparison remains partial and R09 retains its R07 dependency; candidate/AI/multiasset/default/paper/live gates unchanged."
|
||||
],
|
||||
"fixture_cleanup": "Both exact disposable PostgreSQL and Redis containers removed after all final gates. Development services untouched; isolated worktrees and local evidence retained.",
|
||||
"commits": "Wave31 committed3ed7b98. Wave32 remains uncommitted; no push or PR."
|
||||
"commits": "Committed as 397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963 following owner authorization. No push or PR.",
|
||||
"completed_commit": "397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963"
|
||||
},
|
||||
"thirty_third_wave": ["R07"],
|
||||
"thirty_third_wave_base": "397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963",
|
||||
"thirty_third_wave_notes": [
|
||||
"Compare exactly two standalone saved parameter/cost experiments against explicit left trial; default frozen index0, never a best/completed candidate.",
|
||||
"Same-client repeatable read-only snapshot; effective candidate inputs and compact saved summaries; no runtime/provider/full-result reads or writes.",
|
||||
"Only known admission and owner IDs normalize. All retained economic/data/clock/build policies compare exactly; intended strategy/parameter differences remain visible.",
|
||||
"Settings compatibility and saved summary availability remain separate; every outcome and null reason remains visible. No ranking, derived economics or significance/OOS inference.",
|
||||
"R07 functional acceptance is separate from explicitly paused table measurement. After acceptance/commit, R09 can consume that functional component without resuming performance work.",
|
||||
"Root integrates shared contract and actual native browser lifecycle; backend/frontend isolated; independent reviewer; no new-wave commit/push/PR."
|
||||
],
|
||||
"thirty_third_wave_validation": {
|
||||
"state": "partial_validated_uncommitted",
|
||||
"log_directory": "/tmp/stock-bot-wave33.c3IAY2",
|
||||
"integration_base": "397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963",
|
||||
"scope": "R07 functional comparison; table measurement explicitly not run, so full original R07 checklist remains partial.",
|
||||
"source_archive": "/tmp/stock-bot-wave33.c3IAY2/validated-source.tar.gz",
|
||||
"source_archive_sha256": "75a32fb7883ceb58d36ee71fd0b59e4c554e8e1efbc81e7b2b79cd54d08253e0",
|
||||
"source_hashes": {
|
||||
"apps/stock/config/package.json": "cfa5128f4be5185c3737c501ec316715f6f20dccda65918cd87c2161f2d2a96e",
|
||||
"apps/stock/config/src/contracts/experiment-comparison.ts": "11d23fc6a61cd8bc4e4322b8469a6d1f9e4e9ca85dcc48641ba84ccedc940691",
|
||||
"apps/stock/web-api/src/routes/experiments.routes.ts": "7b228a520aa9692e577c75514d10dc0d33d2bfefc98d1ca917e4c4ec8ad546f2",
|
||||
"apps/stock/web-api/src/services/experiment-comparison.ts": "395e3b3d86d0e1a4f8a8674094be25da7ab631dda3fb5bfbd08ecb10236d882e",
|
||||
"apps/stock/web-api/src/services/experiments.service.ts": "f12dd8657acdc8c8380a1b48a8fd887e5761b8cfad98af163ea86221e17ffaad",
|
||||
"apps/stock/web-app/src/app/App.tsx": "6dfbd8a249bb898e83d752675f8c0ddc757a6f51162a695a0f117cf870a40e30",
|
||||
"apps/stock/web-app/src/features/experiments/ExperimentComparisonPage.tsx": "3603ff57ebaf08e6d73b16cd1d92c2a64e596af956309cbe8e1280e73fc9ec3f",
|
||||
"apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx": "f9d2339cbfc5901610cd61f9064fd8e80f198a666c22dc5ee7893947df77944a",
|
||||
"apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx": "76a0d715065ff637d63d81578728ab6efc447aee49112a6ed355357ce8b2b7be",
|
||||
"apps/stock/web-app/src/features/experiments/components/trialMetricText.ts": "7418113711628e91427cce204d74b551b071e25789793591f380d0ce4f015937",
|
||||
"apps/stock/web-app/src/features/experiments/index.ts": "291a41945d0ec33852662c4c26366ad682f74d4e2e59277af021a631c24a64f5",
|
||||
"apps/stock/web-app/src/features/experiments/services/experimentComparisonApi.ts": "94d847ad138446cacdf564a56740f378b4816a312c1db8336f87c7a77d8044af",
|
||||
"test/e2e/workbench.test.ts": "71962e25e40def52b75425b00ff19856c77de6bb3ba4e2ae47f1fdd2b33cc21d",
|
||||
"test/integration/experiment-comparison-api.test.ts": "70e96ea65a42a2281f54ca85a1206518da5037b01fcdc5359d28e1846ac22761",
|
||||
"test/integration/experiment-comparison-ui.test.tsx": "6e22626b8812a9ce5e8ff41ec25aaf8825e9dd20b43653ba3d416c69d54e5b15",
|
||||
"test/integration/experiment-comparison.test.ts": "f01b412e0b045fe76238d5dc542873c74720495917cbf6faf8022d3ed79026b4",
|
||||
"test/postgres/experiment-comparison.test.ts": "dfc6e7ffda1b69acecb7bfb5be65c3d5742e7be58ce108f6284a96df1547c1ce"
|
||||
},
|
||||
"commands": [
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"log": "integration-check-final.log",
|
||||
"result": "Passed all repository gates: secret audit/build/types/contracts/lint; 93 tooling, 43 utility, 44 calculation, 988 integration and 150 Rust tests, zero failures. Four preexisting Rust cases remain ignored."
|
||||
},
|
||||
{
|
||||
"command": "bun run test:postgres",
|
||||
"log": "integration-postgres-final.log",
|
||||
"result": "228 passed, 2013 assertions, zero failures against disposable PostgreSQL and Redis DB15."
|
||||
},
|
||||
{
|
||||
"command": "bun run test:e2e",
|
||||
"log": "integration-browser-final.log",
|
||||
"result": "16 passed, 500 assertions, zero failures; same-origin production Chromium with native release engine."
|
||||
},
|
||||
{
|
||||
"command": "Strict authored-test TypeScript; explicit authored source/test ESLint; changed-source Prettier",
|
||||
"logs": [
|
||||
"root-tests-types-final.log",
|
||||
"authored-lint-final.log",
|
||||
"source-format-final.log"
|
||||
],
|
||||
"result": "Passed, including all new pure/API/UI/PostgreSQL tests and modified native browser acceptance."
|
||||
},
|
||||
{
|
||||
"command": "git diff --check; manifest references/dependency DAG; accepted overlay and source SHA256 verification",
|
||||
"result": "Passed; all55 task references exist, implementation DAG is acyclic;12 exact agent files and all17 integrated source hashes match independent review."
|
||||
}
|
||||
],
|
||||
"review": {
|
||||
"independent_reviewer": "/root/r04_review",
|
||||
"backend": "Six exact owned files reviewed; independent pure/API9 tests/95 assertions and owner native PostgreSQL4/46. Exact policy partition, unavailable default reference, historical no-write reads and genuine concurrent-update repeatable snapshot.",
|
||||
"backend_archive": "/tmp/stock-bot-wave33.c3IAY2/backend-final.tar",
|
||||
"backend_archive_sha256": "2c4c4db694a60390a5e553819baf36b95fa4d83497409bcd4cff32f663887f8f",
|
||||
"frontend": "Six exact owned files reviewed; independent UI53 tests/139 assertions. Pair/reference identity fencing, all outcomes/nulls, click order, effective costs and existing unsaved-navigation protection.",
|
||||
"frontend_archive": "/tmp/stock-bot-wave33.c3IAY2/frontend-final.tar",
|
||||
"frontend_archive_sha256": "cc79b25e3a797ea5fe94d8799a37db5d9d5b77633e503f8d37c4fb2e9164adec",
|
||||
"root": "DTO/export and App route reviewed. Actual five-native-trial browser case confirms saved summary parity, archival/revocation, reference changes/reload/exact run and no new work.",
|
||||
"corrections": "Early browser caught ambiguous reference-select label, fixed explicitly. Review caught mixed-case PostgreSQL UUID identity mismatch, fixed via shared normalized input and client decoder reuse; regressions pass. No remaining source blockers."
|
||||
},
|
||||
"engine": {
|
||||
"debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff",
|
||||
"release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103",
|
||||
"note": "Financial engine unchanged. Full check builds debug; verified unchanged release artifact restored before final database/browser gates."
|
||||
},
|
||||
"limits": [
|
||||
"Exactly two standalone parameter/cost experiments; chronological phases and walk-forward members retain their dedicated workflows.",
|
||||
"Reference defaults to left frozen candidate0 even if unavailable; explicit key must belong to left. Every candidate remains visible, with original order and null reasons.",
|
||||
"Matching retained settings and available compact scalar summaries do not establish economic equivalence, full financial reconciliation, independence, significance or OOS validity.",
|
||||
"No new financial formulas, rankings, result persistence, SQL migration, scheduler or engine path.",
|
||||
"No performance/profiling/benchmarks. Full R07 retains paused table measurement; its accepted functional component may satisfy R09 after commit.",
|
||||
"R05 provider/default cutover and candidate/AI/multiasset/paper/live gates remain unchanged."
|
||||
],
|
||||
"commits": "Wave32 committed397cd0e. Wave33 remains uncommitted; no push or PR.",
|
||||
"fixture_cleanup": "Both exact disposable PostgreSQL37f4d89... and Redisf1e69a88... containers stopped and removed after final gates. Development services untouched; worktrees and local evidence retained."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -88,3 +88,17 @@ The first experiment UI component is committed as `6f64ef6`. Add per-trial faile
|
|||
The retry/history component is independently reviewed and committed as `b373410`; full R07 remains partial. The actual Chromium workflow retries a failed canonical trial, verifies the original immutable inputs despite template edits, replays the accepted receipt after completion and reopens saved failure history and the native result. Interaction tests cover uncertain responses, stale refresh/route responses, cancellation coordination, null/history/error states and explicit discard/new intent. Exact logs and hashes: `manifest.json` → `twenty_eighth_wave_validation`.
|
||||
|
||||
Full R07 remains in progress for broader cross-experiment comparison and table measurements. All performance work stays paused. No new finance, statistics or result-ranking logic was added.
|
||||
|
||||
## Cross-experiment comparison continuation — 2026-10-24
|
||||
|
||||
Compare two standalone saved parameter/cost experiments from the existing list. The explicitly selected left trial is the reference; omitted key means its frozen index zero even if failed or unavailable. Show every original-order outcome. Match retained dataset/window/capital/effective costs/execution/risk/clock/analytics/seed/build/models, normalizing only specified admission/owner IDs; strategy implementation and parameters may intentionally differ. Separate matching settings from compact saved-summary availability. No ranking, financial recomputation or statistical-validity claim.
|
||||
|
||||
The GET API uses one repeatable read-only transaction and existing compact detail reads. Historical reads survive archival/current approval changes. Strict browser decoder verifies pair/reference/ordered row identities; route changes fence late reads, reload retains the reference, and existing editor navigation protection covers comparison links. Actual native browser acceptance plus pure/API/PostgreSQL/UI tests cover cost overrides, incomplete evidence, policy differences, strict errors and snapshot consistency.
|
||||
|
||||
Functional acceptance and the explicitly paused large-table measurement are tracked separately. Do not claim the measurement ran. Once this functional component is accepted and committed, downstream R09 can depend on it without waiting for performance work.
|
||||
|
||||
### Validated comparison handoff
|
||||
|
||||
The functional comparison component is independently accepted and awaiting commit. All 17 integrated source/test/config files match reviewed snapshots. Whole repository gates pass (988 integration /150 Rust), final PostgreSQL 228/2013 assertions and Chromium 16/500; all authored tests pass strict types/lint and changed-source formatting. Exact hashes, commands and review corrections: `manifest.json` → `thirty_third_wave_validation`. Historical compact reads share a repeatable read-only transaction; actual native browser acceptance confirms cost references, changed/archived inputs, saved metrics and exact-run reopening.
|
||||
|
||||
The large-table measurement remains explicitly paused/unrun; full R07 therefore stays partial. After functional component commit, R09 may consume the accepted sweep/comparison/retry UI through a recorded component prerequisite. No new economic formulas, ranking, statistical certification or performance work was added.
|
||||
|
|
|
|||
|
|
@ -123,7 +123,7 @@ Reuse the existing editor ordinary owner, list/detail/retry/history and receipt
|
|||
|
||||
### Validated full-task handoff — 2026-10-24
|
||||
|
||||
Full supported R08 is independently reviewed and `validated_uncommitted`, awaiting owner acceptance/commit. Waves 29–31 provide frozen chronological input preparation, durable fixed-winner selection, immutable reports and bounded nonoverlapping heldout reset-window series. Wave 32 closes bounded cost diagnostics with one existing experiment type, automatic original-cost baseline and 1–99 explicit fee/slippage pairs. Fixed parameters/data/capital/other risk/build settings and the authoritative Rust engine are preserved; existing retry/reproduction and web workbench flows are reused.
|
||||
Full supported R08 is independently reviewed and accepted, committed as `397cd0e` at owner request. Waves 29–31 provide frozen chronological input preparation, durable fixed-winner selection, immutable reports and bounded nonoverlapping heldout reset-window series. Wave 32 closes bounded cost diagnostics with one existing experiment type, automatic original-cost baseline and 1–99 explicit fee/slippage pairs. Fixed parameters/data/capital/other risk/build settings and the authoritative Rust engine are preserved; existing retry/reproduction and web workbench flows are reused.
|
||||
|
||||
Every repository gate passed (926 integration /150 Rust), final PostgreSQL/Redis 224 tests /1967 assertions and Chromium 15 workflows /457 assertions. Exact sources, independent reviews, controlled native fee/slippage/funding oracles, baseline economic parity, SQL/admission/recovery proofs and root browser evidence: `manifest.json` → `thirty_second_wave_validation`.
|
||||
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
type CostSensitivityDetail,
|
||||
type CostSensitivityPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type { ExperimentComparison } from '@stock-bot/stock-config/experiment-comparison';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
|
|
@ -54,6 +55,190 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
test('saved_experiment_comparison_preserves_cost_reference_native_summaries_and_archived_history_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
const { dataset } = canonicalSmaFixture();
|
||||
await retainResearchDataset(f.pool, dataset);
|
||||
const version = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed saved comparison fixture',
|
||||
});
|
||||
const definition = {
|
||||
name: 'Saved comparison template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: dataset.manifest.series[0]!.interval,
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
};
|
||||
const backtest = await f.request('/api/v2/backtests', 'POST', {
|
||||
...definition,
|
||||
autoStart: false,
|
||||
});
|
||||
const costInput = {
|
||||
backtestId: backtest.id,
|
||||
name: 'Older cost experiment',
|
||||
scenarios: [
|
||||
{ feeRate: '0.02', slippageRate: '0' },
|
||||
{ feeRate: '0.01', slippageRate: '0.02' },
|
||||
],
|
||||
};
|
||||
const { preview: costPreview } = (await f.request(
|
||||
'/api/v2/experiments/cost-sensitivity/preview',
|
||||
'POST',
|
||||
costInput
|
||||
)) as { preview: CostSensitivityPreview };
|
||||
const { experiment: costs } = (await f.request(
|
||||
'/api/v2/experiments/cost-sensitivity',
|
||||
'POST',
|
||||
{ ...costInput, previewHash: costPreview.previewHash },
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)) as { experiment: CostSensitivityDetail };
|
||||
const parameterInput = {
|
||||
backtestId: backtest.id,
|
||||
name: 'Newer parameter experiment',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
};
|
||||
const { preview } = (await f.request(
|
||||
'/api/v2/experiments/preview',
|
||||
'POST',
|
||||
parameterInput
|
||||
)) as { preview: ExperimentPreview };
|
||||
const { experiment: parameters } = (await f.request(
|
||||
'/api/v2/experiments',
|
||||
'POST',
|
||||
{ ...parameterInput, previewHash: preview.previewHash },
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)) as { experiment: ExperimentDetail };
|
||||
f.dispatcher.start();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*)::int AS n FROM runs WHERE status='completed'")).rows[0]
|
||||
.n === 5,
|
||||
'five native cost and parameter trials complete'
|
||||
);
|
||||
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
|
||||
...definition,
|
||||
name: 'Mutable template changed after execution',
|
||||
initialCapital: 20000,
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
});
|
||||
await f.request(`/api/v2/backtests/${backtest.id}/archive`, 'POST', { archived: true });
|
||||
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'revoke',
|
||||
reason: 'Historical reads must not require current admission approval',
|
||||
});
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [version.strategyId]);
|
||||
const durableCounts = async () =>
|
||||
(
|
||||
await f.pool.query(`SELECT
|
||||
(SELECT count(*)::int FROM runs) AS runs,
|
||||
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch,
|
||||
(SELECT count(*)::int FROM research_experiments) AS experiments,
|
||||
(SELECT sum(manual_retry_count)::int FROM runs) AS retries`)
|
||||
).rows[0];
|
||||
const before = await durableCounts();
|
||||
const query = new URLSearchParams({ leftId: costs.id, rightId: parameters.id });
|
||||
const endpoint = `/api/v2/experiments/compare?${query}`;
|
||||
const { comparison } = (await f.request(endpoint)) as { comparison: ExperimentComparison };
|
||||
expect(comparison.selection.referenceTrialKey).toBe(costs.trials[0]!.trialKey);
|
||||
expect(comparison.rows.map(row => row.differences)).toEqual([[], ['costs'], ['costs'], [], []]);
|
||||
expect(comparison.rows.map(row => row.ready)).toEqual([true, false, false, true, true]);
|
||||
for (const experiment of comparison.experiments) {
|
||||
for (const trial of experiment.trials) {
|
||||
const result = (await f.request(
|
||||
`/api/v2/runs/${trial.runId}/results`
|
||||
)) as CanonicalRunResult;
|
||||
expect(result.financialEngine).toBe('rust');
|
||||
expect(trial.metrics).toEqual(result.analytics.metrics);
|
||||
expect(trial.unavailable).toEqual(result.analytics.unavailable);
|
||||
}
|
||||
}
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/experiments`);
|
||||
// Click order, rather than the newest-first list, chooses the explicit left reference.
|
||||
await f.page.getByLabel(`Select ${costs.name} for comparison`, { exact: true }).check();
|
||||
await f.page.getByLabel(`Select ${parameters.name} for comparison`, { exact: true }).check();
|
||||
await f.page.getByRole('link', { name: 'Compare selected experiments', exact: true }).click();
|
||||
await f.page.getByRole('heading', { name: 'Compare experiments', exact: true }).waitFor();
|
||||
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
|
||||
expect(new URL(f.page.url()).searchParams.get('leftId')).toBe(costs.id);
|
||||
expect(new URL(f.page.url()).searchParams.get('rightId')).toBe(parameters.id);
|
||||
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
|
||||
costs.trials[0]!.trialKey
|
||||
);
|
||||
expect(await f.page.getByText('Matching settings', { exact: true }).count()).toBe(3);
|
||||
expect(await f.page.getByText('Settings differ', { exact: true }).count()).toBe(2);
|
||||
expect(await f.page.getByText('Saved summary available', { exact: true }).count()).toBe(5);
|
||||
for (const experiment of comparison.experiments) {
|
||||
for (const trial of experiment.trials) {
|
||||
const row = f.page.locator(
|
||||
`tr:has(a[href="/backtests/${backtest.id}/run/${trial.runId}"])`
|
||||
);
|
||||
expect(await row.count()).toBe(1);
|
||||
expect(await row.innerText()).toContain(String(trial.metrics!.totalReturn));
|
||||
}
|
||||
}
|
||||
const referenceKey = costs.trials[1]!.trialKey;
|
||||
const changedRead = f.page.waitForResponse(response => {
|
||||
const url = new URL(response.url());
|
||||
return (
|
||||
url.pathname === '/api/v2/experiments/compare' &&
|
||||
url.searchParams.get('referenceTrialKey') === referenceKey
|
||||
);
|
||||
});
|
||||
await f.page.getByLabel('Reference trial', { exact: true }).selectOption(referenceKey);
|
||||
const response = await changedRead;
|
||||
expect(response.status()).toBe(200);
|
||||
const changed = (await response.json()) as { comparison: ExperimentComparison };
|
||||
expect(changed.comparison.rows.map(row => row.differences)).toEqual([
|
||||
['costs'],
|
||||
[],
|
||||
['costs'],
|
||||
['costs'],
|
||||
['costs'],
|
||||
]);
|
||||
await until(
|
||||
async () => (await f.page.getByText('Matching settings', { exact: true }).count()) === 1,
|
||||
'explicit cost reference replaces comparison'
|
||||
);
|
||||
expect(new URL(f.page.url()).searchParams.get('referenceTrialKey')).toBe(referenceKey);
|
||||
const savedUrl = f.page.url();
|
||||
await f.page.reload();
|
||||
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
|
||||
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
|
||||
referenceKey
|
||||
);
|
||||
expect(await f.page.getByText('Settings differ', { exact: true }).count()).toBe(4);
|
||||
await f.page
|
||||
.locator(`a[href="/backtests/${backtest.id}/run/${costs.trials[1]!.runId}"]`)
|
||||
.click();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
await f.page.goto(savedUrl);
|
||||
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
|
||||
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
|
||||
referenceKey
|
||||
);
|
||||
expect(await durableCounts()).toEqual(before);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('cost_sensitivity_freezes_policy_runs_native_scenarios_and_reopens_existing_experiment_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
|
|
|
|||
128
test/integration/experiment-comparison-api.test.ts
Normal file
128
test/integration/experiment-comparison-api.test.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
|
||||
const tokens = {
|
||||
operator: 'validation-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'validation-service-fixture-not-a-real-secret-1234',
|
||||
read: 'validation-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
|
||||
function fixture(
|
||||
mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
|
||||
query: Query = async () => ({ rows: [] })
|
||||
) {
|
||||
const client = { query: mock(query) };
|
||||
const database = {
|
||||
query: mock(query),
|
||||
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work(client)),
|
||||
};
|
||||
const app = new Hono();
|
||||
if (mode !== 'absent') {
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
disabled: mode === 'disabled',
|
||||
}).mount(app);
|
||||
}
|
||||
app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer));
|
||||
return {
|
||||
database,
|
||||
request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
|
||||
return app.request('/api/v2/experiments' + path, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
||||
...(key ? { 'Idempotency-Key': key } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const leftId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
|
||||
rightId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
|
||||
query = `?leftId=${leftId}&rightId=${rightId}`;
|
||||
describe('experiment comparison HTTP boundary', () => {
|
||||
test('authorized read clients may compare without mutation credentials; unauthenticated reads are denied', async () => {
|
||||
const f = fixture();
|
||||
expect((await f.request('/compare' + query)).status).toBe(401);
|
||||
for (const role of ['read', 'operator', 'service'] as const) {
|
||||
const response = await f.request('/compare' + query, 'GET', undefined, role);
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('unknown/duplicate query keys, malformed IDs, same pair and reference keys fail before transactions', async () => {
|
||||
for (const suffix of [
|
||||
'',
|
||||
`?leftId=${leftId}`,
|
||||
query + '&unknown=1',
|
||||
query + '&leftId=' + leftId,
|
||||
query + '&%6CeftId=' + leftId,
|
||||
query + '&referenceTrialKey=x',
|
||||
`?leftId=${leftId}&rightId=${leftId}`,
|
||||
`?leftId=${leftId}&rightId=${leftId.toUpperCase()}`,
|
||||
query + '&referenceTrialKey=' + 'a'.repeat(64) + '&referenceTrialKey=' + 'a'.repeat(64),
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect((await f.request('/compare' + suffix, 'GET', undefined, 'read')).status).toBe(400);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('valid UUID casing normalizes before querying retained experiment identities', async () => {
|
||||
const identifiers: unknown[] = [];
|
||||
const f = fixture('enabled', async (sql, values) => {
|
||||
if (sql.includes('SELECT id,validation_phase')) {
|
||||
identifiers.push(values?.[0]);
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await f.request(
|
||||
`/compare?leftId=${leftId.toUpperCase()}&rightId=${rightId.toUpperCase()}`,
|
||||
'GET',
|
||||
undefined,
|
||||
'read'
|
||||
)
|
||||
).status
|
||||
).toBe(404);
|
||||
expect(identifiers).toEqual([[leftId, rightId]]);
|
||||
});
|
||||
test('snapshot mode precedes role reads; unsupported phases409 and unexpected DB errors500 are sanitized', async () => {
|
||||
const calls: string[] = [];
|
||||
const f = fixture('enabled', async sql => {
|
||||
calls.push(sql);
|
||||
if (sql.includes('SELECT id,validation_phase')) {
|
||||
return {
|
||||
rows: [
|
||||
{ id: leftId, validation_phase: 'train' },
|
||||
{ id: rightId, validation_phase: null },
|
||||
],
|
||||
};
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
expect((await f.request('/compare' + query, 'GET', undefined, 'read')).status).toBe(409);
|
||||
expect(calls[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
expect(calls).toHaveLength(2);
|
||||
for (const error of [new Error('private storage error'), new z.ZodError([])]) {
|
||||
const broken = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
const response = await broken.request('/compare' + query, 'GET', undefined, 'read');
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}
|
||||
});
|
||||
});
|
||||
994
test/integration/experiment-comparison-ui.test.tsx
Normal file
994
test/integration/experiment-comparison-ui.test.tsx
Normal file
|
|
@ -0,0 +1,994 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement, type ReactElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
costSensitivityInputSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type {
|
||||
ExperimentComparison,
|
||||
ExperimentComparisonInput,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
ExperimentTrial,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
let parseExperimentComparison: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentComparisonApi').parseExperimentComparison;
|
||||
let experimentComparisonApi: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentComparisonApi').experimentComparisonApi;
|
||||
let parseComparisonQuery: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentComparisonApi').parseComparisonQuery;
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'Event', 'ResizeObserver', '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 ExperimentListPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentListPage;
|
||||
let ExperimentComparisonPage: typeof import('../../apps/stock/web-app/src/features/experiments/ExperimentComparisonPage').ExperimentComparisonPage;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
let navigate: ReturnType<typeof router.useNavigate>;
|
||||
let location = '';
|
||||
const backtestId = '11111111-1111-4111-8111-111111111111';
|
||||
const otherBacktestId = '22222222-2222-4222-8222-222222222222';
|
||||
const experimentId = '33333333-3333-4333-8333-333333333333';
|
||||
const otherExperimentId = '44444444-4444-4444-8444-444444444444';
|
||||
const versionId = '55555555-5555-4555-8555-555555555555';
|
||||
const runId = (index: number) => `77777777-7777-4777-8777-${String(index + 1).padStart(12, '0')}`;
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (cause: Error) => void;
|
||||
const promise = new Promise<T>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
type Pending = ReturnType<typeof deferred<Response>> & {
|
||||
path: string;
|
||||
method: string;
|
||||
body: unknown;
|
||||
rawBody: unknown;
|
||||
headers: Headers;
|
||||
settled: boolean;
|
||||
signal?: AbortSignal | null;
|
||||
credentials?: RequestCredentials;
|
||||
};
|
||||
const requests: Pending[] = [];
|
||||
function request(path: string, method = 'GET') {
|
||||
const found = requests.find(
|
||||
item => item.path === path && item.method === method && !item.settled
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(
|
||||
`Missing ${method} ${path}: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}`
|
||||
);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function reply(item: Pending, value: unknown, status = 200) {
|
||||
item.settled = true;
|
||||
item.resolve(Response.json(value, { status }));
|
||||
}
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(label: string) {
|
||||
const found = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === label
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(`Missing button ${label}: ${host.textContent}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function field(label: string) {
|
||||
const found = [...host.querySelectorAll('label')]
|
||||
.find(
|
||||
item => item.firstChild?.textContent?.trim() === label || item.textContent?.trim() === label
|
||||
)
|
||||
?.querySelector('input,select,textarea');
|
||||
if (!found) {
|
||||
throw new Error(`Missing field ${label}`);
|
||||
}
|
||||
return found as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
|
||||
}
|
||||
function change(label: string, value: string) {
|
||||
const input = field(label);
|
||||
const prototype =
|
||||
input.tagName === 'SELECT'
|
||||
? browser.HTMLSelectElement.prototype
|
||||
: input.tagName === 'TEXTAREA'
|
||||
? browser.HTMLTextAreaElement.prototype
|
||||
: browser.HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
|
||||
input.dispatchEvent(
|
||||
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
|
||||
bubbles: true,
|
||||
}) as unknown as Event
|
||||
);
|
||||
}
|
||||
function Probe() {
|
||||
navigate = router.useNavigate();
|
||||
location = router.useLocation().pathname + router.useLocation().search;
|
||||
return null;
|
||||
}
|
||||
async function render(element: ReactElement, path: string) {
|
||||
root ??= createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe))
|
||||
)
|
||||
);
|
||||
}
|
||||
const template = (id = backtestId): Backtest => ({
|
||||
id,
|
||||
name: 'Saved canonical template',
|
||||
strategy: 'sma',
|
||||
strategyVersionId: versionId,
|
||||
symbols: ['X0.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-01-02',
|
||||
initialCapital: 100,
|
||||
config: { canonical: {}, datasetHash: 'a'.repeat(64) },
|
||||
archivedAt: null,
|
||||
createdAt: '2026-10-24',
|
||||
updatedAt: '2026-10-24',
|
||||
});
|
||||
function preview(count = 2, parent = backtestId): ExperimentPreview {
|
||||
const owner = `strategy:${versionId}`;
|
||||
const { config, dataset } = nativeReplayFixture(3, 1, [owner]);
|
||||
const previewId = '00000000-0000-4000-8000-000000000001';
|
||||
config.matching.risk.ledger.sessionId = previewId;
|
||||
config.matching.risk.ledger.accountId = `research:${previewId}`;
|
||||
const builtin = builtinCatalogDescriptors[0]!;
|
||||
const candidates = Array.from({ length: count }, (_, index) => ({
|
||||
index,
|
||||
trialKey: String(index + 1).padStart(64, '0'),
|
||||
parameters: { fastPeriod: index + 2, slowPeriod: 20 },
|
||||
}));
|
||||
return {
|
||||
version: 'research-experiment-preview/v1',
|
||||
previewHash: 'e'.repeat(64),
|
||||
input: {
|
||||
backtestId: parent,
|
||||
name: 'Trend study',
|
||||
grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) },
|
||||
},
|
||||
dataset: dataset.manifest,
|
||||
candidates,
|
||||
request: canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: previewId,
|
||||
backtestId: parent,
|
||||
name: 'Frozen template name',
|
||||
strategy: {
|
||||
familyId: '66666666-6666-4666-8666-666666666666',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: '88888888-8888-4888-8888-888888888888',
|
||||
package: {
|
||||
version: 1,
|
||||
program: builtin.program,
|
||||
parameterSchema: builtin.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: builtin.entryExport,
|
||||
content: 'Never execute fixture code',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: {
|
||||
format: 'bun-lock/v1',
|
||||
content: 'Retained lock',
|
||||
sha256: 'b'.repeat(64),
|
||||
},
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
|
||||
},
|
||||
selection: {
|
||||
strategyId: builtin.program.strategyId,
|
||||
strategyVersion: builtin.program.strategyVersion,
|
||||
ownerId: owner,
|
||||
seed: 17,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '100',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 20 },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'a'.repeat(64),
|
||||
engineWrapperSha256: 'b'.repeat(64),
|
||||
engineBinarySha256: 'c'.repeat(64),
|
||||
dependencyLockSha256: 'd'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: '1.2.17',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
modelArtifacts: [],
|
||||
}),
|
||||
};
|
||||
}
|
||||
function metrics(): NonNullable<ExperimentTrial['metrics']> {
|
||||
return {
|
||||
totalReturn: 0,
|
||||
cagr: null,
|
||||
maxDrawdown: 0,
|
||||
exposureTime: 0,
|
||||
volatility: null,
|
||||
downsideDeviation: null,
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
var95: null,
|
||||
cvar95: null,
|
||||
var99: null,
|
||||
alpha: null,
|
||||
beta: null,
|
||||
informationRatio: null,
|
||||
roundTripCount: null,
|
||||
winRate: null,
|
||||
profitFactor: null,
|
||||
avgWin: null,
|
||||
avgLoss: null,
|
||||
};
|
||||
}
|
||||
function detail(
|
||||
source: ExperimentPreview | CostSensitivityPreview = preview(),
|
||||
statuses: ExperimentTrial['status'][] = source.candidates.map(() => 'pending')
|
||||
): ExperimentDetail | CostSensitivityDetail {
|
||||
const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({
|
||||
...structuredClone(item),
|
||||
runId: statuses[index] === 'missing' ? null : runId(index),
|
||||
attemptNumber: 0,
|
||||
retryCount: 0,
|
||||
status: statuses[index]!,
|
||||
progress: statuses[index] === 'completed' ? 100 : 0,
|
||||
cancelRequested: false,
|
||||
error: statuses[index] === 'failed' ? 'Strategy callback failed' : null,
|
||||
comparable: statuses[index] === 'completed',
|
||||
diagnostic: statuses[index] === 'missing' ? 'Expected child run is missing' : null,
|
||||
metrics: statuses[index] === 'completed' ? metrics() : null,
|
||||
unavailable: statuses[index] === 'completed' ? { sharpeRatio: 'insufficient-periods' } : null,
|
||||
limitations: [],
|
||||
}));
|
||||
return {
|
||||
kind: source.version === 'cost-sensitivity-preview/v1' ? 'cost-sensitivity' : 'parameters',
|
||||
id: experimentId,
|
||||
name: source.input.name,
|
||||
backtestId: source.input.backtestId,
|
||||
createdAt: '2026-10-24T14:00:00Z',
|
||||
cancelRequested: false,
|
||||
trialCount: trials.length,
|
||||
counts: {
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: 0,
|
||||
failed: 0,
|
||||
cancelled: 0,
|
||||
...Object.fromEntries(
|
||||
['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [
|
||||
status,
|
||||
trials.filter(item => item.status === status).length,
|
||||
])
|
||||
),
|
||||
},
|
||||
datasetHash: source.request.datasetHash,
|
||||
strategyVersionId: versionId,
|
||||
previewHash: source.previewHash,
|
||||
preview: source,
|
||||
trials,
|
||||
} as ExperimentDetail | CostSensitivityDetail;
|
||||
}
|
||||
function costs(
|
||||
scenarios = [{ feeRate: '0.00100000', slippageRate: '0.00200000' }]
|
||||
): CostSensitivityPreview {
|
||||
const source = preview(1);
|
||||
source.input.grid = {};
|
||||
const input = costSensitivityInputSchema.parse({
|
||||
backtestId: source.input.backtestId,
|
||||
name: source.input.name,
|
||||
scenarios,
|
||||
});
|
||||
const pairs = [
|
||||
{
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
},
|
||||
...input.scenarios,
|
||||
];
|
||||
return {
|
||||
version: 'cost-sensitivity-preview/v1',
|
||||
previewHash: 'f'.repeat(64),
|
||||
input,
|
||||
source,
|
||||
request: structuredClone(source.request),
|
||||
dataset: structuredClone(source.dataset),
|
||||
candidates: pairs.map((costs, index) => ({
|
||||
index,
|
||||
trialKey: String(index + 3).padStart(64, '0'),
|
||||
parameters: { ...source.request.strategy.selection.parameters },
|
||||
costs,
|
||||
})),
|
||||
};
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
Event: browser.Event,
|
||||
ResizeObserver: browser.ResizeObserver,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ parseExperimentComparison, parseComparisonQuery, experimentComparisonApi } = await import(
|
||||
'../../apps/stock/web-app/src/features/experiments/services/experimentComparisonApi'
|
||||
));
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ ExperimentListPage } = await import('../../apps/stock/web-app/src/features/experiments'));
|
||||
({ ExperimentComparisonPage } = await import(
|
||||
'../../apps/stock/web-app/src/features/experiments/ExperimentComparisonPage'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
location = '';
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
Object.defineProperty(browser, 'fetch', {
|
||||
configurable: true,
|
||||
value: (input: unknown, init?: RequestInit) => {
|
||||
const url = new URL(String(input));
|
||||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: url.pathname + url.search,
|
||||
method: init?.method ?? 'GET',
|
||||
rawBody: init?.body,
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
headers: new Headers(init?.headers),
|
||||
signal: init?.signal,
|
||||
credentials: init?.credentials,
|
||||
settled: false,
|
||||
};
|
||||
requests.push(item);
|
||||
return item.promise; // Deliberately ignore abort: identity fences must still reject stale responses.
|
||||
},
|
||||
});
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser.happyDOM.close();
|
||||
for (const key of keys) {
|
||||
const old = originals.get(key);
|
||||
if (old) {
|
||||
Object.defineProperty(globalThis, key, old);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const thirdExperimentId = '99999999-9999-4999-8999-999999999999';
|
||||
const selection = { leftId: experimentId, rightId: otherExperimentId };
|
||||
const query = (input: ExperimentComparisonInput = selection) =>
|
||||
new URLSearchParams(input).toString();
|
||||
const comparePath = (input: ExperimentComparisonInput = selection) =>
|
||||
`/api/v2/experiments/compare?${query(input)}`;
|
||||
const compareRoute = (input: ExperimentComparisonInput = selection) =>
|
||||
`/experiments/compare?${query(input)}`;
|
||||
function comparison(
|
||||
statuses: ExperimentTrial['status'][] = ['completed', 'completed']
|
||||
): ExperimentComparison {
|
||||
const left = detail(preview(statuses.length), statuses);
|
||||
const right = detail(costs(), ['completed', 'completed']);
|
||||
right.id = otherExperimentId;
|
||||
right.name = right.preview.input.name = 'Cost study';
|
||||
if (right.preview.version === 'cost-sensitivity-preview/v1') {
|
||||
right.preview.source.input.name = 'Cost study';
|
||||
}
|
||||
right.trials.forEach((trial, index) => {
|
||||
trial.runId = runId(index + 20);
|
||||
});
|
||||
const reference = left.trials[0]!;
|
||||
return {
|
||||
version: 'experiment-comparison/v1',
|
||||
policy: 'retained-input-compatibility/v1',
|
||||
selection: { ...selection, referenceTrialKey: reference.trialKey },
|
||||
reference: {
|
||||
experimentId: left.id,
|
||||
trialKey: reference.trialKey,
|
||||
index: reference.index,
|
||||
runId: reference.runId,
|
||||
summaryAvailable: reference.comparable,
|
||||
diagnostic: reference.diagnostic,
|
||||
},
|
||||
experiments: [left, right],
|
||||
rows: [left, right].flatMap(experiment =>
|
||||
experiment.trials.map(trial => {
|
||||
const differs = experiment.id === right.id && trial.index > 0;
|
||||
return {
|
||||
experimentId: experiment.id,
|
||||
trialKey: trial.trialKey,
|
||||
inputCompatibility: differs ? 'mismatch' : 'match',
|
||||
differences: differs ? ['costs'] : [],
|
||||
summaryAvailable: trial.comparable,
|
||||
ready: !differs && trial.comparable && reference.comparable,
|
||||
};
|
||||
})
|
||||
),
|
||||
limitations: ['Retained-input comparison is not a full financial reconciliation.'],
|
||||
};
|
||||
}
|
||||
function referenceTo(value: ExperimentComparison, index: number) {
|
||||
const trial = value.experiments[0].trials[index]!;
|
||||
value.selection.referenceTrialKey = trial.trialKey;
|
||||
value.reference = {
|
||||
experimentId: value.experiments[0].id,
|
||||
trialKey: trial.trialKey,
|
||||
index,
|
||||
runId: trial.runId,
|
||||
summaryAvailable: trial.comparable,
|
||||
diagnostic: trial.diagnostic,
|
||||
};
|
||||
for (const row of value.rows) {
|
||||
row.ready = row.inputCompatibility === 'match' && row.summaryAvailable && trial.comparable;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function routes() {
|
||||
return createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/experiments',
|
||||
element: createElement(ExperimentListPage),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: '/experiments/compare',
|
||||
element: createElement(ExperimentComparisonPage),
|
||||
}),
|
||||
createElement(router.Route, { path: '*', element: createElement('p', null, 'Other page') })
|
||||
);
|
||||
}
|
||||
async function show(value?: ExperimentComparison, input: ExperimentComparisonInput = selection) {
|
||||
await render(routes(), compareRoute(input));
|
||||
if (value) {
|
||||
await flush(() => reply(request(comparePath(input)), { comparison: value }));
|
||||
}
|
||||
}
|
||||
const summary = (id: string, name: string) => ({ ...detail(), id, name });
|
||||
const saved = () => [
|
||||
summary(experimentId, 'First study'),
|
||||
summary(otherExperimentId, 'Second study'),
|
||||
summary(thirdExperimentId, 'Third study'),
|
||||
];
|
||||
async function list() {
|
||||
await render(routes(), `/experiments?backtestId=${backtestId}`);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests?limit=50&offset=0'), [template()]);
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: saved() });
|
||||
});
|
||||
}
|
||||
function checkbox(name: string) {
|
||||
const item = host.querySelector<HTMLInputElement>(
|
||||
`input[aria-label="Select ${name} for comparison"]`
|
||||
);
|
||||
if (!item) {
|
||||
throw new Error(`Missing comparison choice ${name}`);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
function link(text: string) {
|
||||
const item = [...host.querySelectorAll('a')].find(item => item.textContent?.trim() === text);
|
||||
if (!item) {
|
||||
throw new Error(`Missing link ${text}`);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
async function selectTwo() {
|
||||
await flush(() => checkbox('Second study').click());
|
||||
await flush(() => checkbox('First study').click());
|
||||
}
|
||||
|
||||
describe('saved experiment comparison selection', () => {
|
||||
test('uses click order, caps at two, and follows a real comparison link', async () => {
|
||||
await list();
|
||||
expect(button('Compare selected experiments').disabled).toBe(true);
|
||||
await selectTwo();
|
||||
expect(checkbox('Third study').disabled).toBe(true);
|
||||
const href = compareRoute({ leftId: otherExperimentId, rightId: experimentId });
|
||||
expect(link('Compare selected experiments').getAttribute('href')).toBe(href);
|
||||
await flush(() => checkbox('Second study').click());
|
||||
expect(checkbox('Third study').disabled).toBe(false);
|
||||
await flush(() => checkbox('Third study').click());
|
||||
expect(link('Compare selected experiments').getAttribute('href')).toBe(
|
||||
compareRoute({ leftId: experimentId, rightId: thirdExperimentId })
|
||||
);
|
||||
await flush(() => link('Compare selected experiments').click());
|
||||
expect(location).toBe(compareRoute({ leftId: experimentId, rightId: thirdExperimentId }));
|
||||
});
|
||||
test('reconciles disappeared selections after refresh and clears on source-filter change', async () => {
|
||||
await list();
|
||||
await selectTwo();
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), {
|
||||
experiments: saved().slice(1),
|
||||
})
|
||||
);
|
||||
expect(button('Compare selected experiments').disabled).toBe(true);
|
||||
expect(checkbox('Second study').checked).toBe(true);
|
||||
await flush(() => checkbox('Third study').click());
|
||||
await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${otherBacktestId}`), {
|
||||
experiments: saved().map(item => ({ ...item, backtestId: otherBacktestId })),
|
||||
})
|
||||
);
|
||||
expect(checkbox('Second study').checked).toBe(false);
|
||||
expect(checkbox('Third study').checked).toBe(false);
|
||||
});
|
||||
test('late list response cannot restore a previous filter or selection', async () => {
|
||||
await list();
|
||||
await selectTwo();
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
const old = request(`/api/v2/experiments?backtestId=${backtestId}`);
|
||||
await flush(() => navigate('/experiments'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/experiments'), {
|
||||
experiments: [summary(thirdExperimentId, 'Only current')],
|
||||
})
|
||||
);
|
||||
await flush(() => reply(old, { experiments: saved() }));
|
||||
expect(old.signal?.aborted).toBe(true);
|
||||
expect(host.textContent).not.toContain('First study');
|
||||
expect(button('Compare selected experiments').disabled).toBe(true);
|
||||
});
|
||||
test('comparison Link respects ordinary draft navigation refusal', async () => {
|
||||
await list();
|
||||
await selectTwo();
|
||||
await flush(() => change('Experiment name', 'Unsaved hypothesis'));
|
||||
let prompts = 0;
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
value: () => {
|
||||
prompts++;
|
||||
return false;
|
||||
},
|
||||
});
|
||||
await flush(() => link('Compare selected experiments').click());
|
||||
expect(prompts).toBe(1);
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
expect(field('Experiment name').value).toBe('Unsaved hypothesis');
|
||||
});
|
||||
test('comparison Link cannot discard an ambiguous create key without consent', async () => {
|
||||
await list();
|
||||
await selectTwo();
|
||||
const value = preview();
|
||||
await flush(() => {
|
||||
change('Experiment name', value.input.name);
|
||||
change('Parameter grid (JSON)', JSON.stringify(value.input.grid));
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => {
|
||||
first.settled = true;
|
||||
first.reject(new Error('Response lost'));
|
||||
});
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() => link('Compare selected experiments').click());
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
await flush(() => button('Retry experiment submission').click());
|
||||
const retry = request('/api/v2/experiments', 'POST');
|
||||
expect(retry.rawBody).toBe(first.rawBody);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('read-only comparison outcomes and route identity', () => {
|
||||
test('shows original ordered outcomes, effective costs, zero and null reasons, and exact run links', async () => {
|
||||
const value = comparison();
|
||||
value.experiments[0].cancelRequested = true;
|
||||
await show(value);
|
||||
const left = host.querySelector('[aria-label="Left experiment outcomes"]')!;
|
||||
const right = host.querySelector('[aria-label="Right experiment outcomes"]')!;
|
||||
expect(left.querySelectorAll(':scope > div > table > tbody > tr')).toHaveLength(2);
|
||||
expect(right.querySelectorAll(':scope > div > table > tbody > tr')).toHaveLength(2);
|
||||
expect(right.textContent).toContain('Fee: 0.00100000');
|
||||
expect(right.textContent).toContain('Slippage: 0.00200000');
|
||||
expect(right.textContent).toContain('Half-spread:');
|
||||
expect(right.textContent).toContain('Settings differ');
|
||||
expect(left.textContent).toContain('Matching settings');
|
||||
expect(left.textContent).toContain('Saved summary available');
|
||||
expect(left.textContent).toContain('insufficient-periods');
|
||||
expect(
|
||||
left.querySelectorAll(':scope > div > table > tbody > tr')[0]!.children[5]!.textContent
|
||||
).toBe('0');
|
||||
expect(link('Open left trial 1 run').getAttribute('href')).toBe(
|
||||
`/backtests/${backtestId}/run/${runId(0)}`
|
||||
);
|
||||
expect(link('Open right trial 2 run').getAttribute('href')).toBe(
|
||||
`/backtests/${backtestId}/run/${runId(21)}`
|
||||
);
|
||||
expect(host.textContent).toContain('statistical significance');
|
||||
expect(requests.every(item => item.method === 'GET')).toBe(true);
|
||||
});
|
||||
test.each(['failed', 'missing'] as const)(
|
||||
'retains %s frozen first reference instead of choosing a completed trial',
|
||||
async status => {
|
||||
const value = comparison([status, 'completed']);
|
||||
await show(value);
|
||||
expect(field('Reference trial').value).toBe(value.experiments[0].trials[0]!.trialKey);
|
||||
expect(host.querySelector('select[aria-label="Reference trial"]')).not.toBeNull();
|
||||
expect(host.textContent).toContain('Reference saved summary unavailable');
|
||||
expect(host.textContent).not.toContain(
|
||||
'Matching settings and both saved summaries available'
|
||||
);
|
||||
expect(
|
||||
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
||||
).toHaveLength(4);
|
||||
expect(host.textContent).toContain(
|
||||
status === 'missing' ? 'Expected run missing' : 'Strategy callback failed'
|
||||
);
|
||||
}
|
||||
);
|
||||
test('keeps pending/running/paused/cancelled/incomparable outcomes alongside valid summaries', async () => {
|
||||
const value = comparison(['pending', 'running', 'paused', 'cancelled', 'completed']);
|
||||
const incomparable = value.experiments[0].trials[4]!;
|
||||
incomparable.comparable = false;
|
||||
incomparable.diagnostic = 'Retained result identity does not match';
|
||||
incomparable.metrics = null;
|
||||
incomparable.unavailable = null;
|
||||
value.rows[4]!.summaryAvailable = false;
|
||||
await show(value);
|
||||
expect(
|
||||
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
||||
).toHaveLength(7);
|
||||
for (const status of ['pending', 'running', 'paused', 'cancelled']) {
|
||||
expect(host.textContent).toContain(status);
|
||||
}
|
||||
expect(host.textContent).toContain('Retained result identity does not match');
|
||||
expect(host.textContent).toContain('Saved summary available');
|
||||
});
|
||||
test('reference URL changes clear old data, ignore late reads, and reopen the exact reference', async () => {
|
||||
const initial = comparison();
|
||||
await show(initial);
|
||||
await flush(() => button('Refresh comparison').click());
|
||||
const old = request(comparePath());
|
||||
const key = initial.experiments[0].trials[1]!.trialKey;
|
||||
await flush(() => change('Reference trial', key));
|
||||
expect(
|
||||
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
||||
).toHaveLength(0);
|
||||
expect(location).toBe(compareRoute({ ...selection, referenceTrialKey: key }));
|
||||
await flush(() => reply(old, { comparison: initial }));
|
||||
expect(
|
||||
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
||||
).toHaveLength(0);
|
||||
expect(old.signal?.aborted).toBe(true);
|
||||
await flush(() =>
|
||||
reply(request(comparePath({ ...selection, referenceTrialKey: key })), {
|
||||
comparison: referenceTo(comparison(), 1),
|
||||
})
|
||||
);
|
||||
expect(field('Reference trial').value).toBe(key);
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await show(referenceTo(comparison(), 1), { ...selection, referenceTrialKey: key });
|
||||
expect(field('Reference trial').value).toBe(key);
|
||||
});
|
||||
test('pair changes clear loaded data immediately and fence old successes and failures', async () => {
|
||||
await show(comparison());
|
||||
await flush(() => button('Refresh comparison').click());
|
||||
const old = request(comparePath());
|
||||
const next = { leftId: experimentId, rightId: thirdExperimentId };
|
||||
await flush(() => navigate(compareRoute(next)));
|
||||
expect(
|
||||
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
||||
).toHaveLength(0);
|
||||
await flush(() => {
|
||||
old.settled = true;
|
||||
old.reject(new Error('Old pair read failed'));
|
||||
});
|
||||
expect(host.textContent).not.toContain('Old pair read failed');
|
||||
await flush(() => reply(request(comparePath(next)), { error: 'Next experiment missing' }, 404));
|
||||
expect(host.textContent).toContain('Next experiment missing');
|
||||
expect(host.textContent).not.toContain('Cost study');
|
||||
});
|
||||
test('same-selection refresh failure labels retained evidence and refresh retries only reads', async () => {
|
||||
await show(comparison());
|
||||
await flush(() => {
|
||||
button('Refresh comparison').click();
|
||||
button('Refresh comparison').click();
|
||||
});
|
||||
expect(requests.filter(item => item.path === comparePath())).toHaveLength(2);
|
||||
await flush(() => reply(request(comparePath()), { error: 'Database unavailable' }, 500));
|
||||
expect(host.textContent).toContain(
|
||||
'Showing the last loaded comparison for this same selection.'
|
||||
);
|
||||
expect(
|
||||
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
||||
).toHaveLength(4);
|
||||
await flush(() => button('Refresh comparison').click());
|
||||
await flush(() => reply(request(comparePath()), { comparison: comparison() }));
|
||||
expect(host.querySelector('[role="alert"]')).toBeNull();
|
||||
expect(requests.every(item => item.method === 'GET')).toBe(true);
|
||||
});
|
||||
test.each([400, 404, 409, 500])(
|
||||
'shows %i read errors without stale success, then permits explicit retry',
|
||||
async status => {
|
||||
await show();
|
||||
await flush(() =>
|
||||
reply(request(comparePath()), { error: `Read rejected ${status}` }, status)
|
||||
);
|
||||
expect(host.textContent).toContain(`Read rejected ${status}`);
|
||||
expect(
|
||||
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
||||
).toHaveLength(0);
|
||||
await flush(() => button('Refresh comparison').click());
|
||||
await flush(() => reply(request(comparePath()), { comparison: comparison() }));
|
||||
expect(
|
||||
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
||||
).toHaveLength(4);
|
||||
}
|
||||
);
|
||||
test('malformed successful envelope never displays partial comparison', async () => {
|
||||
await show();
|
||||
const bad = comparison();
|
||||
bad.rows.pop();
|
||||
await flush(() => reply(request(comparePath()), { comparison: bad }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(
|
||||
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
||||
).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('strict comparison identity decoding', () => {
|
||||
test('direct API normalizes uppercase IDs for both request and response identity', async () => {
|
||||
const leftId = 'abcdefab-abcd-4abc-8abc-abcdefabcdef';
|
||||
const rightId = 'bcdefabc-bcde-4bcd-8bcd-bcdefabcdefa';
|
||||
const value = comparison();
|
||||
value.selection.leftId = value.experiments[0].id = value.reference.experimentId = leftId;
|
||||
value.selection.rightId = value.experiments[1].id = rightId;
|
||||
for (const row of value.rows) {
|
||||
row.experimentId = row.experimentId === experimentId ? leftId : rightId;
|
||||
}
|
||||
const upper = { leftId: leftId.toUpperCase(), rightId: rightId.toUpperCase() };
|
||||
expect(parseComparisonQuery(new URLSearchParams(upper))).toEqual({ leftId, rightId });
|
||||
const pending = experimentComparisonApi.get(upper);
|
||||
reply(request(comparePath({ leftId, rightId })), { comparison: value });
|
||||
const result = await pending;
|
||||
expect(result.selection).toEqual(value.selection);
|
||||
expect(result.experiments.map(item => item.id)).toEqual([leftId, rightId]);
|
||||
expect(upper.leftId).toBe(leftId.toUpperCase());
|
||||
expect(requests).toHaveLength(1);
|
||||
});
|
||||
test('mixed-case aliases of the same UUID cannot select one experiment twice', async () => {
|
||||
const id = 'abcdefab-abcd-4abc-8abc-abcdefabcdef';
|
||||
const duplicate = { leftId: id, rightId: id.toUpperCase() };
|
||||
expect(() => parseComparisonQuery(new URLSearchParams(duplicate))).toThrow();
|
||||
await expect(experimentComparisonApi.get(duplicate)).rejects.toThrow();
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
test.each([
|
||||
'',
|
||||
`leftId=${experimentId}`,
|
||||
`leftId=${experimentId}&rightId=${experimentId}`,
|
||||
`leftId=bad&rightId=${otherExperimentId}`,
|
||||
`${query()}&referenceTrialKey=bad`,
|
||||
`${query()}&leftId=${experimentId}`,
|
||||
`${query()}&unexpected=true`,
|
||||
`${query()}&referenceTrialKey=${'a'.repeat(64)}&referenceTrialKey=${'b'.repeat(64)}`,
|
||||
])('malformed query %s rejects without a request', async search => {
|
||||
expect(() => parseComparisonQuery(new URLSearchParams(search))).toThrow();
|
||||
await render(routes(), `/experiments/compare?${search}`);
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
const mutations: [string, (value: ExperimentComparison) => void][] = [
|
||||
[
|
||||
'foreign left',
|
||||
value => {
|
||||
value.experiments[0].id = thirdExperimentId;
|
||||
},
|
||||
],
|
||||
[
|
||||
'swapped envelopes',
|
||||
value => {
|
||||
value.experiments.reverse();
|
||||
},
|
||||
],
|
||||
[
|
||||
'selection identity',
|
||||
value => {
|
||||
value.selection.rightId = thirdExperimentId;
|
||||
},
|
||||
],
|
||||
[
|
||||
'implicit reference fallback',
|
||||
value => {
|
||||
referenceTo(value, 1);
|
||||
},
|
||||
],
|
||||
[
|
||||
'reference run',
|
||||
value => {
|
||||
value.reference.runId = runId(25);
|
||||
},
|
||||
],
|
||||
[
|
||||
'reference index',
|
||||
value => {
|
||||
value.reference.index = 1;
|
||||
},
|
||||
],
|
||||
[
|
||||
'reference parent',
|
||||
value => {
|
||||
value.reference.experimentId = otherExperimentId;
|
||||
},
|
||||
],
|
||||
[
|
||||
'reference diagnostic',
|
||||
value => {
|
||||
value.reference.diagnostic = 'Made up';
|
||||
},
|
||||
],
|
||||
[
|
||||
'reference availability',
|
||||
value => {
|
||||
value.reference.summaryAvailable = false;
|
||||
},
|
||||
],
|
||||
[
|
||||
'missing row',
|
||||
value => {
|
||||
value.rows.pop();
|
||||
},
|
||||
],
|
||||
[
|
||||
'duplicate row',
|
||||
value => {
|
||||
value.rows[1] = { ...value.rows[0]! };
|
||||
},
|
||||
],
|
||||
[
|
||||
'wrong order',
|
||||
value => {
|
||||
value.rows.reverse();
|
||||
},
|
||||
],
|
||||
[
|
||||
'foreign row',
|
||||
value => {
|
||||
value.rows[0]!.experimentId = thirdExperimentId;
|
||||
},
|
||||
],
|
||||
[
|
||||
'unknown key',
|
||||
value => {
|
||||
value.rows[0]!.trialKey = 'a'.repeat(64);
|
||||
},
|
||||
],
|
||||
[
|
||||
'empty mismatch',
|
||||
value => {
|
||||
value.rows[0]!.inputCompatibility = 'mismatch';
|
||||
},
|
||||
],
|
||||
[
|
||||
'difference with match',
|
||||
value => {
|
||||
value.rows[0]!.differences = ['costs'];
|
||||
},
|
||||
],
|
||||
[
|
||||
'duplicate dimension',
|
||||
value => {
|
||||
value.rows[3]!.differences = ['costs', 'costs'];
|
||||
},
|
||||
],
|
||||
[
|
||||
'unordered dimensions',
|
||||
value => {
|
||||
value.rows[3]!.differences = ['risk', 'costs'];
|
||||
},
|
||||
],
|
||||
[
|
||||
'availability mismatch',
|
||||
value => {
|
||||
value.rows[0]!.summaryAvailable = false;
|
||||
},
|
||||
],
|
||||
[
|
||||
'false ready',
|
||||
value => {
|
||||
value.rows[0]!.ready = false;
|
||||
},
|
||||
],
|
||||
[
|
||||
'mismatched ready',
|
||||
value => {
|
||||
value.rows[3]!.ready = true;
|
||||
},
|
||||
],
|
||||
[
|
||||
'invalid child count',
|
||||
value => {
|
||||
value.experiments[0].counts.completed = 1;
|
||||
},
|
||||
],
|
||||
[
|
||||
'child parameters changed',
|
||||
value => {
|
||||
value.experiments[0].trials[0]!.parameters = {};
|
||||
},
|
||||
],
|
||||
[
|
||||
'cost trial changed',
|
||||
value => {
|
||||
const trial = value.experiments[1].trials[1]!;
|
||||
if ('costs' in trial) {
|
||||
trial.costs.feeRate = '0.50000000';
|
||||
}
|
||||
},
|
||||
],
|
||||
];
|
||||
test.each(mutations)('rejects %s', (_label, mutate) => {
|
||||
const value = comparison();
|
||||
mutate(value);
|
||||
expect(() => parseExperimentComparison(value, selection)).toThrow();
|
||||
});
|
||||
test('accepts intended strategy differences and server-owned compatibility without comparing finance in browser', () => {
|
||||
const value = comparison();
|
||||
const request = value.experiments[1].preview.request;
|
||||
request.strategy.selection.parameters = { fastPeriod: 7, slowPeriod: 20 };
|
||||
if (value.experiments[1].preview.version === 'cost-sensitivity-preview/v1') {
|
||||
value.experiments[1].preview.source.request.strategy.selection.parameters = {
|
||||
fastPeriod: 7,
|
||||
slowPeriod: 20,
|
||||
};
|
||||
for (const candidate of value.experiments[1].preview.candidates) {
|
||||
candidate.parameters.fastPeriod = 7;
|
||||
}
|
||||
value.experiments[1].preview.source.candidates[0]!.parameters.fastPeriod = 7;
|
||||
}
|
||||
for (const trial of value.experiments[1].trials) {
|
||||
trial.parameters.fastPeriod = 7;
|
||||
}
|
||||
expect(parseExperimentComparison(value, selection).rows[2]!.inputCompatibility).toBe('match');
|
||||
});
|
||||
test('explicit unknown reference is never replaced by the default', () => {
|
||||
expect(() =>
|
||||
parseExperimentComparison(comparison(), { ...selection, referenceTrialKey: 'f'.repeat(64) })
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
399
test/integration/experiment-comparison.test.ts
Normal file
399
test/integration/experiment-comparison.test.ts
Normal file
|
|
@ -0,0 +1,399 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
CostSensitivityInput,
|
||||
WorkbenchExperimentDetail,
|
||||
WorkbenchExperimentPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentComparisonDimensions,
|
||||
type ExperimentComparisonDimension,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import { builtinCatalogDescriptors, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
parseFinancialDecimal,
|
||||
type CanonicalBacktestAnalytics,
|
||||
type HistoricalDatasetV2,
|
||||
} from '@stock-bot/types';
|
||||
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
||||
import { buildCostSensitivityPreview } from '../../apps/stock/web-api/src/services/cost-sensitivity-input';
|
||||
import {
|
||||
compareExperiments,
|
||||
comparisonConditions,
|
||||
parseExperimentComparison,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-comparison';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
PREVIEW_RUN_ID,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const backtestId = '10000000-0000-4000-8000-000000000001';
|
||||
const versionId = '20000000-0000-4000-8000-000000000001';
|
||||
const owner = `strategy:${versionId}`;
|
||||
const input = (): CostSensitivityInput => ({
|
||||
backtestId,
|
||||
name: 'Cost diagnostics',
|
||||
scenarios: [
|
||||
{ feeRate: '0', slippageRate: '0' },
|
||||
{ feeRate: '0.02', slippageRate: '0.01' },
|
||||
],
|
||||
});
|
||||
function source(dataset: HistoricalDatasetV2, raw = input()) {
|
||||
const experiment = { backtestId: raw.backtestId, name: raw.name, grid: {} };
|
||||
const descriptor = builtinCatalogDescriptors[0]!;
|
||||
const policy = structuredClone(nativeReplayFixture(36, 1, [owner]).config);
|
||||
const clock = canonicalRiskSessionClock(dataset);
|
||||
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
||||
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
||||
policy.matching.risk.ledger.riskSession = clock.riskSession;
|
||||
policy.risk_boundaries = clock.riskBoundaries;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: PREVIEW_RUN_ID,
|
||||
backtestId,
|
||||
name: 'Template',
|
||||
strategy: {
|
||||
familyId: '30000000-0000-4000-8000-000000000001',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: '40000000-0000-4000-8000-000000000001',
|
||||
package: {
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'fixture',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
},
|
||||
selection: {
|
||||
strategyId: descriptor.program.strategyId,
|
||||
strategyVersion: descriptor.program.strategyVersion,
|
||||
ownerId: owner,
|
||||
seed: 42,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '40',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'a'.repeat(64),
|
||||
engineWrapperSha256: 'b'.repeat(64),
|
||||
engineBinarySha256: 'c'.repeat(64),
|
||||
dependencyLockSha256: 'd'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: 'fixture',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
modelArtifacts: [],
|
||||
});
|
||||
return buildExperimentPreview(experiment, request, dataset.manifest);
|
||||
}
|
||||
|
||||
function detail(preview: WorkbenchExperimentPreview, id = randomUUID()): WorkbenchExperimentDetail {
|
||||
const metrics: CanonicalBacktestAnalytics['metrics'] = {
|
||||
totalReturn: 0,
|
||||
cagr: null,
|
||||
maxDrawdown: null,
|
||||
exposureTime: null,
|
||||
volatility: null,
|
||||
downsideDeviation: null,
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
var95: null,
|
||||
cvar95: null,
|
||||
var99: null,
|
||||
alpha: null,
|
||||
beta: null,
|
||||
informationRatio: null,
|
||||
roundTripCount: null,
|
||||
winRate: null,
|
||||
profitFactor: null,
|
||||
avgWin: null,
|
||||
avgLoss: null,
|
||||
};
|
||||
return {
|
||||
id,
|
||||
backtestId: preview.input.backtestId,
|
||||
name: preview.input.name,
|
||||
kind: preview.version === 'cost-sensitivity-preview/v1' ? 'cost-sensitivity' : 'parameters',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
cancelRequested: false,
|
||||
trialCount: preview.candidates.length,
|
||||
counts: {
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: preview.candidates.length,
|
||||
failed: 0,
|
||||
cancelled: 0,
|
||||
},
|
||||
datasetHash: preview.request.datasetHash,
|
||||
strategyVersionId: preview.request.strategy.versionId,
|
||||
previewHash: preview.previewHash,
|
||||
preview,
|
||||
trials: preview.candidates.map(candidate => ({
|
||||
...candidate,
|
||||
runId: randomUUID(),
|
||||
attemptNumber: 1,
|
||||
retryCount: 0,
|
||||
status: 'completed' as const,
|
||||
progress: 100,
|
||||
cancelRequested: false,
|
||||
error: null,
|
||||
comparable: true,
|
||||
diagnostic: null,
|
||||
metrics,
|
||||
unavailable: { sharpeRatio: 'insufficient-periods' as const },
|
||||
limitations: ['fixture compact summary'],
|
||||
})),
|
||||
} as WorkbenchExperimentDetail;
|
||||
}
|
||||
const differences = (
|
||||
first: Record<ExperimentComparisonDimension, unknown>,
|
||||
second: Record<ExperimentComparisonDimension, unknown>
|
||||
) =>
|
||||
experimentComparisonDimensions.filter(
|
||||
key => canonicalStrategyJson(first[key]) !== canonicalStrategyJson(second[key])
|
||||
);
|
||||
describe('retained input comparison policy', () => {
|
||||
test('names/run/account/version-owner IDs and strategy/parameters may vary without mutating either input', () => {
|
||||
const data = canonicalSmaFixture().dataset,
|
||||
baseline = source(data),
|
||||
original = structuredClone(baseline),
|
||||
changed = structuredClone(baseline.request),
|
||||
version = randomUUID(),
|
||||
owner = `strategy:${version}`,
|
||||
runId = randomUUID();
|
||||
changed.name = 'Other presentation';
|
||||
changed.runId = runId;
|
||||
changed.backtestId = randomUUID();
|
||||
changed.strategy.familyId = randomUUID();
|
||||
changed.strategy.versionId = version;
|
||||
changed.strategy.reviewId = randomUUID();
|
||||
changed.strategy.package.artifact.content = 'Other trusted implementation';
|
||||
changed.strategy.package.artifact.sha256 = 'f'.repeat(64);
|
||||
changed.strategy.selection.parameters = { fastPeriod: 1, slowPeriod: 3 };
|
||||
changed.strategy.selection.ownerId = owner;
|
||||
changed.policy.matching.risk.ledger.sessionId = runId;
|
||||
changed.policy.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
changed.policy.matching.risk.ledger.ownerIds = [owner];
|
||||
changed.policy.matching.owners[0]!.ownerId = owner;
|
||||
changed.policy.cadence[0]!.owner_id = owner;
|
||||
const before = structuredClone(changed);
|
||||
expect(comparisonConditions(changed, data.manifest)).toEqual(
|
||||
comparisonConditions(baseline.request, data.manifest)
|
||||
);
|
||||
expect(changed).toEqual(before);
|
||||
expect(baseline).toEqual(original);
|
||||
});
|
||||
test('every mutable financial/execution/clock/analytics/seed/build condition lands in its explicit mismatch partition', () => {
|
||||
const data = canonicalSmaFixture().dataset,
|
||||
baseline = source(data).request,
|
||||
original = comparisonConditions(baseline, data.manifest);
|
||||
const cases: [ExperimentComparisonDimension, (r: CanonicalRunRequest) => void][] = [
|
||||
['dataset', r => (r.datasetHash = 'f'.repeat(64))],
|
||||
[
|
||||
'capital',
|
||||
r =>
|
||||
(r.policy.matching.risk.ledger.initialCapital = parseFinancialDecimal('20000.00000000')),
|
||||
],
|
||||
['capital', r => (r.strategy.selection.ownerBudget = parseFinancialDecimal('50.00000000'))],
|
||||
['costs', r => (r.policy.matching.risk.feeRate = parseFinancialDecimal('0.20000000'))],
|
||||
['costs', r => (r.policy.matching.halfSpreadRate = parseFinancialDecimal('0.10000000'))],
|
||||
['costs', r => (r.policy.matching.slippageRate = parseFinancialDecimal('0.10000000'))],
|
||||
['execution', r => (r.policy.matching.latencyMs = 1)],
|
||||
['execution', r => (r.policy.participation_rate = parseFinancialDecimal('0.50000000'))],
|
||||
[
|
||||
'execution',
|
||||
r => {
|
||||
r.strategy.selection.instrumentId = 'OTHER';
|
||||
r.policy.matching.series[0]!.instrumentId = 'OTHER';
|
||||
},
|
||||
],
|
||||
[
|
||||
'execution',
|
||||
r => {
|
||||
r.strategy.selection.seriesId = 'OTHER:1m';
|
||||
r.policy.matching.series[0]!.seriesId = 'OTHER:1m';
|
||||
r.policy.cadence[0]!.series_ids = ['OTHER:1m'];
|
||||
},
|
||||
],
|
||||
[
|
||||
'clock',
|
||||
r =>
|
||||
(r.policy.matching.risk.ledger.riskSession.sessionId =
|
||||
'economic-session-must-not-normalize'),
|
||||
],
|
||||
['clock', r => (r.policy.matching.risk.ledger.riskSession.calendarId = 'other-calendar')],
|
||||
[
|
||||
'clock',
|
||||
r => (r.policy.matching.risk.ledger.riskSession.calendarRevision = 'other-revision'),
|
||||
],
|
||||
['clock', r => (r.policy.matching.risk.ledger.riskSession.startsAt += 1)],
|
||||
[
|
||||
'clock',
|
||||
r =>
|
||||
r.policy.risk_boundaries.push({
|
||||
...r.policy.matching.risk.ledger.riskSession,
|
||||
sessionId: 'later',
|
||||
startsAt: r.policy.matching.risk.ledger.riskSession.startsAt + 1000,
|
||||
}),
|
||||
],
|
||||
['analytics', r => (r.analyticsPolicy.periodsPerYear = 365)],
|
||||
['analytics', r => (r.analyticsPolicy.annualRiskFreeRate = 0.01)],
|
||||
['seed', r => (r.strategy.selection.seed = 99)],
|
||||
];
|
||||
for (const key of [
|
||||
'maxOrderQuantity',
|
||||
'maxPositionQuantity',
|
||||
'maxSymbolExposure',
|
||||
'maxGrossExposure',
|
||||
'maxDailyLoss',
|
||||
'maxDrawdownAmount',
|
||||
] as const) {
|
||||
cases.push([
|
||||
'risk',
|
||||
r => (r.policy.matching.risk[key] = parseFinancialDecimal('20000.00000000')),
|
||||
]);
|
||||
}
|
||||
cases.push(['risk', r => (r.policy.matching.risk.maxMarkAgeMs += 1)]);
|
||||
for (const key of [
|
||||
'workerSha256',
|
||||
'engineWrapperSha256',
|
||||
'engineBinarySha256',
|
||||
'dependencyLockSha256',
|
||||
] as const) {
|
||||
cases.push(['build', r => (r.build[key] = 'f'.repeat(64))]);
|
||||
}
|
||||
for (const key of ['runtimeVersion', 'platform', 'arch'] as const) {
|
||||
cases.push(['build', r => (r.build[key] = 'changed')]);
|
||||
}
|
||||
for (const [dimension, mutate] of cases) {
|
||||
const request = structuredClone(baseline);
|
||||
mutate(request);
|
||||
expect(differences(original, comparisonConditions(request, data.manifest))).toEqual([
|
||||
dimension,
|
||||
]);
|
||||
}
|
||||
const bounds = {
|
||||
...data.manifest,
|
||||
bounds: { ...data.manifest.bounds, tradeEnd: data.manifest.bounds.tradeEnd - 1 },
|
||||
};
|
||||
expect(differences(original, comparisonConditions(baseline, bounds))).toEqual([
|
||||
'dataset',
|
||||
'window',
|
||||
]);
|
||||
const provenance = {
|
||||
...data.manifest,
|
||||
calendars: data.manifest.calendars.map(calendar => ({ ...calendar, revision: 'changed' })),
|
||||
};
|
||||
expect(differences(original, comparisonConditions(baseline, provenance))).toEqual(['dataset']);
|
||||
});
|
||||
test('unsupported currency/reserve/owner modes/models reject canonical parsing instead of silently matching', () => {
|
||||
const data = canonicalSmaFixture().dataset,
|
||||
baseline = source(data).request;
|
||||
for (const mutate of [
|
||||
(r: CanonicalRunRequest) => (r.policy.matching.risk.ledger.baseCurrency = 'EUR'),
|
||||
(r: CanonicalRunRequest) => (r.policy.matching.risk.ledger.reserveOwnerId = 'foreign'),
|
||||
(r: CanonicalRunRequest) => (r.policy.matching.owners[0]!.mode = 'Orders'),
|
||||
(r: CanonicalRunRequest) => (r.policy.allow_exploratory = true),
|
||||
(r: CanonicalRunRequest) => Object.assign(r, { modelArtifacts: [{ id: 'unsupported' }] }),
|
||||
]) {
|
||||
const request = structuredClone(baseline);
|
||||
mutate(request);
|
||||
expect(() => comparisonConditions(request, data.manifest)).toThrow();
|
||||
}
|
||||
});
|
||||
test('effective scenario costs compare across experiments, independently of summary availability and reference order', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
costs = buildCostSensitivityPreview(input(), baseline),
|
||||
left = detail(costs),
|
||||
right = detail(
|
||||
buildCostSensitivityPreview(
|
||||
{ ...input(), scenarios: [...input().scenarios].reverse() },
|
||||
baseline
|
||||
)
|
||||
);
|
||||
const before = structuredClone([left, right] as [
|
||||
WorkbenchExperimentDetail,
|
||||
WorkbenchExperimentDetail,
|
||||
]),
|
||||
selected = left.trials[1]!.trialKey;
|
||||
const compared = compareExperiments(
|
||||
{ leftId: left.id, rightId: right.id, referenceTrialKey: selected },
|
||||
[left, right]
|
||||
);
|
||||
expect(compared.rows.map(r => r.inputCompatibility)).toEqual([
|
||||
'mismatch',
|
||||
'match',
|
||||
'mismatch',
|
||||
'mismatch',
|
||||
'mismatch',
|
||||
'match',
|
||||
]);
|
||||
expect(compared.rows.map(r => r.ready)).toEqual([false, true, false, false, false, true]);
|
||||
expect(compared.experiments).toEqual(before);
|
||||
expect([left, right]).toEqual(before);
|
||||
left.trials[1]!.status = 'failed';
|
||||
left.trials[1]!.comparable = false;
|
||||
left.trials[1]!.diagnostic = 'Retained failure';
|
||||
left.trials[1]!.metrics = null;
|
||||
const failed = compareExperiments(
|
||||
{ leftId: left.id, rightId: right.id, referenceTrialKey: selected },
|
||||
[left, right]
|
||||
);
|
||||
expect(failed.reference.summaryAvailable).toBe(false);
|
||||
expect(failed.reference.diagnostic).toBe('Retained failure');
|
||||
expect(failed.rows.every(r => !r.ready)).toBe(true);
|
||||
expect(failed.rows[5]!.summaryAvailable).toBe(true);
|
||||
expect(failed.rows[5]!.inputCompatibility).toBe('match');
|
||||
});
|
||||
test('missing first candidate remains the default; zero/null metrics and completed cancellation are retained', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
left = detail(buildCostSensitivityPreview(input(), baseline)),
|
||||
right = detail(baseline);
|
||||
left.trials[0]!.runId = null;
|
||||
left.trials[0]!.status = 'missing';
|
||||
left.trials[0]!.comparable = false;
|
||||
left.trials[0]!.diagnostic = 'Expected trial run is missing';
|
||||
left.trials[0]!.metrics = null;
|
||||
right.cancelRequested = true;
|
||||
const comparison = compareExperiments({ leftId: left.id, rightId: right.id }, [left, right]);
|
||||
expect(comparison.selection.referenceTrialKey).toBe(left.trials[0]!.trialKey);
|
||||
expect(comparison.reference.runId).toBeNull();
|
||||
expect(comparison.rows.every(r => !r.ready)).toBe(true);
|
||||
expect(comparison.experiments[1].trials[0]!.metrics!.totalReturn).toBe(0);
|
||||
expect(comparison.experiments[1].trials[0]!.metrics!.sharpeRatio).toBeNull();
|
||||
expect(comparison.experiments[1].trials[0]!.unavailable!.sharpeRatio).toBe(
|
||||
'insufficient-periods'
|
||||
);
|
||||
expect(comparison.experiments[1].cancelRequested).toBe(true);
|
||||
expect(() =>
|
||||
compareExperiments(
|
||||
{ leftId: left.id, rightId: right.id, referenceTrialKey: 'f'.repeat(64) },
|
||||
[left, right]
|
||||
)
|
||||
).toThrow('does not belong');
|
||||
expect(() => parseExperimentComparison({ leftId: left.id, rightId: left.id })).toThrow(
|
||||
'distinct'
|
||||
);
|
||||
});
|
||||
});
|
||||
434
test/postgres/experiment-comparison.test.ts
Normal file
434
test/postgres/experiment-comparison.test.ts
Normal file
|
|
@ -0,0 +1,434 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
import type { PoolClient } from 'pg';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type { CostSensitivityInput } from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
import { chronologicalDataset } from '../fixtures/chronological-validation';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('chronological-validation');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
const tokens = {
|
||||
read: 'comparison-read-fixture-not-a-real-secret-1234',
|
||||
operator: 'chronological-operator-fixture-not-a-real-secret-1234',
|
||||
service: 'chronological-service-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(poolMax = 1, withCosts = true, capital = 10000) {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
// A single connection detects accidental nested pool reads while the admission lock is held.
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
max: poolMax,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
for (const name of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
'08-create-runs-table.sql',
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
...(withCosts ? ['26-cost-sensitivity.sql'] : []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const container = { postgres, logger },
|
||||
api = new BacktestServiceV2(container),
|
||||
experiments = new ExperimentsService(container),
|
||||
catalog = new StrategyCatalogService(container);
|
||||
const version = await catalog.seedBuiltin(
|
||||
'Validation SMA',
|
||||
(await (packages ??= packageBuiltinStrategies()))[0]!,
|
||||
'seed'
|
||||
);
|
||||
const data = canonicalSmaFixture(),
|
||||
dataset = data.dataset;
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const draft = await api.createBacktest(
|
||||
{
|
||||
name: 'Validation template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: ['X0.US'],
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: capital,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
const input: CostSensitivityInput = {
|
||||
backtestId: draft.id,
|
||||
name: 'Explicit cost diagnostics',
|
||||
scenarios: [
|
||||
{ feeRate: '0.001', slippageRate: '0' },
|
||||
{ feeRate: '0', slippageRate: '0.01' },
|
||||
],
|
||||
};
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
readToken: tokens.read,
|
||||
serviceToken: tokens.service,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
}).mount(app);
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') =>
|
||||
app.request('/api/v2/experiments/cost-sensitivity/preview', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` },
|
||||
body: JSON.stringify(raw),
|
||||
});
|
||||
const review = async (decision: 'approve' | 'revoke' = 'approve') => {
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision, reason: 'Disposable validation proof' },
|
||||
'operator'
|
||||
);
|
||||
return (await catalog.getVersionReviews(version.id)).at(-1)!;
|
||||
};
|
||||
const snapshot = async () => {
|
||||
const tables = (
|
||||
await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [
|
||||
schema,
|
||||
])
|
||||
).rows;
|
||||
const rows: Record<string, unknown> = {};
|
||||
for (const { tablename } of tables) {
|
||||
const quoted = '"' + String(tablename).replaceAll('"', '""') + '"';
|
||||
rows[String(tablename)] = (
|
||||
await pool.query(
|
||||
`SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t`
|
||||
)
|
||||
).rows[0].rows;
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
const validations = new ChronologicalValidationService(container);
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const execute = async (id: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('No provider reads allowed');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
|
||||
try {
|
||||
await runner.runQueued(id);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
}
|
||||
};
|
||||
return {
|
||||
cloneTemplate: async (sourceDataset = dataset) =>
|
||||
api.createBacktest(
|
||||
{
|
||||
name: 'Other validation template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: ['X0.US'],
|
||||
startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: capital,
|
||||
config: {
|
||||
datasetHash: sourceDataset.manifest.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
},
|
||||
{ autoStart: false }
|
||||
),
|
||||
app,
|
||||
validations,
|
||||
repository,
|
||||
execute,
|
||||
api,
|
||||
pool,
|
||||
postgres,
|
||||
experiments,
|
||||
catalog,
|
||||
version,
|
||||
draft,
|
||||
dataset,
|
||||
input,
|
||||
request,
|
||||
review,
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
|
||||
const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key });
|
||||
type Fixture = Awaited<ReturnType<typeof fixture>>;
|
||||
async function pair(f: Fixture) {
|
||||
await f.review();
|
||||
const costPreview = await f.experiments.previewCosts(f.input),
|
||||
left = await f.experiments.submitCosts(
|
||||
{ ...f.input, previewHash: costPreview.previewHash },
|
||||
actor()
|
||||
);
|
||||
const input = {
|
||||
backtestId: f.draft.id,
|
||||
name: 'Other parameters',
|
||||
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
||||
},
|
||||
preview = await f.experiments.preview(input),
|
||||
right = await f.experiments.submit({ ...input, previewHash: preview.previewHash }, actor());
|
||||
return { left, right, input: { leftId: left.id, rightId: right.id } };
|
||||
}
|
||||
const request = (f: Fixture, query: Record<string, string>) =>
|
||||
f.app.request('/api/v2/experiments/compare?' + new URLSearchParams(query), {
|
||||
headers: { Authorization: `Bearer ${tokens.read}` },
|
||||
});
|
||||
describe.skipIf(!url)('saved experiment comparison snapshot', () => {
|
||||
test('pool1 native pair returns all compact summaries and actual scenario costs without writes; archive and template edits do not gate historical reopen', async () => {
|
||||
const f = await fixture(),
|
||||
p = await pair(f);
|
||||
for (const trial of [...p.left.trials, ...p.right.trials]) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
const before = await f.snapshot();
|
||||
const compared = await f.experiments.compare(p.input);
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
expect(compared.experiments.map(e => e.id)).toEqual([p.left.id, p.right.id]);
|
||||
expect(compared.rows).toHaveLength(5);
|
||||
expect(compared.rows.map(r => r.inputCompatibility)).toEqual([
|
||||
'match',
|
||||
'mismatch',
|
||||
'mismatch',
|
||||
'match',
|
||||
'match',
|
||||
]);
|
||||
expect(compared.rows.map(r => r.ready)).toEqual([true, false, false, true, true]);
|
||||
expect(compared.experiments[0].trials[0]!.metrics!.totalReturn).toBeCloseTo(-0.00307, 10);
|
||||
expect(compared.experiments[0].trials[0]!.metrics!.sharpeRatio).toBeNull();
|
||||
expect(compared.experiments[0].trials[0]!.unavailable!.sharpeRatio).toBeDefined();
|
||||
expect(
|
||||
compared.experiments[0].trials.every(
|
||||
t => !('financial' in t) && !('trades' in t) && !('sessionReturns' in t)
|
||||
)
|
||||
).toBe(true);
|
||||
const selected = await f.experiments.compare({
|
||||
...p.input,
|
||||
referenceTrialKey: p.left.trials[1]!.trialKey,
|
||||
});
|
||||
expect(selected.reference.index).toBe(1);
|
||||
expect(selected.rows[1]!.ready).toBe(true);
|
||||
expect(selected.rows[3]!.differences).toEqual(['costs']);
|
||||
await f.api.updateBacktest(f.draft.id, {
|
||||
name: 'Mutable presentation',
|
||||
initialCapital: 12000,
|
||||
config: {
|
||||
datasetHash: f.dataset.manifest.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: { ...canonicalSettings, feeRate: '0.5' },
|
||||
},
|
||||
});
|
||||
await f.review('revoke');
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
const saved = await f.snapshot();
|
||||
expect(await f.experiments.compare(p.input)).toEqual(compared);
|
||||
expect(await f.snapshot()).toEqual(saved);
|
||||
const response = await request(f, p.input);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(await response.json()).toEqual({ comparison: compared });
|
||||
const upperCaseResponse = await request(f, {
|
||||
leftId: p.left.id.toUpperCase(),
|
||||
rightId: p.right.id.toUpperCase(),
|
||||
});
|
||||
expect(upperCaseResponse.status).toBe(200);
|
||||
expect(await upperCaseResponse.json()).toEqual({ comparison: compared });
|
||||
}, 60000);
|
||||
test('failed/missing/cancelled/inconsistent outcomes remain visible and never replace the unavailable default reference', async () => {
|
||||
const f = await fixture(),
|
||||
p = await pair(f);
|
||||
await f.execute(p.left.trials[1]!.runId!);
|
||||
await f.execute(p.right.trials[0]!.runId!);
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET status='failed',error='Retained fixture failure',completed_at=NOW() WHERE id=$1",
|
||||
[p.left.trials[0]!.runId]
|
||||
);
|
||||
await f.experiments.cancel(p.left.id);
|
||||
let compared = await f.experiments.compare(p.input);
|
||||
expect(compared.reference.index).toBe(0);
|
||||
expect(compared.reference.diagnostic).toBe('Retained fixture failure');
|
||||
expect(compared.rows.every(r => !r.ready)).toBe(true);
|
||||
expect(compared.experiments[0].trials.map(t => t.status)).toEqual([
|
||||
'failed',
|
||||
'completed',
|
||||
'cancelled',
|
||||
]);
|
||||
expect(compared.rows[1]!.summaryAvailable).toBe(true);
|
||||
expect(compared.experiments[0].cancelRequested).toBe(true);
|
||||
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER');
|
||||
await f.pool.query(
|
||||
'UPDATE runs SET experiment_id=NULL,trial_key=NULL,trial_index=NULL WHERE id=$1',
|
||||
[p.left.trials[0]!.runId]
|
||||
);
|
||||
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER');
|
||||
compared = await f.experiments.compare(p.input);
|
||||
expect(compared.reference.runId).toBeNull();
|
||||
expect(compared.experiments[0].trials[0]!.status).toBe('missing');
|
||||
expect(compared.rows).toHaveLength(5);
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{financial,policy,matching,slippageRate}',$2::jsonb) WHERE run_id=$1",
|
||||
[p.right.trials[0]!.runId, JSON.stringify('0.50000000')]
|
||||
);
|
||||
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
|
||||
compared = await f.experiments.compare(p.input);
|
||||
expect(compared.rows[3]!.summaryAvailable).toBe(false);
|
||||
expect(compared.rows[3]!.inputCompatibility).toBe('match');
|
||||
expect(compared.experiments[1].trials[0]!.diagnostic).toContain('inconsistent');
|
||||
await expect(
|
||||
f.experiments.compare({ ...p.input, referenceTrialKey: 'f'.repeat(64) })
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
}, 60000);
|
||||
test('read-only repeatable snapshot captures both sides before a controlled committed concurrent status change', async () => {
|
||||
const f = await fixture(4),
|
||||
p = await pair(f),
|
||||
trace: string[] = [];
|
||||
const transaction = f.postgres.transaction.bind(f.postgres);
|
||||
let changed = false,
|
||||
mode: unknown;
|
||||
Object.defineProperty(f.postgres, 'transaction', {
|
||||
value: (work: (client: PoolClient) => Promise<unknown>) =>
|
||||
transaction(async client => {
|
||||
const query = client.query.bind(client);
|
||||
const proxy = Object.create(client) as PoolClient;
|
||||
Object.defineProperty(proxy, 'query', {
|
||||
value: async (sql: string, values?: unknown[]) => {
|
||||
trace.push(sql);
|
||||
const result = await query(sql, values);
|
||||
if (sql.startsWith('SET TRANSACTION')) {
|
||||
mode = (
|
||||
await query(
|
||||
"SELECT current_setting('transaction_isolation') AS isolation,current_setting('transaction_read_only') AS readonly"
|
||||
)
|
||||
).rows[0];
|
||||
}
|
||||
if (sql.startsWith('SELECT id,validation_phase') && !changed) {
|
||||
changed = true;
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET status='failed',error='Committed after snapshot',completed_at=NOW() WHERE id=$1",
|
||||
[p.right.trials[0]!.runId]
|
||||
);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
return work(proxy);
|
||||
}),
|
||||
});
|
||||
const compared = await f.experiments.compare(p.input);
|
||||
expect(mode).toEqual({ isolation: 'repeatable read', readonly: 'on' });
|
||||
expect(changed).toBe(true);
|
||||
expect(trace[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
expect(compared.experiments[1].counts.pending).toBe(2);
|
||||
expect(compared.experiments[1].counts.failed).toBe(0);
|
||||
expect(compared.experiments[1].trials.map(t => t.status)).toEqual(['pending', 'pending']);
|
||||
expect(compared.rows.every(r => !r.summaryAvailable)).toBe(true);
|
||||
const fresh = await f.experiments.get(p.right.id);
|
||||
expect(fresh.counts.failed).toBe(1);
|
||||
expect(fresh.trials[0]!.error).toBe('Committed after snapshot');
|
||||
expect(trace.filter(sql => /^(INSERT|UPDATE|DELETE|SELECT .*FOR UPDATE)/i.test(sql))).toEqual(
|
||||
[]
|
||||
);
|
||||
expect(trace.some(sql => /SELECT .*canonical_result\s*(,|FROM)/i.test(sql))).toBe(false);
|
||||
}, 60000);
|
||||
test('standalone role, missing identity and retained corruption produce explicit409/404/sanitized500', async () => {
|
||||
const f = await fixture(),
|
||||
p = await pair(f),
|
||||
data = chronologicalDataset();
|
||||
await retainResearchDataset(f.pool, data.dataset);
|
||||
const template = await f.cloneTemplate(data.dataset);
|
||||
const input = {
|
||||
backtestId: template.id,
|
||||
name: 'Actual chronological phase',
|
||||
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
||||
recipe: data.recipe,
|
||||
},
|
||||
preview = await f.experiments.previewValidation(input),
|
||||
validation = await f.validations.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
actor()
|
||||
);
|
||||
expect((await request(f, { leftId: validation.id, rightId: p.right.id })).status).toBe(409);
|
||||
expect((await request(f, { leftId: randomUUID(), rightId: p.right.id })).status).toBe(404);
|
||||
await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER');
|
||||
await f.pool.query(
|
||||
"UPDATE research_experiments SET preview=jsonb_set(preview,'{previewHash}',to_jsonb(repeat('f',64))) WHERE id=$1",
|
||||
[p.left.id]
|
||||
);
|
||||
await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER');
|
||||
const response = await request(f, p.input);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}, 60000);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue