feat(research): cut over canonical runtime and enforce agent budgets
This commit is contained in:
parent
ab08db82fd
commit
bbf0dd4453
103 changed files with 6138 additions and 3112 deletions
|
|
@ -10,15 +10,13 @@ import type { IServiceContainer } from '@stock-bot/handlers';
|
|||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { Queue } from '@stock-bot/queue';
|
||||
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import type { NativeBacktestResult } from '../../apps/stock/orchestrator/src/backtest/native-result';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import {
|
||||
loadDataset,
|
||||
type DatasetResolver,
|
||||
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import type { BacktestConfig } from '../../apps/stock/orchestrator/src/types';
|
||||
import {
|
||||
|
|
@ -30,6 +28,7 @@ import {
|
|||
handleWebSocketConnection,
|
||||
} from '../../apps/stock/web-api/src/routes/websocket.routes';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import {
|
||||
getWebSocketHandler,
|
||||
|
|
@ -139,23 +138,26 @@ export async function retainDataset(pool: Pool, overrides: Partial<BacktestConfi
|
|||
return dataset;
|
||||
}
|
||||
|
||||
/** Fixed UI lifecycle data, NOT a financial simulator or correctness oracle. */
|
||||
/** Controlled lifecycle around the real canonical engine; no fixture accounting. */
|
||||
class FixtureEngine extends EventEmitter {
|
||||
completion = gate();
|
||||
cancellation = gate();
|
||||
stopped = gate();
|
||||
mode: 'trades' | 'empty' | 'fail' = 'trades';
|
||||
private cancelled = false;
|
||||
async runBacktest(
|
||||
config: BacktestConfig,
|
||||
resolver?: DatasetResolver
|
||||
): Promise<NativeBacktestResult> {
|
||||
if (!resolver) {
|
||||
throw new Error('Fixture must exercise durable dataset resolution');
|
||||
}
|
||||
const dataset = await resolver(() => loadDataset(storage, config));
|
||||
private readonly engine = new RustBacktestAdapter({ logger, storage }, { timeoutMs: 15000 });
|
||||
async runBacktest(): Promise<never> {
|
||||
throw new Error('Legacy execution is retired');
|
||||
}
|
||||
async runCanonical(
|
||||
request: CanonicalRunRequest,
|
||||
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
|
||||
) {
|
||||
this.cancelled = false;
|
||||
this.emit('progress', { progress: 25, currentDate: config.startDate });
|
||||
this.emit('progress', {
|
||||
progress: 25,
|
||||
currentDate: new Date(request.policy.matching.risk.ledger.riskSession.startsAt).toISOString(),
|
||||
});
|
||||
await this.completion.promise;
|
||||
if (this.cancelled) {
|
||||
throw new BacktestCancelledError();
|
||||
|
|
@ -163,53 +165,14 @@ class FixtureEngine extends EventEmitter {
|
|||
if (this.mode === 'fail') {
|
||||
throw new Error('Injected fixture worker failure');
|
||||
}
|
||||
return {
|
||||
backtestId: config.backtestId!,
|
||||
status: 'completed',
|
||||
completedAt: '2024-03-15T00:00:00.000Z',
|
||||
config: {
|
||||
name: config.name!,
|
||||
symbols: config.symbols,
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: config.initialCapital,
|
||||
},
|
||||
metrics: {
|
||||
totalReturn: 0,
|
||||
sharpeRatio: 0,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
totalTrades: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
},
|
||||
equity: [{ date: config.startDate, value: config.initialCapital }],
|
||||
trades:
|
||||
this.mode === 'empty'
|
||||
? []
|
||||
: [
|
||||
{
|
||||
id: 'fixture-fill',
|
||||
symbol: config.symbols[0]!,
|
||||
timestamp: config.startDate,
|
||||
side: 'buy',
|
||||
price: 100,
|
||||
quantity: 3,
|
||||
commission: 0,
|
||||
positionAfter: 3,
|
||||
},
|
||||
],
|
||||
positions: [],
|
||||
analytics: { exposureTime: 0 },
|
||||
executionTime: 0,
|
||||
ohlcData: Object.fromEntries(
|
||||
config.symbols.map(symbol => [symbol, dataset.bars.filter(bar => bar.symbol === symbol)])
|
||||
),
|
||||
};
|
||||
// Empty outcomes use an admitted strategy with insufficient warmup; never edit the result.
|
||||
return this.engine.runCanonical(request, resolveDataset);
|
||||
}
|
||||
async stopBacktest() {
|
||||
this.cancelled = true;
|
||||
if (this.engine.getStatus().isRunning) {
|
||||
await this.engine.stopBacktest();
|
||||
}
|
||||
this.stopped.resolve();
|
||||
await this.cancellation.promise;
|
||||
this.completion.resolve();
|
||||
|
|
@ -227,6 +190,7 @@ class FixtureEngine extends EventEmitter {
|
|||
async shutdown() {
|
||||
this.cancellation.resolve();
|
||||
this.completion.resolve();
|
||||
await this.engine.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -313,6 +277,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
'27-research-evidence-sources.sql',
|
||||
'28-research-agents.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -435,6 +400,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
},
|
||||
} as unknown as NonNullable<IServiceContainer['mongodb']>;
|
||||
const container = { postgres, mongodb, logger } as IServiceContainer;
|
||||
const researchAgents = new ResearchAgentsService(container);
|
||||
const token = randomUUID() + randomUUID();
|
||||
const security = createHttpSecurity({
|
||||
adminToken: token,
|
||||
|
|
@ -442,6 +408,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
browserSessions: true,
|
||||
environment: 'test',
|
||||
origins: [],
|
||||
resolveResearchCredential: request => researchAgents.authenticate(request),
|
||||
});
|
||||
const routes = createRoutes(container, security);
|
||||
const wsRoute = createWebSocketRoute(container, security);
|
||||
|
|
@ -476,6 +443,8 @@ 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/research-agents') &&
|
||||
!pathname.startsWith('/api/v2/research-agent/') &&
|
||||
!pathname.startsWith('/api/v2/experiments') &&
|
||||
!pathname.startsWith('/api/v2/hypotheses/') &&
|
||||
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
|
||||
|
|
@ -657,16 +626,6 @@ export async function fixture(browser: Browser, native = false) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function createInBrowser(page: Page, name: string, run = false) {
|
||||
await page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
||||
await page.getByPlaceholder('My Strategy Backtest').fill(name);
|
||||
await page.getByLabel('Legacy strategy', { exact: true }).selectOption('moving-average');
|
||||
await page.locator('input[type="date"]').nth(0).fill('2024-01-01');
|
||||
await page.locator('input[type="date"]').nth(1).fill('2024-03-15');
|
||||
await page.getByRole('button', { name: run ? 'Save and run' : 'Save', exact: true }).click();
|
||||
await page.waitForURL(run ? /\/backtests\/[^/]+\/run\/[^/]+$/ : /\/backtests\/[^/]+$/);
|
||||
}
|
||||
|
||||
export async function submitInBrowser(page: Page) {
|
||||
await page.getByRole('button', { name: 'New Run', exact: true }).click();
|
||||
const response = page.waitForResponse(
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import type {
|
|||
ExperimentRetryResult,
|
||||
ExperimentTrialRetry,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import type { ResearchAgentRecord } from '@stock-bot/stock-config/research-agents';
|
||||
import type {
|
||||
WalkForwardActionResult,
|
||||
WalkForwardDetail,
|
||||
|
|
@ -43,7 +44,6 @@ import { chronologicalDataset } from '../fixtures/chronological-validation';
|
|||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
import {
|
||||
fixture as createFixture,
|
||||
createInBrowser,
|
||||
gate,
|
||||
retainDataset,
|
||||
submitInBrowser,
|
||||
|
|
@ -63,6 +63,174 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
test('operator_provisions_bounded_agent_views_usage_and_revokes_without_corrupting_accepted_work_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
try {
|
||||
await f.login();
|
||||
const { id: backtestId } = await createCanonicalInBrowser(f, 'Agent baseline');
|
||||
const { project } = await f.request('/api/v2/research-projects', 'POST', {
|
||||
title: 'Agent research',
|
||||
});
|
||||
await f.page.goto(`${f.origin}/research/agents?projectId=${project.id}`);
|
||||
await visible(f.page, 'No research agents configured.');
|
||||
await f.page.getByLabel('Agent name', { exact: true }).fill('Bounded browser researcher');
|
||||
await f.page.getByLabel('Allowed backtest IDs', { exact: true }).fill(backtestId);
|
||||
await f.page.getByLabel('Maximum active trials', { exact: true }).fill('1');
|
||||
await f.page.getByLabel('Maximum trials per experiment', { exact: true }).fill('2');
|
||||
await f.page.getByLabel('Maximum attempt time (ms)', { exact: true }).fill('30000');
|
||||
const creating = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' && response.url().endsWith('/api/v2/research-agents')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Create credential', exact: true }).click();
|
||||
const response = await creating;
|
||||
expect(response.status()).toBe(201);
|
||||
const created = (await response.json()) as { agent: ResearchAgentRecord; token: string };
|
||||
expect(await f.page.getByLabel('New research token', { exact: true }).inputValue()).toBe(
|
||||
created.token
|
||||
);
|
||||
expect(created.agent.allowedProjectIds).toEqual([project.id]);
|
||||
expect(created.agent.grants.map(grant => grant.backtestId)).toEqual([backtestId]);
|
||||
const agentRequest = (path: string, method = 'GET', body?: unknown, key?: string) =>
|
||||
fetch(`${f.origin}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${created.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
...(key ? { 'Idempotency-Key': key } : {}),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const hypothesis = await agentRequest(
|
||||
`/api/v2/research-projects/${project.id}/hypotheses`,
|
||||
'POST',
|
||||
{
|
||||
title: 'Agent proposal awaiting validation',
|
||||
proposition: 'A controlled hypothesis, not proof of profitability.',
|
||||
contentOrigin: 'ai',
|
||||
}
|
||||
);
|
||||
expect(hypothesis.status).toBe(201);
|
||||
expect(JSON.stringify(await hypothesis.json())).toContain(created.agent.id);
|
||||
const input = {
|
||||
backtestId,
|
||||
name: 'Bounded existing strategy experiment',
|
||||
grid: { fastPeriod: [2] },
|
||||
};
|
||||
const previewResponse = await agentRequest('/api/v2/experiments/preview', 'POST', input);
|
||||
expect(previewResponse.status).toBe(200);
|
||||
const { preview } = (await previewResponse.json()) as { preview: ExperimentPreview };
|
||||
const body = { ...input, previewHash: preview.previewHash };
|
||||
const accepted = await agentRequest('/api/v2/experiments', 'POST', body, randomUUID());
|
||||
expect(accepted.status).toBe(202);
|
||||
const { experiment } = (await accepted.json()) as { experiment: ExperimentDetail };
|
||||
expect((await agentRequest('/api/v2/experiments', 'POST', body, randomUUID())).status).toBe(
|
||||
429
|
||||
);
|
||||
expect(
|
||||
(await agentRequest(`/api/v2/backtests/${backtestId}`, 'PUT', { initialCapital: 999999 }))
|
||||
.status
|
||||
).toBe(403);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
||||
const row = (
|
||||
await f.pool.query('SELECT * FROM research_agents WHERE id=$1', [created.agent.id])
|
||||
).rows[0];
|
||||
expect(JSON.stringify(row)).not.toContain(created.token);
|
||||
await f.page.getByRole('button', { name: 'I have saved the credential', exact: true }).click();
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Check budget for Bounded browser researcher', exact: true })
|
||||
.click();
|
||||
await visible(f.page, 'Active trials: 1; available slots: 0');
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Disable Bounded browser researcher', exact: true })
|
||||
.click();
|
||||
await visible(f.page, /Disabled · Revision 2/);
|
||||
expect((await agentRequest('/api/v2/research-agent/budget')).status).toBe(401);
|
||||
// Revocation denies new access. Previously accepted bounded work retains its frozen owner/budget.
|
||||
f.dispatcher.start();
|
||||
const trial = experiment.trials[0];
|
||||
if (!trial?.runId) {
|
||||
throw new Error('Expected admitted agent trial');
|
||||
}
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query('SELECT status FROM runs WHERE id=$1', [trial.runId])).rows[0]
|
||||
?.status === 'completed',
|
||||
'accepted agent trial completes on canonical Rust'
|
||||
);
|
||||
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
|
||||
expect(result.financialEngine).toBe('rust');
|
||||
expect(result.request).toMatchObject({
|
||||
datasetHash: preview.request.datasetHash,
|
||||
strategy: { versionId: preview.request.strategy.versionId },
|
||||
});
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Check budget for Bounded browser researcher', exact: true })
|
||||
.click();
|
||||
await visible(f.page, 'Active trials: 0; available slots: 1');
|
||||
await f.page.reload();
|
||||
await visible(f.page, /Disabled · Revision 2/);
|
||||
expect(await f.page.getByLabel('New research token', { exact: true }).count()).toBe(0);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
/** Lifecycle tests create via the real catalog UI; policy setup is seeded through
|
||||
* the same public API. The full setup UI is exercised by the research workflow below. */
|
||||
async function createCanonicalInBrowser(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
name: string,
|
||||
run = false
|
||||
) {
|
||||
const { dataset } = canonicalSmaFixture();
|
||||
await retainResearchDataset(f.pool, dataset);
|
||||
const version = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
if (version.reviewStatus !== 'approved') {
|
||||
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed canonical lifecycle fixture',
|
||||
});
|
||||
}
|
||||
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
||||
await f.page.getByPlaceholder('My Strategy Backtest').fill(name);
|
||||
await f.page.getByLabel('Strategy family', { exact: true }).selectOption(version.strategyId);
|
||||
await f.page.getByLabel('Immutable strategy version', { exact: true }).selectOption(version.id);
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(f.page, /Parameters validated/);
|
||||
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 id = f.page.url().split('/').at(-1)!;
|
||||
await f.request(`/api/v2/backtests/${id}`, 'PUT', {
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: f.controlled.mode === 'empty' ? 100 : 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: '1m',
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
});
|
||||
await f.page.reload();
|
||||
await visible(f.page, /Canonical execution is available/);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
if (run) {
|
||||
await submitInBrowser(f.page);
|
||||
}
|
||||
return { id, dataset, version };
|
||||
}
|
||||
|
||||
/** Uses real retained native measurements, then reopens the exact source from immutable history. */
|
||||
async function saveSourceFindingInBrowser(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
|
|
@ -1438,14 +1606,16 @@ test('browser_saved_run_lifecycle', async () => {
|
|||
try {
|
||||
await f.login();
|
||||
expect(await f.page.locator('tbody tr').count()).toBe(0);
|
||||
await createInBrowser(f.page, 'Saved browser lifecycle');
|
||||
const { dataset } = await createCanonicalInBrowser(f, 'Saved browser lifecycle');
|
||||
const definition = (await f.pool.query('SELECT * FROM backtests')).rows[0];
|
||||
expect(definition.name).toBe('Saved browser lifecycle');
|
||||
expect(Number(definition.initial_capital)).toBe(100000);
|
||||
expect(Number(definition.initial_capital)).toBe(10000);
|
||||
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: 'Settings', exact: true }).click();
|
||||
expect(await f.page.locator('input[type="date"]').first().inputValue()).toBe('2024-01-01');
|
||||
expect(
|
||||
await f.page.locator('dl[aria-label="Canonical dataset bounds"]').textContent()
|
||||
).toContain(new Date(dataset.manifest.bounds.tradeStart).toISOString());
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
const response = await submitInBrowser(f.page);
|
||||
expect(response.status()).toBe(202);
|
||||
|
|
@ -1453,7 +1623,7 @@ test('browser_saved_run_lifecycle', async () => {
|
|||
expect(response.headers().location).toBe(`/api/v2/runs/${run.id}`);
|
||||
expect(response.request().headers()['idempotency-key']).toBeTruthy();
|
||||
await visible(f.page, 'Pending');
|
||||
await visible(f.page, /Source request \(auto\) — unpinned/);
|
||||
await visible(f.page, /Pinned dataset hash/);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1);
|
||||
expect(await f.page.getByRole('button', { name: /pause|resume/i }).count()).toBe(0);
|
||||
|
|
@ -1479,26 +1649,26 @@ test('browser_saved_run_lifecycle', async () => {
|
|||
).toBe(25);
|
||||
f.controlled.completion.resolve();
|
||||
await visible(f.page, 'Completed');
|
||||
await visible(f.page, 'Research only · Unverified economics');
|
||||
await f.page
|
||||
.getByText('Configuration, provenance and simulation limitations', { exact: true })
|
||||
.click();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
|
||||
const result = await f.request(`/api/v2/runs/${run.id}/results`);
|
||||
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
|
||||
await visible(f.page, result.config.dataset.hash);
|
||||
expect(await f.page.locator('pre').textContent()).toContain('"initialCapital": 100000');
|
||||
expect(result.request.datasetHash).toMatch(/^[a-f0-9]{64}$/);
|
||||
await visible(f.page, result.request.datasetHash);
|
||||
expect(await f.page.locator('pre').textContent()).toContain(
|
||||
'"initialCapital": "10000.00000000"'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'BUY');
|
||||
await visible(f.page, '$100.00');
|
||||
await visible(f.page, 'buy');
|
||||
await visible(f.page, '5.00000000');
|
||||
const savedUrl = f.page.url();
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Completed');
|
||||
expect(f.page.url()).toBe(savedUrl);
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'BUY');
|
||||
await visible(f.page, 'buy');
|
||||
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
|
||||
await f.page.getByText('Saved browser lifecycle', { exact: true }).click();
|
||||
await f.page.getByText('#1', { exact: true }).click();
|
||||
await f.page.getByText(/^#1\s*Canonical$/).click();
|
||||
await visible(f.page, 'Completed');
|
||||
expect(f.page.url()).toBe(savedUrl);
|
||||
expect(
|
||||
|
|
@ -1515,7 +1685,7 @@ test('browser_cancel_failure', async () => {
|
|||
const f = await fixture();
|
||||
try {
|
||||
await f.login();
|
||||
await createInBrowser(f.page, 'Cancel browser run', true);
|
||||
await createCanonicalInBrowser(f, 'Cancel browser run', true);
|
||||
const runId = f.page.url().split('/').at(-1)!;
|
||||
f.dispatcher.start();
|
||||
await visible(f.page, 'Running');
|
||||
|
|
@ -1542,7 +1712,7 @@ test('browser_cancel_failure', async () => {
|
|||
).toBe(0);
|
||||
f.controlled.mode = 'fail';
|
||||
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
|
||||
await createInBrowser(f.page, 'Failed browser run', true);
|
||||
await createCanonicalInBrowser(f, 'Failed browser run', true);
|
||||
await visible(f.page, 'Run failed: Injected fixture worker failure');
|
||||
const failedId = f.page.url().split('/').at(-1)!;
|
||||
expect(
|
||||
|
|
@ -1553,24 +1723,32 @@ test('browser_cancel_failure', async () => {
|
|||
).toBe(0);
|
||||
f.controlled.mode = 'empty';
|
||||
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
|
||||
await createInBrowser(f.page, 'Empty completed browser run', true);
|
||||
await createCanonicalInBrowser(f, 'Empty completed browser run', true);
|
||||
await visible(f.page, 'Completed');
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'No trades executed in this backtest.');
|
||||
await visible(f.page, 'No fills were executed in this completed run.');
|
||||
const emptyId = f.page.url().split('/').at(-1)!;
|
||||
expect((await f.request(`/api/v2/runs/${emptyId}/results`)).trades).toEqual([]);
|
||||
expect((await f.request(`/api/v2/runs/${emptyId}/results`)).financial.projection.fills).toEqual(
|
||||
[]
|
||||
);
|
||||
// A saved completed row whose result is unavailable must not appear as zero trades.
|
||||
const missingResultId = randomUUID();
|
||||
const definitionId = f.page.url().split('/')[4]!;
|
||||
const missingDefinitionId = randomUUID();
|
||||
await f.pool.query(
|
||||
"INSERT INTO runs(id,backtest_id,run_number,status) VALUES ($1,$2,2,'completed')",
|
||||
[missingResultId, definitionId]
|
||||
`INSERT INTO backtests(id,name,strategy,symbols,start_date,end_date,initial_capital) VALUES ($1,'Historical missing result','moving-average','["AAPL.US"]','2024-01-01','2024-02-01',10000)`,
|
||||
[missingDefinitionId]
|
||||
);
|
||||
await f.page.goto(f.page.url().replace(emptyId, missingResultId));
|
||||
await f.pool.query(
|
||||
"INSERT INTO runs(id,backtest_id,run_number,status) VALUES ($1,$2,1,'completed')",
|
||||
[missingResultId, missingDefinitionId]
|
||||
);
|
||||
await f.page.goto(`${f.origin}/backtests/${missingDefinitionId}/run/${missingResultId}`);
|
||||
await visible(f.page, 'Run completed, but saved results are unavailable.');
|
||||
await visible(f.page, 'Retry results');
|
||||
expect(
|
||||
await f.page.getByText('No trades executed in this backtest.', { exact: true }).count()
|
||||
await f.page
|
||||
.getByText('No fills were executed in this completed run.', { exact: true })
|
||||
.count()
|
||||
).toBe(0);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
|
|
@ -1589,7 +1767,7 @@ test('browser_reopen_and_switch', async () => {
|
|||
f.page.on('requestfailed', settled);
|
||||
try {
|
||||
await f.login();
|
||||
await createInBrowser(f.page, 'Selection and reconnect', true);
|
||||
await createCanonicalInBrowser(f, 'Selection and reconnect', true);
|
||||
const firstUrl = f.page.url();
|
||||
const firstId = firstUrl.split('/').at(-1)!;
|
||||
const definitionId = firstUrl.split('/')[4]!;
|
||||
|
|
@ -1637,17 +1815,17 @@ test('browser_reopen_and_switch', async () => {
|
|||
f.controlled.completion.resolve();
|
||||
await visible(f.page, 'Completed');
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
await visible(f.page, '#1');
|
||||
await visible(f.page, /^#1\s*Canonical$/);
|
||||
delayed = f.delayResponse(`/api/v2/runs/${firstId}/results`);
|
||||
const selectionRequest = f.page.waitForRequest(
|
||||
request => new URL(request.url()).pathname === `/api/v2/runs/${firstId}/results`
|
||||
);
|
||||
await f.page.getByText('#1', { exact: true }).click();
|
||||
await f.page.getByText(/^#1\s*Canonical$/).click();
|
||||
const requested = await selectionRequest;
|
||||
await delayed.captured.wait('selected run A result request');
|
||||
await visible(f.page, 'Loading run data...');
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
await f.page.getByText('#2', { exact: true }).click();
|
||||
await f.page.getByText(/^#2\s*Canonical$/).click();
|
||||
await visible(f.page, 'Completed');
|
||||
delayed.release.resolve();
|
||||
await delayed.delivered.wait('delayed result response settlement');
|
||||
|
|
@ -1658,9 +1836,7 @@ test('browser_reopen_and_switch', async () => {
|
|||
await f.page.evaluate(
|
||||
() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))
|
||||
);
|
||||
await f.page
|
||||
.getByText('Configuration, provenance and simulation limitations', { exact: true })
|
||||
.click();
|
||||
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
|
||||
await visible(f.page, secondId);
|
||||
expect(f.page.url()).toBe(secondUrl);
|
||||
expect(await f.page.getByText(firstId, { exact: true }).count()).toBe(0);
|
||||
|
|
@ -1685,83 +1861,135 @@ test('browser_reopen_and_switch', async () => {
|
|||
}
|
||||
});
|
||||
|
||||
test('native_smoke', async () => {
|
||||
test('canonical_native_smoke', async () => {
|
||||
const f = await fixture(true);
|
||||
try {
|
||||
await f.login();
|
||||
await createInBrowser(f.page, 'Actual Rust browser smoke', true);
|
||||
await createCanonicalInBrowser(f, 'Actual Rust browser smoke', true);
|
||||
const runId = f.page.url().split('/').at(-1)!;
|
||||
f.dispatcher.start();
|
||||
await visible(f.page, 'Completed');
|
||||
const result = await f.request(`/api/v2/runs/${runId}/results`);
|
||||
expect(result.engine).toBe('native');
|
||||
expect(result.config.dataset.barCount).toBe(70);
|
||||
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect(result.financialEngine).toBe('rust');
|
||||
expect(result.request.strategy.origin).toBe('builtin');
|
||||
expect(result.request.datasetHash).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(result.financial.projection.fills.length).toBeGreaterThan(0);
|
||||
expect(
|
||||
(await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [runId])).rows[0]
|
||||
).toEqual({ status: 'completed', attempt_number: 1 });
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id=$1', [runId])).rowCount
|
||||
).toBe(1);
|
||||
await visible(f.page, 'Research only · Unverified economics');
|
||||
await visible(f.page, 'Canonical research result');
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, result.trades[0].side.toUpperCase());
|
||||
await visible(f.page, `$${result.trades[0].price.toFixed(2)}`);
|
||||
await visible(f.page, result.financial.projection.fills[0].side);
|
||||
await visible(f.page, result.financial.projection.fills[0].price);
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Completed');
|
||||
await f.page
|
||||
.getByText('Configuration, provenance and simulation limitations', { exact: true })
|
||||
.click();
|
||||
await visible(f.page, result.config.dataset.hash);
|
||||
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
|
||||
await visible(f.page, result.request.datasetHash);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('browser_frozen_dataset_native_run_and_reopen', async () => {
|
||||
const f = await fixture(true);
|
||||
test('browser_legacy_frozen_history_reopens_without_reactivating_retired_execution', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
const dataset = await retainDataset(f.pool);
|
||||
const hash = dataset.manifest.hash;
|
||||
await f.login();
|
||||
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
||||
await f.page.getByPlaceholder('My Strategy Backtest').fill('Frozen dataset browser run');
|
||||
await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen');
|
||||
await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash);
|
||||
expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).inputValue()).toBe(
|
||||
'2024-01-01'
|
||||
const backtestId = randomUUID(),
|
||||
runId = randomUUID();
|
||||
const config = {
|
||||
name: 'Historical frozen dataset',
|
||||
strategy: 'moving-average',
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
parameters: {},
|
||||
dataset: dataset.manifest,
|
||||
};
|
||||
// Explicit pre-cutover history fixture, never an alternative simulator.
|
||||
await f.pool.query(
|
||||
`INSERT INTO backtests(id,name,strategy,symbols,start_date,end_date,initial_capital,config)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`,
|
||||
[
|
||||
backtestId,
|
||||
config.name,
|
||||
config.strategy,
|
||||
JSON.stringify(config.symbols),
|
||||
config.startDate,
|
||||
config.endDate,
|
||||
config.initialCapital,
|
||||
JSON.stringify({ datasetHash: hash, dataFrequency: '1d' }),
|
||||
]
|
||||
);
|
||||
expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).isDisabled()).toBe(true);
|
||||
await f.page.getByRole('button', { name: 'Save and run', exact: true }).click();
|
||||
await f.page.waitForURL(/\/backtests\/[^/]+\/run\/[^/]+$/);
|
||||
const runId = f.page.url().split('/').at(-1)!;
|
||||
await visible(f.page, 'Pending');
|
||||
const pending = await f.request(`/api/v2/runs/${runId}`);
|
||||
expect(pending.dataset).toMatchObject({
|
||||
requestedHash: hash,
|
||||
pinnedHash: null,
|
||||
state: 'requested',
|
||||
});
|
||||
expect(
|
||||
await f.page.getByRole('region', { name: 'Run dataset', exact: true }).textContent()
|
||||
).toContain(hash);
|
||||
f.dispatcher.start();
|
||||
await f.pool.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,status,dataset_hash)
|
||||
VALUES ($1,$2,1,'completed',$3)`,
|
||||
[runId, backtestId, hash]
|
||||
);
|
||||
await f.pool.query(
|
||||
`INSERT INTO backtest_results(run_id,completed_at,engine,configuration,metrics,equity_curve,ohlc_data,trades,positions,analytics,execution_time)
|
||||
VALUES ($1,NOW(),'native',$2,$3,'[]','{}',$4,'[]','{}',1)`,
|
||||
[
|
||||
runId,
|
||||
JSON.stringify(config),
|
||||
JSON.stringify({
|
||||
totalReturn: 0,
|
||||
sharpeRatio: null,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
totalTrades: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
}),
|
||||
JSON.stringify([
|
||||
{
|
||||
kind: 'fill',
|
||||
id: 'historical-fill',
|
||||
symbol: 'AAPL.US',
|
||||
timestamp: '2024-01-02T00:00:00.000Z',
|
||||
side: 'buy',
|
||||
price: 100,
|
||||
quantity: 1,
|
||||
commission: 0,
|
||||
},
|
||||
]),
|
||||
]
|
||||
);
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/backtests/${backtestId}/run/${runId}`);
|
||||
await visible(f.page, 'Completed');
|
||||
await visible(f.page, 'Research only · Unverified economics');
|
||||
const result = await f.request(`/api/v2/runs/${runId}/results`);
|
||||
expect(result.config.dataset.hash).toBe(hash);
|
||||
expect(result.engine).toBe('native');
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect((await f.pool.query('SELECT count(*) FROM backtest_datasets')).rows[0].count).toBe('1');
|
||||
await visible(f.page, 'Research only · Unverified economics');
|
||||
const runDataset = f.page.getByRole('region', { name: 'Run dataset', exact: true });
|
||||
expect(await runDataset.textContent()).toContain('Pinned dataset hash');
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'BUY');
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Completed');
|
||||
expect(await runDataset.textContent()).toContain(hash);
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, result.trades[0].side.toUpperCase());
|
||||
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 expect(
|
||||
f.request(
|
||||
`/api/v2/backtests/${backtestId}/runs`,
|
||||
'POST',
|
||||
{},
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)
|
||||
).rejects.toThrow('409');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
||||
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(result);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
|
|
@ -1775,9 +2003,16 @@ test('browser_intraday_dataset_exact_settings_and_incompatible_submission', asyn
|
|||
const endDate = '2024-01-02T15:30:00.456Z';
|
||||
const dataset = await retainDataset(f.pool, { startDate, endDate, dataFrequency: '1m' });
|
||||
const hash = dataset.manifest.hash;
|
||||
const version = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.login();
|
||||
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
||||
await f.page.getByPlaceholder('My Strategy Backtest').fill('Exact intraday frozen settings');
|
||||
await f.page.getByLabel('Strategy family', { exact: true }).selectOption(version.strategyId);
|
||||
await f.page.getByLabel('Immutable strategy version', { exact: true }).selectOption(version.id);
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(f.page, /Parameters validated/);
|
||||
await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen');
|
||||
await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash);
|
||||
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
|
|
@ -1790,6 +2025,8 @@ test('browser_intraday_dataset_exact_settings_and_incompatible_submission', asyn
|
|||
expect(await f.page.getByLabel('End instant (UTC)', { exact: true }).inputValue()).toBe(
|
||||
endDate
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(f.page, /Parameters validated/);
|
||||
const saved = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'PUT' &&
|
||||
|
|
@ -1817,15 +2054,17 @@ test('browser_intraday_dataset_exact_settings_and_incompatible_submission', asyn
|
|||
[backtestId]
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'New Run', exact: true }).click();
|
||||
const rejected = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith(`/api/v2/backtests/${backtestId}/runs`)
|
||||
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
|
||||
true
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Run current settings', exact: true }).click();
|
||||
expect((await rejected).status()).toBe(400);
|
||||
await visible(f.page, /Frozen dataset does not match/);
|
||||
await expect(
|
||||
f.request(
|
||||
`/api/v2/backtests/${backtestId}/runs`,
|
||||
'POST',
|
||||
{},
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)
|
||||
).rejects.toThrow('409');
|
||||
expect((await f.pool.query('SELECT count(*) FROM runs')).rows[0].count).toBe('0');
|
||||
expect((await f.pool.query('SELECT count(*) FROM backtest_dispatch')).rows[0].count).toBe('0');
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
|
|
@ -1838,7 +2077,7 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
|
|||
const f = await fixture();
|
||||
try {
|
||||
await f.login();
|
||||
await createInBrowser(f.page, 'Retained browser evidence', true);
|
||||
await createCanonicalInBrowser(f, 'Retained browser evidence', true);
|
||||
const savedUrl = f.page.url();
|
||||
const runId = savedUrl.split('/').at(-1)!;
|
||||
const definitionId = savedUrl.split('/')[4]!;
|
||||
|
|
@ -1847,7 +2086,7 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
|
|||
await f.page.getByRole('button', { name: 'Confirm archive', exact: true }).click();
|
||||
await visible(f.page, 'Restore backtest');
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
expect(await f.page.getByPlaceholder('My Strategy Backtest').isDisabled()).toBe(true);
|
||||
expect(await f.page.getByLabel('Backtest name', { exact: true }).isDisabled()).toBe(true);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
|
||||
true
|
||||
|
|
@ -1862,13 +2101,13 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
|
|||
f.controlled.completion.resolve();
|
||||
await visible(f.page, 'Completed');
|
||||
const result = await f.request(`/api/v2/runs/${runId}/results`);
|
||||
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(result.request.datasetHash).toMatch(/^[a-f0-9]{64}$/);
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'BUY');
|
||||
await visible(f.page, 'buy');
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Restore backtest');
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'BUY');
|
||||
await visible(f.page, 'buy');
|
||||
expect(f.page.url()).toBe(savedUrl);
|
||||
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
|
||||
await f.page.getByRole('checkbox', { name: 'Show archived backtests', exact: true }).waitFor();
|
||||
|
|
@ -1879,14 +2118,14 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
|
|||
await f.page.getByRole('checkbox', { name: 'Show archived backtests', exact: true }).check();
|
||||
await f.page.getByText('Retained browser evidence').click();
|
||||
await visible(f.page, 'Restore backtest');
|
||||
await f.page.getByText('#1', { exact: true }).click();
|
||||
await f.page.getByText(/^#1\s*Canonical$/).click();
|
||||
await visible(f.page, 'Completed');
|
||||
expect(f.page.url()).toBe(savedUrl);
|
||||
await f.page.getByRole('button', { name: 'Restore backtest', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'Confirm restore', exact: true }).click();
|
||||
await visible(f.page, 'Archive backtest');
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
expect(await f.page.getByPlaceholder('My Strategy Backtest').isEnabled()).toBe(true);
|
||||
expect(await f.page.getByLabel('Backtest name', { exact: true }).isEnabled()).toBe(true);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
const accepted = await submitInBrowser(f.page);
|
||||
expect(accepted.status()).toBe(202);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue