feat(research): add retained-input parameter sweep workbench
This commit is contained in:
parent
30accfcf43
commit
6f64ef62ba
41 changed files with 4469 additions and 34 deletions
|
|
@ -293,6 +293,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'19-canonical-research.sql',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -416,6 +417,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
!pathname.startsWith('/api/v2/strategies') &&
|
||||
!pathname.startsWith('/api/v2/strategy-versions') &&
|
||||
!pathname.startsWith('/api/v2/research-projects') &&
|
||||
!pathname.startsWith('/api/v2/experiments') &&
|
||||
!pathname.startsWith('/api/v2/hypotheses/') &&
|
||||
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
|
||||
pathname !== '/api/auth/session') ||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
canonicalResearchSettingsSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { ExperimentDetail, ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
|
@ -30,6 +31,189 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
test('retained_experiment_preview_submit_compare_cancel_and_reopen_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 selected = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed canonical fixture for bounded experiments',
|
||||
});
|
||||
const definition = {
|
||||
name: 'Retained sweep template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: selected.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,
|
||||
});
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/backtests/${backtest.id}`);
|
||||
await f.page.getByRole('link', { name: 'Create experiment', exact: true }).click();
|
||||
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
|
||||
await f.page.getByLabel('Experiment name', { exact: true }).fill('Retained SMA sweep');
|
||||
await f.page.getByLabel('Parameter grid (JSON)').fill('{"fastPeriod":[1,2],"slowPeriod":[3]}');
|
||||
const previewing = f.page.waitForResponse(response =>
|
||||
response.url().endsWith('/api/v2/experiments/preview')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
|
||||
const previewResponse = await previewing;
|
||||
expect(previewResponse.status()).toBe(200);
|
||||
const { preview } = (await previewResponse.json()) as { preview: ExperimentPreview };
|
||||
expect(preview.candidates).toHaveLength(2);
|
||||
expect(preview.dataset.hash).toBe(dataset.manifest.hash);
|
||||
expect(preview.dataset.bounds).toEqual(dataset.manifest.bounds);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
const submitting = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' && response.url().endsWith('/api/v2/experiments')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
|
||||
const accepted = await submitting;
|
||||
expect(accepted.status()).toBe(202);
|
||||
const { experiment } = (await accepted.json()) as { experiment: ExperimentDetail };
|
||||
expect(accepted.headers().location).toBe(`/api/v2/experiments/${experiment.id}`);
|
||||
expect(experiment.trialCount).toBe(2);
|
||||
expect(experiment.counts.pending).toBe(2);
|
||||
expect(experiment.trials.map(trial => trial.parameters)).toEqual(
|
||||
preview.candidates.map(candidate => candidate.parameters)
|
||||
);
|
||||
await f.page.waitForURL(`${f.origin}/experiments/${experiment.id}`);
|
||||
const replay = await f.page.evaluate(
|
||||
async ({ body, key }) => {
|
||||
const response = await fetch('/api/v2/experiments', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return { status: response.status, body: await response.json() };
|
||||
},
|
||||
{
|
||||
body: accepted.request().postDataJSON(),
|
||||
key: accepted.request().headers()['idempotency-key']!,
|
||||
}
|
||||
);
|
||||
expect(replay.status).toBe(202);
|
||||
expect(replay.body.experiment.id).toBe(experiment.id);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(2);
|
||||
// Edits after atomic admission cannot change either candidate's economics.
|
||||
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
|
||||
...definition,
|
||||
name: 'Changed after sweep admission',
|
||||
initialCapital: 20000,
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
});
|
||||
f.dispatcher.start();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count ===
|
||||
'2',
|
||||
'both retained canonical experiment trials complete'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click();
|
||||
await visible(f.page, /completed: 2/);
|
||||
const outcomes = f.page.getByRole('region', { name: 'Experiment trial outcomes' });
|
||||
expect(await outcomes.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(2);
|
||||
const completed = (await f.request(`/api/v2/experiments/${experiment.id}`))
|
||||
.experiment as ExperimentDetail;
|
||||
expect(completed.counts.completed).toBe(2);
|
||||
expect(completed.trials.every(trial => trial.comparable && trial.metrics !== null)).toBe(true);
|
||||
expect(JSON.stringify(completed.trials)).not.toMatch(/"financial"|"sessionReturns"|"fills"/);
|
||||
for (const [index, trial] of completed.trials.entries()) {
|
||||
const cell = outcomes.locator('tbody tr').nth(index).locator('td').nth(3);
|
||||
expect(await cell.textContent()).toBe(String(trial.metrics!.totalReturn));
|
||||
}
|
||||
for (const trial of completed.trials) {
|
||||
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
|
||||
expect(trial.parameters).toEqual(result.request.strategy.selection.parameters);
|
||||
expect(result.request.datasetHash).toBe(dataset.manifest.hash);
|
||||
expect(result.request.build).toEqual(preview.request.build);
|
||||
expect(String(result.request.policy.matching.risk.ledger.initialCapital)).toBe(
|
||||
'10000.00000000'
|
||||
);
|
||||
expect(trial.metrics).toEqual(result.analytics.metrics);
|
||||
expect(trial.unavailable).toEqual(result.analytics.unavailable);
|
||||
}
|
||||
const firstRunId = completed.trials[0]!.runId!;
|
||||
await f.page.locator(`a[href="/backtests/${backtest.id}/run/${firstRunId}"]`).click();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
// Experiment linkage belongs to the trial; a standalone reproduction has
|
||||
// only original-run lineage and retains that trial's frozen parameters.
|
||||
await f.page.getByRole('button', { name: 'Reproduce original', exact: true }).click();
|
||||
const reproducing = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/runs/${firstRunId}/reproduce`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Confirm reproduction', exact: true }).click();
|
||||
const reproducedResponse = await reproducing;
|
||||
expect(reproducedResponse.status()).toBe(202);
|
||||
const reproduced = await reproducedResponse.json();
|
||||
await f.page.waitForURL(`${f.origin}/backtests/${backtest.id}/run/${reproduced.id}`);
|
||||
await visible(f.page, 'Economic results match the original.');
|
||||
expect(
|
||||
(
|
||||
await f.pool.query('SELECT experiment_id,original_run_id FROM runs WHERE id=$1', [
|
||||
reproduced.id,
|
||||
])
|
||||
).rows[0]
|
||||
).toEqual({ experiment_id: null, original_run_id: firstRunId });
|
||||
await f.page.getByRole('link', { name: 'Experiments', exact: true }).click();
|
||||
await f.page.getByRole('link', { name: 'Retained SMA sweep', exact: true }).click();
|
||||
await f.page.reload();
|
||||
await f.page.getByRole('heading', { name: 'Retained SMA sweep', exact: true }).waitFor();
|
||||
expect((await f.request(`/api/v2/experiments/${experiment.id}`)).experiment).toEqual(completed);
|
||||
|
||||
// A second pending batch can be cancelled without touching completed evidence.
|
||||
await f.dispatcher.shutdown();
|
||||
await f.page.goto(`${f.origin}/experiments?backtestId=${backtest.id}`);
|
||||
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
|
||||
await f.page.getByLabel('Experiment name', { exact: true }).fill('Cancelled sweep');
|
||||
await f.page.getByLabel('Parameter grid (JSON)').fill('{"slowPeriod":[2,3]}');
|
||||
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
|
||||
const cancellingBatch = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' && response.url().endsWith('/api/v2/experiments')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
|
||||
const cancellationBatch = (await (await cancellingBatch).json()).experiment as ExperimentDetail;
|
||||
await f.page.waitForURL(`${f.origin}/experiments/${cancellationBatch.id}`);
|
||||
const cancelling = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/experiments/${cancellationBatch.id}/cancel`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Cancel remaining trials', exact: true }).click();
|
||||
expect((await cancelling).status()).toBe(200);
|
||||
await visible(f.page, /cancelled: 2/);
|
||||
const cancelled = (await f.request(`/api/v2/experiments/${cancellationBatch.id}`))
|
||||
.experiment as ExperimentDetail;
|
||||
expect(cancelled.cancelRequested).toBe(true);
|
||||
expect(cancelled.counts.cancelled).toBe(2);
|
||||
expect(cancelled.trials.every(trial => trial.metrics === null)).toBe(true);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(3);
|
||||
expect((await f.request(`/api/v2/experiments/${experiment.id}`)).experiment).toEqual(completed);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Serial by design: the production WebSocket projection has a process-local handler.
|
||||
test('browser_saved_run_lifecycle', async () => {
|
||||
const f = await fixture();
|
||||
|
|
|
|||
347
test/integration/experiments-api.test.ts
Normal file
347
test/integration/experiments-api.test.ts
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
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 { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
experimentCandidates,
|
||||
experimentHash,
|
||||
experimentTrialRequest,
|
||||
PREVIEW_RUN_ID,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
const tokens = {
|
||||
operator: 'experiment-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'experiment-service-fixture-not-a-real-secret-1234',
|
||||
read: 'experiment-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
const backtestId = randomUUID(),
|
||||
experimentId = randomUUID();
|
||||
const input = { backtestId, name: 'Sweep', grid: { fastPeriod: [1, 2] } };
|
||||
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 = {
|
||||
...client,
|
||||
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 === undefined ? {} : { 'Idempotency-Key': key }),
|
||||
},
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
function retainedPreview() {
|
||||
const version = randomUUID(),
|
||||
owner = `strategy:${version}`;
|
||||
const fixture = canonicalSmaFixture([owner]);
|
||||
const descriptor = builtinCatalogDescriptors[0]!;
|
||||
const policy = structuredClone(fixture.config);
|
||||
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
||||
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: PREVIEW_RUN_ID,
|
||||
backtestId,
|
||||
name: 'Template',
|
||||
strategy: {
|
||||
familyId: randomUUID(),
|
||||
versionId: version,
|
||||
origin: 'builtin',
|
||||
reviewId: randomUUID(),
|
||||
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: fixture.selections[0],
|
||||
},
|
||||
datasetHash: fixture.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(input, request, fixture.dataset.manifest);
|
||||
}
|
||||
|
||||
describe('experiment HTTP contract', () => {
|
||||
test('mutations require authenticated credential proof including preview/cancel and development bypass', async () => {
|
||||
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
||||
const f = fixture(mode);
|
||||
for (const [path, body] of [
|
||||
['/preview', JSON.stringify(input)],
|
||||
['', JSON.stringify({ ...input, previewHash: 'a'.repeat(64) })],
|
||||
[`/${experimentId}/cancel`, '{}'],
|
||||
]) {
|
||||
expect((await f.request(path, 'POST', body, undefined, 'key')).status).toBe(401);
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('read role lists and inspects but cannot mutate; anonymous reads reject', async () => {
|
||||
const f = fixture();
|
||||
expect((await f.request()).status).toBe(401);
|
||||
expect((await f.request('', 'GET', undefined, 'read')).status).toBe(200);
|
||||
expect((await f.request(`/${experimentId}`, 'GET', undefined, 'read')).status).toBe(404);
|
||||
for (const path of ['/preview', '', `/${experimentId}/cancel`]) {
|
||||
expect((await f.request(path, 'POST', '{}', 'read', 'key')).status).toBe(403);
|
||||
}
|
||||
});
|
||||
test('strict bodies, malformed IDs, raw reserved parameters and receipt keys reject before storage', async () => {
|
||||
const submission = { ...input, previewHash: 'a'.repeat(64) };
|
||||
for (const [path, body, key] of [
|
||||
['/preview', '{', 'key'],
|
||||
['/preview', '[]', 'key'],
|
||||
['/preview', JSON.stringify({ ...input, feeRate: '0' }), 'key'],
|
||||
['/preview', `{"backtestId":"${backtestId}","name":"bad","grid":{"__proto__":[1]}}`, 'key'],
|
||||
['', JSON.stringify(submission), undefined],
|
||||
['', JSON.stringify(submission), 'contains space'],
|
||||
['', JSON.stringify(submission), 'x'.repeat(201)],
|
||||
['', JSON.stringify({ ...submission, previewHash: 'bad' }), 'key'],
|
||||
[`/${experimentId}/cancel`, '{"restart":true}', 'key'],
|
||||
['/bad/cancel', '{}', 'key'],
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400);
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
const f = fixture();
|
||||
expect((await f.request('/bad', 'GET', undefined, 'read')).status).toBe(400);
|
||||
expect((await f.request('?backtestId=bad', 'GET', undefined, 'read')).status).toBe(400);
|
||||
});
|
||||
test('accepted experiment receipts replay with202/Location and compact missing children before template eligibility', async () => {
|
||||
const preview = retainedPreview(),
|
||||
submission = { ...input, previewHash: preview.previewHash },
|
||||
key = 'accepted';
|
||||
const hash = experimentHash({ version: 1, operation: 'create-experiment', submission });
|
||||
for (const principal of ['operator', 'service'] as const) {
|
||||
const f = fixture('enabled', async (sql, values) => {
|
||||
if (sql.includes('submission_principal=$1')) {
|
||||
expect(values).toEqual([principal, key]);
|
||||
return { rows: [{ id: experimentId, submission_hash: hash }] };
|
||||
}
|
||||
if (sql.includes('SELECT r.id')) {
|
||||
return { rows: [] };
|
||||
}
|
||||
expect(sql).not.toContain('FROM backtests');
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: experimentId,
|
||||
backtest_id: backtestId,
|
||||
name: input.name,
|
||||
created_at: '2026-10-24T00:00:00Z',
|
||||
cancel_requested: true,
|
||||
trial_count: 2,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
strategy_version_id: preview.request.strategy.versionId,
|
||||
preview_hash: preview.previewHash,
|
||||
counts: { completed: 2 },
|
||||
preview,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
const response = await f.request('', 'POST', JSON.stringify(submission), principal, key);
|
||||
expect(response.status).toBe(202);
|
||||
expect(response.headers.get('Location')).toBe(`/api/v2/experiments/${experimentId}`);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
const value = await response.json();
|
||||
expect(value.experiment).toMatchObject({
|
||||
id: experimentId,
|
||||
cancelRequested: true,
|
||||
trialCount: 2,
|
||||
counts: { completed: 0 },
|
||||
});
|
||||
expect(value.experiment.trials.map((t: { status: string }) => t.status)).toEqual([
|
||||
'missing',
|
||||
'missing',
|
||||
]);
|
||||
}
|
||||
});
|
||||
test('receipt conflicts and unavailable templates are409, missing is404, unexpected storage/schema errors remain sanitized500', async () => {
|
||||
const conflict = fixture('enabled', async () => ({
|
||||
rows: [{ id: experimentId, submission_hash: 'other' }],
|
||||
}));
|
||||
expect(
|
||||
(
|
||||
await conflict.request(
|
||||
'',
|
||||
'POST',
|
||||
JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }),
|
||||
'operator',
|
||||
'key'
|
||||
)
|
||||
).status
|
||||
).toBe(409);
|
||||
const archived = fixture('enabled', async () => ({
|
||||
rows: [{ id: backtestId, archived_at: '2026-10-24T00:00:00Z' }],
|
||||
}));
|
||||
expect(
|
||||
(await archived.request('/preview', 'POST', JSON.stringify(input), 'operator')).status
|
||||
).toBe(409);
|
||||
const missing = fixture();
|
||||
expect(
|
||||
(await missing.request('/preview', 'POST', JSON.stringify(input), 'operator')).status
|
||||
).toBe(404);
|
||||
expect(
|
||||
(await missing.request(`/${experimentId}/cancel`, 'POST', '{}', 'operator')).status
|
||||
).toBe(404);
|
||||
for (const error of [new Error('private database detail'), new z.ZodError([])]) {
|
||||
const f = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
for (const [path, method, body, key] of [
|
||||
['', 'GET', undefined, undefined],
|
||||
[`/${experimentId}`, 'GET', undefined, undefined],
|
||||
['/preview', 'POST', JSON.stringify(input), undefined],
|
||||
['', 'POST', JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }), 'key'],
|
||||
[`/${experimentId}/cancel`, 'POST', '{}', undefined],
|
||||
]) {
|
||||
const response = await f.request(path, method, body, 'operator', key);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.text()).not.toContain('private');
|
||||
}
|
||||
}
|
||||
});
|
||||
test('detail counts use child rows when statuses change after the earlier metadata query', async () => {
|
||||
const preview = retainedPreview();
|
||||
const f = fixture('enabled', async sql => {
|
||||
if (sql.includes('SELECT r.id')) {
|
||||
return {
|
||||
rows: preview.candidates.map((candidate, index) => {
|
||||
const id = randomUUID();
|
||||
return {
|
||||
id,
|
||||
backtest_id: backtestId,
|
||||
trial_index: index,
|
||||
trial_key: candidate.trialKey,
|
||||
status: index === 0 ? 'completed' : 'failed',
|
||||
progress: index === 0 ? 100 : 50,
|
||||
cancel_requested: false,
|
||||
error: index === 1 ? 'failure' : null,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
request_snapshot: experimentTrialRequest(preview, candidate, id),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: experimentId,
|
||||
backtest_id: backtestId,
|
||||
name: input.name,
|
||||
created_at: '2026-10-24T00:00:00Z',
|
||||
cancel_requested: false,
|
||||
trial_count: 2,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
strategy_version_id: preview.request.strategy.versionId,
|
||||
preview_hash: preview.previewHash,
|
||||
counts: { pending: 2 },
|
||||
preview,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
const response = await f.request(`/${experimentId}`, 'GET', undefined, 'read');
|
||||
expect(response.status).toBe(200);
|
||||
const { experiment } = await response.json();
|
||||
expect(experiment.counts).toEqual({
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: 1,
|
||||
failed: 1,
|
||||
cancelled: 0,
|
||||
});
|
||||
expect(experiment.trials.map((trial: { status: string }) => trial.status)).toEqual([
|
||||
'completed',
|
||||
'failed',
|
||||
]);
|
||||
expect(experiment.trials.every((trial: { comparable: boolean }) => !trial.comparable)).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
test('normalized duplicate parameter sets cannot create duplicate trial identity', () => {
|
||||
const preview = retainedPreview();
|
||||
const descriptor = builtinCatalogDescriptors[1]!;
|
||||
const request = structuredClone(preview.request);
|
||||
request.strategy.package.program = descriptor.program;
|
||||
request.strategy.package.parameterSchema = descriptor.parameterSchema;
|
||||
request.strategy.selection = {
|
||||
...request.strategy.selection,
|
||||
strategyId: 'mean_reversion',
|
||||
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
||||
parameters: {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0.1,
|
||||
minTrendReturn: -0.5,
|
||||
minMomentumReturn: -0.5,
|
||||
maxVolatility: 1,
|
||||
minNotionalVolume: parseFinancialDecimal('0'),
|
||||
regimeFilter: 'none',
|
||||
},
|
||||
};
|
||||
expect(() =>
|
||||
experimentCandidates({ ...input, grid: { minNotionalVolume: ['1', '1.0'] } }, request)
|
||||
).toThrow('Duplicate normalized');
|
||||
});
|
||||
});
|
||||
24
test/integration/experiments-contracts.test.ts
Normal file
24
test/integration/experiments-contracts.test.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
experimentSubmissionSchema,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
|
||||
test('reserved raw grid keys cannot silently become a baseline experiment', () => {
|
||||
for (const key of ['__proto__', 'constructor', 'prototype']) {
|
||||
const input = JSON.parse(
|
||||
`{"backtestId":"00000000-0000-4000-8000-000000000001","name":"Sweep","grid":{"${key}":[1]}}`
|
||||
);
|
||||
expect(experimentInputSchema.safeParse(input).success).toBe(false);
|
||||
expect(
|
||||
experimentSubmissionSchema.safeParse({ ...input, previewHash: 'a'.repeat(64) }).success
|
||||
).toBe(false);
|
||||
}
|
||||
expect(
|
||||
experimentInputSchema.parse({
|
||||
backtestId: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Baseline',
|
||||
grid: {},
|
||||
}).grid
|
||||
).toEqual({});
|
||||
});
|
||||
732
test/integration/experiments-ui.test.tsx
Normal file
732
test/integration/experiments-ui.test.tsx
Normal file
|
|
@ -0,0 +1,732 @@
|
|||
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 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';
|
||||
|
||||
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 ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentDetailPage;
|
||||
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)
|
||||
?.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 = preview(),
|
||||
statuses: ExperimentTrial['status'][] = source.candidates.map(() => 'pending')
|
||||
): ExperimentDetail {
|
||||
const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({
|
||||
...item,
|
||||
runId: statuses[index] === 'missing' ? null : runId(index),
|
||||
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 {
|
||||
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,
|
||||
};
|
||||
}
|
||||
async function list(parent = backtestId) {
|
||||
await render(createElement(ExperimentListPage), `/experiments?backtestId=${parent}`);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests?limit=50&offset=0'), [template(parent)]);
|
||||
reply(request(`/api/v2/experiments?backtestId=${parent}`), { experiments: [] });
|
||||
});
|
||||
}
|
||||
async function ready(value = preview()) {
|
||||
await list(value.input.backtestId);
|
||||
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 }));
|
||||
return value;
|
||||
}
|
||||
async function showDetail(value?: ExperimentDetail) {
|
||||
const routes = createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/experiments/:experimentId',
|
||||
element: createElement(ExperimentDetailPage),
|
||||
})
|
||||
);
|
||||
await render(routes, `/experiments/${value?.id ?? experimentId}`);
|
||||
if (value) {
|
||||
await flush(() => reply(request(`/api/v2/experiments/${value.id}`), { experiment: value }));
|
||||
}
|
||||
}
|
||||
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 });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ ExperimentListPage, ExperimentDetailPage } = await import(
|
||||
'../../apps/stock/web-app/src/features/experiments'
|
||||
));
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('bounded experiment creation', () => {
|
||||
test('preview displays frozen count/window/policies before duplicate-safe admission and exact navigation', async () => {
|
||||
const value = await ready();
|
||||
expect(host.textContent).toContain('No experiments yet.');
|
||||
expect(host.textContent).toContain('2 trials · Frozen template name');
|
||||
expect(host.textContent).toContain(new Date(value.dataset.bounds.tradeStart).toISOString());
|
||||
expect(host.textContent).toContain(value.request.datasetHash);
|
||||
const asset = [...host.querySelectorAll('dt')].find(
|
||||
item => item.textContent === 'Asset / timeframe'
|
||||
);
|
||||
expect(asset?.nextElementSibling?.textContent).toBe('X0.US / 1m');
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toHaveLength(0);
|
||||
await flush(() => {
|
||||
button('Confirm experiment').click();
|
||||
button('Confirm experiment').click();
|
||||
});
|
||||
const post = request('/api/v2/experiments', 'POST');
|
||||
expect(post.body).toEqual({ ...value.input, previewHash: value.previewHash });
|
||||
expect(post.headers.get('Idempotency-Key')).toBeTruthy();
|
||||
expect(post.credentials).toBe('include');
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
await flush(() => reply(post, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
test('every form change invalidates the preview and rejects a late response for the old input', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => change('Experiment name', 'Edited study'));
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const stale = request('/api/v2/experiments/preview', 'POST');
|
||||
await flush(() => change('Parameter grid (JSON)', '{}'));
|
||||
const old = structuredClone(value);
|
||||
old.input.name = 'Edited study';
|
||||
await flush(() => reply(stale, { preview: old }));
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
expect(host.querySelector('[aria-label="Frozen experiment inputs"]')).toBeNull();
|
||||
});
|
||||
test('invalid JSON and reserved keys are rejected before preview; server validation stays visible', async () => {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', 'Trend study');
|
||||
change('Parameter grid (JSON)', '{');
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => change('Parameter grid (JSON)', '{"__proto__":[1]}'));
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(host.textContent).toContain('Invalid parameter name');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => change('Parameter grid (JSON)', '{"fastPeriod":[20],"slowPeriod":[10]}'));
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/experiments/preview', 'POST'),
|
||||
{ error: 'fastPeriod must be below slowPeriod' },
|
||||
400
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('fastPeriod must be below slowPeriod');
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
});
|
||||
test.each(['network', 'malformed', 'foreign', 'server'] as const)(
|
||||
'%s create ambiguity retains byte-identical body/key and locks editing until explicit retry',
|
||||
async failure => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => {
|
||||
if (failure === 'network') {
|
||||
first.settled = true;
|
||||
first.reject(new Error('response lost'));
|
||||
} else if (failure === 'malformed') {
|
||||
reply(first, { experiment: { id: experimentId } }, 202);
|
||||
} else if (failure === 'foreign') {
|
||||
reply(first, { experiment: detail(preview(2, otherBacktestId)) }, 202);
|
||||
} else {
|
||||
reply(first, { error: 'Temporary failure' }, 500);
|
||||
}
|
||||
});
|
||||
expect(host.textContent).toContain('Acceptance is unconfirmed');
|
||||
expect(field('Experiment name').disabled).toBe(true);
|
||||
expect(field('Saved backtest').disabled).toBe(true);
|
||||
expect(button('Preview experiment').disabled).toBe(true);
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [] })
|
||||
);
|
||||
await flush(() => button('Retry experiment submission').click());
|
||||
const second = request('/api/v2/experiments', 'POST');
|
||||
expect(second.rawBody).toBe(first.rawBody);
|
||||
expect(second.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(second, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
}
|
||||
);
|
||||
test('stale-preview conflict does not silently replace intent and explicit new intent requires a fresh preview', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => reply(first, { error: 'Preview changed; refresh inputs' }, 409));
|
||||
expect(host.textContent).toContain('Preview changed; refresh inputs');
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(field('Experiment name').disabled).toBe(true);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
expect(field('Experiment name').disabled).toBe(false);
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
expect(request('/api/v2/experiments', 'POST').headers.get('Idempotency-Key')).not.toBe(
|
||||
first.headers.get('Idempotency-Key')
|
||||
);
|
||||
});
|
||||
test('old create completion cannot navigate after selecting a different backtest', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const old = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
|
||||
await flush(() => reply(old, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments?backtestId=${otherBacktestId}`);
|
||||
expect(field('Experiment name').value).toBe('');
|
||||
expect(host.textContent).not.toContain('Retry experiment submission');
|
||||
});
|
||||
test.each([
|
||||
'wrong-parent',
|
||||
'duplicate-trial',
|
||||
'wrong-dataset',
|
||||
'invalid-date',
|
||||
'wrong-series',
|
||||
] as const)('malformed %s preview never enables admission', async kind => {
|
||||
await list();
|
||||
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());
|
||||
if (kind === 'wrong-parent') {
|
||||
value.input.backtestId = otherBacktestId;
|
||||
}
|
||||
if (kind === 'duplicate-trial') {
|
||||
value.candidates[1]!.trialKey = value.candidates[0]!.trialKey;
|
||||
}
|
||||
if (kind === 'wrong-dataset') {
|
||||
value.dataset = { ...value.dataset, hash: 'f'.repeat(64) };
|
||||
}
|
||||
if (kind === 'invalid-date') {
|
||||
value.dataset = { ...value.dataset, bounds: { ...value.dataset.bounds, tradeEnd: 9e15 } };
|
||||
}
|
||||
if (kind === 'wrong-series') {
|
||||
value.dataset = { ...value.dataset, series: [] };
|
||||
}
|
||||
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
});
|
||||
test('owned links require deliberate discard and keep ambiguous body/key when navigation is declined', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => {
|
||||
first.settled = true;
|
||||
first.reject(new Error('lost'));
|
||||
});
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), {
|
||||
experiments: [detail(value)],
|
||||
})
|
||||
);
|
||||
let prompts = 0;
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
value: () => {
|
||||
prompts++;
|
||||
return false;
|
||||
},
|
||||
});
|
||||
await flush(() =>
|
||||
(host.querySelector(`a[href="/experiments/${experimentId}"]`) as HTMLAnchorElement).click()
|
||||
);
|
||||
await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click());
|
||||
expect(prompts).toBe(2);
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
expect(field('Experiment name').disabled).toBe(true);
|
||||
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'));
|
||||
await flush(() => reply(retry, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
test('list loading/error/empty states recover and saved links preserve missing counts', async () => {
|
||||
await render(createElement(ExperimentListPage), '/experiments');
|
||||
expect(host.textContent).toContain('Loading experiments...');
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/experiments'), { error: 'Read unavailable' }, 500);
|
||||
reply(request('/api/v2/backtests?limit=50&offset=0'), []);
|
||||
});
|
||||
expect(host.textContent).toContain('No saved canonical backtests');
|
||||
expect(host.textContent).toContain('Read unavailable');
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
const value = detail(preview(2), ['completed', 'missing']);
|
||||
await flush(() => reply(request('/api/v2/experiments'), { experiments: [value] }));
|
||||
expect(host.textContent).toContain('missing: 1');
|
||||
expect(host.querySelector(`a[href="/experiments/${experimentId}"]`)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('experiment outcomes and cancellation', () => {
|
||||
test('all states, null reasons, exact zero, mismatches, provenance and exact run links remain visible', async () => {
|
||||
const value = detail(preview(8), [
|
||||
'completed',
|
||||
'failed',
|
||||
'missing',
|
||||
'cancelled',
|
||||
'running',
|
||||
'paused',
|
||||
'pending',
|
||||
'completed',
|
||||
]);
|
||||
value.trials[7]!.comparable = false;
|
||||
value.trials[7]!.diagnostic = 'Retained request does not match the candidate';
|
||||
value.trials[7]!.limitations = ['Result cannot be compared'];
|
||||
value.trials[7]!.metrics = null;
|
||||
value.trials[7]!.unavailable = null;
|
||||
await showDetail(value);
|
||||
expect(host.querySelectorAll('tbody tr')).toHaveLength(8);
|
||||
expect(host.textContent).toContain('missing: 1');
|
||||
expect(host.textContent).toContain('Strategy callback failed');
|
||||
expect(host.textContent).toContain('Child run missing');
|
||||
expect(host.textContent).toContain('Incomparable');
|
||||
expect(host.textContent).toContain('Retained request does not match');
|
||||
expect(host.textContent).toContain('Unavailable: insufficient-periods');
|
||||
const first = host.querySelector('tbody tr')!;
|
||||
expect(first.querySelectorAll('td')[3]!.textContent).toBe('0');
|
||||
expect(first.querySelectorAll('td')[4]!.textContent).toBe('0');
|
||||
expect(host.querySelector(`a[href="/backtests/${backtestId}/run/${runId(0)}"]`)).not.toBeNull();
|
||||
expect(host.querySelectorAll('tbody a')).toHaveLength(7);
|
||||
expect(host.textContent).toContain(value.previewHash);
|
||||
expect(host.textContent).toContain(value.preview.request.build.engineBinarySha256);
|
||||
expect(host.textContent).not.toContain('Retry failed');
|
||||
});
|
||||
test('cancel is explicit and duplicate-safe, retains terminal outcomes and distinguishes requested running work', async () => {
|
||||
const value = detail(preview(3), ['completed', 'running', 'pending']);
|
||||
await showDetail(value);
|
||||
await flush(() => {
|
||||
button('Cancel remaining trials').click();
|
||||
button('Cancel remaining trials').click();
|
||||
});
|
||||
const post = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
|
||||
expect(post.body).toEqual({});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
const cancelled = detail(value.preview, ['completed', 'running', 'cancelled']);
|
||||
cancelled.cancelRequested = true;
|
||||
cancelled.trials[1]!.cancelRequested = true;
|
||||
await flush(() => reply(post, { experiment: cancelled }));
|
||||
expect(host.textContent).toContain('Cancellation requested. Running trials may still finish');
|
||||
expect(host.textContent).toContain('completed: 1');
|
||||
expect(host.textContent).toContain('running: 1');
|
||||
expect(host.textContent).toContain('cancelled: 1');
|
||||
expect(host.textContent).not.toContain('Cancel remaining trials');
|
||||
});
|
||||
test('cancellation response loss is visible and refresh verifies persisted state', async () => {
|
||||
const value = detail();
|
||||
await showDetail(value);
|
||||
await flush(() => button('Cancel remaining trials').click());
|
||||
const post = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
|
||||
await flush(() => {
|
||||
post.settled = true;
|
||||
post.reject(new Error('lost'));
|
||||
});
|
||||
expect(host.textContent).toContain('Refresh to verify the saved state');
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const cancelled = detail(value.preview, ['cancelled', 'cancelled']);
|
||||
cancelled.cancelRequested = true;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { experiment: cancelled })
|
||||
);
|
||||
expect(host.textContent).toContain('cancelled: 2');
|
||||
});
|
||||
test('old detail and cancel responses never overwrite a different selected experiment', async () => {
|
||||
const value = detail();
|
||||
await showDetail(value);
|
||||
await flush(() => button('Cancel remaining trials').click());
|
||||
const oldCancel = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
|
||||
await flush(() => navigate(`/experiments/${otherExperimentId}`));
|
||||
const other = detail(preview(1));
|
||||
other.id = otherExperimentId;
|
||||
other.name = 'Other experiment';
|
||||
other.preview.input.name = other.name;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${otherExperimentId}`), { experiment: other })
|
||||
);
|
||||
const cancelled = detail(value.preview, ['cancelled', 'cancelled']);
|
||||
cancelled.cancelRequested = true;
|
||||
await flush(() => reply(oldCancel, { experiment: cancelled }));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Other experiment');
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const stale = request(`/api/v2/experiments/${otherExperimentId}`);
|
||||
await flush(() => navigate(`/experiments/${experimentId}`));
|
||||
await flush(() => reply(stale, { experiment: other }));
|
||||
expect(host.textContent).not.toContain('Other experiment');
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Trend study');
|
||||
});
|
||||
test.each([
|
||||
'identity',
|
||||
'missing-row',
|
||||
'wrong-parameters',
|
||||
'count-mismatch',
|
||||
'malformed-metrics',
|
||||
] as const)('malformed %s detail fails closed and recovers after refresh', async kind => {
|
||||
await showDetail();
|
||||
const value = detail(preview(), ['completed', 'pending']);
|
||||
if (kind === 'identity') {
|
||||
value.id = otherExperimentId;
|
||||
}
|
||||
if (kind === 'missing-row') {
|
||||
value.trials.pop();
|
||||
}
|
||||
if (kind === 'wrong-parameters') {
|
||||
value.trials[0]!.parameters = { fastPeriod: 19 };
|
||||
}
|
||||
if (kind === 'count-mismatch') {
|
||||
value.counts.completed = 0;
|
||||
}
|
||||
if (kind === 'malformed-metrics') {
|
||||
(value.trials[0]!.metrics as unknown as Record<string, unknown>).totalReturn = '0';
|
||||
}
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.querySelector('tbody')).toBeNull();
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { experiment: detail() })
|
||||
);
|
||||
expect(host.querySelectorAll('tbody tr')).toHaveLength(2);
|
||||
});
|
||||
test('not-found/read failures show recovery controls without claiming an empty result', async () => {
|
||||
await showDetail();
|
||||
expect(host.textContent).toContain('Loading experiment...');
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { error: 'Experiment not found' }, 404)
|
||||
);
|
||||
expect(host.textContent).toContain('Experiment not found');
|
||||
expect(button('Refresh experiment').disabled).toBe(false);
|
||||
expect(host.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -63,6 +63,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -101,6 +101,7 @@ async function fixture() {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ async function fixture() {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -85,6 +85,7 @@ async function fixture() {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
712
test/postgres/experiments.test.ts
Normal file
712
test/postgres/experiments.test.ts
Normal file
|
|
@ -0,0 +1,712 @@
|
|||
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 { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type {
|
||||
CanonicalRunRequest,
|
||||
CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
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 { experimentTrialRequest } from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
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';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('experiments');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(poolMax = 4, withExperiments = true) {
|
||||
const dataset = canonicalSmaFixture().dataset;
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_experiments_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
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',
|
||||
...(withExperiments ? ['22-experiments.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 };
|
||||
const api = new BacktestServiceV2(container);
|
||||
const experiments = new ExperimentsService(container);
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const catalog = new StrategyCatalogService(container);
|
||||
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
|
||||
const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed');
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const definition = {
|
||||
name: 'Canonical API',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(s => s.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 draft = await api.createBacktest(definition, { autoStart: false });
|
||||
const approve = async () => {
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision: 'approve', reason: 'Reviewed retained builtin' },
|
||||
'operator'
|
||||
);
|
||||
return (await catalog.getVersionReviews(version.id)).at(-1)!;
|
||||
};
|
||||
const execute = async (id: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Canonical execution must never load provider data');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: new PostgresBacktestRunRepository(postgres),
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
await runner.runQueued(id);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
}
|
||||
};
|
||||
return {
|
||||
pool,
|
||||
schema,
|
||||
api,
|
||||
experiments,
|
||||
repository,
|
||||
catalog,
|
||||
pkg,
|
||||
version,
|
||||
draft,
|
||||
definition,
|
||||
dataset,
|
||||
approve,
|
||||
execute,
|
||||
app: new Hono().route('/', createExperimentRoutes(container)),
|
||||
};
|
||||
}
|
||||
|
||||
const receipt = (key: string = randomUUID()) => ({ principal: 'operator' as const, key });
|
||||
async function prepare(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
grid: Record<string, (string | number | boolean)[]> = { fastPeriod: [1, 2] }
|
||||
) {
|
||||
await f.approve();
|
||||
const input = { backtestId: f.draft.id, name: 'Retained SMA search', grid };
|
||||
const preview = await f.experiments.preview(input);
|
||||
const submission = { ...input, previewHash: preview.previewHash };
|
||||
return { input, preview, submission };
|
||||
}
|
||||
async function totals(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
return (
|
||||
await f.pool.query(`SELECT (SELECT count(*)::int FROM research_experiments) AS experiments,
|
||||
(SELECT count(*)::int FROM runs) AS runs,(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
|
||||
).rows[0];
|
||||
}
|
||||
async function rawTrial(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
experiment: Awaited<ReturnType<ExperimentsService['get']>>,
|
||||
changes: Record<string, unknown> = {}
|
||||
) {
|
||||
const id = randomUUID();
|
||||
const candidate = experiment.preview.candidates[0]!;
|
||||
const request = experimentTrialRequest(experiment.preview, candidate, id);
|
||||
const row = {
|
||||
id,
|
||||
backtest: f.draft.id,
|
||||
request,
|
||||
dataset: request.datasetHash,
|
||||
experiment: experiment.id,
|
||||
key: candidate.trialKey,
|
||||
index: candidate.index,
|
||||
original: null,
|
||||
principal: null,
|
||||
receiptKey: null,
|
||||
hash: null,
|
||||
...changes,
|
||||
};
|
||||
return f.pool.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index,original_run_id,submission_principal,submission_key,submission_hash)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending',NULL,$3,$4,$5,$6,$7,$8,$9,$10,$11 FROM runs WHERE backtest_id=$2`,
|
||||
[
|
||||
row.id,
|
||||
row.backtest,
|
||||
row.request,
|
||||
row.dataset,
|
||||
row.experiment,
|
||||
row.key,
|
||||
row.index,
|
||||
row.original,
|
||||
row.principal,
|
||||
row.receiptKey,
|
||||
row.hash,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('retained-input experiments', () => {
|
||||
test('deterministic_grid validates every combination, duplicates, unknown/reserved axes and bounded expansion', async () => {
|
||||
const f = await fixture(1);
|
||||
const { preview } = await prepare(f, { slowPeriod: [4, 3], fastPeriod: [1, 2] });
|
||||
const reordered = await f.experiments.preview({
|
||||
...preview.input,
|
||||
grid: { fastPeriod: [1, 2], slowPeriod: [4, 3] },
|
||||
});
|
||||
expect(reordered).toEqual(preview);
|
||||
expect(preview.candidates.map(c => c.parameters)).toEqual([
|
||||
{ fastPeriod: 1, slowPeriod: 4 },
|
||||
{ fastPeriod: 1, slowPeriod: 3 },
|
||||
{ fastPeriod: 2, slowPeriod: 4 },
|
||||
{ fastPeriod: 2, slowPeriod: 3 },
|
||||
]);
|
||||
expect(preview.candidates.map(c => c.index)).toEqual([0, 1, 2, 3]);
|
||||
expect(preview.dataset).toEqual(f.dataset.manifest);
|
||||
expect((await f.experiments.preview({ ...preview.input, grid: {} })).candidates).toHaveLength(
|
||||
1
|
||||
);
|
||||
for (const grid of [
|
||||
{ fastPeriod: [1, 1] },
|
||||
{ fastPeriod: [2, 3] },
|
||||
{ unknown: [1] },
|
||||
{ fastPeriod: [] },
|
||||
{
|
||||
fastPeriod: Array.from({ length: 10 }, (_, i) => i + 1),
|
||||
slowPeriod: Array.from({ length: 11 }, (_, i) => i + 20),
|
||||
},
|
||||
JSON.parse('{"__proto__":[1]}'),
|
||||
{ constructor: [1] },
|
||||
]) {
|
||||
await expect(f.experiments.preview({ ...preview.input, grid })).rejects.toMatchObject({
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
expect(await totals(f)).toEqual({ experiments: 0, runs: 0, dispatch: 0 });
|
||||
});
|
||||
|
||||
test('frozen trials execute real Rust with distinct parameters and exact template/data/policy/build; compact saved summaries reopen', async () => {
|
||||
const f = await fixture(1);
|
||||
const before = await f.api.getBacktest(f.draft.id);
|
||||
const { preview, submission } = await prepare(f, { fastPeriod: [1], slowPeriod: [3, 10] });
|
||||
const experiment = await f.experiments.submit(submission, receipt());
|
||||
expect(experiment.trialCount).toBe(2);
|
||||
expect(experiment.counts.pending).toBe(2);
|
||||
expect(experiment.trials.every(t => !t.comparable && t.metrics === null)).toBe(true);
|
||||
const rows = (await f.pool.query('SELECT * FROM runs ORDER BY trial_index')).rows;
|
||||
for (const row of rows) {
|
||||
expect(row.submission_key).toBeNull();
|
||||
expect(row.original_run_id).toBeNull();
|
||||
expect(row.request_snapshot).toEqual(
|
||||
experimentTrialRequest(preview, preview.candidates[row.trial_index]!, row.id)
|
||||
);
|
||||
await f.execute(row.id);
|
||||
}
|
||||
const detail = await f.experiments.get(experiment.id);
|
||||
expect(detail.counts).toEqual({
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: 2,
|
||||
failed: 0,
|
||||
cancelled: 0,
|
||||
});
|
||||
expect(detail.trials.every(t => t.comparable)).toBe(true);
|
||||
for (const trial of detail.trials) {
|
||||
const result = await f.api.getRunResults(trial.runId!);
|
||||
expect(result && 'kind' in result && result.financialEngine).toBe('rust');
|
||||
if (!result || !('kind' in result)) {
|
||||
throw new Error('Canonical result expected');
|
||||
}
|
||||
expect(trial.metrics).toEqual(result.analytics.metrics);
|
||||
expect(trial.unavailable).toEqual(result.analytics.unavailable);
|
||||
expect(trial.metrics!.alpha).toBeNull();
|
||||
expect(trial.limitations).toEqual([
|
||||
...result.financial.limitations,
|
||||
...result.financial.modelLimitations,
|
||||
]);
|
||||
}
|
||||
expect(detail.trials[0]!.metrics!.totalReturn).not.toEqual(
|
||||
detail.trials[1]!.metrics!.totalReturn
|
||||
);
|
||||
expect(detail.trials[1]!.metrics!.totalReturn).toBe(0);
|
||||
expect(detail.trials[1]!.unavailable!.totalReturn).toBeUndefined();
|
||||
expect(await f.api.getBacktest(f.draft.id)).toEqual(before);
|
||||
expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 });
|
||||
expect((await f.experiments.list(f.draft.id))[0]).toMatchObject({
|
||||
id: experiment.id,
|
||||
trialCount: 2,
|
||||
counts: { completed: 2 },
|
||||
});
|
||||
expect(await f.experiments.list(randomUUID())).toEqual([]);
|
||||
expect(JSON.stringify(detail.trials)).not.toContain('sessionReturns');
|
||||
expect(JSON.stringify(detail.trials)).not.toContain('equity_curve');
|
||||
});
|
||||
|
||||
test('stale preview refuses edits/reviews and accepted receipt survives archive and review changes', async () => {
|
||||
const f = await fixture();
|
||||
const { input, submission } = await prepare(f);
|
||||
await f.api.updateBacktest(f.draft.id, { name: 'Changed template' });
|
||||
await expect(f.experiments.submit(submission, receipt())).rejects.toMatchObject({
|
||||
status: 409,
|
||||
});
|
||||
expect(await totals(f)).toEqual({ experiments: 0, runs: 0, dispatch: 0 });
|
||||
const next = await f.experiments.preview(input);
|
||||
await f.approve();
|
||||
await expect(
|
||||
f.experiments.submit({ ...input, previewHash: next.previewHash }, receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
const current = { ...input, previewHash: (await f.experiments.preview(input)).previewHash };
|
||||
const key = receipt();
|
||||
const accepted = await f.experiments.submit(current, key);
|
||||
await f.catalog.reviewVersion(
|
||||
f.version.id,
|
||||
{ decision: 'revoke', reason: 'No new admissions' },
|
||||
'operator'
|
||||
);
|
||||
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,
|
||||
]);
|
||||
expect((await f.experiments.submit(current, key)).id).toBe(accepted.id);
|
||||
await expect(f.experiments.submit(current, receipt())).rejects.toMatchObject({ status: 409 });
|
||||
await expect(
|
||||
f.experiments.submit({ ...current, name: 'Different' }, key)
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 });
|
||||
});
|
||||
|
||||
test('duplicate_expand_race and cross-parent global receipt conflict admit exactly one atomic batch', async () => {
|
||||
const f = await fixture();
|
||||
const { submission } = await prepare(f);
|
||||
const key = receipt();
|
||||
const [a, b] = await Promise.all([
|
||||
f.experiments.submit(submission, key),
|
||||
f.experiments.submit(submission, key),
|
||||
]);
|
||||
expect(a.id).toBe(b.id);
|
||||
expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 });
|
||||
const other = await f.api.createBacktest(
|
||||
{ ...f.definition, name: 'Other parent' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const input = { ...submission, backtestId: other.id };
|
||||
const otherPreview = await f.experiments.preview({
|
||||
backtestId: other.id,
|
||||
name: submission.name,
|
||||
grid: submission.grid,
|
||||
});
|
||||
input.previewHash = otherPreview.previewHash;
|
||||
const raceKey = receipt();
|
||||
const result = await Promise.allSettled([
|
||||
f.experiments.submit(submission, raceKey),
|
||||
f.experiments.submit(input, raceKey),
|
||||
]);
|
||||
expect(result.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(
|
||||
result
|
||||
.filter(r => r.status === 'rejected')
|
||||
.map(r => (r as PromiseRejectedResult).reason.status)
|
||||
).toEqual([409]);
|
||||
expect(await totals(f)).toEqual({ experiments: 2, runs: 4, dispatch: 4 });
|
||||
});
|
||||
|
||||
test('dispatch insertion failure rolls the manifest, every trial and every outbox entry back', async () => {
|
||||
const f = await fixture();
|
||||
const { submission } = await prepare(f);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION fail_second_dispatch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF (SELECT trial_index FROM runs WHERE id=NEW.run_id)=1 THEN RAISE EXCEPTION 'fixture dispatch failure'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER fixture_dispatch_failure BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION fail_second_dispatch()`);
|
||||
const key = receipt();
|
||||
await expect(f.experiments.submit(submission, key)).rejects.toThrow('fixture dispatch failure');
|
||||
expect(await totals(f)).toEqual({ experiments: 0, runs: 0, dispatch: 0 });
|
||||
await f.pool.query('DROP TRIGGER fixture_dispatch_failure ON backtest_dispatch');
|
||||
expect((await f.experiments.submit(submission, key)).trialCount).toBe(2);
|
||||
});
|
||||
|
||||
test('SQL guards reject manifest/receipt/linkage mutation, direct altered requests and missing identity', async () => {
|
||||
const f = await fixture();
|
||||
const { preview, submission } = await prepare(f);
|
||||
const experiment = await f.experiments.submit(submission, receipt());
|
||||
const id = experiment.trials[0]!.runId!;
|
||||
for (const sql of [
|
||||
"UPDATE research_experiments SET name='changed' WHERE id=$1",
|
||||
"UPDATE research_experiments SET preview_hash=repeat('a',64) WHERE id=$1",
|
||||
"UPDATE research_experiments SET submission_key='other' WHERE id=$1",
|
||||
"UPDATE research_experiments SET preview=preview-'candidates' WHERE id=$1",
|
||||
'DELETE FROM research_experiments WHERE id=$1',
|
||||
]) {
|
||||
await expect(f.pool.query(sql, [experiment.id])).rejects.toMatchObject({ code: '23514' });
|
||||
}
|
||||
await expect(f.pool.query('TRUNCATE research_experiments CASCADE')).rejects.toMatchObject({
|
||||
code: '23514',
|
||||
});
|
||||
for (const assignment of [
|
||||
'experiment_id=NULL',
|
||||
'trial_index=4',
|
||||
"trial_key=repeat('a',64)",
|
||||
"request_snapshot=request_snapshot-'policy'",
|
||||
]) {
|
||||
await expect(
|
||||
f.pool.query(`UPDATE runs SET ${assignment} WHERE id=$1`, [id])
|
||||
).rejects.toMatchObject({ code: '23514' });
|
||||
}
|
||||
for (const changes of [
|
||||
{ index: 99 },
|
||||
{ key: 'a'.repeat(64) },
|
||||
{ dataset: 'a'.repeat(64) },
|
||||
{ original: id },
|
||||
{ principal: 'operator', receiptKey: 'key', hash: 'a'.repeat(64) },
|
||||
{ request: { ...preview.request, name: 'changed' } },
|
||||
{ request: null },
|
||||
{ backtest: randomUUID() },
|
||||
{ experiment: null },
|
||||
]) {
|
||||
await expect(rawTrial(f, experiment, changes)).rejects.toBeDefined();
|
||||
}
|
||||
for (const mutate of [
|
||||
(p: typeof preview) => {
|
||||
delete (p.request as unknown as Record<string, unknown>).build;
|
||||
},
|
||||
(p: typeof preview) => {
|
||||
p.candidates[0]!.parameters = {};
|
||||
},
|
||||
(p: typeof preview) => {
|
||||
p.request.policy.matching.risk.feeRate =
|
||||
'0.00000000' as typeof p.request.policy.matching.risk.feeRate;
|
||||
},
|
||||
]) {
|
||||
const altered = structuredClone(preview);
|
||||
mutate(altered);
|
||||
await expect(
|
||||
f.pool.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash)
|
||||
VALUES($1,$2,$3,$4,$5,'operator',$6,$7)`,
|
||||
[
|
||||
randomUUID(),
|
||||
f.draft.id,
|
||||
preview.input.name,
|
||||
altered,
|
||||
preview.previewHash,
|
||||
randomUUID(),
|
||||
'a'.repeat(64),
|
||||
]
|
||||
)
|
||||
).rejects.toBeDefined();
|
||||
}
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/22-experiments.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
expect((await f.experiments.get(experiment.id)).preview).toEqual(preview);
|
||||
});
|
||||
|
||||
test('cancel_batch is idempotent, preserves completed results and fences running/paused completion and pending claims', async () => {
|
||||
const f = await fixture();
|
||||
const { submission } = await prepare(f, { fastPeriod: [1, 2], slowPeriod: [3, 4] });
|
||||
const experiment = await f.experiments.submit(submission, receipt());
|
||||
await f.execute(experiment.trials[0]!.runId!);
|
||||
const completedBefore = await f.api.getRunResults(experiment.trials[0]!.runId!);
|
||||
const requests = (
|
||||
await f.pool.query(
|
||||
'SELECT request_snapshot FROM runs WHERE experiment_id=$1 ORDER BY trial_index',
|
||||
[experiment.id]
|
||||
)
|
||||
).rows.map(r => r.request_snapshot as CanonicalRunRequest);
|
||||
const active = await f.repository.startCanonical(requests[1]!);
|
||||
await f.repository.startCanonical(requests[2]!);
|
||||
await f.pool.query("UPDATE runs SET status='paused' WHERE id=$1", [requests[2]!.runId]);
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Provider access forbidden');
|
||||
},
|
||||
},
|
||||
});
|
||||
let computed;
|
||||
try {
|
||||
computed = await engine.runCanonical(requests[1]!, async () => f.dataset);
|
||||
} finally {
|
||||
await engine.shutdown();
|
||||
}
|
||||
const result: CanonicalRunResult = {
|
||||
kind: 'canonical-result/v1',
|
||||
runId: active.runId,
|
||||
backtestId: f.draft.id,
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
executionTime: 0,
|
||||
financialEngine: 'rust',
|
||||
strategyExecution: 'typescript-retained-builtin/v1',
|
||||
request: requests[1]!,
|
||||
...computed,
|
||||
};
|
||||
const cancelled = await f.experiments.cancel(experiment.id);
|
||||
expect(cancelled.counts).toEqual({
|
||||
pending: 0,
|
||||
running: 1,
|
||||
paused: 1,
|
||||
completed: 1,
|
||||
failed: 0,
|
||||
cancelled: 1,
|
||||
});
|
||||
expect(cancelled.trials.map(t => t.cancelRequested)).toEqual([false, true, true, true]);
|
||||
expect(await f.experiments.cancel(experiment.id)).toEqual(cancelled);
|
||||
await expect(f.repository.completeCanonical(result, active.attemptId)).rejects.toThrow(
|
||||
'Backtest cancelled'
|
||||
);
|
||||
expect(
|
||||
(await f.pool.query('SELECT 1 FROM backtest_results WHERE run_id=$1', [active.runId])).rows
|
||||
).toHaveLength(0);
|
||||
await f.repository.cancel(active.runId, active.attemptId);
|
||||
expect((await f.experiments.get(experiment.id)).trials[1]!.status).toBe('cancelled');
|
||||
await expect(f.repository.startCanonical(requests[3]!)).rejects.toThrow();
|
||||
await expect(
|
||||
f.repository.loadCanonicalDataset(active.runId, active.attemptId, requests[1]!.datasetHash)
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
f.pool.query('UPDATE research_experiments SET cancel_requested=FALSE WHERE id=$1', [
|
||||
experiment.id,
|
||||
])
|
||||
).rejects.toMatchObject({ code: '23514' });
|
||||
await expect(rawTrial(f, experiment)).rejects.toMatchObject({ code: '23514' });
|
||||
expect(await f.api.getRunResults(experiment.trials[0]!.runId!)).toEqual(completedBefore);
|
||||
// A claim racing cancellation either loses admission or becomes a cancel-requested active run.
|
||||
const fresh = await f.experiments.submit(submission, receipt());
|
||||
const request = (
|
||||
await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [fresh.trials[0]!.runId])
|
||||
).rows[0].request_snapshot;
|
||||
await Promise.allSettled([
|
||||
f.repository.startCanonical(request),
|
||||
f.experiments.cancel(fresh.id),
|
||||
]);
|
||||
const raced = (await f.experiments.get(fresh.id)).trials[0]!;
|
||||
expect(['running', 'cancelled']).toContain(raced.status);
|
||||
expect(raced.cancelRequested).toBe(true);
|
||||
});
|
||||
|
||||
test('missing/null/failed/incomparable outcomes remain visible and summaries select no full result or financial arrays', async () => {
|
||||
const f = await fixture();
|
||||
const { submission } = await prepare(f, { fastPeriod: [1, 2], slowPeriod: [3, 4] });
|
||||
const experiment = await f.experiments.submit(submission, receipt());
|
||||
await f.execute(experiment.trials[0]!.runId!);
|
||||
await f.pool.query("UPDATE runs SET status='failed',error='fixture failure' WHERE id=$1", [
|
||||
experiment.trials[1]!.runId,
|
||||
]);
|
||||
// Deliberate corruption is restricted to this disposable schema and verifies fail-closed reads.
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
const originalResult = (
|
||||
await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [
|
||||
experiment.trials[0]!.runId,
|
||||
])
|
||||
).rows[0].canonical_result;
|
||||
for (const [path, value] of [
|
||||
['{analytics,version}', 2],
|
||||
['{analytics,policy,sampling}', 'unsupported'],
|
||||
['{analytics,policy,variance}', 'population'],
|
||||
['{financial,policy,matching,risk,feeRate}', '0.00000000'],
|
||||
['{financial,identity,datasetHash}', 'a'.repeat(64)],
|
||||
['{analytics,metrics,totalReturn}', null],
|
||||
]) {
|
||||
await f.pool.query(
|
||||
'UPDATE backtest_results SET canonical_result=jsonb_set($1::jsonb,$2::text[],$3::jsonb) WHERE run_id=$4',
|
||||
[originalResult, path, JSON.stringify(value), experiment.trials[0]!.runId]
|
||||
);
|
||||
const trial = (await f.experiments.get(experiment.id)).trials[0]!;
|
||||
expect(trial.comparable).toBe(false);
|
||||
expect(trial.metrics).toBeNull();
|
||||
expect(trial.diagnostic).not.toBeNull();
|
||||
}
|
||||
await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [
|
||||
originalResult,
|
||||
experiment.trials[0]!.runId,
|
||||
]);
|
||||
await f.pool.query(
|
||||
`UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,policy,periodsPerYear}','1') WHERE run_id=$1`,
|
||||
[experiment.trials[0]!.runId]
|
||||
);
|
||||
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
|
||||
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER ALL');
|
||||
await f.pool.query('ALTER TABLE backtest_dispatch DISABLE TRIGGER ALL');
|
||||
await f.pool.query('DELETE FROM backtest_dispatch WHERE run_id=$1', [
|
||||
experiment.trials[3]!.runId,
|
||||
]);
|
||||
await f.pool.query('DELETE FROM runs WHERE id=$1', [experiment.trials[3]!.runId]);
|
||||
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER ALL');
|
||||
await f.pool.query('ALTER TABLE backtest_dispatch ENABLE TRIGGER ALL');
|
||||
const detail = await f.experiments.get(experiment.id);
|
||||
expect(detail.trialCount).toBe(4);
|
||||
expect(detail.trials.map(t => t.status)).toEqual(['completed', 'failed', 'pending', 'missing']);
|
||||
expect(detail.trials.every(t => t.metrics === null && !t.comparable)).toBe(true);
|
||||
expect(detail.trials[1]!.error).toBe('fixture failure');
|
||||
expect(detail.trials[3]!.runId).toBeNull();
|
||||
const source = readFileSync(
|
||||
new URL('../../apps/stock/web-api/src/services/experiments.service.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const projection = source.slice(
|
||||
source.indexOf('SELECT r.id'),
|
||||
source.indexOf('ORDER BY r.trial_index')
|
||||
);
|
||||
expect(projection).not.toMatch(/canonical_result\s*(?:,|AS\s+\w+)/i);
|
||||
expect(projection).not.toContain("->'financial'");
|
||||
expect(projection).not.toContain('sessionReturns');
|
||||
});
|
||||
|
||||
test('current original-family archive lock serializes preview and new admission without rewriting accepted receipts', async () => {
|
||||
const f = await fixture();
|
||||
const { input, submission } = await prepare(f);
|
||||
const key = receipt();
|
||||
const accepted = await f.experiments.submit(submission, key);
|
||||
const blocker = await f.pool.connect();
|
||||
let pending: Promise<unknown> | undefined;
|
||||
try {
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
pending = f.experiments.preview(input).then(
|
||||
value => ({ value }),
|
||||
error => ({ error })
|
||||
);
|
||||
let waiting = false;
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
const rows = (
|
||||
await f.pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
|
||||
[f.schema]
|
||||
)
|
||||
).rows;
|
||||
if (rows.length) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
await blocker.query('COMMIT');
|
||||
expect(await pending).toMatchObject({ error: { status: 409 } });
|
||||
} finally {
|
||||
await blocker.query('ROLLBACK');
|
||||
blocker.release();
|
||||
await pending;
|
||||
}
|
||||
await expect(f.experiments.submit(submission, receipt())).rejects.toMatchObject({
|
||||
status: 409,
|
||||
});
|
||||
expect((await f.experiments.submit(submission, key)).id).toBe(accepted.id);
|
||||
expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 });
|
||||
});
|
||||
|
||||
test('first SQL22 upgrade preserves ordinary and reproduction snapshots, receipts, leases and results', async () => {
|
||||
const f = await fixture(4, false);
|
||||
await f.approve();
|
||||
const original = await f.api.createRun({ backtestId: f.draft.id }, receipt());
|
||||
await f.execute(original.id);
|
||||
const reproduction = await f.api.reproduceRun(original.id, receipt());
|
||||
const leased = await f.api.createRun({ backtestId: f.draft.id }, receipt());
|
||||
await f.repository.startCanonical(
|
||||
(await f.repository.load(leased.id))!.config as CanonicalRunRequest
|
||||
);
|
||||
const before = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows;
|
||||
const results = (await f.pool.query('SELECT * FROM backtest_results')).rows;
|
||||
const outbox = (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows;
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/22-experiments.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
const after = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows;
|
||||
expect(
|
||||
after.map(
|
||||
({
|
||||
experiment_id: _experimentId,
|
||||
trial_key: _trialKey,
|
||||
trial_index: _trialIndex,
|
||||
...row
|
||||
}) => row
|
||||
)
|
||||
).toEqual(before);
|
||||
expect(
|
||||
after.every(r => r.experiment_id === null && r.trial_key === null && r.trial_index === null)
|
||||
).toBe(true);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_results')).rows).toEqual(results);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows).toEqual(
|
||||
outbox
|
||||
);
|
||||
await f.execute(reproduction.id);
|
||||
expect((await f.api.getReproductionComparison(reproduction.id)).status).toBe('match');
|
||||
const ordinary = await f.api.createRun({ backtestId: f.draft.id }, receipt());
|
||||
expect(ordinary.status).toBe('pending');
|
||||
const input = { backtestId: f.draft.id, name: 'After upgrade', grid: {} };
|
||||
const preview = await f.experiments.preview(input);
|
||||
expect(
|
||||
(await f.experiments.submit({ ...input, previewHash: preview.previewHash }, receipt()))
|
||||
.trialCount
|
||||
).toBe(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -24,6 +24,7 @@ const migrations = [
|
|||
'19-canonical-research.sql',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -26,7 +26,8 @@ const retention =
|
|||
'\n' +
|
||||
sql('19-canonical-research.sql') +
|
||||
'\n' +
|
||||
sql('21-run-reproduction.sql');
|
||||
sql('21-run-reproduction.sql') +
|
||||
sql('22-experiments.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ async function fixture() {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ async function fixture(poolMax = 4, withReproduction = true) {
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
...(withReproduction ? ['21-run-reproduction.sql'] : []),
|
||||
...(withReproduction ? ['21-run-reproduction.sql', '22-experiments.sql'] : []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue