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
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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue