test(research): measure experiment tables at supported limits
This commit is contained in:
parent
0c6aec4dc6
commit
ab08db82fd
7 changed files with 1344 additions and 30 deletions
922
scripts/benchmark-experiment-tables.ts
Normal file
922
scripts/benchmark-experiment-tables.ts
Normal file
|
|
@ -0,0 +1,922 @@
|
|||
/**
|
||||
* Production UI-only benchmark; synthetic compact DTOs, no financial correctness claim.
|
||||
* bun run scripts/benchmark-experiment-tables.ts --self-test # 1-row smoke, one sample
|
||||
* bun run scripts/benchmark-experiment-tables.ts --measure --samples=5
|
||||
* Builds Vite, serves loopback fixtures, runs Chromium. JSON stdout; build diagnostics stderr.
|
||||
* Cold navigation means a fresh context/page in one browser, NOT a flushed OS/disk cache. Warm samples
|
||||
* use the same page after an excluded refresh. No latency threshold is a correctness gate.
|
||||
*/
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { availableParallelism, cpus, loadavg, release, totalmem } from 'node:os';
|
||||
import { dirname, join, relative, resolve, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { chromium, type Browser, type Page } from 'playwright';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
costSensitivityInputSchema,
|
||||
type CostSensitivityPreview,
|
||||
type WorkbenchExperimentDetail,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type { ExperimentComparison } from '@stock-bot/stock-config/experiment-comparison';
|
||||
import {
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentPreview,
|
||||
type ExperimentTrial,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import { nativeReplayFixture } from '../test/fixtures/native-replay';
|
||||
|
||||
const root = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
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')}`;
|
||||
const sha256 = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex');
|
||||
export const scope =
|
||||
'Synthetic compact DTO production-UI rendering only; no engine, database, queue, financial correctness or research-throughput claim.';
|
||||
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];
|
||||
assert(builtin);
|
||||
const candidates = Array.from({ length: count }, (_, index) => ({
|
||||
index,
|
||||
trialKey: String(index + 1).padStart(64, '0'),
|
||||
parameters: { fastPeriod: index + 2, slowPeriod: 201 },
|
||||
}));
|
||||
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: 201 },
|
||||
},
|
||||
},
|
||||
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,
|
||||
};
|
||||
}
|
||||
/** Fixed status pattern includes zero, numeric, null, failure, missing and incomparable evidence. */
|
||||
export function tableFixture(count: number, cost = false): WorkbenchExperimentDetail {
|
||||
assert(
|
||||
Number.isSafeInteger(count) && count >= 1 && count <= MAX_EXPERIMENT_TRIALS,
|
||||
'Use 1–100 rows'
|
||||
);
|
||||
assert(!cost || count >= 2, 'Cost scenarios require a baseline and a scenario');
|
||||
const source = preview(cost ? 1 : count, cost ? otherBacktestId : backtestId);
|
||||
source.input.name = `Synthetic ${cost ? 'cost' : 'parameter'} study (${count} trials)`;
|
||||
let retained: ExperimentPreview | CostSensitivityPreview = source;
|
||||
if (cost) {
|
||||
source.input.grid = {};
|
||||
const input = costSensitivityInputSchema.parse({
|
||||
backtestId: source.input.backtestId,
|
||||
name: source.input.name,
|
||||
scenarios: Array.from({ length: count - 1 }, (_, i) => ({
|
||||
feeRate: `0.${String(i + 1).padStart(8, '0')}`,
|
||||
slippageRate: '0.00010000',
|
||||
})),
|
||||
});
|
||||
const pairs = [
|
||||
{
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
},
|
||||
...input.scenarios,
|
||||
];
|
||||
retained = {
|
||||
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 + 101).padStart(64, '0'),
|
||||
parameters: { ...source.request.strategy.selection.parameters },
|
||||
costs,
|
||||
})),
|
||||
};
|
||||
}
|
||||
const pattern: ExperimentTrial['status'][] = [
|
||||
'completed',
|
||||
'completed',
|
||||
'completed',
|
||||
'failed',
|
||||
'pending',
|
||||
'running',
|
||||
'paused',
|
||||
'cancelled',
|
||||
'missing',
|
||||
];
|
||||
const trials = retained.candidates.map((candidate, index) => {
|
||||
const status = pattern[index % pattern.length];
|
||||
assert(status);
|
||||
const comparable = status === 'completed' && index % pattern.length !== 2;
|
||||
return {
|
||||
...candidate,
|
||||
runId: status === 'missing' ? null : runId(index + (cost ? 1000 : 0)),
|
||||
attemptNumber: 0,
|
||||
retryCount: 0,
|
||||
status,
|
||||
progress: status === 'completed' ? 100 : status === 'running' ? 37 : 0,
|
||||
cancelRequested: false,
|
||||
error: status === 'failed' ? `Synthetic callback failure ${index + 1}` : null,
|
||||
comparable,
|
||||
diagnostic:
|
||||
status === 'missing'
|
||||
? 'Expected child run is missing'
|
||||
: status === 'completed' && !comparable
|
||||
? 'Retained summary provenance mismatch'
|
||||
: null,
|
||||
metrics: comparable
|
||||
? {
|
||||
...metrics(),
|
||||
totalReturn: index % 9 === 0 ? 0 : index / 1000,
|
||||
maxDrawdown: index % 9 === 0 ? 0 : 0.125,
|
||||
sharpeRatio: index % 9 === 0 ? null : 1.25,
|
||||
}
|
||||
: null,
|
||||
unavailable: comparable
|
||||
? index % 9 === 0
|
||||
? { sharpeRatio: 'insufficient-periods' }
|
||||
: {}
|
||||
: null,
|
||||
limitations: [`Synthetic trial ${index + 1}; not measured trading performance`],
|
||||
};
|
||||
});
|
||||
const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const;
|
||||
return {
|
||||
kind: cost ? 'cost-sensitivity' : 'parameters',
|
||||
id: cost ? otherExperimentId : experimentId,
|
||||
name: retained.input.name,
|
||||
backtestId: retained.input.backtestId,
|
||||
createdAt: '2026-10-24T14:00:00Z',
|
||||
cancelRequested: false,
|
||||
standalone: true,
|
||||
trialCount: count,
|
||||
counts: Object.fromEntries(
|
||||
statuses.map(status => [status, trials.filter(trial => trial.status === status).length])
|
||||
) as WorkbenchExperimentDetail['counts'],
|
||||
datasetHash: retained.request.datasetHash,
|
||||
strategyVersionId: versionId,
|
||||
previewHash: retained.previewHash,
|
||||
preview: retained,
|
||||
trials,
|
||||
} as WorkbenchExperimentDetail;
|
||||
}
|
||||
|
||||
export function comparisonFixture(referenceIndex = 0): ExperimentComparison {
|
||||
const left = tableFixture(100),
|
||||
right = tableFixture(100, true),
|
||||
reference = left.trials[referenceIndex];
|
||||
assert(reference, 'Reference index must exist');
|
||||
return {
|
||||
version: 'experiment-comparison/v1',
|
||||
policy: 'retained-input-compatibility/v1',
|
||||
selection: { leftId: left.id, rightId: right.id, 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 match = experiment.id === left.id || trial.index === 0;
|
||||
return {
|
||||
experimentId: experiment.id,
|
||||
trialKey: trial.trialKey,
|
||||
inputCompatibility: match ? 'match' : 'mismatch',
|
||||
differences: match ? [] : ['costs'],
|
||||
summaryAvailable: trial.comparable,
|
||||
ready: match && trial.comparable && reference.comparable,
|
||||
};
|
||||
})
|
||||
),
|
||||
limitations: [scope],
|
||||
};
|
||||
}
|
||||
|
||||
/** Visible generation marker prevents a refresh from being timed against previous rows. */
|
||||
export function withResponseRevision(
|
||||
value: WorkbenchExperimentDetail | ExperimentComparison,
|
||||
revision: number
|
||||
): WorkbenchExperimentDetail | ExperimentComparison {
|
||||
assert(Number.isSafeInteger(revision) && revision > 0);
|
||||
const result = structuredClone(value);
|
||||
const experiments = 'experiments' in result ? result.experiments : [result];
|
||||
for (const experiment of experiments) {
|
||||
const trial = experiment.trials.at(-1);
|
||||
assert(trial);
|
||||
trial.limitations = [
|
||||
...trial.limitations.filter(text => !text.startsWith('Synthetic response revision ')),
|
||||
`Synthetic response revision ${revision}`,
|
||||
];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Fails if the compact payload acquires a full-result field; no HTTP result endpoint exists here. */
|
||||
export function assertCompact(value: unknown): void {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(assertCompact);
|
||||
} else if (value !== null && typeof value === 'object') {
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
assert(
|
||||
!['financial', 'trades', 'ohlcData', 'equity', 'fills', 'trace', 'returns'].includes(key),
|
||||
`Full result field: ${key}`
|
||||
);
|
||||
assertCompact(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
export function parseArguments(args: string[]) {
|
||||
let measure = false,
|
||||
selfTest = false,
|
||||
samples: number | undefined;
|
||||
for (const arg of args) {
|
||||
if (arg === '--measure' && !measure) {
|
||||
measure = true;
|
||||
} else if (arg === '--self-test' && !selfTest) {
|
||||
selfTest = true;
|
||||
} else if (/^--samples=[1-9]\d*$/.test(arg) && samples === undefined) {
|
||||
samples = Number(arg.slice(10));
|
||||
} else {
|
||||
throw new Error(`Unknown or repeated argument: ${arg}`);
|
||||
}
|
||||
}
|
||||
assert(!(measure && selfTest), 'Choose --measure or --self-test');
|
||||
samples ??= measure ? 5 : 1;
|
||||
assert(
|
||||
Number.isSafeInteger(samples) && samples <= 100 && (!measure || samples >= 3),
|
||||
'Measurement uses 3–100 samples; smoke uses 1–100'
|
||||
);
|
||||
return { measure, samples };
|
||||
}
|
||||
export function summarize(values: number[]) {
|
||||
assert(
|
||||
values.length && values.every(value => Number.isFinite(value) && value >= 0),
|
||||
'Missing or invalid samples'
|
||||
);
|
||||
const sorted = [...values].sort((a, b) => a - b),
|
||||
mid = Math.floor(sorted.length / 2);
|
||||
return {
|
||||
count: sorted.length,
|
||||
min: sorted[0],
|
||||
median: sorted.length % 2 ? sorted[mid] : ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2,
|
||||
max: sorted.at(-1),
|
||||
p95: sorted.length >= 20 ? sorted[Math.ceil(sorted.length * 0.95) - 1] : null,
|
||||
};
|
||||
}
|
||||
|
||||
type BrowserTiming = {
|
||||
sequence: number;
|
||||
actionStart: number;
|
||||
fetchStart: number;
|
||||
jsonResolved: number;
|
||||
readyAt: number;
|
||||
url: string;
|
||||
};
|
||||
type ProbeWindow = Window & { tableProbe: { records: BrowserTiming[]; errors: string[] } };
|
||||
/** Instrument browser-local fetch/body/readiness, not Playwright round-trip latency. */
|
||||
function installProbe({ comparison, count }: { comparison: boolean; count: number }) {
|
||||
const state = { records: [] as BrowserTiming[], errors: [] as string[] };
|
||||
(window as unknown as ProbeWindow).tableProbe = state;
|
||||
const label = comparison ? 'Refresh comparison' : 'Refresh experiment';
|
||||
let actionStart = 0;
|
||||
document.addEventListener(
|
||||
'click',
|
||||
event => {
|
||||
const target = event.target as Element | null;
|
||||
if (target?.closest('button')?.textContent?.trim() === label) {
|
||||
actionStart = performance.now();
|
||||
}
|
||||
},
|
||||
true
|
||||
);
|
||||
document.addEventListener(
|
||||
'change',
|
||||
event => {
|
||||
if ((event.target as Element | null)?.getAttribute('aria-label') === 'Reference trial') {
|
||||
actionStart = performance.now();
|
||||
}
|
||||
},
|
||||
true
|
||||
);
|
||||
const original = window.fetch.bind(window);
|
||||
const instrumentedFetch = async (...args: Parameters<Window['fetch']>) => {
|
||||
const url = String(args[0]);
|
||||
if (!url.includes('/api/v2/experiments/')) {
|
||||
return original(...args);
|
||||
}
|
||||
const sample: BrowserTiming = {
|
||||
sequence: state.records.length + 1,
|
||||
actionStart,
|
||||
fetchStart: performance.now(),
|
||||
jsonResolved: 0,
|
||||
readyAt: 0,
|
||||
url,
|
||||
};
|
||||
state.records.push(sample);
|
||||
const response = await original(...args),
|
||||
json = response.json.bind(response);
|
||||
response.json = async () => {
|
||||
const body: unknown = await json();
|
||||
sample.jsonResolved = performance.now();
|
||||
const envelope = body as {
|
||||
experiment?: WorkbenchExperimentDetail;
|
||||
comparison?: ExperimentComparison;
|
||||
};
|
||||
const experiments =
|
||||
envelope.comparison?.experiments ?? (envelope.experiment ? [envelope.experiment] : []);
|
||||
const markers = experiments.map(experiment => experiment.trials.at(-1)?.limitations.at(-1));
|
||||
const ready = () => {
|
||||
const button = [...document.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === label
|
||||
);
|
||||
const selectors = comparison
|
||||
? ['Left experiment outcomes', 'Right experiment outcomes']
|
||||
: ['Experiment trial outcomes'];
|
||||
const expectedKey = new URL(sample.url).searchParams.get('referenceTrialKey');
|
||||
return (
|
||||
!!button &&
|
||||
!button.disabled &&
|
||||
markers.length === selectors.length &&
|
||||
selectors.every((name, index) => {
|
||||
const rows = document.querySelectorAll(
|
||||
`section[aria-label="${name}"] > div > table > tbody > tr`
|
||||
);
|
||||
const marker = markers[index];
|
||||
return (
|
||||
rows.length === count &&
|
||||
!!marker &&
|
||||
marker.startsWith('Synthetic response revision ') &&
|
||||
!!rows[rows.length - 1]?.textContent?.includes(marker)
|
||||
);
|
||||
}) &&
|
||||
(!expectedKey ||
|
||||
document.querySelector<HTMLSelectElement>('select[aria-label="Reference trial"]')
|
||||
?.value === expectedKey) &&
|
||||
!document.querySelector('[role="alert"]')
|
||||
);
|
||||
};
|
||||
const check = () => {
|
||||
if (performance.now() - sample.jsonResolved > 30000) {
|
||||
state.errors.push(`UI readiness timed out: ${document.body.innerText.slice(-3000)}`);
|
||||
} else if (ready()) {
|
||||
requestAnimationFrame(() => {
|
||||
if (ready()) {
|
||||
sample.readyAt = performance.now();
|
||||
} else {
|
||||
requestAnimationFrame(check);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
requestAnimationFrame(check);
|
||||
}
|
||||
};
|
||||
requestAnimationFrame(check);
|
||||
return body;
|
||||
};
|
||||
return response;
|
||||
};
|
||||
Object.defineProperty(window, 'fetch', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: instrumentedFetch,
|
||||
});
|
||||
}
|
||||
|
||||
const metricLabel = (
|
||||
trial: ExperimentTrial,
|
||||
key: 'totalReturn' | 'maxDrawdown' | 'sharpeRatio'
|
||||
) => {
|
||||
const value = trial.metrics?.[key];
|
||||
return value === null || value === undefined
|
||||
? `Unavailable${trial.unavailable?.[key] ? `: ${trial.unavailable[key]}` : ''}`
|
||||
: String(value);
|
||||
};
|
||||
type RowSnapshot = {
|
||||
cells: (string | undefined)[];
|
||||
parameters: string | null | undefined;
|
||||
links: { text: string | null; href: string | null }[];
|
||||
};
|
||||
/** Every row checked after timing capture, including offscreen rows. No row sampling. */
|
||||
async function verifyPage(page: Page, value: WorkbenchExperimentDetail | ExperimentComparison) {
|
||||
const comparison = 'experiments' in value;
|
||||
const experiments = comparison ? value.experiments : [value];
|
||||
const snapshot = await page.evaluate(() => ({
|
||||
body: document.body.innerText,
|
||||
sections: [...document.querySelectorAll('section[aria-label$="outcomes"]')].map(section => ({
|
||||
label: section.getAttribute('aria-label'),
|
||||
text: section.textContent,
|
||||
rows: [...section.querySelectorAll(':scope > div > table > tbody > tr')].map(row => ({
|
||||
cells: [...row.querySelectorAll('td')].map(cell => cell.textContent?.trim()),
|
||||
parameters: row.querySelector('pre')?.textContent,
|
||||
links: [...row.querySelectorAll('a')].map(link => ({
|
||||
text: link.textContent,
|
||||
href: link.getAttribute('href'),
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
}));
|
||||
assert.equal(snapshot.sections.length, experiments.length);
|
||||
for (const [side, experiment] of experiments.entries()) {
|
||||
const section = snapshot.sections[side];
|
||||
assert(section);
|
||||
assert.equal(section.rows.length, experiment.trialCount);
|
||||
const counts = `${experiment.trialCount} trials · ${Object.entries(experiment.counts)
|
||||
.map(([status, count]) => `${status}: ${count}`)
|
||||
.join(
|
||||
' · '
|
||||
)} · missing: ${experiment.trials.filter(trial => trial.status === 'missing').length}`;
|
||||
assert(
|
||||
(comparison ? section.text : snapshot.body)?.includes(counts),
|
||||
`Missing count summary: ${counts}`
|
||||
);
|
||||
for (const [index, trial] of experiment.trials.entries()) {
|
||||
const row: RowSnapshot | undefined = section.rows[index];
|
||||
assert(row);
|
||||
assert.deepEqual(JSON.parse(row.parameters ?? ''), trial.parameters);
|
||||
assert(row.cells[1]?.startsWith(trial.status));
|
||||
const offset = comparison ? 5 : 3;
|
||||
for (const [i, key] of (['totalReturn', 'maxDrawdown', 'sharpeRatio'] as const).entries()) {
|
||||
assert.equal(row.cells[offset + i], metricLabel(trial, key));
|
||||
}
|
||||
for (const text of [trial.error, trial.diagnostic, ...trial.limitations].filter(Boolean)) {
|
||||
assert(row.cells.at(-1)?.includes(String(text)));
|
||||
}
|
||||
const link = row.links.filter(item => item.text?.startsWith('Open '));
|
||||
assert.deepEqual(
|
||||
link,
|
||||
trial.runId
|
||||
? [
|
||||
{
|
||||
text: `Open ${comparison ? `${side === 0 ? 'left' : 'right'} ` : ''}trial ${index + 1} run`,
|
||||
href: `/backtests/${experiment.backtestId}/run/${trial.runId}`,
|
||||
},
|
||||
]
|
||||
: []
|
||||
);
|
||||
if (comparison) {
|
||||
const expected = value.rows[side * experiment.trialCount + index];
|
||||
assert(expected);
|
||||
assert(
|
||||
row.cells[3]?.startsWith(
|
||||
expected.inputCompatibility === 'match' ? 'Matching settings' : 'Settings differ'
|
||||
)
|
||||
);
|
||||
assert(
|
||||
row.cells[4]?.includes(
|
||||
expected.ready
|
||||
? 'Matching settings and both saved summaries available'
|
||||
: 'Comparison evidence not ready'
|
||||
)
|
||||
);
|
||||
assert.equal(row.cells[4]?.startsWith('Saved summary available'), trial.comparable);
|
||||
const costs = (
|
||||
trial as ExperimentTrial & { costs?: { feeRate: string; slippageRate: string } }
|
||||
).costs ?? {
|
||||
feeRate: experiment.preview.request.policy.matching.risk.feeRate,
|
||||
slippageRate: experiment.preview.request.policy.matching.slippageRate,
|
||||
};
|
||||
assert.equal(
|
||||
row.cells[2],
|
||||
`Fee: ${costs.feeRate}Half-spread: ${experiment.preview.request.policy.matching.halfSpreadRate}Slippage: ${costs.slippageRate}`
|
||||
);
|
||||
} else {
|
||||
assert.equal(
|
||||
row.cells[2],
|
||||
trial.comparable
|
||||
? 'Comparable'
|
||||
: trial.status === 'completed'
|
||||
? 'Incomparable'
|
||||
: 'Not evaluated'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function collectTiming(page: Page, sequence: number) {
|
||||
await page.waitForFunction(
|
||||
expected => {
|
||||
const state = (window as unknown as ProbeWindow).tableProbe;
|
||||
if (state.errors.length) {
|
||||
throw new Error(state.errors.join('\n'));
|
||||
}
|
||||
return !!state.records[expected - 1]?.readyAt;
|
||||
},
|
||||
sequence,
|
||||
{ timeout: 35000 }
|
||||
);
|
||||
const raw = await page.evaluate(
|
||||
expected => (window as unknown as ProbeWindow).tableProbe.records[expected - 1],
|
||||
sequence
|
||||
);
|
||||
assert(raw);
|
||||
return {
|
||||
raw,
|
||||
durationsMs: {
|
||||
actionToReady: raw.readyAt - raw.actionStart,
|
||||
fetchAndJson: raw.jsonResolved - raw.fetchStart,
|
||||
jsonToTwoFrameReady: raw.readyAt - raw.jsonResolved,
|
||||
},
|
||||
};
|
||||
}
|
||||
function fileIdentities(directory: string): { path: string; bytes: number; sha256: string }[] {
|
||||
return readdirSync(directory, { withFileTypes: true })
|
||||
.flatMap(entry => {
|
||||
const path = join(directory, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
return fileIdentities(path);
|
||||
}
|
||||
const bytes = readFileSync(path);
|
||||
return [{ path: relative(root, path), bytes: bytes.length, sha256: sha256(bytes) }];
|
||||
})
|
||||
.sort((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
async function command(args: string[]) {
|
||||
const proc = Bun.spawn(args, {
|
||||
cwd: root,
|
||||
env: { ...process.env, NODE_ENV: 'production', VITE_API_BASE_URL: '' },
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
});
|
||||
const [out, err, exit] = await Promise.all([
|
||||
new Response(proc.stdout).text(),
|
||||
new Response(proc.stderr).text(),
|
||||
proc.exited,
|
||||
]);
|
||||
assert.equal(exit, 0, `${args.join(' ')}\n${out}\n${err}`);
|
||||
return { out, err };
|
||||
}
|
||||
|
||||
type RequestRecord = { method: string; path: string; bytes: number; sha256: string };
|
||||
type TimingResult = Awaited<ReturnType<typeof collectTiming>>;
|
||||
type ReferenceTiming = TimingResult & {
|
||||
referenceIndex: number;
|
||||
referenceSummaryAvailable: boolean;
|
||||
};
|
||||
type Sample = {
|
||||
workload: string;
|
||||
repeat: number;
|
||||
fixture: { bytes: number; sha256: string };
|
||||
cold: TimingResult;
|
||||
warmupExcluded: TimingResult;
|
||||
refresh: TimingResult;
|
||||
referenceChanges: ReferenceTiming[];
|
||||
apiRequests: RequestRecord[];
|
||||
};
|
||||
export async function main(args: string[]) {
|
||||
const options = parseArguments(args),
|
||||
startedAt = new Date().toISOString(),
|
||||
initialLoad = loadavg();
|
||||
const buildStart = performance.now(),
|
||||
build = await command([process.execPath, 'run', '--cwd', 'apps/stock/web-app', 'build']);
|
||||
process.stderr.write(build.out + build.err);
|
||||
const buildMs = performance.now() - buildStart,
|
||||
dist = join(root, 'apps/stock/web-app/dist');
|
||||
let active: WorkbenchExperimentDetail | ExperimentComparison = tableFixture(1),
|
||||
responseRevision = 0;
|
||||
const requests: RequestRecord[] = [],
|
||||
unexpected: string[] = [],
|
||||
blockedFonts = new Set<string>();
|
||||
const server = Bun.serve({
|
||||
hostname: '127.0.0.1',
|
||||
port: 0,
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url);
|
||||
if (url.pathname.startsWith('/api/')) {
|
||||
let body: unknown;
|
||||
if (request.method === 'GET' && url.pathname === '/api/auth/session') {
|
||||
body = { authenticated: true, role: 'admin' };
|
||||
} else if (
|
||||
request.method === 'GET' &&
|
||||
url.pathname === '/api/v2/experiments/compare' &&
|
||||
'experiments' in active
|
||||
) {
|
||||
assert.equal(url.searchParams.get('leftId'), experimentId);
|
||||
assert.equal(url.searchParams.get('rightId'), otherExperimentId);
|
||||
const key = url.searchParams.get('referenceTrialKey'),
|
||||
index = key
|
||||
? active.experiments[0].trials.findIndex(trial => trial.trialKey === key)
|
||||
: 0;
|
||||
active = comparisonFixture(index);
|
||||
body = { comparison: active };
|
||||
} else if (
|
||||
request.method === 'GET' &&
|
||||
!('experiments' in active) &&
|
||||
url.pathname === `/api/v2/experiments/${active.id}` &&
|
||||
!url.search
|
||||
) {
|
||||
body = { experiment: active };
|
||||
} else {
|
||||
unexpected.push(`${request.method} ${url.pathname}${url.search}`);
|
||||
return new Response('Unexpected API request', { status: 403 });
|
||||
}
|
||||
if (url.pathname.startsWith('/api/v2/experiments/')) {
|
||||
active = withResponseRevision(active, ++responseRevision);
|
||||
body = 'experiments' in active ? { comparison: active } : { experiment: active };
|
||||
}
|
||||
assertCompact(body);
|
||||
const serialized = JSON.stringify(body);
|
||||
requests.push({
|
||||
method: request.method,
|
||||
path: url.pathname + url.search,
|
||||
bytes: Buffer.byteLength(serialized),
|
||||
sha256: sha256(serialized),
|
||||
});
|
||||
return new Response(serialized, {
|
||||
headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
|
||||
});
|
||||
}
|
||||
const path = resolve(dist, `.${decodeURIComponent(url.pathname)}`);
|
||||
if (request.method !== 'GET' || !path.startsWith(dist + sep)) {
|
||||
return new Response('Not found', { status: 404 });
|
||||
}
|
||||
const file = Bun.file(path);
|
||||
return new Response((await file.exists()) ? file : Bun.file(join(dist, 'index.html')));
|
||||
},
|
||||
});
|
||||
const origin = `http://127.0.0.1:${server.port}`;
|
||||
const samples: Sample[] = [];
|
||||
let browser: Browser | undefined,
|
||||
browserVersion = '',
|
||||
browserLaunchMs = 0;
|
||||
try {
|
||||
const launchStart = performance.now();
|
||||
// Bun 1.2.17/Playwright loses its control pipe after repeated launches: use the existing E2E lifecycle.
|
||||
browser = await chromium.launch({ headless: true });
|
||||
browserLaunchMs = performance.now() - launchStart;
|
||||
browserVersion = browser.version();
|
||||
for (const workload of options.measure
|
||||
? ([1, 25, 100, 'comparison'] as const)
|
||||
: ([1] as const)) {
|
||||
const comparison = workload === 'comparison',
|
||||
count = comparison ? 100 : workload;
|
||||
for (let repeat = 0; repeat < options.samples; repeat++) {
|
||||
active = comparison ? comparisonFixture() : tableFixture(count);
|
||||
const payload = JSON.stringify(active),
|
||||
requestStart = requests.length;
|
||||
responseRevision = 0;
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1440, height: 1080 },
|
||||
deviceScaleFactor: 1,
|
||||
serviceWorkers: 'block',
|
||||
});
|
||||
try {
|
||||
await context.route('**/*', route => {
|
||||
if (new URL(route.request().url()).origin !== origin) {
|
||||
if (new URL(route.request().url()).hostname === 'fonts.googleapis.com') {
|
||||
blockedFonts.add(route.request().url());
|
||||
} else {
|
||||
unexpected.push(route.request().url());
|
||||
}
|
||||
return route.abort();
|
||||
}
|
||||
return route.continue();
|
||||
});
|
||||
const page = await context.newPage(),
|
||||
errors: string[] = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(installProbe, { comparison, count });
|
||||
const path = comparison
|
||||
? `/experiments/compare?leftId=${experimentId}&rightId=${otherExperimentId}`
|
||||
: `/experiments/${experimentId}`;
|
||||
await page.goto(origin + path);
|
||||
const cold = await collectTiming(page, 1);
|
||||
await verifyPage(page, active);
|
||||
const button = page.getByRole('button', {
|
||||
name: comparison ? 'Refresh comparison' : 'Refresh experiment',
|
||||
exact: true,
|
||||
});
|
||||
await button.click();
|
||||
const warmup = await collectTiming(page, 2);
|
||||
await verifyPage(page, active);
|
||||
await button.click();
|
||||
const refresh = await collectTiming(page, 3);
|
||||
await verifyPage(page, active);
|
||||
const referenceChanges: ReferenceTiming[] = [];
|
||||
if (comparison) {
|
||||
for (const [i, referenceIndex] of [3, 1].entries()) {
|
||||
const reference = comparisonFixture(referenceIndex).reference;
|
||||
await page
|
||||
.getByLabel('Reference trial', { exact: true })
|
||||
.selectOption(reference.trialKey);
|
||||
const timing = await collectTiming(page, 4 + i);
|
||||
await verifyPage(page, active);
|
||||
referenceChanges.push({
|
||||
referenceIndex,
|
||||
referenceSummaryAvailable: reference.summaryAvailable,
|
||||
...timing,
|
||||
});
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
assert.deepEqual(unexpected, []);
|
||||
const apiRequests = requests.slice(requestStart);
|
||||
assert.equal(
|
||||
apiRequests.filter(request => request.path.startsWith('/api/v2/experiments/')).length,
|
||||
comparison ? 5 : 3
|
||||
);
|
||||
samples.push({
|
||||
workload: comparison ? 'comparison-100+100' : `detail-${count}`,
|
||||
repeat,
|
||||
fixture: { bytes: Buffer.byteLength(payload), sha256: sha256(payload) },
|
||||
cold,
|
||||
warmupExcluded: warmup,
|
||||
refresh,
|
||||
referenceChanges,
|
||||
apiRequests,
|
||||
});
|
||||
process.stderr.write(
|
||||
`${comparison ? 'comparison-100+100' : `detail-${count}`} sample ${repeat + 1}/${options.samples}: verified\n`
|
||||
);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
await browser?.close();
|
||||
} finally {
|
||||
await server.stop(true);
|
||||
}
|
||||
}
|
||||
const sourceFiles = [
|
||||
'scripts/benchmark-experiment-tables.ts',
|
||||
'scripts/test/benchmark-experiment-tables.test.ts',
|
||||
'test/fixtures/native-replay.ts',
|
||||
];
|
||||
const source = {
|
||||
commit: (await command(['git', 'rev-parse', 'HEAD'])).out.trim(),
|
||||
status: (await command(['git', 'status', '--porcelain'])).out,
|
||||
files: sourceFiles.map(path => ({ path, sha256: sha256(readFileSync(join(root, path))) })),
|
||||
};
|
||||
const assets = fileIdentities(dist),
|
||||
host = {
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
osRelease: release(),
|
||||
cpu: cpus()[0]?.model,
|
||||
cpus: cpus().length,
|
||||
availableParallelism: availableParallelism(),
|
||||
totalMemoryBytes: totalmem(),
|
||||
loadBefore: initialLoad,
|
||||
loadAfter: loadavg(),
|
||||
};
|
||||
const groups = [...new Set(samples.map(sample => sample.workload))].map(workload => {
|
||||
const group = samples.filter(sample => sample.workload === workload);
|
||||
return {
|
||||
workload,
|
||||
coldActionToReadyMs: summarize(group.map(sample => sample.cold.durationsMs.actionToReady)),
|
||||
warmRefreshMs: summarize(group.map(sample => sample.refresh.durationsMs.actionToReady)),
|
||||
warmJsonToReadyMs: summarize(
|
||||
group.map(sample => sample.refresh.durationsMs.jsonToTwoFrameReady)
|
||||
),
|
||||
referenceChanges: [3, 1].flatMap(referenceIndex => {
|
||||
const values = group.flatMap(sample =>
|
||||
sample.referenceChanges
|
||||
.filter(change => change.referenceIndex === referenceIndex)
|
||||
.map(change => change.durationsMs.actionToReady)
|
||||
);
|
||||
return values.length ? [{ referenceIndex, actionToReadyMs: summarize(values) }] : [];
|
||||
}),
|
||||
};
|
||||
});
|
||||
return {
|
||||
version: 'experiment-table-ui-benchmark/v1',
|
||||
scope,
|
||||
startedAt,
|
||||
completedAt: new Date().toISOString(),
|
||||
options,
|
||||
source,
|
||||
host,
|
||||
runtime: {
|
||||
bun: Bun.version,
|
||||
browser: browserVersion,
|
||||
browserLaunchMs,
|
||||
viewport: { width: 1440, height: 1080 },
|
||||
deviceScaleFactor: 1,
|
||||
},
|
||||
build: {
|
||||
mode: 'production',
|
||||
durationMs: buildMs,
|
||||
assets,
|
||||
sha256: sha256(JSON.stringify(assets)),
|
||||
},
|
||||
measurement: {
|
||||
cold: 'Fresh context/page in one Chromium process, navigation epoch to two-frame readiness; browser launch measured once separately. Browser process and OS/disk caches are not reset.',
|
||||
warm: 'Same page, after one excluded refresh; reference changes exercise route remounts without browser restart.',
|
||||
readiness:
|
||||
'Browser-local action/fetch/JSON timestamps then two requestAnimationFrame callbacks with full row count, new response revision on final row, and enabled refresh control; proxy for visible readiness, not exact paint or React CPU time.',
|
||||
network:
|
||||
'Loopback synthetic compact DTO responses; browser routing disables HTTP cache. No database/native/queue measurements.',
|
||||
p95: 'Only reported with at least 20 samples; five samples cannot establish tail latency.',
|
||||
limits:
|
||||
'External Google Fonts blocked; fallback system fonts used. No memory, scrolling/input latency, real-network, retained artifact-size distribution, server storage or financial throughput claim. All rows are checked after timing.',
|
||||
},
|
||||
blockedExternalFonts: [...blockedFonts],
|
||||
summary: groups,
|
||||
samples,
|
||||
};
|
||||
}
|
||||
if (import.meta.main) {
|
||||
main(process.argv.slice(2))
|
||||
.then(report => process.stdout.write(JSON.stringify(report, null, 2) + '\n'))
|
||||
.catch(cause => {
|
||||
process.stderr.write(String(cause?.stack ?? cause) + '\n');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
154
scripts/test/benchmark-experiment-tables.test.ts
Normal file
154
scripts/test/benchmark-experiment-tables.test.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import { costSensitivityInputSchema } from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import { experimentInputSchema } from '@stock-bot/stock-config/experiments';
|
||||
import {
|
||||
assertCompact,
|
||||
comparisonFixture,
|
||||
parseArguments,
|
||||
scope,
|
||||
summarize,
|
||||
tableFixture,
|
||||
withResponseRevision,
|
||||
} from '../benchmark-experiment-tables';
|
||||
|
||||
describe('production experiment table measurement', () => {
|
||||
test('bounded explicit workloads; smoke cannot be mistaken for measured trial set', () => {
|
||||
expect(parseArguments([])).toEqual({ measure: false, samples: 1 });
|
||||
expect(parseArguments(['--self-test'])).toEqual({ measure: false, samples: 1 });
|
||||
expect(parseArguments(['--measure'])).toEqual({ measure: true, samples: 5 });
|
||||
expect(parseArguments(['--samples=20', '--measure'])).toEqual({ measure: true, samples: 20 });
|
||||
for (const args of [
|
||||
['--measure', '--samples=1'],
|
||||
['--samples=101'],
|
||||
['--samples=0'],
|
||||
['--measure', '--self-test'],
|
||||
['--measure', '--measure'],
|
||||
['--samples=3', '--samples=3'],
|
||||
['--unknown'],
|
||||
]) {
|
||||
expect(() => parseArguments(args)).toThrow();
|
||||
}
|
||||
for (const count of [0, 101, 1.5, Infinity]) {
|
||||
expect(() => tableFixture(count)).toThrow();
|
||||
}
|
||||
expect(scope).toContain('no engine, database, queue, financial correctness');
|
||||
});
|
||||
test.each([1, 25, 100])(
|
||||
'%i rows preserve candidate order, source identity and every compact outcome',
|
||||
count => {
|
||||
const detail = tableFixture(count);
|
||||
expect(detail).toEqual(tableFixture(count));
|
||||
expect(detail.trialCount).toBe(count);
|
||||
expect(detail.trials).toHaveLength(count);
|
||||
expect(detail.preview.candidates).toHaveLength(count);
|
||||
expect(canonicalRunRequestSchema.safeParse(detail.preview.request).success).toBe(true);
|
||||
expect(experimentInputSchema.safeParse(detail.preview.input).success).toBe(true);
|
||||
expect(() => assertCompact(detail)).not.toThrow();
|
||||
expect(new Set(detail.trials.map(trial => trial.trialKey)).size).toBe(count);
|
||||
expect(detail.trials.map(trial => trial.index)).toEqual(
|
||||
Array.from({ length: count }, (_, i) => i)
|
||||
);
|
||||
expect(
|
||||
Object.values(detail.counts).reduce((sum, value) => sum + value, 0) +
|
||||
detail.trials.filter(trial => trial.status === 'missing').length
|
||||
).toBe(count);
|
||||
for (const [index, trial] of detail.trials.entries()) {
|
||||
expect(detail.preview.candidates[index]?.parameters).toEqual(trial.parameters);
|
||||
expect(detail.preview.candidates[index]?.trialKey).toBe(trial.trialKey);
|
||||
expect(trial.status === 'missing').toBe(trial.runId === null);
|
||||
}
|
||||
expect(detail.trials[0]?.metrics?.totalReturn).toBe(0);
|
||||
expect(detail.trials[0]?.metrics?.sharpeRatio).toBeNull();
|
||||
expect(detail.trials[0]?.unavailable?.sharpeRatio).toBe('insufficient-periods');
|
||||
if (count > 1) {
|
||||
expect(new Set(detail.trials.map(trial => trial.status))).toEqual(
|
||||
new Set(['completed', 'failed', 'pending', 'running', 'paused', 'cancelled', 'missing'])
|
||||
);
|
||||
expect(detail.trials[1]?.metrics?.sharpeRatio).toBe(1.25);
|
||||
expect(detail.trials[2]?.status).toBe('completed');
|
||||
expect(detail.trials[2]?.comparable).toBe(false);
|
||||
expect(detail.trials[2]?.metrics).toBeNull();
|
||||
expect(detail.trials[3]?.error).toContain('callback failure');
|
||||
}
|
||||
}
|
||||
);
|
||||
test('comparison is all 200 rows, cost scenarios keep parameters fixed and settings/summary states separate', () => {
|
||||
const value = comparisonFixture(),
|
||||
[left, right] = value.experiments;
|
||||
expect(value.rows).toHaveLength(200);
|
||||
expect(value.rows.filter(row => row.inputCompatibility === 'match')).toHaveLength(101);
|
||||
expect(value.rows.filter(row => row.inputCompatibility === 'mismatch')).toHaveLength(99);
|
||||
expect(value.rows.filter(row => row.summaryAvailable)).toHaveLength(46);
|
||||
expect(value.rows.filter(row => row.ready)).toHaveLength(24);
|
||||
expect(value.rows.map(row => row.trialKey)).toEqual(
|
||||
[...left.trials, ...right.trials].map(trial => trial.trialKey)
|
||||
);
|
||||
expect(right.preview.version).toBe('cost-sensitivity-preview/v1');
|
||||
expect(costSensitivityInputSchema.safeParse(right.preview.input).success).toBe(true);
|
||||
expect(new Set(right.trials.map(trial => JSON.stringify(trial.parameters))).size).toBe(1);
|
||||
expect(
|
||||
new Set(
|
||||
[...left.trials, ...right.trials].flatMap(trial => (trial.runId ? [trial.runId] : []))
|
||||
).size
|
||||
).toBe(178);
|
||||
expect(() => assertCompact(value)).not.toThrow();
|
||||
const failed = comparisonFixture(3),
|
||||
missing = comparisonFixture(8);
|
||||
for (const unavailable of [failed, missing]) {
|
||||
expect(unavailable.reference.summaryAvailable).toBe(false);
|
||||
expect(unavailable.rows.some(row => row.ready)).toBe(false);
|
||||
expect(unavailable.rows.filter(row => row.summaryAvailable)).toHaveLength(46);
|
||||
expect(unavailable.rows).toHaveLength(200);
|
||||
}
|
||||
expect(missing.reference.runId).toBeNull();
|
||||
expect(comparisonFixture(1).reference.index).toBe(1);
|
||||
expect(() => comparisonFixture(100)).toThrow();
|
||||
});
|
||||
test('refresh marker changes visible final rows without altering retained inputs or economic summaries', () => {
|
||||
for (const original of [tableFixture(100), comparisonFixture()]) {
|
||||
const first = withResponseRevision(original, 1),
|
||||
second = withResponseRevision(first, 2);
|
||||
const experiments = 'experiments' in second ? second.experiments : [second];
|
||||
const before = 'experiments' in original ? original.experiments : [original];
|
||||
for (const [index, experiment] of experiments.entries()) {
|
||||
expect(before[index]?.preview).toEqual(experiment.preview);
|
||||
expect(before[index]?.trials.map(trial => trial.metrics)).toEqual(
|
||||
experiment.trials.map(trial => trial.metrics)
|
||||
);
|
||||
expect(
|
||||
experiment.trials
|
||||
.at(-1)
|
||||
?.limitations.filter(text => text.startsWith('Synthetic response revision '))
|
||||
).toEqual(['Synthetic response revision 2']);
|
||||
}
|
||||
expect(JSON.stringify(original)).not.toContain('Synthetic response revision');
|
||||
expect(JSON.stringify(first)).toContain('Synthetic response revision 1');
|
||||
}
|
||||
});
|
||||
test('full result blobs anywhere in an envelope are rejected', () => {
|
||||
for (const field of [
|
||||
'financial',
|
||||
'trades',
|
||||
'ohlcData',
|
||||
'equity',
|
||||
'fills',
|
||||
'trace',
|
||||
'returns',
|
||||
]) {
|
||||
expect(() => assertCompact({ comparison: { experiments: [{ [field]: [] }] } })).toThrow(
|
||||
'Full result'
|
||||
);
|
||||
}
|
||||
});
|
||||
test('raw samples remain unmodified, median is defined and small samples make no tail claim', () => {
|
||||
const values = [10, 1, 3, 2];
|
||||
expect(summarize(values)).toEqual({ count: 4, min: 1, median: 2.5, max: 10, p95: null });
|
||||
expect(values).toEqual([10, 1, 3, 2]);
|
||||
expect(summarize([3, 1, 2]).median).toBe(2);
|
||||
expect(summarize(Array.from({ length: 20 }, (_, i) => i + 1)).p95).toBe(19);
|
||||
for (const invalid of [[], [NaN], [Infinity], [-1]]) {
|
||||
expect(() => summarize(invalid)).toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue