feat(research): run retained strategies through durable canonical engine

This commit is contained in:
Boki 2026-10-23 21:59:09 -04:00
parent d929db707a
commit 618fb9e33c
58 changed files with 6596 additions and 779 deletions

View file

@ -1,6 +1,13 @@
import { createHash, randomUUID } from 'node:crypto';
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { chromium, type Browser, type Request } from 'playwright';
import {
canonicalResearchSettingsSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
import {
fixture as createFixture,
createInBrowser,
@ -537,7 +544,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(
f.page,
'Parameters validated for this immutable version. Execution remains unavailable.'
'Parameters validated for this immutable version. Execution eligibility depends on the saved dataset, policy and reviewed executable.'
);
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).click();
await f.page.waitForURL(
@ -561,7 +568,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(
f.page,
'Parameters validated for this immutable version. Execution remains unavailable.'
'Parameters validated for this immutable version. Execution eligibility depends on the saved dataset, policy and reviewed executable.'
);
expect(
await f.page.getByRole('button', { name: 'Save and run', exact: true }).isDisabled()
@ -608,7 +615,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(
f.page,
'Parameters validated for this immutable version. Execution remains unavailable.'
'Parameters validated for this immutable version. Execution eligibility depends on the saved dataset, policy and reviewed executable.'
);
};
const saveVisibleSettings = async () => {
@ -701,3 +708,206 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
await f.close();
}
});
test('browser_approved_canonical_strategy_setup_run_and_reopen', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
const oracle = canonicalSmaFixture();
const retained = await retainResearchDataset(f.pool, oracle.dataset);
const seeded = await f.seedCatalog();
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
expect(selected.reviewStatus).toBe('pending');
await f.login();
await f.page.goto(`${f.origin}/strategies/${selected.strategyId}/versions/${selected.id}`);
// Approval is an authenticated human review of an immutable built-in, not a run bypass.
await f.page
.getByLabel('Review reason', { exact: true })
.fill('Reviewed retained SMA fixture and next-open oracle.');
const approval = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/strategy-versions/${selected.id}/reviews`)
);
await f.page.getByRole('button', { name: 'Approve built-in version', exact: true }).click();
expect((await approval).status()).toBe(201);
await visible(f.page, /This immutable built-in version has an approval record/);
await f.page.getByLabel('fastPeriod', { exact: true }).fill('2');
await f.page.getByLabel('slowPeriod', { exact: true }).fill('3');
const validate = async () => {
const response = f.page.waitForResponse(
reply =>
reply.request().method() === 'POST' &&
reply.url().endsWith(`/strategy-versions/${selected.id}/validate`)
);
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
expect((await response).status()).toBe(200);
await visible(f.page, /Parameters validated for this immutable version/);
};
await validate();
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).click();
await f.page.waitForURL(
url =>
url.pathname === '/backtests' && url.searchParams.get('strategyVersionId') === selected.id
);
await f.page.getByPlaceholder('My Strategy Backtest').fill('Reviewed canonical browser oracle');
await until(
async () =>
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
selected.id,
'canonical draft immutable version'
);
await f.page.locator('input[type="date"]').nth(0).fill('2024-01-01');
await f.page.locator('input[type="date"]').nth(1).fill('2024-01-02');
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('3');
await validate();
expect(
await f.page.getByRole('button', { name: 'Save and run', exact: true }).isDisabled()
).toBe(true);
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
await f.page.waitForURL(/\/backtests\/[^/?]+$/);
const backtestId = f.page.url().split('/').at(-1)!;
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
true
);
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
await f.page.getByRole('button', { name: 'Configure canonical research', exact: true }).click();
await f.page.getByLabel('Canonical dataset', { exact: true }).selectOption(retained.hash);
await visible(f.page, new Date(retained.bounds.tradeStart).toISOString());
await visible(f.page, new Date(retained.bounds.tradeEnd).toISOString());
await f.page.getByLabel('Initial capital (USD)', { exact: true }).fill('10000');
const policyFields = [
['Owner budget', canonicalSettings.ownerBudget],
['Fee rate', canonicalSettings.feeRate],
['Half-spread rate', canonicalSettings.halfSpreadRate],
['Slippage rate', canonicalSettings.slippageRate],
['Volume participation rate', canonicalSettings.participationRate],
['Order latency (ms)', canonicalSettings.latencyMs],
['Maximum order quantity', canonicalSettings.maxOrderQuantity],
['Maximum position quantity', canonicalSettings.maxPositionQuantity],
['Maximum asset exposure', canonicalSettings.maxSymbolExposure],
['Maximum gross exposure', canonicalSettings.maxGrossExposure],
['Maximum risk-period loss', canonicalSettings.maxDailyLoss],
['Maximum drawdown amount', canonicalSettings.maxDrawdownAmount],
['Maximum mark age (ms)', canonicalSettings.maxMarkAgeMs],
['Random seed', canonicalSettings.seed],
['Reporting periods per year', canonicalSettings.periodsPerYear],
['Annual risk-free rate', canonicalSettings.annualRiskFreeRate],
] as const;
for (const [label, value] of policyFields) {
await f.page.getByLabel(label, { exact: true }).fill(value === null ? '' : String(value));
}
await until(
async () =>
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
selected.id,
'canonical setup immutable version'
);
await validate();
const saving = f.page.waitForResponse(
response =>
response.request().method() === 'PUT' && response.url().endsWith(`/backtests/${backtestId}`)
);
await f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).click();
const savedResponse = await saving;
expect(savedResponse.status()).toBe(200);
const sent = savedResponse.request().postDataJSON();
expect(sent.config).toEqual({
datasetHash: retained.hash,
dataFrequency: '1m',
canonical: canonicalResearchSettingsSchema.parse(canonicalSettings),
});
expect(sent.symbols).toEqual(['X0.US']);
expect(sent.initialCapital).toBe(10000);
expect(sent.startDate).toBe(new Date(retained.bounds.tradeStart).toISOString());
expect(sent.endDate).toBe(new Date(retained.bounds.tradeEnd).toISOString());
expect(sent.strategyVersionId).toBe(selected.id);
expect(sent.strategyParameters).toEqual({ fastPeriod: 2, slowPeriod: 3 });
await visible(f.page, /Canonical execution is available for this saved configuration/);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
const accepted = await submitInBrowser(f.page);
expect(accepted.status()).toBe(202);
expect(accepted.request().postDataJSON()).toEqual({ speedMultiplier: null });
const run = await accepted.json();
const admitted = (
await f.pool.query('SELECT request_snapshot,dataset_hash FROM runs WHERE id=$1', [run.id])
).rows[0];
expect(admitted.dataset_hash).toBe(retained.hash);
expect(admitted.request_snapshot.kind).toBe('canonical-research/v1');
expect(admitted.request_snapshot.strategy.versionId).toBe(selected.id);
expect(admitted.request_snapshot.strategy.selection.parameters).toEqual({
fastPeriod: 2,
slowPeriod: 3,
});
expect(admitted.request_snapshot.strategy.package.artifact.sha256).toBe(
selected.package.artifact.sha256
);
await visible(f.page, 'Pending');
f.dispatcher.start();
await visible(f.page, 'Canonical research result');
await visible(f.page, 'Completed');
const result = (await f.request(`/api/v2/runs/${run.id}/results`)) as CanonicalRunResult;
expect(result.kind).toBe('canonical-result/v1');
expect(result.request).toEqual(admitted.request_snapshot);
expect(result.financialEngine).toBe('rust');
expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000');
expect(String(result.financial.projection.valuation.fees)).toBe('0.70000000');
expect(
result.financial.projection.fills.map(fill => [
fill.side,
String(fill.quantity),
String(fill.price),
String(fill.fee.amount),
])
).toEqual([
['buy', '10.00000000', '5.00000000', '0.50000000'],
['sell', '10.00000000', '2.00000000', '0.20000000'],
]);
expect(result.analytics.metrics.roundTripCount).toBeNull();
await visible(f.page, '9969.30000000');
await visible(f.page, 'Unavailable — unsupported round trips');
const provenance = f.page.getByRole('region', {
name: 'Canonical result provenance',
exact: true,
});
expect(await provenance.textContent()).toContain(selected.id);
expect(await provenance.textContent()).toContain(retained.hash);
expect(await provenance.textContent()).toContain(selected.package.artifact.sha256);
expect(await provenance.textContent()).toContain(result.request.build.engineBinarySha256);
expect(
await f.page.getByText('Research only · Unverified economics', { exact: true }).count()
).toBe(0);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'Canonical fills (2)');
expect(await f.page.locator('tbody tr').count()).toBe(2);
await visible(f.page, '0.50000000');
await visible(f.page, '0.20000000');
const completedUrl = f.page.url();
await f.page.reload();
await visible(f.page, 'Canonical research result');
await visible(f.page, '9969.30000000');
expect(f.page.url()).toBe(completedUrl);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'Canonical fills (2)');
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
const stored = (
await f.pool.query(
'SELECT canonical_result,metrics,trades FROM backtest_results WHERE run_id=$1',
[run.id]
)
).rows[0];
expect(stored.canonical_result).toEqual(result);
expect(stored.metrics).toBeNull();
expect(stored.trades).toBeNull();
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});