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);
|
||||
|
|
|
|||
13
test/fixtures/backtest-crash-owner.ts
vendored
13
test/fixtures/backtest-crash-owner.ts
vendored
|
|
@ -17,16 +17,21 @@ if (
|
|||
!schema ||
|
||||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
|
||||
!runId
|
||||
)
|
||||
) {
|
||||
throw new Error('Unsafe crash fixture target');
|
||||
}
|
||||
const logger = getLogger('crash-owner');
|
||||
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 500);
|
||||
repository.loadCanonicalDataset = async () => {
|
||||
process.send?.({ type: 'claimed' });
|
||||
return new Promise(() => {});
|
||||
};
|
||||
const runner = new BacktestRunner({
|
||||
engine: new RustBacktestAdapter({
|
||||
logger,
|
||||
|
|
@ -36,9 +41,5 @@ const runner = new BacktestRunner({
|
|||
repository,
|
||||
logger,
|
||||
heartbeatMs: 50,
|
||||
prepare: async () => {
|
||||
process.send?.({ type: 'claimed' });
|
||||
await new Promise<void>(() => {});
|
||||
},
|
||||
});
|
||||
await runner.runQueued(runId);
|
||||
|
|
|
|||
75
test/fixtures/canonical-admission.ts
vendored
Normal file
75
test/fixtures/canonical-admission.ts
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
import type { Pool } from 'pg';
|
||||
import type { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.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 './canonical-research';
|
||||
import { canonicalSmaFixture } from './canonical-sma';
|
||||
import { logger } from './execution';
|
||||
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
/** Real approved admission on a caller-owned disposable PostgreSQL schema. */
|
||||
export async function canonicalAdmissionFixture(
|
||||
pool: Pool,
|
||||
postgres: PostgreSQLClient,
|
||||
initializeTables = true
|
||||
) {
|
||||
for (const name of initializeTables
|
||||
? [
|
||||
'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',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]
|
||||
: []) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
if (!Object.hasOwn(postgres, 'query')) {
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
}
|
||||
const dataset = canonicalSmaFixture().dataset;
|
||||
const api = new BacktestServiceV2({ postgres, logger });
|
||||
const catalog = new StrategyCatalogService({ postgres, logger });
|
||||
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
|
||||
const version = await catalog.seedBuiltin('Cutover retained SMA', pkg, 'seed');
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision: 'approve', reason: 'Cutover native fixture' },
|
||||
'operator'
|
||||
);
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const definition = {
|
||||
name: 'Canonical cutover fixture',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.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 draft = await api.createBacktest(definition, { autoStart: false });
|
||||
return { api, catalog, version, draft, definition, dataset };
|
||||
}
|
||||
192
test/fixtures/canonical-runner.ts
vendored
Normal file
192
test/fixtures/canonical-runner.ts
vendored
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { expect } from 'bun:test';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { type BacktestExecutionEngine } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { type BacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { canonicalSmaFixture } from './canonical-sma';
|
||||
|
||||
const logger = { error() {} };
|
||||
export function canonicalRunnerFixture() {
|
||||
const versionId = randomUUID(),
|
||||
runId = randomUUID(),
|
||||
ownerId = `strategy:${versionId}`;
|
||||
const { dataset, config, selections } = canonicalSmaFixture([ownerId]);
|
||||
config.matching.risk.ledger.sessionId = runId;
|
||||
config.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
const descriptor = builtinCatalogDescriptors.find(d => d.program.strategyId === 'sma_crossover')!;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId,
|
||||
backtestId: randomUUID(),
|
||||
name: 'Runner boundary',
|
||||
strategy: {
|
||||
familyId: randomUUID(),
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: randomUUID(),
|
||||
selection: selections[0],
|
||||
package: {
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'not executed by this lifecycle 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' },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
modelArtifacts: [],
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'd'.repeat(64),
|
||||
engineWrapperSha256: 'e'.repeat(64),
|
||||
engineBinarySha256: 'f'.repeat(64),
|
||||
dependencyLockSha256: 'b'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: 'fixture',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
});
|
||||
const events: string[] = [];
|
||||
let result: CanonicalRunResult | undefined;
|
||||
let heartbeatFailure = false;
|
||||
let status = 'pending';
|
||||
const repo: BacktestRunRepository = {
|
||||
async start() {
|
||||
throw new Error('legacy claim must not run');
|
||||
},
|
||||
async startCanonical(input) {
|
||||
events.push('claim');
|
||||
status = 'running';
|
||||
return {
|
||||
runId,
|
||||
backtestId: request.backtestId,
|
||||
attemptId: 'attempt',
|
||||
config: structuredClone(input),
|
||||
};
|
||||
},
|
||||
async load() {
|
||||
return { status, config: structuredClone(request) };
|
||||
},
|
||||
async rejectPending() {
|
||||
events.push('reject');
|
||||
status = 'failed';
|
||||
},
|
||||
async heartbeat() {
|
||||
events.push('heartbeat');
|
||||
if (heartbeatFailure) {
|
||||
throw new Error('lost');
|
||||
}
|
||||
return { cancelRequested: false };
|
||||
},
|
||||
async loadDataset() {
|
||||
throw new Error('v1 data must not run');
|
||||
},
|
||||
async freezeDataset() {
|
||||
throw new Error('provider freeze must not run');
|
||||
},
|
||||
async loadCanonicalDataset(_id, _attempt, hash) {
|
||||
expect(hash).toBe(dataset.manifest.hash);
|
||||
events.push('dataset');
|
||||
return dataset;
|
||||
},
|
||||
async complete() {
|
||||
throw new Error('legacy completion must not run');
|
||||
},
|
||||
async completeCanonical(input) {
|
||||
events.push('complete');
|
||||
result = input;
|
||||
status = 'completed';
|
||||
},
|
||||
async updateProgress() {
|
||||
events.push('progress');
|
||||
},
|
||||
async fail() {
|
||||
events.push('fail');
|
||||
status = 'failed';
|
||||
},
|
||||
async cancel() {
|
||||
events.push('cancel');
|
||||
status = 'cancelled';
|
||||
},
|
||||
async updateControl() {},
|
||||
};
|
||||
const engine = Object.assign(new EventEmitter(), {
|
||||
async runBacktest(): Promise<never> {
|
||||
throw new Error('legacy simulator must not run');
|
||||
},
|
||||
async runCanonical(
|
||||
_input: typeof request,
|
||||
resolve: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
|
||||
) {
|
||||
await resolve(new AbortController().signal);
|
||||
events.push('execute');
|
||||
// Economic validation belongs to the actual worker/SQL fixtures; this fixture probes lifecycle only.
|
||||
return {
|
||||
financial: {} as CanonicalRunResult['financial'],
|
||||
analytics: {} as CanonicalRunResult['analytics'],
|
||||
};
|
||||
},
|
||||
async stopBacktest() {
|
||||
events.push('stop');
|
||||
},
|
||||
async pauseBacktest() {},
|
||||
async resumeBacktest() {},
|
||||
setSpeedMultiplier() {},
|
||||
getStatus() {
|
||||
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 };
|
||||
},
|
||||
async shutdown() {},
|
||||
}) satisfies BacktestExecutionEngine;
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
repository: repo,
|
||||
engineName: 'native',
|
||||
logger,
|
||||
heartbeatMs: 5,
|
||||
heartbeatTimeoutMs: 50,
|
||||
});
|
||||
return {
|
||||
request,
|
||||
dataset,
|
||||
repo,
|
||||
engine,
|
||||
runner,
|
||||
events,
|
||||
get result() {
|
||||
return result;
|
||||
},
|
||||
setStatus(next: string) {
|
||||
status = next;
|
||||
},
|
||||
loseLease() {
|
||||
heartbeatFailure = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((a, b) => {
|
||||
resolve = a;
|
||||
reject = b;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
62
test/fixtures/historical-run.ts
vendored
Normal file
62
test/fixtures/historical-run.ts
vendored
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import type { Pool } from 'pg';
|
||||
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
|
||||
import type {
|
||||
BacktestServiceV2,
|
||||
RunSubmission,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
|
||||
/** Insert an already accepted pre-cutover row for read/custody compatibility tests.
|
||||
* This is not an admission API or executable simulator, and cannot seed catalog requests.
|
||||
*/
|
||||
export async function seedHistoricalRun(
|
||||
pool: Pool,
|
||||
api: BacktestServiceV2,
|
||||
input: { backtestId: string },
|
||||
receipt?: RunSubmission
|
||||
) {
|
||||
const definition = await api.getBacktest(input.backtestId);
|
||||
if (!definition || definition.strategyVersionId !== null || definition.strategy === 'catalog') {
|
||||
throw new Error('Historical fixture requires a legacy template');
|
||||
}
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(
|
||||
{
|
||||
name: definition.name,
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
},
|
||||
{ runId, backtestId: definition.id, speedMultiplier: null }
|
||||
);
|
||||
const hash = receipt
|
||||
? createHash('sha256')
|
||||
.update(JSON.stringify({ version: 1, backtestId: definition.id, speedMultiplier: null }))
|
||||
.digest('hex')
|
||||
: null;
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [definition.id]);
|
||||
await client.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,request_snapshot,submission_principal,submission_key,submission_hash)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3,$4,$5,$6 FROM runs WHERE backtest_id=$2`,
|
||||
[runId, definition.id, snapshot, receipt?.principal ?? null, receipt?.key ?? null, hash]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
|
||||
await client.query('COMMIT');
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
const saved = await api.getRun(runId);
|
||||
if (!saved) {
|
||||
throw new Error('Historical fixture row missing');
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
11
test/fixtures/native-backtest-worker.ts
vendored
11
test/fixtures/native-backtest-worker.ts
vendored
|
|
@ -1,3 +1,4 @@
|
|||
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import {
|
||||
nativeWorkerRequestSchema,
|
||||
type NativeWorkerMessage,
|
||||
|
|
@ -11,13 +12,13 @@ function send(message: NativeWorkerMessage | { invalid: boolean }): Promise<void
|
|||
|
||||
process.once('message', async (input: unknown) => {
|
||||
const request = nativeWorkerRequestSchema.parse(input);
|
||||
if (request.type !== 'run') {
|
||||
throw new Error('Legacy fixture only');
|
||||
if (request.type !== 'runReplayTrace') {
|
||||
throw new Error('Canonical replay lifecycle fixture only');
|
||||
}
|
||||
const { config } = request;
|
||||
// Fixture controls are run labels, not unsupported production strategy parameters.
|
||||
const behavior = config.name?.startsWith('fixture:')
|
||||
? config.name.slice('fixture:'.length)
|
||||
const behavior = config.matching.risk.ledger.sessionId.startsWith('fixture:')
|
||||
? config.matching.risk.ledger.sessionId.slice('fixture:'.length)
|
||||
: undefined;
|
||||
if (!behavior) {
|
||||
// The same adapter can recover and run the actual Rust engine after a failed worker.
|
||||
|
|
@ -49,7 +50,7 @@ process.once('message', async (input: unknown) => {
|
|||
process.exit(0);
|
||||
return;
|
||||
case 'result-then-block':
|
||||
await send({ type: 'result', result: '{}' });
|
||||
await send({ type: 'result', result: JSON.stringify(executeReplayTrace(request).result) });
|
||||
while (true) {
|
||||
Math.sqrt(Math.random());
|
||||
}
|
||||
|
|
|
|||
123
test/integration/async-strategy-replay.test.ts
Normal file
123
test/integration/async-strategy-replay.test.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplaySessionAsync,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type { ReplayResultFormat } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
function setup() {
|
||||
const fixture = nativeReplayFixture(8, 1, ['A', 'B']);
|
||||
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
||||
const programs: StrategyProgram<number>[] = ['A', 'B'].map(ownerId => ({
|
||||
ownerId,
|
||||
strategyId: 'async-parity',
|
||||
strategyVersion: '1',
|
||||
mode: 'target',
|
||||
seed: ownerId === 'A' ? 12 : 34,
|
||||
initialState: 0,
|
||||
decide(context) {
|
||||
expect(context.observations.every(bar => bar.available_at <= context.now)).toBe(true);
|
||||
expect(context.positions.every(position => position.ownerId === ownerId)).toBe(true);
|
||||
expect(context.previousAdmission?.decision.ownerId ?? ownerId).toBe(ownerId);
|
||||
return {
|
||||
nextState: context.state + 1,
|
||||
intent: {
|
||||
mode: 'target',
|
||||
targets: [
|
||||
{
|
||||
instrumentId: 'X0.US',
|
||||
quantity: parseFinancialDecimal(context.random() > 0.5 ? '1' : '0'),
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
}));
|
||||
const controller = new StrategyController(load.identity, programs, load.config);
|
||||
return { load, programs, controller };
|
||||
}
|
||||
|
||||
for (const resultFormat of ['trace', 'projection', 'report'] satisfies ReplayResultFormat[]) {
|
||||
test(`async controller preserves synchronous ${resultFormat} economics, state and admission order`, async () => {
|
||||
const { load, programs, controller } = setup();
|
||||
const synchronous = runStrategyReplay(load, programs, { resultFormat, eventBudget: 1 });
|
||||
const phases: string[] = [];
|
||||
const asynchronous = await runReplaySessionAsync(
|
||||
new NativeReplaySession(load),
|
||||
{
|
||||
async stage(context, observations) {
|
||||
phases.push('stage');
|
||||
await Promise.resolve();
|
||||
expect(Object.isFrozen(context.view)).toBe(true);
|
||||
expect(Object.isFrozen(observations)).toBe(true);
|
||||
return controller.stage(context, observations);
|
||||
},
|
||||
async committed(outcome) {
|
||||
phases.push('commit');
|
||||
await Promise.resolve();
|
||||
controller.committed(outcome);
|
||||
},
|
||||
},
|
||||
{ resultFormat, eventBudget: 256 }
|
||||
);
|
||||
expect(asynchronous.result).toEqual(synchronous.result);
|
||||
expect(controller.snapshot()).toEqual(synchronous.diagnostics);
|
||||
expect(phases).toEqual(Array.from({ length: 7 }, () => ['stage', 'commit']).flat());
|
||||
expect(asynchronous.metrics.submitCalls).toBe(synchronous.metrics.submitCalls);
|
||||
});
|
||||
}
|
||||
|
||||
for (const phase of ['stage', 'commit'] as const) {
|
||||
test(`async ${phase} rejection disposes the native session and preserves only acknowledged diagnostics`, async () => {
|
||||
const { load, controller } = setup();
|
||||
const session = new NativeReplaySession(load);
|
||||
const dispose = session.dispose.bind(session);
|
||||
let disposals = 0;
|
||||
session.dispose = () => {
|
||||
disposals++;
|
||||
dispose();
|
||||
};
|
||||
await expect(
|
||||
runReplaySessionAsync(session, {
|
||||
async stage(context, observations) {
|
||||
await Promise.resolve();
|
||||
if (phase === 'stage') {
|
||||
throw new Error('isolated stage lost');
|
||||
}
|
||||
return controller.stage(context, observations);
|
||||
},
|
||||
async committed() {
|
||||
await Promise.resolve();
|
||||
throw new Error('isolated commit lost');
|
||||
},
|
||||
})
|
||||
).rejects.toThrow(`isolated ${phase} lost`);
|
||||
expect(disposals).toBe(1);
|
||||
expect(controller.snapshot().committedBarriers).toBe(0);
|
||||
expect(() => session.advance(1)).toThrow();
|
||||
});
|
||||
}
|
||||
|
||||
test('async malformed financial decisions fail before an acknowledgement and still dispose', async () => {
|
||||
const { load } = setup();
|
||||
const session = new NativeReplaySession(load);
|
||||
let acknowledged = false;
|
||||
await expect(
|
||||
runReplaySessionAsync(session, {
|
||||
async stage() {
|
||||
return [{ intent: { mode: 'target', targets: [] } }] as never;
|
||||
},
|
||||
async committed() {
|
||||
acknowledged = true;
|
||||
},
|
||||
})
|
||||
).rejects.toThrow();
|
||||
expect(acknowledged).toBe(false);
|
||||
expect(() => session.advance(1)).toThrow();
|
||||
});
|
||||
|
|
@ -45,6 +45,13 @@ const timers = new Map<
|
|||
{ at: number; delay: number; callback: () => void; repeat: boolean }
|
||||
>();
|
||||
|
||||
function submittedBody(request: { body?: string }): string {
|
||||
if (typeof request.body !== 'string') {
|
||||
throw new Error('Submission body is missing');
|
||||
}
|
||||
return request.body;
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason: Error) => void;
|
||||
|
|
@ -68,7 +75,9 @@ function request(path: string, method = 'GET') {
|
|||
const found = requests.find(
|
||||
item => item.path === path && item.method === method && !item.settled
|
||||
);
|
||||
if (!found) throw new Error(`No pending ${method} ${path}`);
|
||||
if (!found) {
|
||||
throw new Error(`No pending ${method} ${path}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function reply(pending: Request, body: unknown, status = 200) {
|
||||
|
|
@ -115,18 +124,21 @@ const results = (id: string): RunResult => ({
|
|||
winRate: 0,
|
||||
totalTrades: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
},
|
||||
equity: [],
|
||||
ohlcData: {},
|
||||
positions: [],
|
||||
trades: [],
|
||||
analytics: {},
|
||||
analytics: { exposureTime: null },
|
||||
executionTime: 0,
|
||||
});
|
||||
const definition = {
|
||||
id: 'definition',
|
||||
name: 'Fixture',
|
||||
strategy: 'sma',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
symbols: ['A.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-02-01',
|
||||
|
|
@ -174,9 +186,13 @@ async function advance(ms: number) {
|
|||
const due = [...timers].filter(([, timer]) => timer.at <= now);
|
||||
await flush(() => {
|
||||
for (const [id, timer] of due) {
|
||||
if (!timers.has(id)) continue;
|
||||
if (!timers.has(id)) {
|
||||
continue;
|
||||
}
|
||||
timers.delete(id);
|
||||
if (timer.repeat) timers.set(id, { ...timer, at: now + timer.delay });
|
||||
if (timer.repeat) {
|
||||
timers.set(id, { ...timer, at: now + timer.delay });
|
||||
}
|
||||
timer.callback();
|
||||
}
|
||||
});
|
||||
|
|
@ -187,7 +203,9 @@ function click(label: string) {
|
|||
const button =
|
||||
buttons.find(item => item.textContent?.trim() === label) ??
|
||||
buttons.find(item => item.getAttribute('aria-label') === label);
|
||||
if (!button) throw new Error(`Missing button ${label}`);
|
||||
if (!button) {
|
||||
throw new Error(`Missing button ${label}`);
|
||||
}
|
||||
button.click();
|
||||
}
|
||||
function HookHost({ socket = false }: { socket?: boolean }) {
|
||||
|
|
@ -196,7 +214,9 @@ function HookHost({ socket = false }: { socket?: boolean }) {
|
|||
useWebSocket({
|
||||
runId: socket ? (latest.currentRun?.id ?? null) : null,
|
||||
onMessage: message => {
|
||||
if (message.type !== 'pong') void latest.refreshRun(message.runId);
|
||||
if (message.type !== 'pong') {
|
||||
void latest.refreshRun(message.runId);
|
||||
}
|
||||
},
|
||||
});
|
||||
return latest.currentRun
|
||||
|
|
@ -210,7 +230,13 @@ function HookHost({ socket = false }: { socket?: boolean }) {
|
|||
}
|
||||
async function mount(element: ReactElement = createElement(HookHost)) {
|
||||
root = createRoot(host);
|
||||
await flush(() => root!.render(element));
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
element.type === CreateBacktestDialog
|
||||
? createElement(router.MemoryRouter, null, element)
|
||||
: element
|
||||
)
|
||||
);
|
||||
}
|
||||
async function select(id: string) {
|
||||
await flush(() => {
|
||||
|
|
@ -260,8 +286,9 @@ beforeAll(async () => {
|
|||
WebSocket: TestSocket,
|
||||
ResizeObserver: browser.ResizeObserver,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
}))
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
({ useBacktestV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2'
|
||||
|
|
@ -291,6 +318,9 @@ beforeEach(() => {
|
|||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
if (new URL(String(input)).pathname.endsWith('/canonical-capability')) {
|
||||
return Promise.resolve(Response.json({ available: true, reason: null }));
|
||||
}
|
||||
const pending: Request = {
|
||||
...deferred<Response>(),
|
||||
path: new URL(String(input)).pathname,
|
||||
|
|
@ -304,10 +334,12 @@ beforeEach(() => {
|
|||
requests.push(pending);
|
||||
// Deliberately ignore abort: guards must also reject a late server continuation.
|
||||
return pending.promise;
|
||||
}) as typeof browser.fetch;
|
||||
}) as unknown as typeof browser.fetch;
|
||||
const schedule = (repeat: boolean, original: typeof setTimeout) =>
|
||||
((callback: () => void, delay?: number, ...args: unknown[]) => {
|
||||
if (![1000, 3000, 30000].includes(delay ?? 0)) return original(callback, delay, ...args);
|
||||
if (![1000, 3000, 30000].includes(delay ?? 0)) {
|
||||
return original(callback, delay, ...args);
|
||||
}
|
||||
const id = ++timerId;
|
||||
timers.set(id, { at: now + delay!, delay: delay!, callback, repeat });
|
||||
return id;
|
||||
|
|
@ -315,16 +347,22 @@ beforeEach(() => {
|
|||
globalThis.setTimeout = schedule(false, realTimeout);
|
||||
globalThis.setInterval = schedule(true, realInterval as typeof setTimeout) as typeof setInterval;
|
||||
globalThis.clearTimeout = ((id: number) => {
|
||||
if (!timers.delete(id)) realClearTimeout(id);
|
||||
if (!timers.delete(id)) {
|
||||
realClearTimeout(id);
|
||||
}
|
||||
}) as typeof clearTimeout;
|
||||
globalThis.clearInterval = ((id: number) => {
|
||||
if (!timers.delete(id)) realClearInterval(id);
|
||||
if (!timers.delete(id)) {
|
||||
realClearInterval(id);
|
||||
}
|
||||
}) as typeof clearInterval;
|
||||
});
|
||||
afterEach(async () => {
|
||||
let leakedTimers = 0;
|
||||
try {
|
||||
if (root) await flush(() => root!.unmount());
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
leakedTimers = timers.size;
|
||||
} finally {
|
||||
root = undefined;
|
||||
|
|
@ -343,8 +381,11 @@ afterAll(async () => {
|
|||
} finally {
|
||||
for (const key of globals) {
|
||||
const descriptor = savedGlobals.get(key);
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -607,6 +648,45 @@ describe('actual detail page result states', () => {
|
|||
});
|
||||
|
||||
async function nameBacktest() {
|
||||
const family = { id: 'family', name: 'Test strategy', archived: false };
|
||||
const version = {
|
||||
id: 'version-one',
|
||||
strategyId: 'family',
|
||||
ordinal: 1,
|
||||
origin: 'builtin',
|
||||
package: {
|
||||
parameterSchema: {
|
||||
type: 'object',
|
||||
properties: {},
|
||||
required: [],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
await flush(() => reply(request('/api/v2/strategies'), { strategies: [family] }));
|
||||
const choose = (label: string, value: string) => {
|
||||
const select = host.querySelector(`select[aria-label="${label}"]`)!;
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLSelectElement.prototype, 'value')!.set!.call(
|
||||
select,
|
||||
value
|
||||
);
|
||||
select.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
|
||||
};
|
||||
await flush(() => choose('Strategy family', 'family'));
|
||||
await flush(() => reply(request('/api/v2/strategies/family/versions'), { versions: [version] }));
|
||||
await flush(() => choose('Immutable strategy version', 'version-one'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version, reviews: [] })
|
||||
);
|
||||
await flush(() => reply(request('/api/v2/strategies/family'), { strategy: family }));
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: {},
|
||||
runnable: false,
|
||||
reason: 'Configure canonical settings',
|
||||
})
|
||||
);
|
||||
await flush(() => {
|
||||
const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!;
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
||||
|
|
@ -643,175 +723,109 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
});
|
||||
const saving = request('/api/v2/backtests', 'POST');
|
||||
expect(JSON.parse(saving.body!).autoStart).toBe(false);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
await flush(() => reply(saving, definition));
|
||||
expect(created).toEqual([definition]);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
expect(
|
||||
requests.filter(item => item.path.endsWith('/runs') && item.method === 'POST')
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
for (const failure of ['rejection', 'lost successful response'] as const) {
|
||||
test(`save_and_run_failure: ${failure} retries the saved definition, frozen body and key`, async () => {
|
||||
const created: { definition: Backtest; run?: Run }[] = [];
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
onClose: () => {},
|
||||
onCreated: (value, submitted) => created.push({ definition: value, run: submitted }),
|
||||
})
|
||||
);
|
||||
await nameBacktest();
|
||||
await flush(() => {
|
||||
click('Save and run');
|
||||
click('Save and run');
|
||||
});
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(first.headers.get('Idempotency-Key')).toBeTruthy();
|
||||
expect(JSON.parse(first.body!)).toEqual({ speedMultiplier: null });
|
||||
// In the lost-response case the server has accepted A; the transport fails.
|
||||
await flush(() =>
|
||||
failure === 'rejection'
|
||||
? reply(first, { error: 'Submission unavailable' }, 503)
|
||||
: fail(first)
|
||||
);
|
||||
expect(created).toHaveLength(0);
|
||||
expect(host.textContent).toContain('Backtest saved, but run submission failed');
|
||||
expect(host.querySelector('fieldset')!.disabled).toBe(true);
|
||||
await flush(() => {
|
||||
click('Retry submission');
|
||||
click('Retry submission');
|
||||
});
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(requests.filter(item => item.path === '/api/v2/backtests')).toHaveLength(1);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(3);
|
||||
await flush(() => reply(retry, run('A', 'pending'), 202));
|
||||
expect(created).toEqual([{ definition, run: run('A', 'pending') }]);
|
||||
});
|
||||
}
|
||||
test('new dialog cannot submit legacy or unconfigured execution', async () => {
|
||||
await mount(createElement(CreateBacktestDialog, { onClose: () => {}, onCreated: () => {} }));
|
||||
expect(host.querySelector('[aria-label="Strategy mode"]')).toBeNull();
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save and run'));
|
||||
expect(requests.some(item => item.path === '/api/v2/backtests' && item.method === 'POST')).toBe(
|
||||
false
|
||||
);
|
||||
expect(host.textContent).toContain('financial policies before running');
|
||||
});
|
||||
|
||||
for (const boundary of ['definition', 'submission'] as const) {
|
||||
test(`dialog unmount during ${boundary} ignores late completion and navigation`, async () => {
|
||||
let navigated = false;
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
onClose: () => {},
|
||||
onCreated: () => {
|
||||
navigated = true;
|
||||
},
|
||||
})
|
||||
);
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save and run'));
|
||||
if (boundary === 'submission') {
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
}
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await flush(() =>
|
||||
reply(
|
||||
request(
|
||||
boundary === 'definition' ? '/api/v2/backtests' : '/api/v2/backtests/definition/runs',
|
||||
'POST'
|
||||
),
|
||||
boundary === 'definition' ? definition : run('A')
|
||||
)
|
||||
);
|
||||
expect(navigated).toBe(false);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(
|
||||
boundary === 'definition' ? 1 : 2
|
||||
);
|
||||
});
|
||||
}
|
||||
test('dialog unmount during save ignores late completion and navigation', async () => {
|
||||
let navigated = false;
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
onClose: () => {},
|
||||
onCreated: () => {
|
||||
navigated = true;
|
||||
},
|
||||
})
|
||||
);
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save'));
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
expect(navigated).toBe(false);
|
||||
expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('closing cannot race the definition write and refresh a list before the row exists', async () => {
|
||||
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
|
||||
test('save rejects double clicks and close while pending, then navigates to configure', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: ['/backtests'] },
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests',
|
||||
element: createElement(BacktestListPageV2),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement('p', null, 'Saved definition'),
|
||||
})
|
||||
),
|
||||
createElement(LocationProbe)
|
||||
)
|
||||
);
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
await flush(() => click('New Backtest'));
|
||||
await nameBacktest();
|
||||
// The ref guard must work before the disabled state has rendered.
|
||||
await flush(() => {
|
||||
click('Save and run');
|
||||
click('Save');
|
||||
click('Save');
|
||||
click('Close backtest dialog');
|
||||
click('Close');
|
||||
});
|
||||
expect(host.querySelector('[aria-label="Close backtest dialog"]')).not.toBeNull();
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
||||
).toHaveLength(1);
|
||||
await flush(() => click('Close'));
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
expect(pageLocation).toBe('/backtests');
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
await flush(() => click('Close'));
|
||||
await flush(() => reply(request('/api/v2/backtests'), [definition]));
|
||||
await flush(() => reply(submitting, run('A', 'pending'), 202));
|
||||
expect(host.textContent).toContain('Create and manage backtest configurations');
|
||||
expect(host.querySelector('[aria-label="Close backtest dialog"]')).toBeNull();
|
||||
expect(pageLocation).toBe('/backtests/definition');
|
||||
expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('closing saved-but-failed dialog reloads the real list without navigating', async () => {
|
||||
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
await flush(() => click('New Backtest'));
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save and run'));
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
await flush(() => fail(request('/api/v2/backtests/definition/runs', 'POST')));
|
||||
await flush(() => click('Close'));
|
||||
await flush(() => reply(request('/api/v2/backtests'), [definition]));
|
||||
// Virtualized rows need real layout (W04). Here verify the refetch and that
|
||||
// the real list, not a detail route, remains mounted after closing.
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
||||
).toHaveLength(2);
|
||||
expect(host.textContent).toContain('Create and manage backtest configurations');
|
||||
expect(host.textContent).not.toContain('Retry submission');
|
||||
});
|
||||
|
||||
for (const intent of ['Save', 'Save and run'] as const) {
|
||||
test(`real list ${intent} navigates only after the requested operation succeeds`, async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: ['/backtests'] },
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests',
|
||||
element: createElement(BacktestListPageV2),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement('p', null, 'Saved definition'),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id/run/:runId',
|
||||
element: createElement('p', null, 'Submitted run'),
|
||||
})
|
||||
),
|
||||
createElement(LocationProbe)
|
||||
)
|
||||
);
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
await flush(() => click('New Backtest'));
|
||||
await nameBacktest();
|
||||
await flush(() => click(intent));
|
||||
expect(pageLocation).toBe('/backtests');
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
if (intent === 'Save and run') {
|
||||
expect(pageLocation).toBe('/backtests');
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition/runs', 'POST'), run('A', 'pending'), 202)
|
||||
);
|
||||
}
|
||||
expect(pageLocation).toBe(
|
||||
`/backtests/definition${intent === 'Save and run' ? '/run/A' : ''}`
|
||||
);
|
||||
test('legacy template stays readable but never creates a new run', async () => {
|
||||
await mount();
|
||||
await flush(() => {
|
||||
void latest.loadBacktest('definition');
|
||||
});
|
||||
}
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
strategy: 'sma',
|
||||
strategyVersionId: null,
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => {
|
||||
void latest.createRun();
|
||||
});
|
||||
expect(latest.submissionError).toContain('Legacy execution is retired');
|
||||
expect(requests.some(item => item.method === 'POST')).toBe(false);
|
||||
expect(latest.backtest?.name).toBe('Fixture');
|
||||
});
|
||||
|
||||
test('closing new-run confirmation prevents late successful submission from navigating', async () => {
|
||||
await mountPage('failed');
|
||||
|
|
@ -852,7 +866,7 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
expect(host.textContent).toContain('Run failed: B failure');
|
||||
await flush(() => click('Retry submission'));
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(submitting.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(submitting));
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(submitting.headers.get('Idempotency-Key'));
|
||||
});
|
||||
|
||||
|
|
@ -880,7 +894,7 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
void latest.createRun(9);
|
||||
});
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(first));
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, run('A', 'pending'), 202));
|
||||
expect(latest.runs.filter(item => item.id === 'A')).toHaveLength(1);
|
||||
|
|
@ -889,7 +903,7 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
});
|
||||
const next = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(next.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: 9 });
|
||||
expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: null });
|
||||
await flush(() => reply(next, run('B', 'pending'), 202));
|
||||
expect(latest.runs.map(item => item.id)).toEqual(['B', 'A']);
|
||||
});
|
||||
|
|
@ -913,7 +927,7 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
await flush(() => click('Retry submission'));
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(first));
|
||||
});
|
||||
|
||||
for (const change of ['selection', 'backtest', 'unmount'] as const) {
|
||||
|
|
@ -1051,7 +1065,7 @@ describe('template archive and restore', () => {
|
|||
void latest.createRun(9);
|
||||
});
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(first));
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, run('A', 'completed'), 202));
|
||||
expect(latest.hasPendingSubmission).toBe(false);
|
||||
|
|
@ -1074,7 +1088,7 @@ describe('template archive and restore', () => {
|
|||
});
|
||||
const fresh = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(fresh.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: 9 });
|
||||
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: null });
|
||||
await flush(() => reply(fresh, run('B', 'pending'), 202));
|
||||
expect(latest.runResults).toBe(savedResults);
|
||||
});
|
||||
|
|
@ -1090,7 +1104,7 @@ describe('template archive and restore', () => {
|
|||
expect(button('Retry submission').disabled).toBe(false);
|
||||
await flush(() => click('Retry submission'));
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(first));
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, run('A', 'running'), 202));
|
||||
expect(button('Run current settings').disabled).toBe(true);
|
||||
|
|
@ -1132,6 +1146,9 @@ describe('template archive and restore', () => {
|
|||
409
|
||||
)
|
||||
);
|
||||
if (typeof failure !== 'string') {
|
||||
throw new Error('Expected a retained-history refusal');
|
||||
}
|
||||
expect(failure).toContain('Archive it');
|
||||
expect(latest.error).toBe(failure);
|
||||
expect(latest.backtest?.id).toBe('definition');
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,201 +1,10 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import {
|
||||
BacktestCancelledError,
|
||||
type BacktestExecutionEngine,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import {
|
||||
BacktestLeaseLostError,
|
||||
type BacktestRunRepository,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
const logger = { error() {} };
|
||||
function setup() {
|
||||
const versionId = randomUUID(),
|
||||
runId = randomUUID(),
|
||||
ownerId = `strategy:${versionId}`;
|
||||
const { dataset, config, selections } = canonicalSmaFixture([ownerId]);
|
||||
config.matching.risk.ledger.sessionId = runId;
|
||||
config.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
const descriptor = builtinCatalogDescriptors.find(d => d.program.strategyId === 'sma_crossover')!;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId,
|
||||
backtestId: randomUUID(),
|
||||
name: 'Runner boundary',
|
||||
strategy: {
|
||||
familyId: randomUUID(),
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: randomUUID(),
|
||||
selection: selections[0],
|
||||
package: {
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'not executed by this lifecycle 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' },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
modelArtifacts: [],
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'd'.repeat(64),
|
||||
engineWrapperSha256: 'e'.repeat(64),
|
||||
engineBinarySha256: 'f'.repeat(64),
|
||||
dependencyLockSha256: 'b'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: 'fixture',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
});
|
||||
const events: string[] = [];
|
||||
let result: CanonicalRunResult | undefined;
|
||||
let heartbeatFailure = false;
|
||||
let status = 'pending';
|
||||
const repo: BacktestRunRepository = {
|
||||
async start() {
|
||||
throw new Error('legacy claim must not run');
|
||||
},
|
||||
async startCanonical(input) {
|
||||
events.push('claim');
|
||||
status = 'running';
|
||||
return {
|
||||
runId,
|
||||
backtestId: request.backtestId,
|
||||
attemptId: 'attempt',
|
||||
config: structuredClone(input),
|
||||
};
|
||||
},
|
||||
async load() {
|
||||
return { status, config: structuredClone(request) };
|
||||
},
|
||||
async rejectPending() {
|
||||
events.push('reject');
|
||||
status = 'failed';
|
||||
},
|
||||
async heartbeat() {
|
||||
events.push('heartbeat');
|
||||
if (heartbeatFailure) {
|
||||
throw new Error('lost');
|
||||
}
|
||||
return { cancelRequested: false };
|
||||
},
|
||||
async loadDataset() {
|
||||
throw new Error('v1 data must not run');
|
||||
},
|
||||
async freezeDataset() {
|
||||
throw new Error('provider freeze must not run');
|
||||
},
|
||||
async loadCanonicalDataset(_id, _attempt, hash) {
|
||||
expect(hash).toBe(dataset.manifest.hash);
|
||||
events.push('dataset');
|
||||
return dataset;
|
||||
},
|
||||
async complete() {
|
||||
throw new Error('legacy completion must not run');
|
||||
},
|
||||
async completeCanonical(input) {
|
||||
events.push('complete');
|
||||
result = input;
|
||||
status = 'completed';
|
||||
},
|
||||
async updateProgress() {
|
||||
events.push('progress');
|
||||
},
|
||||
async fail() {
|
||||
events.push('fail');
|
||||
status = 'failed';
|
||||
},
|
||||
async cancel() {
|
||||
events.push('cancel');
|
||||
status = 'cancelled';
|
||||
},
|
||||
async updateControl() {},
|
||||
};
|
||||
const engine = Object.assign(new EventEmitter(), {
|
||||
async runBacktest(): Promise<never> {
|
||||
throw new Error('legacy simulator must not run');
|
||||
},
|
||||
async runCanonical(
|
||||
_input: typeof request,
|
||||
resolve: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
|
||||
) {
|
||||
await resolve(new AbortController().signal);
|
||||
events.push('execute');
|
||||
// Economic validation belongs to the actual worker/SQL fixtures; this fixture probes lifecycle only.
|
||||
return {
|
||||
financial: {} as CanonicalRunResult['financial'],
|
||||
analytics: {} as CanonicalRunResult['analytics'],
|
||||
};
|
||||
},
|
||||
async stopBacktest() {
|
||||
events.push('stop');
|
||||
},
|
||||
async pauseBacktest() {},
|
||||
async resumeBacktest() {},
|
||||
setSpeedMultiplier() {},
|
||||
getStatus() {
|
||||
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 };
|
||||
},
|
||||
async shutdown() {},
|
||||
}) satisfies BacktestExecutionEngine;
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
repository: repo,
|
||||
engineName: 'native',
|
||||
logger,
|
||||
heartbeatMs: 5,
|
||||
heartbeatTimeoutMs: 50,
|
||||
async prepare() {
|
||||
throw new Error('legacy preparation must not run');
|
||||
},
|
||||
});
|
||||
return {
|
||||
request,
|
||||
dataset,
|
||||
repo,
|
||||
engine,
|
||||
runner,
|
||||
events,
|
||||
get result() {
|
||||
return result;
|
||||
},
|
||||
loseLease() {
|
||||
heartbeatFailure = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((a, b) => {
|
||||
resolve = a;
|
||||
reject = b;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { deferred, canonicalRunnerFixture as setup } from '../fixtures/canonical-runner';
|
||||
|
||||
describe('canonical jobs share the durable runner lifecycle', () => {
|
||||
test('queued canonical result preserves admitted request and bypasses every legacy seam', async () => {
|
||||
|
|
|
|||
150
test/integration/canonical-worker-lifecycle.test.ts
Normal file
150
test/integration/canonical-worker-lifecycle.test.ts
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import {
|
||||
BacktestCancelledError,
|
||||
BacktestTimeoutError,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { canonicalRunnerFixture, deferred } from '../fixtures/canonical-runner';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const workerUrl = new URL('../fixtures/native-backtest-worker.ts', import.meta.url);
|
||||
function start(behavior: string) {
|
||||
const fixture = nativeReplayFixture(),
|
||||
ready = deferred<number>(),
|
||||
controller = new AbortController();
|
||||
fixture.config.matching.risk.ledger.sessionId = `fixture:${behavior}`;
|
||||
const worker = new NativeBacktestWorker(workerUrl);
|
||||
const result = worker
|
||||
.execute(
|
||||
{
|
||||
type: 'runReplayTrace',
|
||||
version: 1,
|
||||
dataset: fixture.dataset,
|
||||
config: fixture.config,
|
||||
trace: [1, 2].map(offset => ({
|
||||
at: fixture.start + offset * fixture.minute,
|
||||
ownerId: 'A',
|
||||
intent: { mode: 'target' as const, targets: [] },
|
||||
})),
|
||||
resultFormat: 'report',
|
||||
eventBudget: 1,
|
||||
},
|
||||
controller.signal,
|
||||
progress => {
|
||||
if (progress.message.startsWith('Fixture worker ready:')) {
|
||||
ready.resolve(Number(progress.message.split(':')[1]));
|
||||
}
|
||||
}
|
||||
)
|
||||
.catch(error => {
|
||||
ready.reject(error);
|
||||
return error;
|
||||
});
|
||||
return { result, ready: ready.promise, controller };
|
||||
}
|
||||
function exited(pid: number) {
|
||||
expect(pid).toBeGreaterThan(0);
|
||||
expect(() => process.kill(pid, 0)).toThrow();
|
||||
}
|
||||
test.each(['crash', 'no-result', 'malformed', 'invalid-result', 'reported-error'])(
|
||||
'canonical worker %s cannot publish a result and is reaped before rejection',
|
||||
async behavior => {
|
||||
const execution = start(behavior),
|
||||
pid = await execution.ready;
|
||||
expect(await execution.result).toBeInstanceOf(Error);
|
||||
exited(pid);
|
||||
}
|
||||
);
|
||||
test('blocking canonical worker can be killed without blocking the parent event loop', async () => {
|
||||
const execution = start('block'),
|
||||
pid = await execution.ready;
|
||||
let tick = false;
|
||||
await new Promise<void>(resolve =>
|
||||
setTimeout(() => {
|
||||
tick = true;
|
||||
resolve();
|
||||
}, 5)
|
||||
);
|
||||
expect(tick).toBe(true);
|
||||
execution.controller.abort(new BacktestCancelledError());
|
||||
expect(await execution.result).toBeInstanceOf(BacktestCancelledError);
|
||||
exited(pid);
|
||||
});
|
||||
test('a deadline kills a noncooperative worker and preserves its timeout reason', async () => {
|
||||
const execution = start('block'),
|
||||
pid = await execution.ready;
|
||||
execution.controller.abort(new BacktestTimeoutError(10));
|
||||
expect(await execution.result).toBeInstanceOf(BacktestTimeoutError);
|
||||
exited(pid);
|
||||
});
|
||||
test('valid financial result is not accepted while the child is still alive', async () => {
|
||||
const execution = start('result-then-block'),
|
||||
pid = await execution.ready;
|
||||
let settled = false;
|
||||
execution.result.then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
expect(settled).toBe(false);
|
||||
execution.controller.abort(new BacktestCancelledError());
|
||||
expect(await execution.result).toBeInstanceOf(BacktestCancelledError);
|
||||
exited(pid);
|
||||
});
|
||||
test('canonical adapter cancellation during retained dataset reads prevents a late worker', async () => {
|
||||
const f = canonicalRunnerFixture(),
|
||||
entered = deferred<void>(),
|
||||
release = deferred<void>();
|
||||
let providerReads = 0,
|
||||
progress = 0;
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger: { error() {} },
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
providerReads++;
|
||||
return [];
|
||||
},
|
||||
},
|
||||
});
|
||||
engine.on('progress', () => progress++);
|
||||
const result = engine
|
||||
.runCanonical(f.request, async () => {
|
||||
entered.resolve();
|
||||
await release.promise;
|
||||
return f.dataset;
|
||||
})
|
||||
.catch(error => error);
|
||||
await entered.promise;
|
||||
await engine.stopBacktest();
|
||||
expect(await result).toBeInstanceOf(BacktestCancelledError);
|
||||
release.resolve();
|
||||
await Promise.resolve();
|
||||
expect(providerReads).toBe(0);
|
||||
expect(progress).toBe(0);
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
await engine.shutdown();
|
||||
await f.runner.shutdown();
|
||||
});
|
||||
test('canonical adapter timeout covers retained input loading and shutdown closes later work', async () => {
|
||||
const f = canonicalRunnerFixture();
|
||||
const engine = new RustBacktestAdapter(
|
||||
{
|
||||
logger: { error() {} },
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('provider must not run');
|
||||
},
|
||||
},
|
||||
},
|
||||
{ timeoutMs: 20 }
|
||||
);
|
||||
await expect(
|
||||
engine.runCanonical(f.request, async () => new Promise(() => {}))
|
||||
).rejects.toBeInstanceOf(BacktestTimeoutError);
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
await engine.shutdown();
|
||||
await expect(engine.runCanonical(f.request, async () => f.dataset)).rejects.toThrow(
|
||||
'shutting down'
|
||||
);
|
||||
await f.runner.shutdown();
|
||||
});
|
||||
|
|
@ -20,8 +20,25 @@ import type {
|
|||
} 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 { parseValidationDetail } from '../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
test('saved validation decodes explicit research agent actors without accepting malformed identities', () => {
|
||||
const value = document('reported');
|
||||
if (!value.selection || !value.report) {
|
||||
throw new Error('Reported fixture needs immutable selection and report');
|
||||
}
|
||||
const actor = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
value.selection.principal = actor;
|
||||
value.report.principal = actor;
|
||||
const parsed = parseValidationDetail(value);
|
||||
expect(parsed.selection?.principal).toBe(actor);
|
||||
expect(parsed.report?.principal).toBe(actor);
|
||||
expect(() =>
|
||||
parseValidationDetail({ ...value, report: { ...value.report, principal: 'agent:operator' } })
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
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)]));
|
||||
|
|
|
|||
|
|
@ -717,7 +717,7 @@ describe('immutable retry failure history', () => {
|
|||
expect(host.textContent).toContain('Retry 1 · previous attempt 1');
|
||||
expect(host.textContent).not.toContain('No accepted manual retries');
|
||||
});
|
||||
test('history is lazy and renders empty/loading states then exact nullable failure snapshots', async () => {
|
||||
test('history renders loading/empty states, exact nullable failure snapshots and research agent authorship', async () => {
|
||||
const value = failure(0, 0);
|
||||
value.trials[0]!.error = null;
|
||||
await show(value);
|
||||
|
|
@ -728,6 +728,7 @@ describe('immutable retry failure history', () => {
|
|||
expect(host.textContent).toContain('No accepted manual retries for this trial');
|
||||
await flush(() => button('Refresh retry history for trial 1').click());
|
||||
const saved = receipt(value);
|
||||
saved.principal = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
await flush(() => reply(request(historyPath()), { retries: [saved] }));
|
||||
expect(host.textContent).toContain('Retry 1 · previous attempt 0');
|
||||
expect(host.textContent).toContain('No error was recorded for this failure');
|
||||
|
|
@ -736,6 +737,7 @@ describe('immutable retry failure history', () => {
|
|||
expect(host.textContent).toContain(saved.completedAt!);
|
||||
expect(host.textContent).toContain(saved.recordedAt);
|
||||
expect(host.textContent).toContain(saved.reviewId);
|
||||
expect(host.textContent).toContain(saved.principal);
|
||||
expect(host.textContent).toContain('not a complete history of automatic recovery attempts');
|
||||
});
|
||||
test.each(['partial', 'foreign', 'unordered', 'duplicate', 'http'] as const)(
|
||||
|
|
|
|||
|
|
@ -266,7 +266,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
validateDataset(first, { ...datasetConfig(), datasetHash: 'f'.repeat(64) })
|
||||
).toThrow('does not match');
|
||||
});
|
||||
test('replays stored provider fixtures and produces identical trades and metrics', async () => {
|
||||
test('stored provider fixtures normalize into identical frozen inputs before admission', async () => {
|
||||
const { documents, mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
|
|
@ -287,16 +287,11 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
slippage: 0,
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
});
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
const first = await engine.runBacktest(config);
|
||||
const second = await engine.runBacktest(config);
|
||||
expect(first.status).toBe('completed');
|
||||
expect(first.trades.length).toBeGreaterThan(0);
|
||||
expect(first.trades).toEqual(second.trades);
|
||||
expect(first.metrics).toEqual(second.metrics);
|
||||
expect(first.equity).toEqual(second.equity);
|
||||
expect(first.metrics.totalReturn).toBeFinite();
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
const first = await loadDataset(storage, config);
|
||||
const second = await loadDataset(storage, config);
|
||||
expect(first).toEqual(second);
|
||||
expect(first.bars).toHaveLength(fixture.length);
|
||||
expect(first.manifest.hash).toBe(second.manifest.hash);
|
||||
});
|
||||
|
||||
test('all listings retain their first same-timestamp bar and deterministic tie ordering', async () => {
|
||||
|
|
@ -310,16 +305,14 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
};
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
const first = await engine.runBacktest(config);
|
||||
const second = await engine.runBacktest(config);
|
||||
const first = await loadDataset(storage, config);
|
||||
const second = await loadDataset(storage, config);
|
||||
for (const id of config.symbols) {
|
||||
expect(first.ohlcData[id]).toHaveLength(fixture.length);
|
||||
expect(first.ohlcData[id]?.[0]?.timestamp).toBe(start.getTime());
|
||||
const bars = first.bars.filter(bar => bar.symbol === id);
|
||||
expect(bars).toHaveLength(fixture.length);
|
||||
expect(bars[0]?.timestamp).toBe(start.getTime());
|
||||
}
|
||||
expect(first.trades).toEqual(second.trades);
|
||||
expect(first.metrics).toEqual(second.metrics);
|
||||
expect(first.equity).toEqual(second.equity);
|
||||
expect(first).toEqual(second);
|
||||
});
|
||||
|
||||
test('rejects malformed provider records before writing anything', async () => {
|
||||
|
|
@ -347,7 +340,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
);
|
||||
});
|
||||
|
||||
test('empty storage and unknown strategies fail without leaving the engine running', async () => {
|
||||
test('retired provider-at-execution entry refuses before storage or native strategy resolution', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
|
|
@ -360,9 +353,11 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
await expect(engine.runBacktest(config)).rejects.toThrow('No historical data');
|
||||
await expect(engine.runBacktest(config)).rejects.toThrow(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
await expect(engine.runBacktest({ ...config, strategy: 'does-not-exist' })).rejects.toThrow(
|
||||
'Unknown native strategy'
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -118,7 +118,7 @@ const config = () =>
|
|||
});
|
||||
|
||||
describe('EOD intraday ingestion → research storage', () => {
|
||||
test('ingest_5m_freeze_replay: real writer/admission, v2 freeze and legacy native replay', async () => {
|
||||
test('ingest_5m_freeze: real writer, v2 freeze and historical v1 compatibility', async () => {
|
||||
const store = memoryStore();
|
||||
const response = intradayResponse();
|
||||
expect(await ingest(store.mongodb, response)).toEqual({
|
||||
|
|
@ -166,7 +166,7 @@ describe('EOD intraday ingestion → research storage', () => {
|
|||
).toBe(true);
|
||||
expect(validateDatasetV2(JSON.parse(JSON.stringify(dataset)))).toEqual(dataset);
|
||||
|
||||
// V1 runtime stays V1. This checks storage compatibility, not future F06 replay correctness.
|
||||
// Historical V1 payloads remain readable; production execution requires V2 admission.
|
||||
const legacy = await loadDataset(storage, config());
|
||||
expect(
|
||||
legacy.bars.map(({ timestamp, open, high, low, close, volume }) => ({
|
||||
|
|
@ -182,19 +182,10 @@ describe('EOD intraday ingestion → research storage', () => {
|
|||
legacy.manifest.hash
|
||||
);
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
try {
|
||||
const first = await engine.runBacktest(config(), async () => legacy);
|
||||
const second = await engine.runBacktest(config(), async () => legacy);
|
||||
expect(first.status).toBe('completed');
|
||||
expect(first.ohlcData[identity.eodSearchCode]).toHaveLength(78);
|
||||
expect(first.ohlcData[identity.eodSearchCode]?.[0]?.timestamp).toBe(start.getTime());
|
||||
expect(first.trades.length).toBeGreaterThan(0);
|
||||
expect(first.trades).toEqual(second.trades);
|
||||
expect(first.equity).toEqual(second.equity);
|
||||
expect(first.metrics).toEqual(second.metrics);
|
||||
} finally {
|
||||
await engine.shutdown();
|
||||
}
|
||||
await expect(engine.runBacktest(config(), async () => legacy)).rejects.toThrow(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
await engine.shutdown();
|
||||
});
|
||||
|
||||
test('supported collections, UTC seconds and half-open fractional boundaries', async () => {
|
||||
|
|
@ -210,7 +201,7 @@ describe('EOD intraday ingestion → research storage', () => {
|
|||
['1m', 'eodIntraday1M'],
|
||||
['5m', 'eodIntraday5M'],
|
||||
['1h', 'eodIntraday1H'],
|
||||
]) {
|
||||
] as const) {
|
||||
const bars = await storage.getHistoricalBars(
|
||||
identity.eodSearchCode,
|
||||
new Date(start.getTime() + 1),
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ test('canonical paper rejects invalid role/configuration before resolving servic
|
|||
config.matching.series[0]!.mode = 'Open';
|
||||
await expect(
|
||||
registerOrchestratorServices(container, {
|
||||
role: 'paper',
|
||||
canonicalPaper: config,
|
||||
})
|
||||
).rejects.toThrow('Quote execution only');
|
||||
|
|
@ -40,6 +41,6 @@ test('live defaults, research canonical configuration and missing custody fail b
|
|||
createContainer(config({ defaultMode: 'backtest', canonicalPaper: paperFeedConfiguration() }))
|
||||
).rejects.toThrow('requires a paper composition');
|
||||
await expect(
|
||||
createContainer(config({ canonicalPaper: paperFeedConfiguration() }))
|
||||
createContainer(config({ defaultMode: 'paper', canonicalPaper: paperFeedConfiguration() }))
|
||||
).rejects.toThrow('requires durable PostgreSQL');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -361,7 +361,8 @@ describe('canonical paper HTTP failure and legacy gateway isolation', () => {
|
|||
const response = await f.app.request(path, { method, headers });
|
||||
expect(response.status).toBe(409);
|
||||
expect(await response.json()).toEqual({
|
||||
error: 'Legacy account gateway unavailable in canonical paper mode',
|
||||
error:
|
||||
'Legacy account execution is retired; use the explicitly configured canonical paper runtime',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
203
test/integration/research-agents-api.test.ts
Normal file
203
test/integration/research-agents-api.test.ts
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import {
|
||||
createHttpSecurity,
|
||||
getCredentialHttpPrincipal,
|
||||
getResearchHttpPrincipal,
|
||||
} from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { createResearchAgentSchema } from '@stock-bot/stock-config/research-agents';
|
||||
import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
|
||||
import { researchAgentDatabaseError } from '../../apps/stock/web-api/src/services/research-agent-budget';
|
||||
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
|
||||
|
||||
const agent = `agent:${randomUUID()}` as const;
|
||||
const token = 'sb-research.fixture-token';
|
||||
const adminToken = 'operator-test-secret-12345678901234567890';
|
||||
const serviceToken = 'service-test-secret-123456789012345678901';
|
||||
const limits = {
|
||||
maxActiveTrials: 2,
|
||||
maxTrialsPerExperiment: 4,
|
||||
maxBarEvaluationsPerExperiment: 1000,
|
||||
maxAttemptWallMs: 1000,
|
||||
maxAttempts: 2,
|
||||
};
|
||||
function boundary(disabled = false, resolver = true) {
|
||||
const resolve = mock(async () => ({ principal: agent }));
|
||||
const security = createHttpSecurity({
|
||||
adminToken,
|
||||
serviceToken,
|
||||
disabled,
|
||||
environment: 'test',
|
||||
browserSessions: true,
|
||||
...(resolver ? { resolveResearchCredential: resolve } : {}),
|
||||
});
|
||||
const app = new Hono();
|
||||
security.mount(app);
|
||||
app.all('/api/v2/experiments', c =>
|
||||
c.json({
|
||||
principal: getResearchHttpPrincipal(c.req.raw),
|
||||
privileged: getCredentialHttpPrincipal(c.req.raw) ?? null,
|
||||
})
|
||||
);
|
||||
return { app, security, resolve };
|
||||
}
|
||||
test('research HTTP identity is distinct; Origin and upgrades are fenced before asynchronous resolution', async () => {
|
||||
const f = boundary();
|
||||
for (const headers of [{ Origin: 'https://evil.invalid' }, { Upgrade: 'websocket' }] as Record<
|
||||
string,
|
||||
string
|
||||
>[]) {
|
||||
const response = await f.app.request('/api/v2/experiments', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, ...headers },
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
expect(response.headers.get('cache-control')).toBe('no-store');
|
||||
}
|
||||
expect(f.resolve).toHaveBeenCalledTimes(0);
|
||||
const response = await f.app.request('/api/v2/experiments', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ principal: agent, privileged: null });
|
||||
expect(
|
||||
f.security.authorize(
|
||||
new Request('http://localhost/api/v2/experiments', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
)?.status
|
||||
).toBe(403);
|
||||
});
|
||||
test('research credential never becomes a privileged session or bypasses disabled/unrelated authentication', async () => {
|
||||
for (const f of [boundary(true), boundary(false, false)]) {
|
||||
const response = await f.app.request('/api/v2/experiments', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
expect(f.resolve).toHaveBeenCalledTimes(0);
|
||||
expect(f.security.researchEnabled).toBe(false);
|
||||
const login = await f.app.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
expect(login.status).toBe(403);
|
||||
expect(login.headers.get('set-cookie')).toBeNull();
|
||||
}
|
||||
const f = boundary();
|
||||
const login = await f.app.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
expect(login.status).toBe(403);
|
||||
expect(login.headers.get('set-cookie')).toBeNull();
|
||||
});
|
||||
test('operator-only provisioning fails closed without enabled research authentication before storage', async () => {
|
||||
const query = mock(async () => {
|
||||
throw new Error('denied operation touched storage');
|
||||
});
|
||||
const container = {
|
||||
postgres: { query },
|
||||
logger: { error: mock(() => {}) },
|
||||
} as unknown as IServiceContainer;
|
||||
for (const disabled of [false, true]) {
|
||||
const f = boundary(disabled);
|
||||
f.app.route('/', createResearchAgentRoutes(container, f.security.researchEnabled));
|
||||
for (const bearer of [token, serviceToken, ...(disabled ? [adminToken] : [])]) {
|
||||
const response = await f.app.request('/api/v2/research-agents', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
}
|
||||
}
|
||||
expect(query).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
test('resolver exact write capabilities refuse trading, operators, foreign evidence and ownership impersonation', async () => {
|
||||
const projectId = randomUUID(),
|
||||
experimentId = randomUUID(),
|
||||
familyId = randomUUID();
|
||||
const query = mock(async (sql: string) => ({
|
||||
rows: sql.includes('token_hash')
|
||||
? [{ id: agent, enabled: true, policy: { allowedProjectIds: [projectId] } }]
|
||||
: [{ submission_principal: 'operator', owner_principal: 'operator', project_id: projectId }],
|
||||
}));
|
||||
const service = new ResearchAgentsService({
|
||||
postgres: { query },
|
||||
} as unknown as IServiceContainer);
|
||||
const check = (path: string, method = 'POST') =>
|
||||
service.authenticate(
|
||||
new Request(`http://localhost${path}`, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
);
|
||||
for (const path of [
|
||||
'/api/v2/research-agents',
|
||||
'/api/v2/backtests',
|
||||
'/api/v2/datasets/retain',
|
||||
'/api/v2/strategy-versions/' + familyId + '/review',
|
||||
'/api/operations/start',
|
||||
'/api/v2/runs/' + experimentId + '/reproduce',
|
||||
`/api/v2/experiments/${experimentId}/cancel`,
|
||||
`/api/v2/strategies/${familyId}/versions`,
|
||||
`/api/v2/research-projects/${randomUUID()}/hypotheses`,
|
||||
]) {
|
||||
expect(await check(path)).toBeInstanceOf(Response);
|
||||
expect(((await check(path)) as Response).status).toBe(403);
|
||||
}
|
||||
expect(await check(`/api/v2/research-projects/${projectId}/hypotheses`)).toEqual({
|
||||
principal: agent,
|
||||
});
|
||||
expect(await check('/api/v2/experiments/preview')).toEqual({ principal: agent });
|
||||
expect(await check(`/api/v2/experiments/${experimentId}`, 'GET')).toEqual({ principal: agent });
|
||||
expect(await check('/api/v2/research-agents', 'GET')).toBeInstanceOf(Response);
|
||||
});
|
||||
test('quota diagnostics remain distinguishable from arbitrary database failures; policy is strict and bounded', () => {
|
||||
expect(
|
||||
researchAgentDatabaseError({ code: 'P0001', message: 'research_budget:capacity' })?.status
|
||||
).toBe(429);
|
||||
expect(
|
||||
researchAgentDatabaseError({ code: 'P0001', message: 'research_access:denied' })?.status
|
||||
).toBe(403);
|
||||
expect(researchAgentDatabaseError(new Error('database unavailable'))).toBeNull();
|
||||
expect(
|
||||
researchAgentDatabaseError({ code: '23514', message: 'research_budget:spoof' })
|
||||
).toBeNull();
|
||||
expect(
|
||||
createResearchAgentSchema.parse({
|
||||
name: 'Agent',
|
||||
allowedProjectIds: [],
|
||||
allowedBacktestIds: [],
|
||||
limits,
|
||||
}).limits
|
||||
).toEqual(limits);
|
||||
for (const bad of [
|
||||
{ ...limits, maxAttempts: 4 },
|
||||
{ ...limits, maxActiveTrials: 0 },
|
||||
{ ...limits, maxAttemptWallMs: 2147483648 },
|
||||
]) {
|
||||
expect(
|
||||
createResearchAgentSchema.safeParse({
|
||||
name: 'Agent',
|
||||
allowedProjectIds: [],
|
||||
allowedBacktestIds: [],
|
||||
limits: bad,
|
||||
}).success
|
||||
).toBe(false);
|
||||
}
|
||||
expect(
|
||||
createResearchAgentSchema.safeParse({
|
||||
name: 'Agent',
|
||||
allowedProjectIds: [],
|
||||
allowedBacktestIds: [],
|
||||
limits,
|
||||
ownerPrincipal: 'operator',
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
345
test/integration/research-agents-ui.test.tsx
Normal file
345
test/integration/research-agents-ui.test.tsx
Normal file
|
|
@ -0,0 +1,345 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import type { ResearchAgentRecord } from '@stock-bot/stock-config/research-agents';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const names = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const globals = names.map(
|
||||
name => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const
|
||||
);
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let router: typeof import('react-router-dom');
|
||||
let Page: typeof import('../../apps/stock/web-app/src/features/research/ResearchAgentsPage').ResearchAgentsPage;
|
||||
let api: typeof import('../../apps/stock/web-app/src/features/research/services/researchAgentsApi').researchAgentsApi;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
const agentId = 'agent:11111111-1111-4111-8111-111111111111';
|
||||
const projectId = '22222222-2222-4222-8222-222222222222';
|
||||
const backtestId = '33333333-3333-4333-8333-333333333333';
|
||||
const record = (extra: Partial<ResearchAgentRecord> = {}): ResearchAgentRecord => ({
|
||||
id: agentId,
|
||||
name: 'Research worker',
|
||||
enabled: true,
|
||||
revision: 1,
|
||||
allowedProjectIds: [projectId],
|
||||
grants: [{ backtestId, policyHash: 'a'.repeat(64) }],
|
||||
limits: {
|
||||
maxActiveTrials: 1,
|
||||
maxTrialsPerExperiment: 10,
|
||||
maxBarEvaluationsPerExperiment: 100000,
|
||||
maxAttemptWallMs: 60000,
|
||||
maxAttempts: 3,
|
||||
},
|
||||
createdAt: '2026-10-24T12:00:00.000Z',
|
||||
updatedAt: '2026-10-24T12:00:00.000Z',
|
||||
...extra,
|
||||
});
|
||||
type Pending = {
|
||||
path: string;
|
||||
method: string;
|
||||
body: unknown;
|
||||
resolve: (response: Response) => void;
|
||||
reject: (error: Error) => void;
|
||||
settled: boolean;
|
||||
};
|
||||
const calls: Pending[] = [];
|
||||
function pending(path = '', method = 'GET') {
|
||||
const value = calls.find(
|
||||
call =>
|
||||
!call.settled && call.path === `/api/v2/research-agents${path}` && call.method === method
|
||||
);
|
||||
if (!value) {
|
||||
throw new Error(`Missing request ${method} ${path}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function reply(call: Pending, body: unknown, status = 200) {
|
||||
call.settled = true;
|
||||
call.resolve(Response.json(body, { status }));
|
||||
}
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(text: string) {
|
||||
const value = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === text
|
||||
);
|
||||
if (!value) {
|
||||
throw new Error(`Missing button ${text}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
async function fill(label: string, value: string) {
|
||||
await flush(() => {
|
||||
const input = host.querySelector(`[aria-label="${label}"]`)!;
|
||||
const prototype =
|
||||
input.tagName === 'TEXTAREA'
|
||||
? browser.HTMLTextAreaElement.prototype
|
||||
: browser.HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
|
||||
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
}
|
||||
async function mount(agents: ResearchAgentRecord[] = []) {
|
||||
root = createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: [`/research/agents?projectId=${projectId}`] },
|
||||
createElement(Page)
|
||||
)
|
||||
)
|
||||
);
|
||||
await flush(() => reply(pending(), { agents }));
|
||||
}
|
||||
async function draft() {
|
||||
await fill('Agent name', 'Research worker');
|
||||
await fill('Allowed backtest IDs', backtestId);
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [name, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ ResearchAgentsPage: Page } = await import(
|
||||
'../../apps/stock/web-app/src/features/research/ResearchAgentsPage'
|
||||
));
|
||||
({ researchAgentsApi: api } = await import(
|
||||
'../../apps/stock/web-app/src/features/research/services/researchAgentsApi'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
calls.length = 0;
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) =>
|
||||
new Promise<Response>((resolve, reject) => {
|
||||
calls.push({
|
||||
path: new URL(String(input)).pathname,
|
||||
method: init?.method ?? 'GET',
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
resolve,
|
||||
reject,
|
||||
settled: false,
|
||||
});
|
||||
})) as unknown as typeof browser.fetch;
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(() => {
|
||||
browser.happyDOM.abort();
|
||||
for (const [name, descriptor] of globals) {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, name, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, name);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('explicit scoped creation posts one bounded policy, shows credential once and never starts work', async () => {
|
||||
await mount();
|
||||
expect(host.textContent).toContain('No research agents configured.');
|
||||
expect(
|
||||
(host.querySelector('[aria-label="Allowed project IDs"]') as HTMLTextAreaElement).value
|
||||
).toBe(projectId);
|
||||
await draft();
|
||||
await flush(() => {
|
||||
button('Create credential').click();
|
||||
button('Create credential').click();
|
||||
});
|
||||
const request = pending('', 'POST');
|
||||
expect(request.body).toEqual({
|
||||
name: 'Research worker',
|
||||
allowedProjectIds: [projectId],
|
||||
allowedBacktestIds: [backtestId],
|
||||
limits: record().limits,
|
||||
});
|
||||
expect(calls.filter(call => call.method === 'POST')).toHaveLength(1);
|
||||
await flush(() =>
|
||||
reply(request, { agent: record(), token: 'fixture-generated-credential' }, 201)
|
||||
);
|
||||
expect(
|
||||
(host.querySelector('[aria-label="New research token"]') as HTMLTextAreaElement).value
|
||||
).toBe('fixture-generated-credential');
|
||||
expect(button('Create credential').disabled).toBe(true);
|
||||
expect(host.textContent).toContain('Revision 1');
|
||||
expect(host.textContent).toContain('a'.repeat(64));
|
||||
await flush(() => button('I have saved the credential').click());
|
||||
expect(host.querySelector('[aria-label="New research token"]')).toBeNull();
|
||||
expect(calls.some(call => /runs|experiments|paper/.test(call.path))).toBe(false);
|
||||
});
|
||||
|
||||
test('malformed scope and invalid budgets preserve draft without writing', async () => {
|
||||
await mount();
|
||||
await draft();
|
||||
await fill('Maximum active trials', '0');
|
||||
await flush(() =>
|
||||
host
|
||||
.querySelector('form')!
|
||||
.dispatchEvent(
|
||||
new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('limits.maxActiveTrials');
|
||||
expect(calls.some(call => call.method === 'POST')).toBe(false);
|
||||
await fill('Maximum active trials', '1');
|
||||
await fill('Allowed project IDs', 'not-a-uuid');
|
||||
await flush(() => button('Create credential').click());
|
||||
expect(host.textContent).toContain('allowedProjectIds');
|
||||
expect(calls.some(call => call.method === 'POST')).toBe(false);
|
||||
expect((host.querySelector('[aria-label="Agent name"]') as HTMLInputElement).value).toBe(
|
||||
'Research worker'
|
||||
);
|
||||
});
|
||||
|
||||
test('ambiguous creation forbids blind retry and permits inspecting and disabling the retained credential', async () => {
|
||||
await mount();
|
||||
await draft();
|
||||
await flush(() => button('Create credential').click());
|
||||
const request = pending('', 'POST');
|
||||
await flush(() => {
|
||||
request.settled = true;
|
||||
request.reject(new Error('Response lost'));
|
||||
});
|
||||
expect(host.textContent).toContain('token cannot be recovered');
|
||||
expect(button('Create credential').disabled).toBe(true);
|
||||
expect(button('I have checked the saved agents').disabled).toBe(true);
|
||||
await flush(() => button('I have checked the saved agents').click());
|
||||
expect(button('Create credential').disabled).toBe(true);
|
||||
await flush(() => button('Create credential').click());
|
||||
expect(calls.filter(call => call.method === 'POST')).toHaveLength(1);
|
||||
await flush(() => button('Check saved agents').click());
|
||||
await flush(() => reply(pending(), { error: 'List unavailable' }, 503));
|
||||
expect(button('I have checked the saved agents').disabled).toBe(true);
|
||||
await flush(() => button('Check saved agents').click());
|
||||
expect(button('I have checked the saved agents').disabled).toBe(true);
|
||||
await flush(() => reply(pending(), { agents: [record()] }));
|
||||
expect(button('I have checked the saved agents').disabled).toBe(false);
|
||||
await flush(() => button('Disable Research worker').click());
|
||||
expect(pending(`/${encodeURIComponent(agentId)}`, 'PATCH').body).toEqual({
|
||||
expectedRevision: 1,
|
||||
enabled: false,
|
||||
});
|
||||
await flush(() =>
|
||||
reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), {
|
||||
agent: record({ enabled: false, revision: 2 }),
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Disabled');
|
||||
expect(button('Create credential').disabled).toBe(true);
|
||||
await flush(() => button('I have checked the saved agents').click());
|
||||
expect(button('Create credential').disabled).toBe(false);
|
||||
});
|
||||
|
||||
test('failed list is explicit and refresh recovers; obsolete budget response cannot replace refreshed state', async () => {
|
||||
await mount([record()]);
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
const old = pending(`/${encodeURIComponent(agentId)}/budget`);
|
||||
await flush(() => button('Refresh agents').click());
|
||||
await flush(() => reply(pending(), { error: 'Store unavailable' }, 503));
|
||||
expect(host.textContent).toContain('Store unavailable');
|
||||
expect(host.textContent).not.toContain('No research agents configured');
|
||||
await flush(() => button('Refresh agents').click());
|
||||
await flush(() => reply(pending(), { agents: [record()] }));
|
||||
await flush(() => reply(old, { agent: record(), activeTrials: 1, remainingActiveTrials: 0 }));
|
||||
expect(host.textContent).not.toContain('Active trials:');
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
await flush(() =>
|
||||
reply(pending(`/${encodeURIComponent(agentId)}/budget`), {
|
||||
agent: record(),
|
||||
activeTrials: 1,
|
||||
remainingActiveTrials: 0,
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Active trials: 1; available slots: 0');
|
||||
});
|
||||
|
||||
test('policy conflict refreshes rather than overwriting the newer revision', async () => {
|
||||
await mount([record()]);
|
||||
await flush(() => button('Disable Research worker').click());
|
||||
await flush(() =>
|
||||
reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), { error: 'Revision changed' }, 409)
|
||||
);
|
||||
expect(host.textContent).toContain('Refresh to verify');
|
||||
await flush(() => reply(pending(), { agents: [record({ revision: 3, enabled: false })] }));
|
||||
expect(host.textContent).toContain('Revision 3');
|
||||
expect(calls.filter(call => call.method === 'PATCH')).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('budget identity/capacity and update identity/revision mismatches reject', async () => {
|
||||
const budget = api.budget(agentId);
|
||||
reply(pending(`/${encodeURIComponent(agentId)}/budget`), {
|
||||
agent: record(),
|
||||
activeTrials: 1,
|
||||
remainingActiveTrials: 1,
|
||||
});
|
||||
await expect(budget).rejects.toThrow('capacity mismatch');
|
||||
const update = api.update(agentId, { expectedRevision: 1, enabled: false });
|
||||
reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), {
|
||||
agent: record({ revision: 1, enabled: false }),
|
||||
});
|
||||
await expect(update).rejects.toThrow('revision mismatch');
|
||||
});
|
||||
|
||||
test('unmount fences late credential response', async () => {
|
||||
await mount();
|
||||
await draft();
|
||||
await flush(() => button('Create credential').click());
|
||||
const request = pending('', 'POST');
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await flush(() => reply(request, { agent: record(), token: 'fixture-late-credential' }, 201));
|
||||
expect(host.textContent).toBe('');
|
||||
});
|
||||
|
||||
test('per-agent budget request order fences older success and failure responses', async () => {
|
||||
await mount([record()]);
|
||||
const path = `/${encodeURIComponent(agentId)}/budget`;
|
||||
const newerRequest = () => {
|
||||
const value = calls
|
||||
.filter(call => !call.settled && call.path === `/api/v2/research-agents${path}`)
|
||||
.at(-1);
|
||||
if (!value) {
|
||||
throw new Error('Missing newer budget request');
|
||||
}
|
||||
return value;
|
||||
};
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
const olderSuccess = pending(path);
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
const newestSuccess = newerRequest();
|
||||
expect(newestSuccess).not.toBe(olderSuccess);
|
||||
await flush(() =>
|
||||
reply(newestSuccess, { agent: record(), activeTrials: 0, remainingActiveTrials: 1 })
|
||||
);
|
||||
await flush(() =>
|
||||
reply(olderSuccess, { agent: record(), activeTrials: 1, remainingActiveTrials: 0 })
|
||||
);
|
||||
expect(host.textContent).toContain('Active trials: 0; available slots: 1');
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
const olderFailure = pending(path);
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
await flush(() =>
|
||||
reply(newerRequest(), { agent: record(), activeTrials: 1, remainingActiveTrials: 0 })
|
||||
);
|
||||
await flush(() => reply(olderFailure, { error: 'Obsolete unavailable response' }, 503));
|
||||
expect(host.textContent).toContain('Active trials: 1; available slots: 0');
|
||||
expect(host.textContent).not.toContain('Obsolete unavailable response');
|
||||
});
|
||||
|
|
@ -2,19 +2,19 @@ import { asFunction, asValue, createContainer as createDiContainer } from 'awili
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { defaultRiskLimits } from '../../apps/stock/orchestrator/src/execution/model';
|
||||
import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes';
|
||||
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { config, logger, makeExecution } from '../fixtures/execution';
|
||||
import { logger } from '../fixtures/execution';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function compose(options: Parameters<typeof registerOrchestratorServices>[1] = {}) {
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
|
|
@ -30,42 +30,44 @@ async function compose(options: Parameters<typeof registerOrchestratorServices>[
|
|||
const services: OrchestratorServices = { logger };
|
||||
container.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(container, options);
|
||||
const runtime = services.custom!;
|
||||
cleanup.push(async () => {
|
||||
await runtime.BacktestRunner!.shutdown();
|
||||
await runtime.ModeManager!.shutdown();
|
||||
await runtime.StrategyManager!.shutdown();
|
||||
await services.custom!.BacktestRunner!.shutdown();
|
||||
await container.dispose();
|
||||
});
|
||||
return runtime;
|
||||
return { services, container };
|
||||
}
|
||||
|
||||
describe('research runtime composition admission', () => {
|
||||
test.each([true, false])(
|
||||
'legacy_paper_combination_rejected_before_prepare (initializeMode=%s)',
|
||||
async initializeMode => {
|
||||
describe('canonical research-only default composition', () => {
|
||||
test.each(['paper', 'research-only'] as const)(
|
||||
'%s refuses retired TypeScript financial execution before resolving services',
|
||||
async role => {
|
||||
let resolved = 0;
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
container.register({
|
||||
serviceContainer: asFunction(() => {
|
||||
resolved++;
|
||||
throw new Error('Runtime services must not be resolved');
|
||||
throw new Error('must not resolve');
|
||||
}),
|
||||
});
|
||||
await expect(
|
||||
registerOrchestratorServices(container, { useRustEngine: false, initializeMode })
|
||||
).rejects.toThrow('TypeScript backtests require a research-only composition');
|
||||
registerOrchestratorServices(container, { role, useRustEngine: false })
|
||||
).rejects.toThrow('Legacy financial execution is retired');
|
||||
expect(resolved).toBe(0);
|
||||
}
|
||||
);
|
||||
|
||||
test('unsafe application startup fails before connection setup', async () => {
|
||||
const config = {
|
||||
services: { orchestrator: { backtesting: { useRustEngine: false } } },
|
||||
} as StockAppConfig;
|
||||
await expect(createContainer(config)).rejects.toThrow('Unsupported runtime combination');
|
||||
test('paper requires explicit canonical configuration before connections, including initializeMode false', async () => {
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
await expect(
|
||||
registerOrchestratorServices(container, { role: 'paper', initializeMode: false })
|
||||
).rejects.toThrow('explicit canonicalPaper');
|
||||
await expect(
|
||||
createContainer({ services: { orchestrator: { defaultMode: 'paper' } } } as StockAppConfig)
|
||||
).rejects.toThrow('explicit canonicalPaper');
|
||||
await expect(
|
||||
createContainer({
|
||||
services: { orchestrator: { backtesting: { useRustEngine: false } } },
|
||||
} as StockAppConfig)
|
||||
).rejects.toThrow('Legacy financial execution is retired');
|
||||
});
|
||||
|
||||
test('unchecked role and backend options fail closed before service resolution', async () => {
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
for (const options of [
|
||||
|
|
@ -82,70 +84,45 @@ describe('research runtime composition admission', () => {
|
|||
).rejects.toThrow('role' in options ? 'Unsupported runtime role' : 'must be a boolean');
|
||||
}
|
||||
});
|
||||
|
||||
test('standalone_legacy_research_allowed without automatic paper initialization', async () => {
|
||||
const runtime = await compose({
|
||||
role: 'research-only',
|
||||
useRustEngine: false,
|
||||
allowSyntheticData: true,
|
||||
syntheticSeed: 42,
|
||||
});
|
||||
expect(runtime.BacktestEngine).toBeInstanceOf(BacktestEngine);
|
||||
expect(runtime.ModeManager!.getConfig()).toBeNull();
|
||||
await runtime.ModeManager!.initializeMode(config);
|
||||
const result = await runtime.BacktestEngine!.runBacktest(config);
|
||||
expect(result.status).toBe('completed');
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect(runtime.ModeManager!.getConfig()).toEqual(config);
|
||||
});
|
||||
|
||||
test('research_only_paper_activation_denied through every exposed initializer', async () => {
|
||||
const runtime = await compose({ role: 'research-only', useRustEngine: false });
|
||||
const mode = runtime.ModeManager!;
|
||||
const execution = runtime.ExecutionService!;
|
||||
await mode.initializeMode(config);
|
||||
const engine = mode.getTradingEngine();
|
||||
const account = await execution.getAccount();
|
||||
const paper = { mode: 'paper' as const, startingCapital: 123 };
|
||||
let shutdowns = 0;
|
||||
mode.on('shutdown', () => shutdowns++);
|
||||
|
||||
await expect(mode.initializeMode(paper)).rejects.toThrow('only permits backtest');
|
||||
await expect(mode.transitionMode('backtest', 'paper', paper)).rejects.toThrow(
|
||||
'only permits backtest'
|
||||
test.each([{}, { role: 'research-only' as const }])(
|
||||
'default and explicit research compose one canonical engine without any account/feed/mode gateway',
|
||||
async options => {
|
||||
const { services, container } = await compose(options);
|
||||
expect(services.custom!.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
|
||||
for (const key of [
|
||||
'ModeManager',
|
||||
'ExecutionService',
|
||||
'MarketDataService',
|
||||
'StrategyManager',
|
||||
'PaperTradingManager',
|
||||
'CanonicalPaperRuntime',
|
||||
]) {
|
||||
expect(services.custom).not.toHaveProperty(key);
|
||||
expect(container.hasRegistration(key)).toBe(false);
|
||||
}
|
||||
const app = createRoutes(services);
|
||||
expect(await (await app.request('/health')).json()).toMatchObject({
|
||||
mode: 'research-only',
|
||||
execution: 'canonical-research',
|
||||
});
|
||||
expect((await app.request('/api/recovery')).status).toBe(503);
|
||||
for (const path of ['/api/orders', '/api/positions']) {
|
||||
expect((await app.request(path, { method: 'POST' })).status).toBe(409);
|
||||
}
|
||||
expect(await (await app.request('/api/paper/readiness')).json()).toMatchObject({
|
||||
configured: false,
|
||||
active: false,
|
||||
ready: false,
|
||||
operatorHalted: true,
|
||||
accountId: null,
|
||||
});
|
||||
}
|
||||
);
|
||||
test('cannot overlay the canonical graph on a legacy account runtime', async () => {
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
container.register({ serviceContainer: asValue({ logger, custom: { ExecutionService: {} } }) });
|
||||
await expect(registerOrchestratorServices(container)).rejects.toThrow(
|
||||
'fresh runtime composition'
|
||||
);
|
||||
await expect(execution.initialize(paper, engine)).rejects.toThrow('only permits backtest');
|
||||
const live = {
|
||||
mode: 'live' as const,
|
||||
broker: 'ib',
|
||||
accountId: 'not-a-real-account',
|
||||
accountType: 'cash' as const,
|
||||
riskLimits: { ...defaultRiskLimits },
|
||||
};
|
||||
await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
|
||||
await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled');
|
||||
expect(shutdowns).toBe(0);
|
||||
expect(mode.getTradingEngine()).toBe(engine);
|
||||
expect(mode.getConfig()).toEqual(config);
|
||||
expect(await execution.getAccount()).toEqual(account);
|
||||
});
|
||||
|
||||
test('paper composition defaults to native and cannot be switched to a legacy shared mode', async () => {
|
||||
const runtime = await compose({ initializeMode: false });
|
||||
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
|
||||
await expect(runtime.ModeManager!.initializeMode(config)).rejects.toThrow('only permits paper');
|
||||
await expect(
|
||||
runtime.ExecutionService!.initialize(config, makeExecution().engine)
|
||||
).rejects.toThrow('only permits paper');
|
||||
expect(runtime.ModeManager!.getConfig()).toBeNull();
|
||||
});
|
||||
|
||||
test('research-only native composition also forbids paper startup and activation', async () => {
|
||||
const runtime = await compose({ role: 'research-only' });
|
||||
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
|
||||
expect(runtime.ModeManager!.getConfig()).toBeNull();
|
||||
await expect(
|
||||
runtime.ModeManager!.initializeMode({ mode: 'paper', startingCapital: 10000 })
|
||||
).rejects.toThrow('only permits backtest');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -23,9 +23,35 @@ import {
|
|||
import { buildExperimentPreview } from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview';
|
||||
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
import { parseWalkForwardDetail } from '../../apps/stock/web-app/src/features/experiments/services/walkForwardApi';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
|
||||
test('saved walk-forward report preserves agent authorship across nested validation evidence', () => {
|
||||
const value = document('reported');
|
||||
if (!value.report) {
|
||||
throw new Error('Reported fixture needs its immutable report');
|
||||
}
|
||||
const actor = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
value.report.principal = actor;
|
||||
for (const window of value.windows) {
|
||||
if (!window.validation?.selection || !window.validation.report) {
|
||||
throw new Error('Reported window needs its selection and report');
|
||||
}
|
||||
window.validation.selection.principal = actor;
|
||||
window.validation.report.principal = actor;
|
||||
}
|
||||
const parsed = parseWalkForwardDetail(value);
|
||||
expect(parsed.report?.principal).toBe(actor);
|
||||
expect(parsed.windows.map(window => window.validation?.report?.principal)).toEqual([
|
||||
actor,
|
||||
actor,
|
||||
]);
|
||||
expect(() =>
|
||||
parseWalkForwardDetail({ ...value, report: { ...value.report, principal: 'agent:operator' } })
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
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)]));
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { seedHistoricalRun } from '../fixtures/historical-run';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('catalog-draft-test');
|
||||
|
|
@ -329,7 +330,10 @@ describe.skipIf(!url)('saved catalog backtest drafts on PostgreSQL', () => {
|
|||
{ autoStart: false }
|
||||
);
|
||||
const receipt = { principal: 'operator' as const, key: 'legacy' };
|
||||
const run = await f.api.createRun({ backtestId: legacy.id }, receipt);
|
||||
await expect(f.api.createRun({ backtestId: legacy.id }, receipt)).rejects.toThrow(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: legacy.id }, receipt);
|
||||
const before = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id]))
|
||||
.rows[0].request_snapshot;
|
||||
await f.api.updateBacktest(legacy.id, { name: 'Later edit' });
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
type BacktestRequest,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { DatasetCatalogService } from '../../apps/stock/web-api/src/services/dataset-catalog.service';
|
||||
import { seedHistoricalRun } from '../fixtures/historical-run';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('dataset-catalog-test');
|
||||
|
|
@ -200,7 +201,7 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
|
|||
}
|
||||
});
|
||||
|
||||
test('missing, inconsistent, malformed and unsupported selected snapshots reject before any run/outbox is inserted', async () => {
|
||||
test('legacy admission refuses missing, inconsistent, malformed and unsupported snapshots before any run/outbox is inserted', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(
|
||||
{ ...request(), config: { fastPeriod: 2, slowPeriod: 3 } },
|
||||
|
|
@ -230,7 +231,9 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
|
|||
saved.id,
|
||||
{ ...request().config, datasetHash: 'e'.repeat(64) },
|
||||
]);
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow('not found');
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
||||
0
|
||||
|
|
@ -288,23 +291,20 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
|
|||
const retained = await f.api.getBacktest(saved.id);
|
||||
expect(retained!.endDate.toISOString()).toBe(manifest().endDate);
|
||||
expect(retained!.config.datasetHash).toBe(hash);
|
||||
expect((await f.api.createRun({ backtestId: saved.id })).dataset.requestedHash).toBe(hash);
|
||||
expect(
|
||||
(await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id })).dataset.requestedHash
|
||||
).toBe(hash);
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
});
|
||||
|
||||
test('selected run snapshots commit atomically and same-key retry returns its original receipt before mutable definition validation', async () => {
|
||||
test('historical selected snapshots and original receipts survive retired admission and later definition edits', async () => {
|
||||
const f = await fixture();
|
||||
await f.insert(hash, { manifest: manifest(), bars: [{}] });
|
||||
const saved = await f.api.createBacktest(request(), { autoStart: false });
|
||||
await f.pool.query(
|
||||
`CREATE FUNCTION reject_dataset_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected outbox failure'; END $$; CREATE TRIGGER reject_dataset_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_dataset_outbox()`
|
||||
);
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
|
||||
'injected outbox failure'
|
||||
);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
|
||||
await f.pool.query('DROP TRIGGER reject_dataset_outbox ON backtest_dispatch');
|
||||
const submission = { principal: 'operator' as const, key: 'dataset-retry' };
|
||||
const first = await f.api.createRun({ backtestId: saved.id }, submission);
|
||||
const first = await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id }, submission);
|
||||
expect(first.dataset).toEqual({
|
||||
requestedHash: hash,
|
||||
pinnedHash: null,
|
||||
|
|
@ -334,7 +334,7 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
|
|||
{ ...request(), config: { dataSource: 'eod' } },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const run = await f.api.createRun({ backtestId: saved.id });
|
||||
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id });
|
||||
expect(run.dataset).toEqual({
|
||||
requestedHash: null,
|
||||
pinnedHash: null,
|
||||
|
|
|
|||
|
|
@ -10,10 +10,12 @@ import { HandlerRegistry } from '@stock-bot/handler-registry';
|
|||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { Queue } from '@stock-bot/queue';
|
||||
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
backtestRequestFromDefinition,
|
||||
parseBacktestRequest,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
|
|
@ -28,6 +30,8 @@ import {
|
|||
RunSubmissionConflictError,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('durable-backtest-test');
|
||||
|
|
@ -35,19 +39,23 @@ const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
|||
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
async function until(check: () => Promise<boolean>, timeoutMs = 3_000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if (await check()) return;
|
||||
if (await check()) {
|
||||
return;
|
||||
}
|
||||
await sleep(20);
|
||||
}
|
||||
throw new Error('Timed out waiting for durable workflow');
|
||||
}
|
||||
|
||||
async function fixture() {
|
||||
async function fixture(historical = false) {
|
||||
if (
|
||||
!url ||
|
||||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
|
||||
|
|
@ -59,7 +67,11 @@ async function fixture() {
|
|||
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
options: `-c search_path=${schema}`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
|
|
@ -96,7 +108,7 @@ async function fixture() {
|
|||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
|
|
@ -124,20 +136,23 @@ async function fixture() {
|
|||
const api = new BacktestServiceV2({ postgres, logger }, async () => {
|
||||
throw new Error('No HTTP execution dispatch allowed');
|
||||
});
|
||||
const definition = await api.createBacktest(
|
||||
{
|
||||
name: 'Durable fixture',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 },
|
||||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
// A response DTO includes nullable catalog markers; legacy input deliberately omits them.
|
||||
const definitionInput = {
|
||||
const legacyDefinition = historical
|
||||
? await api.createBacktest(
|
||||
{
|
||||
name: 'Durable fixture',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 },
|
||||
},
|
||||
{ autoStart: false }
|
||||
)
|
||||
: undefined;
|
||||
const canonical = historical ? undefined : await canonicalAdmissionFixture(pool, postgres, false);
|
||||
const definition = canonical?.draft ?? legacyDefinition!;
|
||||
const definitionInput = canonical?.definition ?? {
|
||||
name: definition.name,
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
|
|
@ -146,6 +161,25 @@ async function fixture() {
|
|||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
};
|
||||
// This raw insertion represents already accepted pre-cutover history. It is
|
||||
// deliberately not exposed through a service or production admission switch.
|
||||
const historicalRun = async (_request: { backtestId: string }) => {
|
||||
if (!historical) {
|
||||
throw new Error('Historical fixture only');
|
||||
}
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(definitionInput, {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
});
|
||||
await pool.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,request_snapshot)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3 FROM runs WHERE backtest_id=$2`,
|
||||
[runId, definition.id, snapshot]
|
||||
);
|
||||
await pool.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
|
||||
return { id: runId };
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
|
||||
const history = { reads: 0, unavailable: false };
|
||||
const storage = {
|
||||
|
|
@ -200,10 +234,27 @@ async function fixture() {
|
|||
return worker;
|
||||
};
|
||||
const snapshot = async (runId: string) =>
|
||||
BacktestConfigSchema.parse(
|
||||
canonicalRunRequestSchema.parse(
|
||||
(await pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [runId])).rows[0]
|
||||
.request_snapshot
|
||||
);
|
||||
const legacySnapshot = async (runId: string) =>
|
||||
BacktestConfigSchema.parse(
|
||||
(await pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
|
||||
.request_snapshot
|
||||
);
|
||||
const report = async (request: CanonicalRunRequest): Promise<CanonicalRunResult> => ({
|
||||
kind: 'canonical-result/v1',
|
||||
runId: request.runId,
|
||||
backtestId: request.backtestId,
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
executionTime: 1,
|
||||
financialEngine: 'rust',
|
||||
strategyExecution: 'typescript-retained-builtin/v1',
|
||||
request,
|
||||
...(await engine.runCanonical(request, async () => canonical!.dataset)),
|
||||
});
|
||||
const expire = async (runId: string) => {
|
||||
await pool.query(
|
||||
"UPDATE runs SET lease_expires_at = NOW() - INTERVAL '1 second' WHERE id = $1",
|
||||
|
|
@ -224,6 +275,10 @@ async function fixture() {
|
|||
dispatcher,
|
||||
enqueueWorker,
|
||||
snapshot,
|
||||
legacySnapshot,
|
||||
historicalRun,
|
||||
report,
|
||||
canonical,
|
||||
expire,
|
||||
history,
|
||||
storage,
|
||||
|
|
@ -246,7 +301,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const original = await f.snapshot(runs[0]!.id);
|
||||
await f.api.updateBacktest(f.definition.id, {
|
||||
initialCapital: 12345,
|
||||
config: { fastPeriod: 4, slowPeriod: 9 },
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 4 },
|
||||
});
|
||||
expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe(
|
||||
runs[0]!.id
|
||||
|
|
@ -282,17 +337,27 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
[f.definition.id, second.id].map(backtestId => f.api.createRun({ backtestId }, submission))
|
||||
);
|
||||
try {
|
||||
// Both parent-row locks are held, neither run exists yet, and both transactions
|
||||
// are inside their INSERT. Releasing shared waiters forces the unique-index race.
|
||||
// Both requests passed their initial receipt lookup and hold distinct parent
|
||||
// locks. One waits inside INSERT; the other waits on the shared strategy
|
||||
// family lock. The stale second receipt lookup must still conflict after
|
||||
// the first transaction commits, rather than returning its unrelated run.
|
||||
await until(
|
||||
async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int AS count FROM pg_locks WHERE locktype = 'advisory' AND classid = 40303 AND objid = $1 AND NOT granted",
|
||||
[barrierKey]
|
||||
"SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
|
||||
[f.schema]
|
||||
)
|
||||
).rows[0].count === 2
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int AS count FROM pg_locks WHERE locktype='advisory' AND classid=40303 AND objid=$1 AND NOT granted",
|
||||
[barrierKey]
|
||||
)
|
||||
).rows[0].count
|
||||
).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
} finally {
|
||||
await barrier.query('SELECT pg_advisory_unlock(40303, $1)', [barrierKey]);
|
||||
|
|
@ -313,7 +378,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
);
|
||||
});
|
||||
|
||||
test('different principals can reuse keys; concurrent distinct and legacy submissions preserve run numbering', async () => {
|
||||
test('different principals can reuse keys; concurrent distinct and unkeyed submissions preserve run numbering', async () => {
|
||||
const f = await fixture();
|
||||
const runs = await Promise.all([
|
||||
f.api.createRun({ backtestId: f.definition.id }, { principal: 'operator', key: 'shared' }),
|
||||
|
|
@ -354,7 +419,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('save_only route honors autoStart; authenticated keyed submissions return202/Location or409', async () => {
|
||||
test('save_only catalog route requires explicit false; authenticated keyed submissions return202/Location or409', async () => {
|
||||
const f = await fixture();
|
||||
const app = new Hono();
|
||||
createHttpSecurity({ disabled: true, environment: 'test' }).mount(app);
|
||||
|
|
@ -387,11 +452,14 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
expect(response.headers.get('Location')).toBe(`/api/v2/runs/${run.id}`);
|
||||
expect((await (await post({ speedMultiplier: null })).json()).id).toBe(run.id);
|
||||
expect((await post({ speedMultiplier: 2 })).status).toBe(409);
|
||||
const legacy = await app.request('/api/v2/backtests', {
|
||||
const saveOnly = await app.request('/api/v2/backtests', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...body, autoStart: undefined }),
|
||||
});
|
||||
expect(await f.api.listRuns((await legacy.json()).id)).toHaveLength(1);
|
||||
expect(saveOnly.status).toBe(400);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM backtests')).rows[0].count).toBe(
|
||||
2
|
||||
);
|
||||
});
|
||||
|
||||
test('cookie renewal and admin bearer replay the same operator submission while service keys are separate', async () => {
|
||||
|
|
@ -442,9 +510,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const f = await fixture(true);
|
||||
const run = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const config = await f.legacySnapshot(run.id);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
|
|
@ -461,51 +529,40 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
.dataset_hash
|
||||
).toBeNull();
|
||||
});
|
||||
test('prepared snapshots survive owner loss and replay through JSONB without provider reads', async () => {
|
||||
test('retained canonical inputs survive owner loss and replay without provider reads', async () => {
|
||||
const f = await fixture();
|
||||
const parameters = {
|
||||
...f.definition.config,
|
||||
dataFrequency: '1d',
|
||||
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
||||
};
|
||||
await f.api.updateBacktest(f.definition.id, { config: parameters });
|
||||
const first = await f.runner.runQueued(
|
||||
(await f.api.createRun({ backtestId: f.definition.id })).id
|
||||
);
|
||||
const baseline = (await f.api.getRunResults(first.runId))!;
|
||||
expect(baseline.config.parameters).toEqual(parameters);
|
||||
const first = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.runner.runQueued(first.id);
|
||||
const baseline = await f.api.getRunResults(first.id);
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const old = await f.repository.start(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.loadDataset(
|
||||
const old = await f.repository.startCanonical(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.loadCanonicalDataset(
|
||||
run.id,
|
||||
old.attemptId,
|
||||
baseline.config.dataset!.hash
|
||||
f.canonical!.dataset.manifest.hash
|
||||
);
|
||||
expect(frozen?.bars).toHaveLength(70);
|
||||
await f.expire(run.id);
|
||||
await expect(f.repository.loadDataset(run.id, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
await expect(f.repository.freezeDataset(run.id, old.attemptId, frozen!)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
const reads = f.history.reads;
|
||||
await expect(
|
||||
f.repository.loadCanonicalDataset(run.id, old.attemptId, frozen.manifest.hash)
|
||||
).rejects.toBeInstanceOf(BacktestLeaseLostError);
|
||||
f.history.unavailable = true;
|
||||
await f.dispatcher.tick();
|
||||
await f.runner.runQueued(run.id);
|
||||
const replay = (await f.api.getRunResults(run.id))!;
|
||||
expect(f.history.reads).toBe(reads);
|
||||
expect(replay.config.dataset).toEqual(baseline.config.dataset);
|
||||
expect(replay.config.parameters).toEqual(parameters);
|
||||
expect(replay.trades).toEqual(baseline.trades);
|
||||
expect(replay.metrics).toEqual(baseline.metrics);
|
||||
const replay = await f.api.getRunResults(run.id);
|
||||
if (!baseline || !replay || !('financial' in baseline) || !('financial' in replay)) {
|
||||
throw new Error('Canonical results required');
|
||||
}
|
||||
expect(f.history.reads).toBe(0);
|
||||
expect(replay.financial.projection.valuation).toEqual(baseline.financial.projection.valuation);
|
||||
expect(replay.financial.projection.fills).toEqual(baseline.financial.projection.fills);
|
||||
expect(replay.analytics).toEqual(baseline.analytics);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('snapshot insertion and the run pointer roll back together; frozen inputs cannot be replaced', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const f = await fixture(true);
|
||||
const run = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const config = await f.legacySnapshot(run.id);
|
||||
const claim = await f.repository.start(config);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
await f.pool
|
||||
|
|
@ -536,9 +593,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('cancellation after snapshot insertion aborts preparation and rolls back the run pointer and payload', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const f = await fixture(true);
|
||||
const run = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const config = await f.legacySnapshot(run.id);
|
||||
const claim = await f.repository.start(config);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
const controller = new AbortController();
|
||||
|
|
@ -549,10 +606,14 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
work(
|
||||
new Proxy(client, {
|
||||
get(target, key) {
|
||||
if (key !== 'query') return Reflect.get(target, key);
|
||||
if (key !== 'query') {
|
||||
return Reflect.get(target, key);
|
||||
}
|
||||
return async (sql: string, params?: unknown[]) => {
|
||||
const result = await target.query(sql, params);
|
||||
if (sql.startsWith('INSERT INTO backtest_datasets')) controller.abort(reason);
|
||||
if (sql.startsWith('INSERT INTO backtest_datasets')) {
|
||||
controller.abort(reason);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
},
|
||||
|
|
@ -574,9 +635,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('restored snapshots are revalidated rather than trusted by their content-addressed key', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const f = await fixture(true);
|
||||
const run = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const config = await f.legacySnapshot(run.id);
|
||||
const claim = await f.repository.start(config);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
// Model corrupt historical storage at initial insertion; retained evidence cannot be edited.
|
||||
|
|
@ -595,14 +656,15 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
await expect(f.runner.runQueued(run.id)).rejects.toThrow('hash/content');
|
||||
expect((await f.runner.runQueued(run.id)).status).toBe('failed');
|
||||
expect((await f.api.getRun(run.id))?.error).toContain('Legacy backtest execution is retired');
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('failed');
|
||||
expect(await f.api.getRunResults(run.id)).toBeNull();
|
||||
expect(f.history.reads).toBe(reads);
|
||||
});
|
||||
|
||||
test('a missing retained dataset fails a historical request without provider fallback', async () => {
|
||||
const f = await fixture();
|
||||
const f = await fixture(true);
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(
|
||||
{ ...f.definitionInput, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
|
||||
|
|
@ -615,56 +677,38 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
);
|
||||
await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]);
|
||||
f.history.unavailable = true;
|
||||
await expect(f.runner.runQueued(runId)).rejects.toThrow('Frozen dataset not found');
|
||||
expect((await f.runner.runQueued(runId)).status).toBe('failed');
|
||||
expect((await f.api.getRun(runId))?.error).toContain('Legacy backtest execution is retired');
|
||||
expect(f.history.reads).toBe(0);
|
||||
expect((await f.api.getRun(runId))?.status).toBe('failed');
|
||||
expect(await f.api.getRunResults(runId)).toBeNull();
|
||||
});
|
||||
|
||||
test('an explicit dataset replay rejects a different listing or date range', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.runner.runQueued(run.id);
|
||||
const result = (await f.api.getRunResults(run.id))!;
|
||||
await expect(
|
||||
f.runner.runBacktest({
|
||||
...(await f.snapshot(run.id)),
|
||||
runId: undefined,
|
||||
endDate: '2024-03-16T00:00:00.000Z',
|
||||
datasetHash: result.config.dataset!.hash,
|
||||
})
|
||||
).rejects.toThrow('does not match');
|
||||
});
|
||||
test('API acceptance uses the runner contract before writing a run or dispatch intent', async () => {
|
||||
test('canonical admission rejects template ranges inconsistent with its retained dataset', async () => {
|
||||
const f = await fixture();
|
||||
await expect(
|
||||
f.api.updateBacktest(f.definition.id, { config: { commission: -1 } })
|
||||
).rejects.toThrow('commission');
|
||||
expect((await f.api.getBacktest(f.definition.id))?.config).toEqual(f.definition.config);
|
||||
// Model malformed historical configuration that bypassed today's API validator.
|
||||
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
|
||||
f.api.updateBacktest(f.definition.id, { endDate: '2025-01-01T00:00:00.000Z' })
|
||||
).rejects.toThrow('trade bounds');
|
||||
await f.pool.query('UPDATE backtests SET end_date=$2 WHERE id=$1', [
|
||||
f.definition.id,
|
||||
JSON.stringify({ ...f.definition.config, slippage: 0.2 }),
|
||||
'2025-01-01T00:00:00.000Z',
|
||||
]);
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow('slippage');
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow();
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
||||
});
|
||||
test('canonical admission rejects malformed policy and legacy pacing before run/outbox writes', async () => {
|
||||
const f = await fixture();
|
||||
await expect(
|
||||
f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 })
|
||||
).rejects.toThrow('maximum speed');
|
||||
await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [
|
||||
f.definition.id,
|
||||
{ ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '-1' } },
|
||||
]);
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow();
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0);
|
||||
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
|
||||
f.definition.id,
|
||||
JSON.stringify(f.definition.config),
|
||||
]);
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 });
|
||||
const snapshot = (
|
||||
await f.pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
|
||||
).rows[0].request_snapshot;
|
||||
const expected = backtestRequestFromDefinition(f.definitionInput, {
|
||||
runId: run.id,
|
||||
backtestId: f.definition.id,
|
||||
speedMultiplier: 7,
|
||||
});
|
||||
expect(parseBacktestRequest(snapshot)).toEqual(expected);
|
||||
expect(snapshot.speed).toBe('5x');
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => {
|
||||
|
|
@ -691,8 +735,8 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [run.id])).rows
|
||||
).toHaveLength(1);
|
||||
await f.api.updateBacktest(f.definition.id, {
|
||||
config: { fastPeriod: 999 },
|
||||
symbols: ['MUTATED.TEST'],
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 4 },
|
||||
name: 'Mutated after admission',
|
||||
});
|
||||
// A fresh dispatcher models an API restart after SQL commit but before the first publish.
|
||||
const restarted = new BacktestDispatcher(f.postgres, f.queue, logger);
|
||||
|
|
@ -701,8 +745,12 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
f.enqueueWorker();
|
||||
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
|
||||
const result = await f.api.getRunResults(run.id);
|
||||
expect(result?.config.symbols).toEqual(['FIXTURE.TEST']);
|
||||
expect(result?.config.parameters.fastPeriod).toBe(3);
|
||||
expect(result).toHaveProperty('kind', 'canonical-result/v1');
|
||||
if (!result || !('request' in result)) {
|
||||
throw new Error('Canonical result required');
|
||||
}
|
||||
expect(result.request.strategy.selection.instrumentId).toBe(f.definition.symbols[0]!);
|
||||
expect(result.request.strategy.selection.parameters).toMatchObject({ fastPeriod: 2 });
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
|
||||
});
|
||||
|
||||
|
|
@ -711,8 +759,8 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const claims = await Promise.allSettled([
|
||||
f.repository.start(config),
|
||||
f.repository.start(config),
|
||||
f.repository.startCanonical(config),
|
||||
f.repository.startCanonical(config),
|
||||
]);
|
||||
expect(claims.filter(result => result.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(claims.filter(result => result.status === 'rejected')).toHaveLength(1);
|
||||
|
|
@ -736,14 +784,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
|
||||
test('expired owners cannot heartbeat, write progress/control/failure/cancellation, or commit a stale result', async () => {
|
||||
const f = await fixture();
|
||||
const baseline = await f.runner.runBacktest({
|
||||
...(await f.snapshot((await f.api.createRun({ backtestId: f.definition.id })).id)),
|
||||
});
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const old = await f.repository.start(await f.snapshot(run.id));
|
||||
const request = await f.snapshot(run.id);
|
||||
const old = await f.repository.startCanonical(request);
|
||||
const result = await f.report(request);
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
const replacement = await f.repository.start(await f.snapshot(run.id));
|
||||
const replacement = await f.repository.startCanonical(await f.snapshot(run.id));
|
||||
await expect(f.repository.heartbeat(run.id, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
|
|
@ -757,13 +804,12 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
BacktestLeaseLostError
|
||||
);
|
||||
await f.repository.fail(run.id, 'stale failure', old.attemptId);
|
||||
const result = { ...baseline, runId: run.id };
|
||||
await expect(f.repository.complete(result, old.attemptId)).rejects.toBeInstanceOf(
|
||||
await expect(f.repository.completeCanonical(result, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('running');
|
||||
await f.repository.loadDataset(run.id, replacement.attemptId, baseline.config.dataset!.hash);
|
||||
await f.repository.complete(result, replacement.attemptId);
|
||||
await f.repository.loadCanonicalDataset(run.id, replacement.attemptId, request.datasetHash);
|
||||
await f.repository.completeCanonical(result, replacement.attemptId);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows
|
||||
).toHaveLength(1);
|
||||
|
|
@ -773,7 +819,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const shortLease = new PostgresBacktestRunRepository(f.postgres, 300);
|
||||
const claim = await shortLease.start(await f.snapshot(run.id));
|
||||
const claim = await shortLease.startCanonical(await f.snapshot(run.id));
|
||||
await sleep(200);
|
||||
await shortLease.heartbeat(run.id, claim.attemptId);
|
||||
await sleep(150);
|
||||
|
|
@ -792,7 +838,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const shortLease = new PostgresBacktestRunRepository(f.postgres, 300);
|
||||
const claim = await shortLease.start(await f.snapshot(run.id));
|
||||
const claim = await shortLease.startCanonical(await f.snapshot(run.id));
|
||||
const lock = await f.pool.connect();
|
||||
let renewal: Promise<unknown> | undefined;
|
||||
try {
|
||||
|
|
@ -813,20 +859,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
test('cancellation wins against late completion and expires an abandoned cancelled owner truthfully', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const claim = await f.repository.startCanonical(await f.snapshot(run.id));
|
||||
const result = await f.report(await f.snapshot(run.id));
|
||||
await f.api.cancelRun(run.id);
|
||||
expect((await f.repository.heartbeat(run.id, claim.attemptId)).cancelRequested).toBe(true);
|
||||
await expect(
|
||||
f.repository.complete(
|
||||
{
|
||||
runId: run.id,
|
||||
backtestId: f.definition.id,
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
} as never,
|
||||
claim.attemptId
|
||||
)
|
||||
).rejects.toBeInstanceOf(BacktestCancelledError);
|
||||
await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestCancelledError
|
||||
);
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('cancelled');
|
||||
|
|
@ -837,7 +876,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
await f.repository.start(await f.snapshot(run.id));
|
||||
await f.repository.startCanonical(await f.snapshot(run.id));
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe(attempt === 3 ? 'failed' : 'pending');
|
||||
|
|
@ -874,7 +913,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
child.once('error', reject);
|
||||
child.once('exit', code => {
|
||||
clearTimeout(timeout);
|
||||
if (code) reject(new Error(`Crash owner exited: ${code}`));
|
||||
if (code) {
|
||||
reject(new Error(`Crash owner exited: ${code}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('running');
|
||||
|
|
@ -934,7 +975,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('invalid persisted snapshots become failed instead of remaining stranded pending', async () => {
|
||||
const f = await fixture();
|
||||
const f = await fixture(true);
|
||||
const run = { id: randomUUID() };
|
||||
// A legacy malformed snapshot is inserted as found, not fabricated by editing retained evidence.
|
||||
await f.pool.query(
|
||||
|
|
@ -948,15 +989,15 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('migration replay preserves leased owners, backfills legacy pending snapshots, and fails ownerless legacy runs', async () => {
|
||||
const f = await fixture();
|
||||
const f = await fixture(true);
|
||||
const pending = { id: randomUUID() };
|
||||
await f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES ($1,$2,1)', [
|
||||
pending.id,
|
||||
f.definition.id,
|
||||
]);
|
||||
const active = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const oldActive = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(active.id));
|
||||
const active = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const oldActive = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.legacySnapshot(active.id));
|
||||
await f.pool.query("UPDATE runs SET status = 'running' WHERE id = $1", [oldActive.id]);
|
||||
const migration = readFileSync(
|
||||
new URL('../../database/postgres/init/10-durable-backtest-dispatch.sql', import.meta.url),
|
||||
|
|
@ -964,13 +1005,16 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
);
|
||||
await f.pool.query(migration);
|
||||
await f.pool.query(migration);
|
||||
expect((await f.snapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z');
|
||||
expect((await f.legacySnapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z');
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [pending.id])).rows
|
||||
).toHaveLength(1);
|
||||
expect((await f.api.getRun(oldActive.id))?.status).toBe('failed');
|
||||
expect((await f.repository.heartbeat(active.id, claim.attemptId)).cancelRequested).toBe(false);
|
||||
await f.runner.runQueued(pending.id);
|
||||
expect((await f.api.getRun(pending.id))?.status).toBe('completed');
|
||||
expect((await f.api.getRun(pending.id))?.status).toBe('failed');
|
||||
expect((await f.api.getRun(pending.id))?.error).toContain(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ const migrations = [
|
|||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
'27-research-evidence-sources.sql',
|
||||
'28-research-agents.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -8,10 +8,8 @@ import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/
|
|||
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
type OrchestratorServices,
|
||||
} from '../../apps/stock/orchestrator/src/types';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
||||
import { logger } from '../fixtures/execution';
|
||||
import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime';
|
||||
|
||||
|
|
@ -131,6 +129,7 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
|
|||
const services: OrchestratorServices = { logger, postgres: f.postgres };
|
||||
container.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(container, {
|
||||
role: 'paper',
|
||||
canonicalPaper: config,
|
||||
nativeExecutionTimeoutMs: 10000,
|
||||
});
|
||||
|
|
@ -153,36 +152,15 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
|
|||
}
|
||||
expect((await custom.CanonicalPaperRuntime!.status()).active).toBe(false);
|
||||
const before = await f.snapshot();
|
||||
const research = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['RESEARCH.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-01-21T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
config: { fastPeriod: 2, slowPeriod: 3 },
|
||||
});
|
||||
custom.StorageService!.getHistoricalBars = async () =>
|
||||
Array.from({ length: 20 }, (_, i) => {
|
||||
const close = 100 + Math.sin(i) * 5;
|
||||
return {
|
||||
symbol: 'RESEARCH.TEST',
|
||||
source: 'eod' as const,
|
||||
timestamp: new Date(Date.parse(research.startDate) + i * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
expect((await custom.BacktestEngine!.runBacktest(research)).status).toBe('completed');
|
||||
const research = await canonicalAdmissionFixture(f.pool, f.postgres);
|
||||
custom.StorageService!.getHistoricalBars = async () => {
|
||||
throw new Error('Canonical execution cannot query providers');
|
||||
};
|
||||
const run = await research.api.createRun({ backtestId: research.draft.id });
|
||||
expect((await custom.BacktestRunner!.runQueued(run.id)).status).toBe('completed');
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
await expect(
|
||||
registerOrchestratorServices(container, { canonicalPaper: config })
|
||||
registerOrchestratorServices(container, { role: 'paper', canonicalPaper: config })
|
||||
).rejects.toThrow('fresh runtime composition');
|
||||
await expect(registerOrchestratorServices(container)).rejects.toThrow(
|
||||
'fresh runtime composition'
|
||||
|
|
|
|||
959
test/postgres/research-agents.test.ts
Normal file
959
test/postgres/research-agents.test.ts
Normal file
|
|
@ -0,0 +1,959 @@
|
|||
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 { createHttpSecurity } from '@stock-bot/di';
|
||||
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 { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
|
||||
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget';
|
||||
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
|
||||
import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.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';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
|
||||
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, withAgents = true, 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_agents_' + 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',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
'27-research-evidence-sources.sql',
|
||||
...(withAgents ? ['28-research-agents.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,
|
||||
postgres,
|
||||
container,
|
||||
agents: new ResearchAgentsService(container),
|
||||
research: new ResearchService(container),
|
||||
schema,
|
||||
api,
|
||||
experiments,
|
||||
repository,
|
||||
catalog,
|
||||
pkg,
|
||||
version,
|
||||
draft,
|
||||
definition,
|
||||
dataset,
|
||||
approve,
|
||||
execute,
|
||||
app: new Hono().route('/', createExperimentRoutes(container)),
|
||||
};
|
||||
}
|
||||
const limits = {
|
||||
maxActiveTrials: 2,
|
||||
maxTrialsPerExperiment: 10,
|
||||
maxBarEvaluationsPerExperiment: 10000,
|
||||
maxAttemptWallMs: 60000,
|
||||
maxAttempts: 2,
|
||||
};
|
||||
function required<T>(value: T | null | undefined): T {
|
||||
if (value === null || value === undefined) {
|
||||
throw new Error('Required fixture value is missing');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
type Fixture = Awaited<ReturnType<typeof fixture>>;
|
||||
const receipt = (principal: string = 'operator', key = randomUUID()) => ({ principal, key });
|
||||
async function provision(f: Fixture, overrides: Partial<typeof limits> = {}) {
|
||||
await f.approve();
|
||||
const project = await f.research.createProject({ title: 'Agent research' }, 'operator');
|
||||
const created = await f.agents.create({
|
||||
name: 'Bounded researcher',
|
||||
allowedProjectIds: [project.id],
|
||||
allowedBacktestIds: [f.draft.id],
|
||||
limits: { ...limits, ...overrides },
|
||||
});
|
||||
return { ...created, project };
|
||||
}
|
||||
async function preparation(
|
||||
f: Fixture,
|
||||
name = 'Agent search',
|
||||
backtestId = f.draft.id,
|
||||
grid = { fastPeriod: [1, 2] }
|
||||
) {
|
||||
const input = { backtestId, name, grid };
|
||||
const preview = await f.experiments.preview(input);
|
||||
return { ...input, previewHash: preview.previewHash };
|
||||
}
|
||||
async function requestFor(f: Fixture, id: string): Promise<CanonicalRunRequest> {
|
||||
return (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [id])).rows[0]
|
||||
.request_snapshot;
|
||||
}
|
||||
async function totals(f: Fixture) {
|
||||
return (
|
||||
await f.pool.query(
|
||||
'SELECT (SELECT count(*)::int FROM runs) runs,(SELECT count(*)::int FROM research_experiments) experiments,(SELECT count(*)::int FROM backtest_dispatch) dispatch'
|
||||
)
|
||||
).rows[0];
|
||||
}
|
||||
function http(f: Fixture) {
|
||||
const app = new Hono();
|
||||
const security = createHttpSecurity({
|
||||
adminToken: 'operator-test-secret-12345678901234567890',
|
||||
serviceToken: 'service-test-secret-123456789012345678901',
|
||||
environment: 'test',
|
||||
resolveResearchCredential: request => f.agents.authenticate(request),
|
||||
});
|
||||
security.mount(app);
|
||||
app.route('/', createResearchAgentRoutes(f.container, security.researchEnabled));
|
||||
app.route('/', createExperimentRoutes(f.container));
|
||||
app.route('/', createResearchRoutes(f.container));
|
||||
return (path: string, token: string, body?: unknown, key?: string) =>
|
||||
app.request(path, {
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
...(key ? { 'Idempotency-Key': key } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
}
|
||||
describe.skipIf(!url)('authoritative research principals and budgets', () => {
|
||||
test('operator provisioning stores only a hash; real mounted authentication, AI authorship and scoped writes', async () => {
|
||||
const f = await fixture(1),
|
||||
p = await provision(f);
|
||||
const request = http(f);
|
||||
expect(p.token.startsWith('sb-research.')).toBe(true);
|
||||
const stored = (await f.pool.query('SELECT * FROM research_agents WHERE id=$1', [p.agent.id]))
|
||||
.rows[0];
|
||||
expect(JSON.stringify(stored)).not.toContain(p.token);
|
||||
expect(stored.token_hash).toHaveLength(64);
|
||||
const info = await request('/api/v2/research-agent/budget', p.token);
|
||||
expect(info.status).toBe(200);
|
||||
expect((await info.json()).activeTrials).toBe(0);
|
||||
const submitted = await request(
|
||||
`/api/v2/research-projects/${p.project.id}/hypotheses`,
|
||||
p.token,
|
||||
{ title: 'AI hypothesis', proposition: 'Test a bounded signal' }
|
||||
);
|
||||
expect(submitted.status).toBe(201);
|
||||
const hypothesis = await submitted.json();
|
||||
expect(JSON.stringify(hypothesis)).toContain(p.agent.id);
|
||||
expect(JSON.stringify(hypothesis)).toContain('"contentOrigin":"ai"');
|
||||
for (const contentOrigin of ['human', 'unknown']) {
|
||||
const bad = await request(`/api/v2/research-projects/${p.project.id}/hypotheses`, p.token, {
|
||||
title: 'False provenance',
|
||||
proposition: 'not human',
|
||||
contentOrigin,
|
||||
});
|
||||
expect(bad.status).toBe(403);
|
||||
}
|
||||
const denied = await request('/api/v2/research-projects', p.token, { title: 'unauthorized' });
|
||||
expect(denied.status).toBe(403);
|
||||
const foreign = await f.research.createProject({ title: 'Other project' }, 'operator');
|
||||
expect(
|
||||
(
|
||||
await request(`/api/v2/research-projects/${foreign.id}/hypotheses`, p.token, {
|
||||
title: 'Wrong',
|
||||
proposition: 'Wrong project',
|
||||
})
|
||||
).status
|
||||
).toBe(403);
|
||||
expect((await request('/api/v2/research-agents', p.token)).status).toBe(403);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query('SELECT count(*)::int n FROM research_agent_audit WHERE agent_id=$1', [
|
||||
p.agent.id,
|
||||
])
|
||||
).rows[0].n
|
||||
).toBeGreaterThan(2);
|
||||
const clone = await f.catalog.cloneVersion(
|
||||
f.version.id,
|
||||
{ name: 'Agent candidate' },
|
||||
p.agent.id as `agent:${string}`,
|
||||
randomUUID()
|
||||
);
|
||||
expect(String(clone.strategy.ownerPrincipal)).toBe(p.agent.id);
|
||||
expect(clone.version.origin).toBe('candidate');
|
||||
const candidate = await f.api.createBacktest(
|
||||
{ ...f.definition, strategyVersionId: clone.version.id, name: 'Candidate cannot execute' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
await expect(
|
||||
f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [candidate.id] })
|
||||
).rejects.toThrow('approved canonical templates');
|
||||
expect((await totals(f)).runs).toBe(0);
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 1, enabled: false });
|
||||
expect((await request('/api/v2/research-agent/budget', p.token)).status).toBe(401);
|
||||
expect((await f.agents.budget(p.agent.id, true)).agent.enabled).toBe(false);
|
||||
});
|
||||
test('same receipt is exact after quota changes; capacity and grant errors are typed and atomic', async () => {
|
||||
const f = await fixture(1),
|
||||
p = await provision(f);
|
||||
const submission = await preparation(f),
|
||||
key = randomUUID();
|
||||
const run = await f.experiments.submit(submission, receipt(p.agent.id, key));
|
||||
expect(run.trials).toHaveLength(2);
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(2);
|
||||
const policies = (
|
||||
await f.pool.query(
|
||||
'SELECT request_snapshot,research_limits,research_agent_id FROM runs ORDER BY run_number'
|
||||
)
|
||||
).rows;
|
||||
for (const row of policies) {
|
||||
expect(row.research_agent_id).toBe(p.agent.id);
|
||||
expect(row.research_limits).toEqual(limits);
|
||||
expect(
|
||||
await f.pool
|
||||
.query('SELECT research_grant_policy($1::jsonb) AS p', [row.request_snapshot])
|
||||
.then(r => r.rows[0].p)
|
||||
).toEqual(researchGrantPolicy(row.request_snapshot));
|
||||
}
|
||||
await f.agents.update(p.agent.id, {
|
||||
expectedRevision: 1,
|
||||
limits: { ...limits, maxActiveTrials: 1 },
|
||||
allowedBacktestIds: [],
|
||||
});
|
||||
expect((await f.experiments.submit(submission, receipt(p.agent.id, key))).id).toBe(run.id);
|
||||
const before = await totals(f);
|
||||
const denied = await http(f)('/api/v2/experiments', p.token, submission, randomUUID());
|
||||
expect(denied.status).toBe(403);
|
||||
expect(await totals(f)).toEqual(before);
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
|
||||
expect((await http(f)('/api/v2/experiments', p.token, submission, randomUUID())).status).toBe(
|
||||
429
|
||||
);
|
||||
expect(await totals(f)).toEqual(before);
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 3, enabled: false });
|
||||
expect((await http(f)('/api/v2/experiments', p.token, submission, key)).status).toBe(401);
|
||||
await expect(f.experiments.submit(submission, receipt(p.agent.id, key))).rejects.toThrow(
|
||||
'disabled'
|
||||
);
|
||||
});
|
||||
test('concurrent different-parent grids cannot oversubscribe; failure releases durable capacity and ownership is immutable', async () => {
|
||||
const f = await fixture(),
|
||||
p = await provision(f);
|
||||
const other = await f.api.createBacktest(
|
||||
{ ...f.definition, name: 'Second template' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
await f.agents.update(p.agent.id, {
|
||||
expectedRevision: 1,
|
||||
allowedBacktestIds: [f.draft.id, other.id],
|
||||
});
|
||||
const [a, b] = await Promise.all([preparation(f), preparation(f, 'Other', other.id)]);
|
||||
const race = await Promise.allSettled([
|
||||
f.experiments.submit(a, receipt(p.agent.id)),
|
||||
f.experiments.submit(b, receipt(p.agent.id)),
|
||||
]);
|
||||
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(race.filter(r => r.status === 'rejected')).toHaveLength(1);
|
||||
const failed = race.find(r => r.status === 'rejected');
|
||||
if (failed?.status !== 'rejected') {
|
||||
throw new Error('Missing failure');
|
||||
}
|
||||
expect(failed.reason.message).toContain('research_budget:');
|
||||
expect(await totals(f)).toEqual({ runs: 2, experiments: 1, dispatch: 2 });
|
||||
const winner = race.find(r => r.status === 'fulfilled');
|
||||
if (winner?.status !== 'fulfilled') {
|
||||
throw new Error('Missing winner');
|
||||
}
|
||||
const first = winner.value.trials[0]!;
|
||||
const claim = await f.repository.startCanonical(await requestFor(f, required(first.runId)));
|
||||
expect(claim.executionDeadlineAt).toBeGreaterThan(Date.now());
|
||||
await expect(
|
||||
f.pool.query('UPDATE runs SET research_agent_id=NULL WHERE id=$1', [required(first.runId)])
|
||||
).rejects.toThrow('immutable');
|
||||
await expect(
|
||||
f.pool.query(
|
||||
"UPDATE runs SET research_limits=jsonb_set(research_limits,'{maxAttempts}','3') WHERE id=$1",
|
||||
[required(first.runId)]
|
||||
)
|
||||
).rejects.toThrow('immutable');
|
||||
await expect(
|
||||
f.pool.query('UPDATE runs SET attempt_number=0 WHERE id=$1', [required(first.runId)])
|
||||
).rejects.toThrow('cannot be reset');
|
||||
await f.repository.fail(required(first.runId), 'controlled failure', claim.attemptId);
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
|
||||
const single = await preparation(f, 'Replacement', f.draft.id, { fastPeriod: [1] });
|
||||
await f.experiments.submit(single, receipt(p.agent.id));
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(2);
|
||||
await f.experiments.cancel(winner.value.id);
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
|
||||
});
|
||||
test('deadline and attempts survive lease renewal/recovery and revocation; no expired completion', async () => {
|
||||
const f = await fixture(),
|
||||
p = await provision(f, { maxAttemptWallMs: 100, maxAttempts: 1 });
|
||||
const run = await f.experiments.submit(
|
||||
await preparation(f, 'Deadline', f.draft.id, { fastPeriod: [1] }),
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
const id = required(run.trials[0]!.runId);
|
||||
await expect(
|
||||
f.pool.query("UPDATE runs SET status='running' WHERE id=$1", [id])
|
||||
).rejects.toThrow('complete bounded claim');
|
||||
const claim = await f.repository.startCanonical(await requestFor(f, id));
|
||||
const frozen = (await f.pool.query('SELECT research_deadline_at FROM runs WHERE id=$1', [id]))
|
||||
.rows[0].research_deadline_at;
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET lease_expires_at=clock_timestamp()+interval '1 hour' WHERE id=$1",
|
||||
[id]
|
||||
);
|
||||
await expect(
|
||||
f.pool.query(
|
||||
"UPDATE runs SET research_deadline_at=clock_timestamp()+interval '1 hour' WHERE id=$1",
|
||||
[id]
|
||||
)
|
||||
).rejects.toThrow('server-owned');
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 1, enabled: false });
|
||||
await f.pool.query('SELECT pg_sleep(0.12)');
|
||||
await expect(
|
||||
f.pool.query("UPDATE runs SET status='completed',completed_at=NOW() WHERE id=$1", [id])
|
||||
).rejects.toThrow('wall time');
|
||||
const dispatcher = new BacktestDispatcher(
|
||||
f.postgres,
|
||||
{ add: async () => ({}) as never },
|
||||
logger
|
||||
);
|
||||
await dispatcher.tick();
|
||||
await dispatcher.shutdown();
|
||||
const saved = (await f.pool.query('SELECT * FROM runs WHERE id=$1', [id])).rows[0];
|
||||
expect(saved.status).toBe('failed');
|
||||
expect(saved.error).toContain('wall time');
|
||||
expect(saved.research_deadline_at).toEqual(frozen);
|
||||
expect(saved.attempt_number).toBe(1);
|
||||
expect((await f.agents.budget(p.agent.id, true)).activeTrials).toBe(0);
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 2, enabled: true });
|
||||
await expect(
|
||||
f.experiments.retryTrial(
|
||||
run.id,
|
||||
id,
|
||||
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
|
||||
receipt(p.agent.id)
|
||||
)
|
||||
).rejects.toThrow('attempt budget exhausted');
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n
|
||||
).toBe(0);
|
||||
expect(claim.executionDeadlineAt).toBeDefined();
|
||||
});
|
||||
test('ordinary native accounting is unchanged; first migration and reapply preserve saved economic evidence and leases', async () => {
|
||||
const f = await fixture(4, false);
|
||||
await f.approve();
|
||||
const input = await preparation(f);
|
||||
const before = await f.experiments.submit(input, receipt());
|
||||
await f.execute(required(before.trials[0]!.runId));
|
||||
const pending = required(before.trials[1]!.runId);
|
||||
const claim = await f.repository.startCanonical(await requestFor(f, pending));
|
||||
const snapshot = async () => ({
|
||||
runs: (
|
||||
await f.pool.query(
|
||||
"SELECT to_jsonb(r)-ARRAY['research_agent_id','research_limits','research_deadline_at'] AS r FROM runs r ORDER BY id"
|
||||
)
|
||||
).rows,
|
||||
results: (await f.pool.query('SELECT * FROM backtest_results ORDER BY run_id')).rows,
|
||||
experiments: (await f.pool.query('SELECT * FROM research_experiments ORDER BY id')).rows,
|
||||
dispatch: (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows,
|
||||
});
|
||||
const original = await snapshot();
|
||||
const sql = readFileSync(
|
||||
new URL('../../database/postgres/init/28-research-agents.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
await f.pool.query(sql);
|
||||
expect(await snapshot()).toEqual(original);
|
||||
await f.pool.query(sql);
|
||||
expect(await snapshot()).toEqual(original);
|
||||
expect(
|
||||
(await f.pool.query('SELECT attempt_id FROM runs WHERE id=$1', [pending])).rows[0].attempt_id
|
||||
).toBe(claim.attemptId);
|
||||
const p = await provision(f);
|
||||
const agentRun = await f.experiments.submit(
|
||||
await preparation(f, 'Native agent', f.draft.id, { fastPeriod: [1] }),
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
await f.execute(required(agentRun.trials[0]!.runId));
|
||||
const result = await f.api.getRunResults(required(agentRun.trials[0]!.runId));
|
||||
expect(result && 'kind' in result ? result.kind : null).toBe('canonical-result/v1');
|
||||
expect(result?.status).toBe('completed');
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0);
|
||||
const audit = (await f.pool.query('SELECT * FROM research_agent_audit ORDER BY id')).rows;
|
||||
await f.pool.query(sql);
|
||||
expect((await f.pool.query('SELECT * FROM research_agent_audit ORDER BY id')).rows).toEqual(
|
||||
audit
|
||||
);
|
||||
await expect(f.pool.query('DELETE FROM research_agent_audit')).rejects.toThrow(
|
||||
'cannot be rewritten'
|
||||
);
|
||||
});
|
||||
test('manual retry reacquires capacity once and lifetime attempts remain bounded across recovery', async () => {
|
||||
const f = await fixture(),
|
||||
p = await provision(f, { maxActiveTrials: 1, maxAttempts: 2 });
|
||||
const submitted = await f.experiments.submit(
|
||||
await preparation(f, 'Retry', f.draft.id, { fastPeriod: [1] }),
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
const id = required(submitted.trials[0]!.runId),
|
||||
request = await requestFor(f, id),
|
||||
first = await f.repository.startCanonical(request);
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=$1",
|
||||
[id]
|
||||
);
|
||||
const dispatcher = new BacktestDispatcher(
|
||||
f.postgres,
|
||||
{ add: async () => ({}) as never },
|
||||
logger
|
||||
);
|
||||
await dispatcher.tick();
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
|
||||
const second = await f.repository.startCanonical(request);
|
||||
expect(second.executionDeadlineAt).toBeGreaterThanOrEqual(first.executionDeadlineAt!);
|
||||
await f.repository.fail(id, 'Second attempt failed', second.attemptId);
|
||||
const before = await totals(f);
|
||||
await expect(
|
||||
f.experiments.retryTrial(
|
||||
submitted.id,
|
||||
id,
|
||||
{ expectedAttemptNumber: 2, expectedRetryCount: 0 },
|
||||
receipt(p.agent.id)
|
||||
)
|
||||
).rejects.toThrow('attempt budget exhausted');
|
||||
expect(await totals(f)).toEqual(before);
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n
|
||||
).toBe(0);
|
||||
const next = await f.experiments.submit(
|
||||
await preparation(f, 'Manual', f.draft.id, { fastPeriod: [1] }),
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
const nextId = required(next.trials[0]!.runId);
|
||||
const claim = await f.repository.startCanonical(await requestFor(f, nextId));
|
||||
await f.repository.fail(nextId, 'Retryable failure', claim.attemptId);
|
||||
const key = randomUUID(),
|
||||
intent = { expectedAttemptNumber: 1, expectedRetryCount: 0 };
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [] });
|
||||
await expect(
|
||||
f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key))
|
||||
).rejects.toThrow('Operator approval');
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
|
||||
const retry = await f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key));
|
||||
expect(String(retry.retry.principal)).toBe(p.agent.id);
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 3, allowedBacktestIds: [] });
|
||||
expect(
|
||||
(await f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key))).retry.id
|
||||
).toBe(retry.retry.id);
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 4, enabled: false });
|
||||
const resumed = await f.repository.startCanonical(await requestFor(f, nextId));
|
||||
expect(resumed.executionDeadlineAt).toBeDefined();
|
||||
await f.repository.fail(
|
||||
nextId,
|
||||
'Accepted bounded work still runs after token revocation',
|
||||
resumed.attemptId
|
||||
);
|
||||
await dispatcher.shutdown();
|
||||
});
|
||||
test('cost scenarios and chronological/walk-forward phases retain exact baseline grants and bounded planned work', async () => {
|
||||
const data = walkForwardDataset(),
|
||||
f = await fixture(4, true, data.dataset),
|
||||
p = await provision(f, { maxActiveTrials: 4 });
|
||||
const costs = {
|
||||
backtestId: f.draft.id,
|
||||
name: 'Fees',
|
||||
scenarios: [{ feeRate: '0.002', slippageRate: '0.001' }],
|
||||
};
|
||||
const preview = await f.experiments.previewCosts(costs);
|
||||
const cost = await f.experiments.submitCosts(
|
||||
{ ...costs, previewHash: preview.previewHash },
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
expect(cost.trials).toHaveLength(2);
|
||||
await f.experiments.cancel(cost.id);
|
||||
const validation = new ChronologicalValidationService(f.container),
|
||||
walk = new WalkForwardService(f.container);
|
||||
const input = {
|
||||
backtestId: f.draft.id,
|
||||
name: 'Validation',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
recipe: data.windows[0]!,
|
||||
};
|
||||
const prepared = await f.experiments.previewValidation(input);
|
||||
const train = await validation.submit(
|
||||
{ ...input, previewHash: prepared.previewHash },
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
await expect(
|
||||
validation.select(train.id, { previewHash: prepared.previewHash }, receipt())
|
||||
).rejects.toThrow('owning research principal');
|
||||
for (const trial of train.phases[0].experiment!.trials) {
|
||||
await f.execute(required(trial.runId));
|
||||
}
|
||||
await f.agents.update(p.agent.id, {
|
||||
expectedRevision: 1,
|
||||
limits: { ...limits, maxActiveTrials: 1 },
|
||||
});
|
||||
const selectKey = randomUUID();
|
||||
await expect(
|
||||
validation.select(
|
||||
train.id,
|
||||
{ previewHash: prepared.previewHash },
|
||||
receipt(p.agent.id, selectKey)
|
||||
)
|
||||
).rejects.toThrow('research_budget:');
|
||||
expect(
|
||||
(
|
||||
await f.pool.query('SELECT validation_selection FROM research_experiments WHERE id=$1', [
|
||||
train.id,
|
||||
])
|
||||
).rows[0].validation_selection
|
||||
).toBeNull();
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT count(*)::int n FROM research_experiments WHERE validation_parent_id=$1',
|
||||
[train.id]
|
||||
)
|
||||
).rows[0].n
|
||||
).toBe(0);
|
||||
await f.agents.update(p.agent.id, {
|
||||
expectedRevision: 2,
|
||||
limits: { ...limits, maxActiveTrials: 4 },
|
||||
});
|
||||
const selected = await validation.select(
|
||||
train.id,
|
||||
{ previewHash: prepared.previewHash },
|
||||
receipt(p.agent.id, selectKey)
|
||||
);
|
||||
expect(String(selected.receipt.principal)).toBe(p.agent.id);
|
||||
for (const phase of selected.validation.phases.slice(1)) {
|
||||
for (const trial of required(phase.experiment).trials) {
|
||||
await f.execute(required(trial.runId));
|
||||
}
|
||||
}
|
||||
const finalizeInput = {
|
||||
previewHash: prepared.previewHash,
|
||||
selectionHash: required(selected.validation.selection).selectionHash,
|
||||
},
|
||||
finalKey = randomUUID();
|
||||
const sealed = await validation.finalize(
|
||||
train.id,
|
||||
finalizeInput,
|
||||
receipt(p.agent.id, finalKey)
|
||||
);
|
||||
expect(String(required(sealed.validation.report).principal)).toBe(p.agent.id);
|
||||
expect(
|
||||
(await validation.finalize(train.id, finalizeInput, receipt(p.agent.id, finalKey))).receipt
|
||||
).toEqual(sealed.receipt);
|
||||
const walkInput = {
|
||||
backtestId: f.draft.id,
|
||||
name: 'Rolling',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
windows: data.windows,
|
||||
};
|
||||
const walkPreview = await walk.preview(walkInput);
|
||||
await f.agents.update(p.agent.id, {
|
||||
expectedRevision: 3,
|
||||
limits: { ...limits, maxActiveTrials: 4, maxTrialsPerExperiment: 7 },
|
||||
});
|
||||
const before = await totals(f);
|
||||
await expect(
|
||||
walk.submit({ ...walkInput, previewHash: walkPreview.previewHash }, receipt(p.agent.id))
|
||||
).rejects.toThrow('trial or observation budget');
|
||||
expect(await totals(f)).toEqual(before);
|
||||
await f.agents.update(p.agent.id, {
|
||||
expectedRevision: 4,
|
||||
limits: { ...limits, maxActiveTrials: 4 },
|
||||
});
|
||||
const series = await walk.submit(
|
||||
{ ...walkInput, previewHash: walkPreview.previewHash },
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
expect(series.windows).toHaveLength(2);
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(4);
|
||||
for (const window of series.windows) {
|
||||
const member = required(window.validation);
|
||||
for (const trial of required(member.phases[0].experiment).trials) {
|
||||
await f.execute(required(trial.runId));
|
||||
}
|
||||
const selection = await validation.select(
|
||||
member.id,
|
||||
{ previewHash: member.previewHash },
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
for (const phase of selection.validation.phases.slice(1)) {
|
||||
for (const trial of required(phase.experiment).trials) {
|
||||
await f.execute(required(trial.runId));
|
||||
}
|
||||
}
|
||||
await validation.finalize(
|
||||
member.id,
|
||||
{
|
||||
previewHash: member.previewHash,
|
||||
selectionHash: required(selection.validation.selection).selectionHash,
|
||||
},
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
}
|
||||
const reportKey = randomUUID(),
|
||||
reportInput = { previewHash: walkPreview.previewHash };
|
||||
const report = await walk.finalize(series.id, reportInput, receipt(p.agent.id, reportKey));
|
||||
expect(String(required(report.walkForward.report).principal)).toBe(p.agent.id);
|
||||
expect(
|
||||
(await walk.finalize(series.id, reportInput, receipt(p.agent.id, reportKey))).receipt
|
||||
).toEqual(report.receipt);
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0);
|
||||
}, 30000);
|
||||
test('deadline is rechecked at result transaction commit after a valid native result and timely completed transition', async () => {
|
||||
const f = await fixture(),
|
||||
p = await provision(f, { maxAttemptWallMs: 1000 });
|
||||
const run = await f.experiments.submit(
|
||||
await preparation(f, 'Delayed commit', f.draft.id, { fastPeriod: [1] }),
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
const id = required(run.trials[0]!.runId),
|
||||
request = await requestFor(f, id);
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
getHistoricalBars: async () => {
|
||||
throw new Error('Provider forbidden');
|
||||
},
|
||||
},
|
||||
});
|
||||
let economic: Pick<CanonicalRunResult, 'financial' | 'analytics'>;
|
||||
try {
|
||||
economic = await engine.runCanonical(request, async () => f.dataset);
|
||||
} finally {
|
||||
await engine.shutdown();
|
||||
}
|
||||
const claim = await f.repository.startCanonical(request);
|
||||
const result = {
|
||||
kind: 'canonical-result/v1',
|
||||
status: 'completed',
|
||||
runId: id,
|
||||
backtestId: request.backtestId,
|
||||
request,
|
||||
financialEngine: 'rust',
|
||||
strategyExecution: 'typescript-retained-builtin/v1',
|
||||
completedAt: new Date().toISOString(),
|
||||
executionTime: 1,
|
||||
...economic,
|
||||
};
|
||||
const client = await f.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query(
|
||||
"UPDATE runs SET status='completed',progress=100,completed_at=NOW() WHERE id=$1 AND attempt_id=$2",
|
||||
[id, claim.attemptId]
|
||||
);
|
||||
await client.query(
|
||||
"INSERT INTO backtest_results(run_id,completed_at,execution_time,canonical_result,metrics,equity_curve,ohlc_data,trades,positions,analytics) VALUES($1,NOW(),1,$2::jsonb,'null','null','null','null','null','null')",
|
||||
[id, result]
|
||||
);
|
||||
await client.query('SELECT pg_sleep(1.1)');
|
||||
await expect(client.query('COMMIT')).rejects.toThrow(
|
||||
'wall time exceeded before result commit'
|
||||
);
|
||||
} finally {
|
||||
await client.query('ROLLBACK');
|
||||
client.release();
|
||||
}
|
||||
expect((await f.pool.query('SELECT status FROM runs WHERE id=$1', [id])).rows[0].status).toBe(
|
||||
'running'
|
||||
);
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int n FROM backtest_results WHERE run_id=$1', [id]))
|
||||
.rows[0].n
|
||||
).toBe(0);
|
||||
await f.repository.fail(id, 'Budget expired while saving', claim.attemptId);
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0);
|
||||
});
|
||||
|
||||
test('foreign/disabled agent phase and retry receipts fail through service and direct SQL before any mutation', async () => {
|
||||
const data = walkForwardDataset(),
|
||||
f = await fixture(4, true, data.dataset),
|
||||
a = await provision(f),
|
||||
b = await provision(f);
|
||||
const ordinary = await f.experiments.submit(
|
||||
await preparation(f, 'Owned', f.draft.id, { fastPeriod: [1] }),
|
||||
receipt(a.agent.id)
|
||||
);
|
||||
const runId = required(ordinary.trials[0]!.runId),
|
||||
claim = await f.repository.startCanonical(await requestFor(f, runId));
|
||||
await f.repository.fail(runId, 'controlled failure', claim.attemptId);
|
||||
await expect(
|
||||
f.experiments.retryTrial(
|
||||
ordinary.id,
|
||||
runId,
|
||||
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
|
||||
receipt(b.agent.id)
|
||||
)
|
||||
).rejects.toThrow(/owning.*principal/);
|
||||
await expect(
|
||||
f.pool.query(
|
||||
`INSERT INTO experiment_trial_retries(id,experiment_id,run_id,trial_key,retry_number,previous_attempt_number,previous_attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,failure_updated_at,principal,review_id,submission_key,submission_hash)
|
||||
SELECT $1,experiment_id,id,trial_key,1,attempt_number,attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,updated_at,$3,(SELECT id FROM strategy_review_events ORDER BY created_at DESC LIMIT 1),$4,$5 FROM runs WHERE id=$2`,
|
||||
[randomUUID(), runId, b.agent.id, randomUUID(), 'a'.repeat(64)]
|
||||
)
|
||||
).rejects.toThrow(/owning.*principal/);
|
||||
const validation = new ChronologicalValidationService(f.container),
|
||||
input = {
|
||||
backtestId: f.draft.id,
|
||||
name: 'Owned phases',
|
||||
grid: { fastPeriod: [1] },
|
||||
recipe: data.windows[0]!,
|
||||
};
|
||||
const preview = await f.experiments.previewValidation(input),
|
||||
train = await validation.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
receipt(a.agent.id)
|
||||
);
|
||||
await expect(
|
||||
validation.select(train.id, { previewHash: preview.previewHash }, receipt(b.agent.id))
|
||||
).rejects.toThrow(/owning.*principal/);
|
||||
for (const principal of [b.agent.id, a.agent.id]) {
|
||||
if (principal === a.agent.id) {
|
||||
await f.agents.update(principal, { expectedRevision: 1, enabled: false });
|
||||
}
|
||||
for (const column of ['validation_selection', 'validation_report']) {
|
||||
await expect(
|
||||
f.pool.query(`UPDATE research_experiments SET ${column}=$2::jsonb WHERE id=$1`, [
|
||||
train.id,
|
||||
{ principal },
|
||||
])
|
||||
).rejects.toThrow(/owning.*principal/);
|
||||
}
|
||||
}
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n
|
||||
).toBe(0);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT validation_selection,validation_report FROM research_experiments WHERE id=$1',
|
||||
[train.id]
|
||||
)
|
||||
).rows[0]
|
||||
).toEqual({ validation_selection: null, validation_report: null });
|
||||
});
|
||||
test('operator retry reserves owning agent before parent so policy edits cannot deadlock admissions', async () => {
|
||||
const f = await fixture(),
|
||||
p = await provision(f),
|
||||
run = await f.experiments.submit(
|
||||
await preparation(f, 'Lock order', f.draft.id, { fastPeriod: [1] }),
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
const id = required(run.trials[0]!.runId),
|
||||
claim = await f.repository.startCanonical(await requestFor(f, id));
|
||||
await f.repository.fail(id, 'controlled', claim.attemptId);
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM research_agents WHERE id=$1 FOR UPDATE', [p.agent.id]);
|
||||
const retry = f.experiments.retryTrial(
|
||||
run.id,
|
||||
id,
|
||||
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
|
||||
receipt()
|
||||
);
|
||||
try {
|
||||
let waiting = false;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const rows = (
|
||||
await f.pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE 'SELECT id,enabled FROM research_agents%'",
|
||||
[f.schema]
|
||||
)
|
||||
).rows;
|
||||
if (rows.length) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await blocker.query('SELECT pg_sleep(0.01)');
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE NOWAIT', [f.draft.id]);
|
||||
await blocker.query('COMMIT');
|
||||
} finally {
|
||||
await blocker.query('ROLLBACK');
|
||||
blocker.release();
|
||||
}
|
||||
expect((await retry).retry.principal).toBe('operator');
|
||||
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
|
||||
});
|
||||
test('multi-template policy locks all parents before shared strategy families', async () => {
|
||||
const f = await fixture(),
|
||||
p = await provision(f),
|
||||
other = await f.api.createBacktest(
|
||||
{ ...f.definition, name: 'Shared family' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const ids = [f.draft.id, other.id].sort(),
|
||||
blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [ids[1]]);
|
||||
const update = f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: ids });
|
||||
try {
|
||||
let waiting = false;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const rows = (
|
||||
await f.pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE 'SELECT * FROM backtests WHERE id=ANY%'",
|
||||
[f.schema]
|
||||
)
|
||||
).rows;
|
||||
if (rows.length) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await blocker.query('SELECT pg_sleep(0.01)');
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE NOWAIT', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
await blocker.query('COMMIT');
|
||||
} finally {
|
||||
await blocker.query('ROLLBACK');
|
||||
blocker.release();
|
||||
}
|
||||
expect((await update).grants).toHaveLength(2);
|
||||
});
|
||||
test('observation budgets and changed financial policy reject without partial admission', async () => {
|
||||
const f = await fixture(),
|
||||
p = await provision(f, { maxBarEvaluationsPerExperiment: 1 });
|
||||
const input = await preparation(f),
|
||||
before = await totals(f);
|
||||
await expect(f.experiments.submit(input, receipt(p.agent.id))).rejects.toThrow(
|
||||
'trial or observation budget'
|
||||
);
|
||||
expect(await totals(f)).toEqual(before);
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 1, limits });
|
||||
await f.pool.query('UPDATE backtests SET initial_capital=20000 WHERE id=$1', [f.draft.id]);
|
||||
const changed = await preparation(f);
|
||||
expect(changed.previewHash).not.toBe(input.previewHash);
|
||||
await expect(f.experiments.submit(changed, receipt(p.agent.id))).rejects.toThrow(
|
||||
'Operator approval'
|
||||
);
|
||||
expect(await totals(f)).toEqual(before);
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
|
||||
expect((await f.experiments.submit(changed, receipt(p.agent.id))).trials).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
|
@ -12,6 +12,7 @@ import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-d
|
|||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import { seedHistoricalRun } from '../fixtures/historical-run';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('research-retention-test');
|
||||
|
|
@ -172,7 +173,9 @@ async function waitForBlocked(pool: Pool, schema: string) {
|
|||
describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
||||
test('retained_run_delete_restricted_postgres blocks raw cascades, mutations and truncation while preserving runless legacy deletion', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun(
|
||||
const run = await seedHistoricalRun(
|
||||
f.pool,
|
||||
f.api,
|
||||
{ backtestId: f.definition.id },
|
||||
{ principal: 'operator', key: 'retained' }
|
||||
);
|
||||
|
|
@ -217,7 +220,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
test('archive_preserves_replay hides discovery only and rejects new admission or edits until restored', async () => {
|
||||
const f = await fixture();
|
||||
const receipt = { principal: 'operator' as const, key: 'archive-retry' };
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id }, receipt);
|
||||
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id }, receipt);
|
||||
const before = await f.snapshot(run.id);
|
||||
const archived = await f.api.archiveBacktest(f.definition.id, true);
|
||||
expect(archived?.archivedAt).toBeString();
|
||||
|
|
@ -247,12 +250,15 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
expect((await f.api.updateBacktest(f.definition.id, { name: 'Restored' }))?.name).toBe(
|
||||
'Restored'
|
||||
);
|
||||
expect((await f.api.createRun({ backtestId: f.definition.id })).runNumber).toBe(2);
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
expect(await f.api.listRuns(f.definition.id)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('archive and admission use one parent lock, including direct repository inserts', async () => {
|
||||
const f = await fixture();
|
||||
const accepted = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const accepted = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.definition.id]);
|
||||
|
|
@ -279,7 +285,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
|
||||
test('accepted archived work retains binding, lease recovery, controls, progress and terminal result writes', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
|
||||
await f.api.archiveBacktest(f.definition.id, true);
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.freezeDataset(
|
||||
|
|
@ -319,7 +325,10 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
await f.api.updateRunProgress(run.id, { progress: 90, attemptId: retry.attemptId });
|
||||
await f.repository.complete(result(run.id, f.definition.id, frozen), retry.attemptId);
|
||||
const saved = await f.api.getRunResults(run.id);
|
||||
expect(saved?.config.dataset?.hash).toBe(frozen.manifest.hash);
|
||||
if (!saved || !('config' in saved)) {
|
||||
throw new Error('Expected preserved historical result');
|
||||
}
|
||||
expect(saved.config.dataset?.hash).toBe(frozen.manifest.hash);
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2);
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('completed');
|
||||
await f.pool.query(retention);
|
||||
|
|
@ -329,7 +338,9 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
|
||||
test('run identity and frozen inputs reject rewrites while legacy NULL snapshots can be populated once', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun(
|
||||
const run = await seedHistoricalRun(
|
||||
f.pool,
|
||||
f.api,
|
||||
{ backtestId: f.definition.id },
|
||||
{ principal: 'service', key: 'immutable' }
|
||||
);
|
||||
|
|
@ -381,7 +392,9 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
test('pending and running cancellation/failure still terminate accepted archived requests', async () => {
|
||||
const f = await fixture();
|
||||
const runs = await Promise.all(
|
||||
Array.from({ length: 4 }, () => f.api.createRun({ backtestId: f.definition.id }))
|
||||
Array.from({ length: 4 }, () =>
|
||||
seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id })
|
||||
)
|
||||
);
|
||||
await f.api.archiveBacktest(f.definition.id, true);
|
||||
await f.api.cancelRun(runs[0]!.id);
|
||||
|
|
@ -405,7 +418,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
|
||||
test('preexisting corrupted datasets remain immutable and fail checksum verification on retrieval', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const dataset = await f.dataset(run.id);
|
||||
const corrupt = structuredClone(dataset);
|
||||
|
|
@ -430,7 +443,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
|
||||
test('HTTP archive/list/delete errors are actionable and direct saved resources remain accessible', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
|
||||
const archived = await f.app.request(`/api/v2/backtests/${f.definition.id}/archive`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ archived: true }),
|
||||
|
|
|
|||
|
|
@ -1,91 +1,28 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { asValue } from 'awilix';
|
||||
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
type OrchestratorServices,
|
||||
} from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger, quote } from '../fixtures/execution';
|
||||
import { CounterStrategy } from '../fixtures/strategy-recovery';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
||||
import { logger } from '../fixtures/execution';
|
||||
import { paperFixture, paperFrame } from '../fixtures/paper-runtime';
|
||||
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
const research = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['RESEARCH.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
});
|
||||
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
|
||||
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
|
||||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
|
||||
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
|
||||
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id), completed_at timestamptz,
|
||||
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
|
||||
execution_time numeric);`);
|
||||
for (const filename of [
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'11-simulation-execution-ledger.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.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',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const paper = await paperFixture();
|
||||
cleanup.push(paper.close);
|
||||
await paper.runtime.connect({ sourceId: 'fixture', connectionId: 'one' });
|
||||
await paper.runtime.ingest(paperFrame(1));
|
||||
await paper.runtime.activate({ recoverPending: false });
|
||||
paper.clock(20);
|
||||
await paper.runtime.ingest(paperFrame(2));
|
||||
const admitted = await canonicalAdmissionFixture(paper.pool, paper.postgres);
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
enableCache: false,
|
||||
|
|
@ -97,187 +34,109 @@ async function fixture() {
|
|||
enableProxy: false,
|
||||
})
|
||||
.build();
|
||||
const services: OrchestratorServices = { logger, postgres };
|
||||
const services: OrchestratorServices = { logger, postgres: paper.postgres };
|
||||
container.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(container, {
|
||||
initializeMode: false,
|
||||
nativeExecutionTimeoutMs: 5000,
|
||||
});
|
||||
const runtime = services.custom!;
|
||||
const mode = runtime.ModeManager!;
|
||||
const runner = runtime.BacktestRunner!;
|
||||
const market = runtime.MarketDataService!;
|
||||
const storage = runtime.StorageService!;
|
||||
const execution = runtime.ExecutionService!;
|
||||
const strategies = runtime.StrategyManager!;
|
||||
const feed = { connected: false };
|
||||
// Only the external transport is offline; real admission, ledger, checkpoints and replay run.
|
||||
const feedStart = spyOn(market, 'initialize').mockImplementation(async () => {
|
||||
feed.connected = true;
|
||||
});
|
||||
const originalShutdown = market.shutdown.bind(market);
|
||||
const feedStop = spyOn(market, 'shutdown').mockImplementation(async () => {
|
||||
feed.connected = false;
|
||||
await originalShutdown();
|
||||
});
|
||||
const lifecycle = [
|
||||
feedStart,
|
||||
feedStop,
|
||||
spyOn(execution, 'initialize'),
|
||||
spyOn(execution, 'shutdown'),
|
||||
spyOn(storage, 'initialize'),
|
||||
spyOn(storage, 'shutdown'),
|
||||
spyOn(strategies, 'restoreStrategies'),
|
||||
spyOn(strategies, 'shutdown'),
|
||||
];
|
||||
await registerOrchestratorServices(container);
|
||||
const runtime = services.custom!,
|
||||
runner = runtime.BacktestRunner!,
|
||||
engine = runtime.BacktestEngine!;
|
||||
cleanup.push(async () => {
|
||||
try {
|
||||
await runner.shutdown();
|
||||
await mode.shutdown();
|
||||
await strategies.shutdown();
|
||||
await container.dispose();
|
||||
} finally {
|
||||
for (const method of lifecycle) method.mockRestore();
|
||||
}
|
||||
await runner.shutdown();
|
||||
await paper.runtime.shutdown();
|
||||
await container.dispose();
|
||||
});
|
||||
await mode.initializeMode({
|
||||
mode: 'paper',
|
||||
accountId: 'paper-fixture',
|
||||
startingCapital: 10000,
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
});
|
||||
const strategy = new CounterStrategy(execution);
|
||||
await strategies.attachStrategy(strategy);
|
||||
await market.subscribeToSymbol('A');
|
||||
market.ingest(quote('paper-one', 100, 100, Date.now()));
|
||||
await market.flush();
|
||||
expect(strategy.count).toBe(1);
|
||||
expect((await execution.getAccount()).cash).toBe(9899.9);
|
||||
|
||||
let failedRead = false;
|
||||
storage.getHistoricalBars = async () => {
|
||||
if (failedRead) throw new Error('Injected research history failure');
|
||||
return Array.from({ length: 70 }, (_, i) => {
|
||||
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
|
||||
return {
|
||||
symbol: research.symbols[0]!,
|
||||
source: 'eod' as const,
|
||||
timestamp: new Date(Date.parse(research.startDate) + i * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
};
|
||||
const stateHash = async () => {
|
||||
const state: unknown[] = [];
|
||||
for (const [table, columns] of [
|
||||
['simulation_accounts', 'id,state'],
|
||||
['simulation_orders', 'id,payload'],
|
||||
['simulation_fills', 'id,payload'],
|
||||
['simulation_events', 'id,fingerprint'],
|
||||
['simulation_market_inputs', 'id,payload'],
|
||||
['simulation_strategy_journal', 'sequence,payload'],
|
||||
['simulation_strategy_checkpoints', 'strategy_id,payload'],
|
||||
['simulation_strategy_intents', 'client_order_id,payload'],
|
||||
]) {
|
||||
const rows = (await pool.query(`SELECT ${columns} FROM ${table}`)).rows;
|
||||
state.push([table, rows.map(row => canonicalJson(row)).sort()]);
|
||||
}
|
||||
return createHash('sha256').update(canonicalJson(state)).digest('hex');
|
||||
};
|
||||
return {
|
||||
services,
|
||||
pool,
|
||||
runner,
|
||||
mode,
|
||||
execution,
|
||||
market,
|
||||
strategies,
|
||||
strategy,
|
||||
feed,
|
||||
stateHash,
|
||||
lifecycleCounts: () => lifecycle.map(method => method.mock.calls.length),
|
||||
failHistory: (fail: boolean) => {
|
||||
failedRead = fail;
|
||||
},
|
||||
};
|
||||
return { paper, ...admitted, container, services, runtime, runner, engine };
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('research isolation from a real paper ledger', () => {
|
||||
test('legacy_paper_combination_rejected_before_prepare preserves an active paper graph', async () => {
|
||||
const f = await fixture();
|
||||
const engine = f.mode.getTradingEngine();
|
||||
const before = await f.stateHash();
|
||||
const lifecycle = f.lifecycleCounts();
|
||||
await expect(f.mode.initializeMode(research)).rejects.toThrow('only permits paper');
|
||||
await expect(f.mode.transitionMode('paper', 'backtest', research)).rejects.toThrow(
|
||||
'only permits paper'
|
||||
);
|
||||
await expect(f.execution.initialize(research, engine)).rejects.toThrow('only permits paper');
|
||||
expect(f.mode.getTradingEngine()).toBe(engine);
|
||||
expect(f.mode.isPaperMode()).toBe(true);
|
||||
expect(f.feed.connected).toBe(true);
|
||||
expect(f.lifecycleCounts()).toEqual(
|
||||
lifecycle.map((count, index) => count + (index === 2 ? 1 : 0))
|
||||
);
|
||||
expect(await f.stateHash()).toBe(before);
|
||||
});
|
||||
|
||||
test('native_paper_isolation across successful, cancelled and failed durable jobs', async () => {
|
||||
const f = await fixture();
|
||||
const engine = f.mode.getTradingEngine();
|
||||
const paperConfig = f.mode.getConfig();
|
||||
const before = await f.stateHash();
|
||||
const lifecycle = f.lifecycleCounts();
|
||||
const unchanged = async () => {
|
||||
expect(await f.stateHash()).toBe(before);
|
||||
expect(f.mode.getTradingEngine()).toBe(engine);
|
||||
expect(f.mode.getConfig()).toEqual(paperConfig);
|
||||
expect(f.lifecycleCounts()).toEqual(lifecycle);
|
||||
expect(f.market.listenerCount('marketDataBatch')).toBe(1);
|
||||
expect(f.strategies.getActiveStrategies()).toEqual(['counter']);
|
||||
expect(f.feed.connected).toBe(true);
|
||||
};
|
||||
expect((await f.runner.runBacktest(research)).status).toBe('completed');
|
||||
await unchanged();
|
||||
for (let i = 0; i < 2; i++) {
|
||||
let stopped: Promise<void> | undefined;
|
||||
f.runner.once('progress', () => {
|
||||
stopped = f.runner.stopBacktest();
|
||||
});
|
||||
const outcome = await f.runner.runBacktest(research).catch(error => error);
|
||||
await stopped;
|
||||
expect(stopped).toBeDefined();
|
||||
expect(outcome).toBeInstanceOf(BacktestCancelledError);
|
||||
await unchanged();
|
||||
f.failHistory(true);
|
||||
await expect(f.runner.runBacktest(research)).rejects.toThrow(
|
||||
'Injected research history failure'
|
||||
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
|
||||
'canonical research isolation from durable paper custody',
|
||||
() => {
|
||||
test('default research composition cannot activate, reset or overlay the existing paper account', async () => {
|
||||
const f = await fixture(),
|
||||
before = await f.paper.snapshot();
|
||||
for (const key of [
|
||||
'ModeManager',
|
||||
'ExecutionService',
|
||||
'MarketDataService',
|
||||
'StrategyManager',
|
||||
'PaperTradingManager',
|
||||
'CanonicalPaperRuntime',
|
||||
]) {
|
||||
expect(f.runtime).not.toHaveProperty(key);
|
||||
}
|
||||
await expect(registerOrchestratorServices(f.container, { role: 'paper' })).rejects.toThrow(
|
||||
'explicit canonicalPaper'
|
||||
);
|
||||
f.failHistory(false);
|
||||
await expect(
|
||||
registerOrchestratorServices(f.container, { useRustEngine: false })
|
||||
).rejects.toThrow('Legacy financial execution is retired');
|
||||
await expect(
|
||||
registerOrchestratorServices(f.container, {
|
||||
role: 'paper',
|
||||
canonicalPaper: f.paper.configuration,
|
||||
})
|
||||
).rejects.toThrow('fresh runtime composition');
|
||||
expect(await f.paper.snapshot()).toEqual(before);
|
||||
expect((await f.paper.runtime.status()).active).toBe(true);
|
||||
});
|
||||
test('real native success, cancellation and failed durable research leave paper ledger/checkpoint/decisions unchanged', async () => {
|
||||
const f = await fixture(),
|
||||
before = await f.paper.snapshot();
|
||||
const unchanged = async () => {
|
||||
expect(await f.paper.snapshot()).toEqual(before);
|
||||
expect((await f.paper.runtime.status()).active).toBe(true);
|
||||
};
|
||||
const accept = () => f.api.createRun({ backtestId: f.draft.id });
|
||||
const completed = await accept();
|
||||
expect((await f.runner.runQueued(completed.id)).status).toBe('completed');
|
||||
await unchanged();
|
||||
}
|
||||
expect((await f.runner.runBacktest(research)).status).toBe('completed');
|
||||
await unchanged();
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT status, count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text'
|
||||
)
|
||||
).rows
|
||||
).toEqual([
|
||||
{ status: 'cancelled', count: 2 },
|
||||
{ status: 'completed', count: 2 },
|
||||
{ status: 'failed', count: 2 },
|
||||
]);
|
||||
// The existing feed still makes exactly one new durable paper decision after research.
|
||||
f.market.ingest(quote('paper-two', 101, 100, Date.now()));
|
||||
await f.market.flush();
|
||||
expect(f.strategy.count).toBe(2);
|
||||
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2);
|
||||
}, 15000);
|
||||
});
|
||||
const result = await f.api.getRunResults(completed.id);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result).toHaveProperty('kind', 'canonical-result/v1');
|
||||
for (let index = 0; index < 2; index++) {
|
||||
const run = await accept();
|
||||
let stopped: Promise<void> | undefined;
|
||||
f.runner.once('progress', () => {
|
||||
stopped = f.runner.stopBacktest();
|
||||
});
|
||||
const cancelled = await f.runner.runQueued(run.id).catch(error => error);
|
||||
await stopped;
|
||||
expect(stopped).toBeDefined();
|
||||
expect(cancelled).toBeInstanceOf(BacktestCancelledError);
|
||||
await unchanged();
|
||||
const failed = await accept(),
|
||||
original = f.engine.runCanonical;
|
||||
f.engine.runCanonical = async () => {
|
||||
throw new Error('Injected canonical execution failure');
|
||||
};
|
||||
try {
|
||||
await expect(f.runner.runQueued(failed.id)).rejects.toThrow(
|
||||
'Injected canonical execution failure'
|
||||
);
|
||||
} finally {
|
||||
f.engine.runCanonical = original;
|
||||
}
|
||||
await unchanged();
|
||||
}
|
||||
expect((await f.runner.runQueued((await accept()).id)).status).toBe('completed');
|
||||
await unchanged();
|
||||
expect(
|
||||
(
|
||||
await f.paper.pool.query(
|
||||
'SELECT status,count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text'
|
||||
)
|
||||
).rows
|
||||
).toEqual([
|
||||
{ status: 'cancelled', count: 2 },
|
||||
{ status: 'completed', count: 2 },
|
||||
{ status: 'failed', count: 2 },
|
||||
]);
|
||||
f.paper.clock(30);
|
||||
await f.paper.runtime.ingest(paperFrame(3));
|
||||
const continued = await f.paper.snapshot();
|
||||
expect(continued.owners[0]!.diagnostic.nextDecisionSequence).toBe(
|
||||
before.owners[0]!.diagnostic.nextDecisionSequence + 1
|
||||
);
|
||||
expect(continued.account.view.portfolio.positions).toHaveLength(1);
|
||||
}, 15000);
|
||||
}
|
||||
);
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ 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';
|
||||
import { seedHistoricalRun } from '../fixtures/historical-run';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('research-workspace');
|
||||
|
|
@ -96,7 +97,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
|
|||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
const run = await backtests.createRun({ backtestId: definition.id });
|
||||
const run = await seedHistoricalRun(pool, backtests, { backtestId: definition.id });
|
||||
// Fixed old-display fixtures exercise custody/conversion, not financial simulation.
|
||||
await pool.query(
|
||||
`INSERT INTO backtest_results(run_id,metrics,equity_curve,ohlc_data,trades,positions,analytics,execution_time,engine)
|
||||
|
|
@ -326,7 +327,7 @@ describe.skipIf(!url)('research workspace retained narratives and evidence', ()
|
|||
expect(revised.updatedBy).toBe('operator');
|
||||
await expect(
|
||||
f.service.createHypothesis(p.id, { ...hypothesisInput, contentOrigin: 'human' }, 'service')
|
||||
).rejects.toThrow('cannot declare human');
|
||||
).rejects.toThrow('Only operator credentials can declare human authorship');
|
||||
await expect(
|
||||
f.service.reviseHypothesis(
|
||||
h.id,
|
||||
|
|
@ -535,7 +536,9 @@ describe.skipIf(!url)('research workspace retained narratives and evidence', ()
|
|||
).rejects.toThrow();
|
||||
}
|
||||
const { run, definition } = await f.legacy();
|
||||
const missingResult = await f.backtests.createRun({ backtestId: definition.id });
|
||||
const missingResult = await seedHistoricalRun(f.pool, f.backtests, {
|
||||
backtestId: definition.id,
|
||||
});
|
||||
await f.pool.query("UPDATE runs SET status='completed' WHERE id=$1", [missingResult.id]);
|
||||
for (const bad of [
|
||||
reference(randomUUID()),
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ 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';
|
||||
import { seedHistoricalRun } from '../fixtures/historical-run';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('run-reproduction');
|
||||
|
|
@ -600,7 +601,7 @@ describe.skipIf(!url)('retained original-run reproduction', () => {
|
|||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
const legacyRun = await f.api.createRun({ backtestId: legacy.id });
|
||||
const legacyRun = await seedHistoricalRun(f.pool, f.api, { backtestId: legacy.id });
|
||||
await f.pool.query("UPDATE runs SET status='completed' WHERE id=$1", [legacyRun.id]);
|
||||
expect((await f.api.getRun(legacyRun.id))?.originalRunId).toBeNull();
|
||||
expect((await f.api.getReproductionPreview(legacyRun.id)).reason).toContain(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue