feat(research): run retained strategies through durable canonical engine
This commit is contained in:
parent
d929db707a
commit
618fb9e33c
58 changed files with 6596 additions and 779 deletions
|
|
@ -290,6 +290,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -331,8 +332,15 @@ export async function fixture(browser: Browser, native = false) {
|
|||
maxAttempts: 3,
|
||||
});
|
||||
const controlled = new FixtureEngine();
|
||||
const historicalDataReads: string[] = [];
|
||||
const runStorage: Pick<StorageService, 'getHistoricalBars'> = {
|
||||
async getHistoricalBars(...args) {
|
||||
historicalDataReads.push(args[0]);
|
||||
return storage.getHistoricalBars(...args);
|
||||
},
|
||||
};
|
||||
const engine = native
|
||||
? new RustBacktestAdapter({ logger, storage }, { timeoutMs: 15000 })
|
||||
? new RustBacktestAdapter({ logger, storage: runStorage }, { timeoutMs: 15000 })
|
||||
: controlled;
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
|
|
@ -560,6 +568,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
login,
|
||||
close,
|
||||
unexpectedNetwork,
|
||||
historicalDataReads,
|
||||
seedCatalog: () => seedBuiltinCatalog(new StrategyCatalogService(container)),
|
||||
};
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,13 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { afterAll, beforeAll, expect, test } from 'bun:test';
|
||||
import { chromium, type Browser, type Request } from 'playwright';
|
||||
import {
|
||||
canonicalResearchSettingsSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
import {
|
||||
fixture as createFixture,
|
||||
createInBrowser,
|
||||
|
|
@ -537,7 +544,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
|
|||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(
|
||||
f.page,
|
||||
'Parameters validated for this immutable version. Execution remains unavailable.'
|
||||
'Parameters validated for this immutable version. Execution eligibility depends on the saved dataset, policy and reviewed executable.'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).click();
|
||||
await f.page.waitForURL(
|
||||
|
|
@ -561,7 +568,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
|
|||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(
|
||||
f.page,
|
||||
'Parameters validated for this immutable version. Execution remains unavailable.'
|
||||
'Parameters validated for this immutable version. Execution eligibility depends on the saved dataset, policy and reviewed executable.'
|
||||
);
|
||||
expect(
|
||||
await f.page.getByRole('button', { name: 'Save and run', exact: true }).isDisabled()
|
||||
|
|
@ -608,7 +615,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
|
|||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(
|
||||
f.page,
|
||||
'Parameters validated for this immutable version. Execution remains unavailable.'
|
||||
'Parameters validated for this immutable version. Execution eligibility depends on the saved dataset, policy and reviewed executable.'
|
||||
);
|
||||
};
|
||||
const saveVisibleSettings = async () => {
|
||||
|
|
@ -701,3 +708,206 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
|
|||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('browser_approved_canonical_strategy_setup_run_and_reopen', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
const oracle = canonicalSmaFixture();
|
||||
const retained = await retainResearchDataset(f.pool, oracle.dataset);
|
||||
const seeded = await f.seedCatalog();
|
||||
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
|
||||
expect(selected.reviewStatus).toBe('pending');
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/strategies/${selected.strategyId}/versions/${selected.id}`);
|
||||
|
||||
// Approval is an authenticated human review of an immutable built-in, not a run bypass.
|
||||
await f.page
|
||||
.getByLabel('Review reason', { exact: true })
|
||||
.fill('Reviewed retained SMA fixture and next-open oracle.');
|
||||
const approval = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith(`/strategy-versions/${selected.id}/reviews`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Approve built-in version', exact: true }).click();
|
||||
expect((await approval).status()).toBe(201);
|
||||
await visible(f.page, /This immutable built-in version has an approval record/);
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('2');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('3');
|
||||
const validate = async () => {
|
||||
const response = f.page.waitForResponse(
|
||||
reply =>
|
||||
reply.request().method() === 'POST' &&
|
||||
reply.url().endsWith(`/strategy-versions/${selected.id}/validate`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
expect((await response).status()).toBe(200);
|
||||
await visible(f.page, /Parameters validated for this immutable version/);
|
||||
};
|
||||
await validate();
|
||||
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).click();
|
||||
await f.page.waitForURL(
|
||||
url =>
|
||||
url.pathname === '/backtests' && url.searchParams.get('strategyVersionId') === selected.id
|
||||
);
|
||||
await f.page.getByPlaceholder('My Strategy Backtest').fill('Reviewed canonical browser oracle');
|
||||
await until(
|
||||
async () =>
|
||||
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
|
||||
selected.id,
|
||||
'canonical draft immutable version'
|
||||
);
|
||||
await f.page.locator('input[type="date"]').nth(0).fill('2024-01-01');
|
||||
await f.page.locator('input[type="date"]').nth(1).fill('2024-01-02');
|
||||
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
|
||||
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('3');
|
||||
await validate();
|
||||
expect(
|
||||
await f.page.getByRole('button', { name: 'Save and run', exact: true }).isDisabled()
|
||||
).toBe(true);
|
||||
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
await f.page.waitForURL(/\/backtests\/[^/?]+$/);
|
||||
const backtestId = f.page.url().split('/').at(-1)!;
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
|
||||
true
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'Configure canonical research', exact: true }).click();
|
||||
await f.page.getByLabel('Canonical dataset', { exact: true }).selectOption(retained.hash);
|
||||
await visible(f.page, new Date(retained.bounds.tradeStart).toISOString());
|
||||
await visible(f.page, new Date(retained.bounds.tradeEnd).toISOString());
|
||||
await f.page.getByLabel('Initial capital (USD)', { exact: true }).fill('10000');
|
||||
const policyFields = [
|
||||
['Owner budget', canonicalSettings.ownerBudget],
|
||||
['Fee rate', canonicalSettings.feeRate],
|
||||
['Half-spread rate', canonicalSettings.halfSpreadRate],
|
||||
['Slippage rate', canonicalSettings.slippageRate],
|
||||
['Volume participation rate', canonicalSettings.participationRate],
|
||||
['Order latency (ms)', canonicalSettings.latencyMs],
|
||||
['Maximum order quantity', canonicalSettings.maxOrderQuantity],
|
||||
['Maximum position quantity', canonicalSettings.maxPositionQuantity],
|
||||
['Maximum asset exposure', canonicalSettings.maxSymbolExposure],
|
||||
['Maximum gross exposure', canonicalSettings.maxGrossExposure],
|
||||
['Maximum risk-period loss', canonicalSettings.maxDailyLoss],
|
||||
['Maximum drawdown amount', canonicalSettings.maxDrawdownAmount],
|
||||
['Maximum mark age (ms)', canonicalSettings.maxMarkAgeMs],
|
||||
['Random seed', canonicalSettings.seed],
|
||||
['Reporting periods per year', canonicalSettings.periodsPerYear],
|
||||
['Annual risk-free rate', canonicalSettings.annualRiskFreeRate],
|
||||
] as const;
|
||||
for (const [label, value] of policyFields) {
|
||||
await f.page.getByLabel(label, { exact: true }).fill(value === null ? '' : String(value));
|
||||
}
|
||||
await until(
|
||||
async () =>
|
||||
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
|
||||
selected.id,
|
||||
'canonical setup immutable version'
|
||||
);
|
||||
await validate();
|
||||
const saving = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'PUT' && response.url().endsWith(`/backtests/${backtestId}`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).click();
|
||||
const savedResponse = await saving;
|
||||
expect(savedResponse.status()).toBe(200);
|
||||
const sent = savedResponse.request().postDataJSON();
|
||||
expect(sent.config).toEqual({
|
||||
datasetHash: retained.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: canonicalResearchSettingsSchema.parse(canonicalSettings),
|
||||
});
|
||||
expect(sent.symbols).toEqual(['X0.US']);
|
||||
expect(sent.initialCapital).toBe(10000);
|
||||
expect(sent.startDate).toBe(new Date(retained.bounds.tradeStart).toISOString());
|
||||
expect(sent.endDate).toBe(new Date(retained.bounds.tradeEnd).toISOString());
|
||||
expect(sent.strategyVersionId).toBe(selected.id);
|
||||
expect(sent.strategyParameters).toEqual({ fastPeriod: 2, slowPeriod: 3 });
|
||||
await visible(f.page, /Canonical execution is available for this saved configuration/);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
const accepted = await submitInBrowser(f.page);
|
||||
expect(accepted.status()).toBe(202);
|
||||
expect(accepted.request().postDataJSON()).toEqual({ speedMultiplier: null });
|
||||
const run = await accepted.json();
|
||||
const admitted = (
|
||||
await f.pool.query('SELECT request_snapshot,dataset_hash FROM runs WHERE id=$1', [run.id])
|
||||
).rows[0];
|
||||
expect(admitted.dataset_hash).toBe(retained.hash);
|
||||
expect(admitted.request_snapshot.kind).toBe('canonical-research/v1');
|
||||
expect(admitted.request_snapshot.strategy.versionId).toBe(selected.id);
|
||||
expect(admitted.request_snapshot.strategy.selection.parameters).toEqual({
|
||||
fastPeriod: 2,
|
||||
slowPeriod: 3,
|
||||
});
|
||||
expect(admitted.request_snapshot.strategy.package.artifact.sha256).toBe(
|
||||
selected.package.artifact.sha256
|
||||
);
|
||||
await visible(f.page, 'Pending');
|
||||
f.dispatcher.start();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
await visible(f.page, 'Completed');
|
||||
const result = (await f.request(`/api/v2/runs/${run.id}/results`)) as CanonicalRunResult;
|
||||
expect(result.kind).toBe('canonical-result/v1');
|
||||
expect(result.request).toEqual(admitted.request_snapshot);
|
||||
expect(result.financialEngine).toBe('rust');
|
||||
expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000');
|
||||
expect(String(result.financial.projection.valuation.fees)).toBe('0.70000000');
|
||||
expect(
|
||||
result.financial.projection.fills.map(fill => [
|
||||
fill.side,
|
||||
String(fill.quantity),
|
||||
String(fill.price),
|
||||
String(fill.fee.amount),
|
||||
])
|
||||
).toEqual([
|
||||
['buy', '10.00000000', '5.00000000', '0.50000000'],
|
||||
['sell', '10.00000000', '2.00000000', '0.20000000'],
|
||||
]);
|
||||
expect(result.analytics.metrics.roundTripCount).toBeNull();
|
||||
await visible(f.page, '9969.30000000');
|
||||
await visible(f.page, 'Unavailable — unsupported round trips');
|
||||
const provenance = f.page.getByRole('region', {
|
||||
name: 'Canonical result provenance',
|
||||
exact: true,
|
||||
});
|
||||
expect(await provenance.textContent()).toContain(selected.id);
|
||||
expect(await provenance.textContent()).toContain(retained.hash);
|
||||
expect(await provenance.textContent()).toContain(selected.package.artifact.sha256);
|
||||
expect(await provenance.textContent()).toContain(result.request.build.engineBinarySha256);
|
||||
expect(
|
||||
await f.page.getByText('Research only · Unverified economics', { exact: true }).count()
|
||||
).toBe(0);
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'Canonical fills (2)');
|
||||
expect(await f.page.locator('tbody tr').count()).toBe(2);
|
||||
await visible(f.page, '0.50000000');
|
||||
await visible(f.page, '0.20000000');
|
||||
const completedUrl = f.page.url();
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
await visible(f.page, '9969.30000000');
|
||||
expect(f.page.url()).toBe(completedUrl);
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, 'Canonical fills (2)');
|
||||
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
|
||||
const stored = (
|
||||
await f.pool.query(
|
||||
'SELECT canonical_result,metrics,trades FROM backtest_results WHERE run_id=$1',
|
||||
[run.id]
|
||||
)
|
||||
).rows[0];
|
||||
expect(stored.canonical_result).toEqual(result);
|
||||
expect(stored.metrics).toBeNull();
|
||||
expect(stored.trades).toBeNull();
|
||||
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
91
test/fixtures/canonical-research.ts
vendored
Normal file
91
test/fixtures/canonical-research.ts
vendored
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import type { CanonicalResearchSettings } from '@stock-bot/stock-config/canonical-research';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
|
||||
export const canonicalSettings: CanonicalResearchSettings = {
|
||||
version: 1,
|
||||
seed: 42,
|
||||
ownerBudget: '40',
|
||||
feeRate: '0.01',
|
||||
halfSpreadRate: '0',
|
||||
slippageRate: '0',
|
||||
latencyMs: 0,
|
||||
participationRate: '1',
|
||||
maxOrderQuantity: '10000',
|
||||
maxPositionQuantity: '10000',
|
||||
maxSymbolExposure: '10000',
|
||||
maxGrossExposure: '10000',
|
||||
maxDailyLoss: '10000',
|
||||
maxDrawdownAmount: '10000',
|
||||
maxMarkAgeMs: 345600000,
|
||||
periodsPerYear: 252,
|
||||
annualRiskFreeRate: 0,
|
||||
};
|
||||
|
||||
/** Explicit retained exchange sessions straddle US DST; labels are never UTC midnights. */
|
||||
export function canonicalDailyDataset() {
|
||||
const sessions = [
|
||||
{
|
||||
date: '2024-03-08',
|
||||
open: Date.parse('2024-03-08T14:30:00Z'),
|
||||
close: Date.parse('2024-03-08T21:00:00Z'),
|
||||
},
|
||||
{
|
||||
date: '2024-03-11',
|
||||
open: Date.parse('2024-03-11T13:30:00Z'),
|
||||
close: Date.parse('2024-03-11T20:00:00Z'),
|
||||
},
|
||||
];
|
||||
const start = sessions[0]!.open,
|
||||
end = sessions[1]!.close;
|
||||
return createDatasetV2({
|
||||
metadata: {
|
||||
calendars: [
|
||||
{
|
||||
id: 'retained-test-calendar',
|
||||
venue: 'TEST',
|
||||
timeZone: 'America/New_York',
|
||||
revision: 'dst-fixture-v1',
|
||||
source: 'synthetic',
|
||||
startDate: '2024-03-08',
|
||||
endDate: '2024-03-12',
|
||||
sessions,
|
||||
},
|
||||
],
|
||||
series: [
|
||||
{
|
||||
id: 'X0.US:1d',
|
||||
instrumentId: 'X0.US',
|
||||
interval: '1d',
|
||||
calendarId: 'retained-test-calendar',
|
||||
venue: 'TEST',
|
||||
source: { provider: 'synthetic', revision: 'v1' },
|
||||
timestamp: 'session-date',
|
||||
availability: 'explicit',
|
||||
adjustment: 'raw',
|
||||
},
|
||||
],
|
||||
executionSeries: [{ instrumentId: 'X0.US', seriesId: 'X0.US:1d' }],
|
||||
bounds: { warmupStart: start, tradeStart: sessions[1]!.open, tradeEnd: end },
|
||||
universe: {
|
||||
selection: 'point-in-time',
|
||||
asOf: start,
|
||||
revision: 'v1',
|
||||
instrumentIds: ['X0.US'],
|
||||
},
|
||||
corporateActions: [
|
||||
{ instrumentId: 'X0.US', status: 'action-free', start, end, revision: 'v1', actions: [] },
|
||||
],
|
||||
},
|
||||
bars: sessions.map((session, index) => ({
|
||||
seriesId: 'X0.US:1d',
|
||||
timestamp: session.date,
|
||||
availableAt: session.close,
|
||||
sourceSequence: index,
|
||||
open: 10,
|
||||
high: 12,
|
||||
low: 9,
|
||||
close: 11,
|
||||
volume: 1000,
|
||||
})),
|
||||
});
|
||||
}
|
||||
331
test/integration/canonical-durable-runner.test.ts
Normal file
331
test/integration/canonical-durable-runner.test.ts
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
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 };
|
||||
}
|
||||
|
||||
describe('canonical jobs share the durable runner lifecycle', () => {
|
||||
test('queued canonical result preserves admitted request and bypasses every legacy seam', async () => {
|
||||
const f = setup();
|
||||
expect(await f.runner.runQueued(f.request.runId)).toEqual({
|
||||
runId: f.request.runId,
|
||||
status: 'completed',
|
||||
});
|
||||
expect(f.events).toEqual(['claim', 'heartbeat', 'dataset', 'execute', 'complete']);
|
||||
expect(f.result?.request).toEqual(f.request);
|
||||
expect(f.result?.kind).toBe('canonical-result/v1');
|
||||
expect(await f.runner.runQueued(f.request.runId)).toEqual({
|
||||
runId: f.request.runId,
|
||||
status: 'completed',
|
||||
});
|
||||
expect(f.events.filter(e => e === 'execute')).toHaveLength(1);
|
||||
await expect(f.runner.runBacktest(f.request)).rejects.toThrow();
|
||||
await f.runner.shutdown();
|
||||
});
|
||||
test('legacy entry refuses canonical markers even when the remaining fields look legacy', async () => {
|
||||
const f = setup();
|
||||
const legacy = {
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['X.US'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-02-01T00:00:00.000Z',
|
||||
initialCapital: 10000,
|
||||
dataFrequency: '1d',
|
||||
};
|
||||
for (const marker of [
|
||||
{ kind: 'canonical-research/v1' },
|
||||
{ kind: 'canonical-research/v999' },
|
||||
{ canonical: {} },
|
||||
]) {
|
||||
await expect(f.runner.runBacktest({ ...legacy, ...marker })).rejects.toThrow(
|
||||
'Retained strategy versions'
|
||||
);
|
||||
}
|
||||
expect(f.events).toEqual([]);
|
||||
await f.runner.shutdown();
|
||||
});
|
||||
test('a runner without canonical execution fails without preparation or legacy/provider fallback', async () => {
|
||||
const f = setup();
|
||||
const engine: BacktestExecutionEngine = f.engine;
|
||||
delete engine.runCanonical;
|
||||
const fail = f.repo.fail.bind(f.repo);
|
||||
let savedFailure: string | undefined;
|
||||
f.repo.fail = async (runId, error, attemptId) => {
|
||||
savedFailure = error;
|
||||
await fail(runId, error, attemptId);
|
||||
};
|
||||
try {
|
||||
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow(
|
||||
'Canonical execution capabilities are unavailable'
|
||||
);
|
||||
expect(savedFailure).toBe('Canonical execution capabilities are unavailable');
|
||||
expect(f.events).toEqual(['claim', 'heartbeat', 'fail']);
|
||||
expect(f.result).toBeUndefined();
|
||||
expect(await f.runner.runQueued(f.request.runId)).toEqual({
|
||||
runId: f.request.runId,
|
||||
status: 'failed',
|
||||
});
|
||||
expect(f.events).toEqual(['claim', 'heartbeat', 'fail']);
|
||||
} finally {
|
||||
await f.runner.shutdown();
|
||||
}
|
||||
});
|
||||
test('cancel waits for execution to finish before committing cancellation', async () => {
|
||||
const f = setup(),
|
||||
entered = deferred<void>(),
|
||||
reaped = deferred<void>(),
|
||||
exit = deferred<never>();
|
||||
f.engine.runCanonical = async () => {
|
||||
entered.resolve();
|
||||
return exit.promise;
|
||||
};
|
||||
f.engine.stopBacktest = async () => {
|
||||
f.events.push('stop');
|
||||
await reaped.promise;
|
||||
exit.reject(new BacktestCancelledError());
|
||||
};
|
||||
const run = f.runner.runQueued(f.request.runId);
|
||||
const failed = run.catch(error => error);
|
||||
await entered.promise;
|
||||
let stopped = false;
|
||||
const stop = f.runner.stopBacktest(f.request.runId).then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(stopped).toBe(false);
|
||||
expect(f.events).not.toContain('cancel');
|
||||
reaped.resolve();
|
||||
await stop;
|
||||
expect(await failed).toBeInstanceOf(BacktestCancelledError);
|
||||
expect(f.events).toContain('cancel');
|
||||
expect(f.events).not.toContain('complete');
|
||||
await f.runner.shutdown();
|
||||
});
|
||||
test('lease loss stops execution without overwriting a newer owner terminal state', async () => {
|
||||
const f = setup(),
|
||||
entered = deferred<void>(),
|
||||
exit = deferred<never>();
|
||||
f.engine.runCanonical = async () => {
|
||||
entered.resolve();
|
||||
return exit.promise;
|
||||
};
|
||||
f.engine.stopBacktest = async () => {
|
||||
f.events.push('stop');
|
||||
exit.reject(new BacktestCancelledError());
|
||||
};
|
||||
const run = f.runner.runQueued(f.request.runId);
|
||||
const failed = run.catch(error => error);
|
||||
await entered.promise;
|
||||
f.loseLease();
|
||||
expect(await failed).toBeInstanceOf(BacktestLeaseLostError);
|
||||
expect(f.events).toContain('stop');
|
||||
expect(f.events).not.toContain('fail');
|
||||
expect(f.events).not.toContain('cancel');
|
||||
expect(f.events).not.toContain('complete');
|
||||
await f.runner.shutdown();
|
||||
});
|
||||
test('invalid persisted canonical kind never becomes a legacy run', async () => {
|
||||
const f = setup();
|
||||
f.repo.load = async () => ({
|
||||
status: 'pending',
|
||||
config: { ...f.request, kind: 'canonical-research/v2' },
|
||||
});
|
||||
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow();
|
||||
expect(f.events).toEqual(['reject']);
|
||||
await f.runner.shutdown();
|
||||
});
|
||||
});
|
||||
1001
test/integration/canonical-workbench.test.tsx
Normal file
1001
test/integration/canonical-workbench.test.tsx
Normal file
File diff suppressed because it is too large
Load diff
351
test/integration/retained-strategy-worker.test.ts
Normal file
351
test/integration/retained-strategy-worker.test.ts
Normal file
|
|
@ -0,0 +1,351 @@
|
|||
import { fork } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { beforeAll, describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { parseFinancialDecimal, type StrategyVersionPackage } from '@stock-bot/types';
|
||||
import {
|
||||
canonicalWorkerUrl,
|
||||
readCanonicalBuildIdentity,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/canonical-build';
|
||||
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
|
||||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import {
|
||||
nativeWorkerRequestSchema,
|
||||
parseRetainedStrategyResult,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-worker-protocol';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const runId = 'b96aae03-f6d6-43b5-a006-a160e37f012b';
|
||||
const versionId = '212a7d31-893d-46c9-910b-2234566f20d6';
|
||||
const ownerId = `strategy:${versionId}`;
|
||||
const sha = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
|
||||
let packages: StrategyVersionPackage[];
|
||||
beforeAll(async () => {
|
||||
packages = await packageBuiltinStrategies();
|
||||
});
|
||||
|
||||
async function input(strategyId = 'sma_crossover') {
|
||||
const { dataset, config } = nativeReplayFixture(24, 1, [ownerId]);
|
||||
config.matching.risk.ledger.sessionId = runId;
|
||||
config.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
const pkg = structuredClone(packages.find(item => item.program.strategyId === strategyId)!);
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId,
|
||||
backtestId: '4ea6a0fa-7bab-416f-b99e-ef9456567f66',
|
||||
name: 'Exact retained built-in',
|
||||
strategy: {
|
||||
familyId: '05c49df3-08a4-40c5-b78d-4ee3364ac7a9',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: 'e06828fc-8b37-4631-bf32-828d6095fdb6',
|
||||
package: pkg,
|
||||
selection: {
|
||||
strategyId,
|
||||
strategyVersion: pkg.program.strategyVersion,
|
||||
ownerId,
|
||||
seed: 17,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '100',
|
||||
parameters:
|
||||
strategyId === 'sma_crossover'
|
||||
? { fastPeriod: 1, slowPeriod: 2 }
|
||||
: {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0,
|
||||
minTrendReturn: -0.9,
|
||||
minMomentumReturn: -0.9,
|
||||
maxVolatility: 1,
|
||||
minNotionalVolume: '0',
|
||||
regimeFilter: 'none',
|
||||
},
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
build: await readCanonicalBuildIdentity(),
|
||||
modelArtifacts: [],
|
||||
});
|
||||
return { type: 'runRetainedStrategy' as const, request, dataset };
|
||||
}
|
||||
|
||||
function retainedSource(request: CanonicalRunRequest, source: string) {
|
||||
request.strategy.package.artifact.content = source;
|
||||
request.strategy.package.artifact.sha256 = sha(source);
|
||||
}
|
||||
|
||||
async function execute(value: Awaited<ReturnType<typeof input>>) {
|
||||
const raw = await new NativeBacktestWorker().execute(
|
||||
value,
|
||||
new AbortController().signal,
|
||||
() => {}
|
||||
);
|
||||
return { raw, result: parseRetainedStrategyResult(raw, value.request) };
|
||||
}
|
||||
|
||||
describe('retained canonical strategy worker', () => {
|
||||
test.each(['sma_crossover', 'mean_reversion'])(
|
||||
'%s exact packaged bytes match the native report and repeat identically',
|
||||
async strategyId => {
|
||||
const value = await input(strategyId);
|
||||
const load = prepareReplayLoad(value.dataset, value.request.policy);
|
||||
const direct = runStrategyReplay(
|
||||
load,
|
||||
[createBuiltinStrategy(value.request.strategy.selection)],
|
||||
{
|
||||
resultFormat: 'report',
|
||||
}
|
||||
).result;
|
||||
const expected = buildCanonicalBacktestReport(direct, value.request.analyticsPolicy);
|
||||
const first = await execute(value);
|
||||
expect(first.result.financial).toEqual(expected.financial);
|
||||
expect(first.result.analytics).toEqual(expected.analytics);
|
||||
expect(first.result.build).toEqual(value.request.build);
|
||||
expect(first.result.artifactHash).toBe(value.request.strategy.package.artifact.sha256);
|
||||
expect((await execute(value)).raw).toBe(first.raw);
|
||||
}
|
||||
);
|
||||
|
||||
test('a retained version executes its own bytes when the current constructor differs', async () => {
|
||||
const value = await input();
|
||||
const current = runStrategyReplay(
|
||||
prepareReplayLoad(value.dataset, value.request.policy),
|
||||
[createBuiltinStrategy(value.request.strategy.selection)],
|
||||
{ resultFormat: 'report' }
|
||||
).result;
|
||||
expect(current.projection.fills.length).toBeGreaterThan(0);
|
||||
// An earlier retained implementation that holds cash, with the same author API.
|
||||
retainedSource(
|
||||
value.request,
|
||||
`export function createSmaStrategy(selection) {
|
||||
return { ownerId:selection.ownerId, strategyId:selection.strategyId,
|
||||
strategyVersion:selection.strategyVersion, seed:selection.seed, mode:'target',
|
||||
initialState:{draws:0}, decide(context) { context.random();
|
||||
return {nextState:{draws:context.state.draws+1}, intent:{mode:'target',targets:[]}}; }
|
||||
};
|
||||
}`
|
||||
);
|
||||
const first = await execute(value);
|
||||
expect(first.result.financial.projection.fills).toEqual([]);
|
||||
expect(first.result.financial.projection.valuation.equity).toBe(parseFinancialDecimal('10000'));
|
||||
expect(first.result.analytics.metrics.exposureTime).toBe(0);
|
||||
expect(first.result.analytics.metrics.roundTripCount).toBeNull();
|
||||
expect((await execute(value)).raw).toBe(first.raw);
|
||||
});
|
||||
|
||||
test('build and retained hashes are checked before module or factory side effects', async () => {
|
||||
for (const changed of [
|
||||
'workerSha256',
|
||||
'engineWrapperSha256',
|
||||
'engineBinarySha256',
|
||||
'dependencyLockSha256',
|
||||
'runtimeVersion',
|
||||
'platform',
|
||||
'arch',
|
||||
] as const) {
|
||||
const value = await input();
|
||||
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
|
||||
value.request.build[changed] = changed.endsWith('Sha256') ? 'f'.repeat(64) : 'wrong-build';
|
||||
await expect(execute(value)).rejects.toThrow('build identity mismatch');
|
||||
}
|
||||
for (const changed of ['artifact', 'dependencyLock'] as const) {
|
||||
const value = await input();
|
||||
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
|
||||
value.request.strategy.package[changed].sha256 = 'f'.repeat(64);
|
||||
await expect(execute(value)).rejects.toThrow('artifact or dependency lock hash mismatch');
|
||||
}
|
||||
const verified = await input();
|
||||
retainedSource(verified.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
|
||||
await expect(execute(verified)).rejects.toThrow('RETAINED_MODULE_EXECUTED');
|
||||
});
|
||||
|
||||
test('eligible exact single-series data and ownership are required before bundle import', async () => {
|
||||
const value = await input();
|
||||
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
|
||||
const corrupt = {
|
||||
...value,
|
||||
dataset: {
|
||||
manifest: structuredClone(value.dataset.manifest),
|
||||
bars: value.dataset.bars.map(bar => ({ ...bar })),
|
||||
},
|
||||
};
|
||||
corrupt.dataset.bars[0]!.volume += 1;
|
||||
await expect(execute(corrupt)).rejects.toThrow('Dataset v2');
|
||||
const other = nativeReplayFixture(24, 2, [ownerId]).dataset;
|
||||
value.request.datasetHash = other.manifest.hash;
|
||||
await expect(
|
||||
new NativeBacktestWorker().execute(
|
||||
{ ...value, dataset: other },
|
||||
new AbortController().signal,
|
||||
() => {}
|
||||
)
|
||||
).rejects.toThrow('Execution series must exactly match');
|
||||
const candidate = await input();
|
||||
expect(() =>
|
||||
nativeWorkerRequestSchema.parse({
|
||||
...candidate,
|
||||
request: {
|
||||
...candidate.request,
|
||||
strategy: { ...candidate.request.strategy, origin: 'candidate' },
|
||||
},
|
||||
})
|
||||
).toThrow();
|
||||
const owners = await input();
|
||||
owners.request.policy.matching.risk.ledger.ownerIds.push('second-owner');
|
||||
await expect(execute(owners)).rejects.toThrow('single-asset');
|
||||
});
|
||||
|
||||
test('factory identity, missing exports, thrown decisions and no-result exits fail closed', async () => {
|
||||
for (const [source, reason] of [
|
||||
['export const somethingElse = 1;', 'factory export is missing'],
|
||||
['export function createSmaStrategy() { return {}; }', 'factory identity or API mismatch'],
|
||||
[
|
||||
'export function createSmaStrategy(selection) { selection.seed = 99; return {}; }',
|
||||
'readonly',
|
||||
],
|
||||
['process.exit(0);', 'exited without a result'],
|
||||
[
|
||||
'export function createSmaStrategy() { throw new Error("bad retained factory"); }',
|
||||
'bad retained factory',
|
||||
],
|
||||
[
|
||||
'export function createSmaStrategy(selection) { return { ...selection, mode:"target", initialState:null, decide() { throw new Error("bad retained decision"); } }; }',
|
||||
'bad retained decision',
|
||||
],
|
||||
]) {
|
||||
const value = await input();
|
||||
retainedSource(value.request, source!);
|
||||
await expect(execute(value)).rejects.toThrow(reason!);
|
||||
}
|
||||
});
|
||||
|
||||
test('capture detaches all admitted inputs before the caller can mutate them', async () => {
|
||||
const value = structuredClone(await input());
|
||||
const captured = structuredClone(value.request);
|
||||
const running = new NativeBacktestWorker().execute(
|
||||
value,
|
||||
new AbortController().signal,
|
||||
() => {}
|
||||
);
|
||||
value.request.strategy.package.artifact.content = 'throw new Error("mutated");';
|
||||
value.request.strategy.selection.seed = 222;
|
||||
value.request.build.engineBinarySha256 = 'f'.repeat(64);
|
||||
(value.dataset.bars as unknown[]).length = 0;
|
||||
const result = parseRetainedStrategyResult(await running, captured);
|
||||
expect(result.artifactHash).toBe(captured.strategy.package.artifact.sha256);
|
||||
expect(result.financial.projection.fills.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('result parser rejects false identity, policy and statistical claims', async () => {
|
||||
const value = await input();
|
||||
const { raw } = await execute(value);
|
||||
for (const mutate of [
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.type = 'strategyReplayResult';
|
||||
},
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.version = 2;
|
||||
},
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.artifactHash = 'f'.repeat(64);
|
||||
},
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.build.workerSha256 = 'f'.repeat(64);
|
||||
},
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.financial.identity.sessionId = 'wrong';
|
||||
},
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.financial.identity.datasetHash = 'f'.repeat(64);
|
||||
},
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.financial.policy.matching.risk.feeRate = '0';
|
||||
},
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.analytics.metrics.exposureTime = null;
|
||||
},
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.analytics.metrics.roundTripCount = 0;
|
||||
},
|
||||
(result: ReturnType<typeof JSON.parse>) => {
|
||||
result.analytics.policy.periodsPerYear = 365;
|
||||
},
|
||||
]) {
|
||||
const result = JSON.parse(raw);
|
||||
mutate(result);
|
||||
expect(() => parseRetainedStrategyResult(JSON.stringify(result), value.request)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('alternate and source workers cannot claim the bundled worker identity', async () => {
|
||||
const value = await input();
|
||||
const sourceUrl = new URL(
|
||||
'../../apps/stock/orchestrator/src/backtest/native-worker.ts',
|
||||
import.meta.url
|
||||
);
|
||||
await expect(
|
||||
new NativeBacktestWorker(sourceUrl).execute(value, new AbortController().signal, () => {})
|
||||
).rejects.toThrow('canonical bundled worker');
|
||||
expect(
|
||||
await new NativeBacktestWorker(canonicalWorkerUrl).execute(
|
||||
value,
|
||||
new AbortController().signal,
|
||||
() => {}
|
||||
)
|
||||
).toContain('retainedStrategyResult');
|
||||
// Bypass the supervisor to test the source child's independent own-file check.
|
||||
const messages = await new Promise<{ type: string; message?: string }[]>((resolve, reject) => {
|
||||
const child = fork(fileURLToPath(sourceUrl), [], {
|
||||
execPath: process.execPath,
|
||||
execArgv: [],
|
||||
serialization: 'json',
|
||||
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
||||
});
|
||||
const received: { type: string; message?: string }[] = [];
|
||||
const timer = setTimeout(() => {
|
||||
child.kill('SIGKILL');
|
||||
reject(new Error('Source worker timeout'));
|
||||
}, 5000);
|
||||
child.stderr?.resume();
|
||||
child.on('message', message => received.push(message as { type: string; message?: string }));
|
||||
child.on('error', reject);
|
||||
child.on('close', () => {
|
||||
clearTimeout(timer);
|
||||
resolve(received);
|
||||
});
|
||||
child.send(value);
|
||||
});
|
||||
expect(messages).toEqual([
|
||||
{
|
||||
type: 'error',
|
||||
message: 'Canonical research requires the bundled worker from this checkout',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('hard cancellation discards retained execution and the worker can be reused', async () => {
|
||||
const value = await input();
|
||||
const worker = new NativeBacktestWorker();
|
||||
const abort = new AbortController();
|
||||
await expect(
|
||||
worker.execute(value, abort.signal, () => abort.abort(new Error('cancel retained replay')))
|
||||
).rejects.toThrow('cancel retained replay');
|
||||
expect(
|
||||
JSON.parse(await worker.execute(value, new AbortController().signal, () => {})).type
|
||||
).toBe('retainedStrategyResult');
|
||||
});
|
||||
});
|
||||
|
|
@ -953,7 +953,7 @@ describe('strategy workbench', () => {
|
|||
await flush(() => {
|
||||
void latest.createRun(null);
|
||||
});
|
||||
expect(latest.submissionError).toContain('save-only');
|
||||
expect(latest.submissionError).toContain('configure a supported canonical dataset');
|
||||
expect(requests.some(item => item.method === 'POST')).toBe(false);
|
||||
let cancelled = false;
|
||||
await flush(() =>
|
||||
|
|
|
|||
368
test/postgres/canonical-durable-backtest.test.ts
Normal file
368
test/postgres/canonical-durable-backtest.test.ts
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type { Queue } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { readCanonicalBuildIdentity } from '../../apps/stock/orchestrator/src/backtest/canonical-build';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('canonical-durable-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
async function fixture(options: { corruptDataset?: boolean; buildMismatch?: boolean } = {}) {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety PostgreSQL required');
|
||||
}
|
||||
const schema = `stock_bot_safety_canonical_${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 NOT NULL,strategy text NOT NULL,symbols jsonb NOT NULL,
|
||||
start_date timestamptz NOT NULL,end_date timestamptz NOT NULL,initial_capital numeric NOT NULL,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 NOT NULL,equity_curve jsonb NOT NULL,ohlc_data jsonb NOT NULL,trades jsonb NOT NULL,positions jsonb NOT NULL,analytics jsonb NOT NULL,execution_time integer);`);
|
||||
for (const filename of [
|
||||
'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',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, 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 versionId = randomUUID(),
|
||||
familyId = randomUUID(),
|
||||
reviewId = randomUUID(),
|
||||
runId = randomUUID(),
|
||||
backtestId = randomUUID();
|
||||
const oracle = canonicalSmaFixture([`strategy:${versionId}`]);
|
||||
oracle.config.matching.risk.ledger.sessionId = runId;
|
||||
oracle.config.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
const pkg = (await (packages ??= packageBuiltinStrategies())).find(
|
||||
p => p.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
const build = await readCanonicalBuildIdentity();
|
||||
if (options.buildMismatch) {
|
||||
build.workerSha256 = '0'.repeat(64);
|
||||
}
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId,
|
||||
backtestId,
|
||||
name: 'Retained canonical oracle',
|
||||
strategy: {
|
||||
familyId,
|
||||
versionId,
|
||||
reviewId,
|
||||
origin: 'builtin',
|
||||
package: pkg,
|
||||
selection: oracle.selections[0],
|
||||
},
|
||||
datasetHash: oracle.dataset.manifest.hash,
|
||||
policy: oracle.config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
build,
|
||||
modelArtifacts: [],
|
||||
});
|
||||
const payload = {
|
||||
...oracle.dataset,
|
||||
bars: oracle.dataset.bars.map((bar, i) => ({
|
||||
...bar,
|
||||
...(options.corruptDataset && i === 0 ? { close: 999 } : {}),
|
||||
})),
|
||||
};
|
||||
await pool.query(
|
||||
`INSERT INTO strategies(id,name,owner_principal,updated_by,builtin_key) VALUES ($1,'Fixture','operator','operator','sma_crossover')`,
|
||||
[familyId]
|
||||
);
|
||||
await pool.query(
|
||||
`INSERT INTO strategy_versions(id,strategy_id,ordinal,envelope,created_by,origin,submission_key,submission_fingerprint)
|
||||
VALUES ($1,$2,1,$3,'operator','builtin',$4,$5)`,
|
||||
[versionId, familyId, pkg, randomUUID(), 'a'.repeat(64)]
|
||||
);
|
||||
await pool.query(
|
||||
`INSERT INTO strategy_review_events(id,version_id,ordinal,decision,actor,reason) VALUES ($1,$2,1,'approve','operator','fixture')`,
|
||||
[reviewId, versionId]
|
||||
);
|
||||
await pool.query(`INSERT INTO backtest_datasets(hash,payload) VALUES ($1,$2)`, [
|
||||
request.datasetHash,
|
||||
payload,
|
||||
]);
|
||||
await pool.query(
|
||||
`INSERT INTO backtests(id,name,strategy,symbols,start_date,end_date,initial_capital,config,strategy_version_id,strategy_parameters)
|
||||
VALUES ($1,$2,'catalog',$3,$4,$5,10000,'{}',$6,$7)`,
|
||||
[
|
||||
backtestId,
|
||||
request.name,
|
||||
JSON.stringify(['X0.US']),
|
||||
new Date(oracle.dataset.manifest.bounds.tradeStart),
|
||||
new Date(oracle.dataset.manifest.bounds.tradeEnd),
|
||||
versionId,
|
||||
request.strategy.selection.parameters,
|
||||
]
|
||||
);
|
||||
const admit = async () => {
|
||||
await pool.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,status,request_snapshot,dataset_hash) VALUES ($1,$2,1,'pending',$3,$4)`,
|
||||
[runId, backtestId, request, request.datasetHash]
|
||||
);
|
||||
await pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]);
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 5000);
|
||||
const storage = {
|
||||
async getHistoricalBars(): Promise<never> {
|
||||
throw new Error('Canonical replay must never fetch provider data');
|
||||
},
|
||||
};
|
||||
const engine = new RustBacktestAdapter({ logger, storage }, { timeoutMs: 10000 });
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
repository,
|
||||
engineName: 'native',
|
||||
logger,
|
||||
heartbeatMs: 20,
|
||||
});
|
||||
const dispatcher = new BacktestDispatcher(
|
||||
postgres,
|
||||
{
|
||||
async add() {
|
||||
return {} as Awaited<ReturnType<Queue['add']>>;
|
||||
},
|
||||
},
|
||||
logger,
|
||||
{ intervalMs: 20, republishMs: 20, maxAttempts: 3 }
|
||||
);
|
||||
cleanup.push(() => runner.shutdown());
|
||||
cleanup.push(() => dispatcher.shutdown());
|
||||
const row = async () => (await pool.query('SELECT * FROM runs WHERE id=$1', [runId])).rows[0];
|
||||
const saved = async () =>
|
||||
(await pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [runId])).rows[0];
|
||||
return {
|
||||
pool,
|
||||
repository,
|
||||
engine,
|
||||
runner,
|
||||
dispatcher,
|
||||
request,
|
||||
dataset: oracle.dataset,
|
||||
admit,
|
||||
row,
|
||||
saved,
|
||||
};
|
||||
}
|
||||
|
||||
(url ? describe : describe.skip)('retained canonical durable PostgreSQL execution', () => {
|
||||
test('only a matching admitted canonical snapshot can be claimed', async () => {
|
||||
const f = await fixture();
|
||||
await expect(f.repository.startCanonical(f.request)).rejects.toThrow('missing');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
const raw = {
|
||||
...parseBacktestRequest({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['X.US'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-02-01T00:00:00.000Z',
|
||||
initialCapital: 10000,
|
||||
dataFrequency: '1d',
|
||||
}),
|
||||
kind: 'canonical-research/v999',
|
||||
};
|
||||
await expect(f.repository.start(raw)).rejects.toThrow('Retained strategy versions');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
await f.admit();
|
||||
await expect(f.repository.startCanonical({ ...f.request, name: 'different' })).rejects.toThrow(
|
||||
'snapshot'
|
||||
);
|
||||
expect((await f.row()).attempt_number).toBe(0);
|
||||
const claim = await f.repository.startCanonical(f.request);
|
||||
expect(claim.config).toEqual(f.request);
|
||||
await expect(f.repository.startCanonical(f.request)).rejects.toThrow('claimed');
|
||||
});
|
||||
test('retained worker result survives template edits/archive and approval revocation; terminal replay is an acknowledgement', async () => {
|
||||
const f = await fixture();
|
||||
await f.admit();
|
||||
await f.pool.query(
|
||||
`UPDATE backtests SET name='edited',strategy_parameters='{"fastPeriod":3,"slowPeriod":8}',archived_at=NOW() WHERE id=$1`,
|
||||
[f.request.backtestId]
|
||||
);
|
||||
await f.pool.query(
|
||||
`INSERT INTO strategy_review_events(id,version_id,ordinal,decision,actor,reason) VALUES ($1,$2,2,'revoke','operator','later')`,
|
||||
[randomUUID(), f.request.strategy.versionId]
|
||||
);
|
||||
expect(await f.runner.runQueued(f.request.runId)).toEqual({
|
||||
runId: f.request.runId,
|
||||
status: 'completed',
|
||||
});
|
||||
const row = await f.saved(),
|
||||
result = row.canonical_result as CanonicalRunResult;
|
||||
expect(result.request).toEqual(f.request);
|
||||
expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000');
|
||||
expect(result.financial.projection.fills).toHaveLength(2);
|
||||
expect(result.financial.projection.fills.map(fill => String(fill.fee.amount))).toEqual([
|
||||
'0.50000000',
|
||||
'0.20000000',
|
||||
]);
|
||||
for (const key of [
|
||||
'metrics',
|
||||
'equity_curve',
|
||||
'trades',
|
||||
'positions',
|
||||
'analytics',
|
||||
'configuration',
|
||||
'engine',
|
||||
]) {
|
||||
expect(row[key]).toBeNull();
|
||||
}
|
||||
const legacyNulls = (
|
||||
await f.pool.query(
|
||||
`SELECT metrics IS NOT NULL AND metrics='null'::jsonb AS absent_projection FROM backtest_results WHERE run_id=$1`,
|
||||
[f.request.runId]
|
||||
)
|
||||
).rows[0];
|
||||
expect(legacyNulls.absent_projection).toBe(true);
|
||||
await f.runner.runQueued(f.request.runId);
|
||||
expect((await f.row()).attempt_number).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
|
||||
await expect(
|
||||
f.pool.query(`UPDATE backtest_results SET canonical_result='{}' WHERE run_id=$1`, [
|
||||
f.request.runId,
|
||||
])
|
||||
).rejects.toThrow('Retained');
|
||||
});
|
||||
test('expired owner is fenced and replacement reuses the identical snapshot and dataset', async () => {
|
||||
const f = await fixture();
|
||||
await f.admit();
|
||||
const old = await f.repository.startCanonical(f.request);
|
||||
expect(
|
||||
await f.repository.loadCanonicalDataset(old.runId, old.attemptId, f.request.datasetHash)
|
||||
).toEqual(f.dataset);
|
||||
const baseline = await f.engine.runCanonical(f.request, async () => f.dataset);
|
||||
await f.pool.query(
|
||||
`UPDATE runs SET lease_expires_at=clock_timestamp()-INTERVAL '1 second' WHERE id=$1`,
|
||||
[old.runId]
|
||||
);
|
||||
await f.dispatcher.tick();
|
||||
expect((await f.row()).status).toBe('pending');
|
||||
const replacement = await f.repository.startCanonical(f.request);
|
||||
const result: CanonicalRunResult = {
|
||||
kind: 'canonical-result/v1',
|
||||
runId: f.request.runId,
|
||||
backtestId: f.request.backtestId,
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
executionTime: 1,
|
||||
financialEngine: 'rust',
|
||||
strategyExecution: 'typescript-retained-builtin/v1',
|
||||
request: f.request,
|
||||
...baseline,
|
||||
};
|
||||
await expect(
|
||||
f.repository.loadCanonicalDataset(old.runId, old.attemptId, f.request.datasetHash)
|
||||
).rejects.toBeInstanceOf(BacktestLeaseLostError);
|
||||
await expect(f.repository.completeCanonical(result, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
const repeated = await f.engine.runCanonical(replacement.config, signal =>
|
||||
f.repository.loadCanonicalDataset(
|
||||
replacement.runId,
|
||||
replacement.attemptId,
|
||||
replacement.config.datasetHash,
|
||||
signal
|
||||
)
|
||||
);
|
||||
expect(repeated).toEqual(baseline);
|
||||
await f.repository.completeCanonical({ ...result, ...repeated }, replacement.attemptId);
|
||||
expect((await f.row()).attempt_number).toBe(2);
|
||||
expect((await f.saved()).canonical_result.financial).toEqual(baseline.financial);
|
||||
});
|
||||
test('cancellation wins against late canonical completion without a partial result', async () => {
|
||||
const f = await fixture();
|
||||
await f.admit();
|
||||
const claim = await f.repository.startCanonical(f.request);
|
||||
const report = await f.engine.runCanonical(f.request, async () => f.dataset);
|
||||
await f.pool.query('UPDATE runs SET cancel_requested=true WHERE id=$1', [claim.runId]);
|
||||
const result: CanonicalRunResult = {
|
||||
kind: 'canonical-result/v1',
|
||||
runId: f.request.runId,
|
||||
backtestId: f.request.backtestId,
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
executionTime: 1,
|
||||
financialEngine: 'rust',
|
||||
strategyExecution: 'typescript-retained-builtin/v1',
|
||||
request: f.request,
|
||||
...report,
|
||||
};
|
||||
await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestCancelledError
|
||||
);
|
||||
expect(await f.saved()).toBeUndefined();
|
||||
await f.repository.cancel(claim.runId, claim.attemptId);
|
||||
expect((await f.row()).status).toBe('cancelled');
|
||||
});
|
||||
test('a failed canonical result insert rolls back terminal completion and records failure', async () => {
|
||||
const f = await fixture();
|
||||
await f.admit();
|
||||
await f.pool.query(
|
||||
`ALTER TABLE backtest_results ADD CONSTRAINT injected_result_failure CHECK (canonical_result IS NULL)`
|
||||
);
|
||||
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow('injected_result_failure');
|
||||
expect((await f.row()).status).toBe('failed');
|
||||
expect(await f.saved()).toBeUndefined();
|
||||
});
|
||||
for (const defect of ['corruptDataset', 'buildMismatch'] as const) {
|
||||
test(`${defect} fails closed without provider fallback or result`, async () => {
|
||||
const f = await fixture({ [defect]: true });
|
||||
await f.admit();
|
||||
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow();
|
||||
expect((await f.row()).status).toBe('failed');
|
||||
expect(await f.saved()).toBeUndefined();
|
||||
expect((await f.row()).request_snapshot).toEqual(f.request);
|
||||
expect((await f.row()).dataset_hash).toBe(f.request.datasetHash);
|
||||
});
|
||||
}
|
||||
});
|
||||
424
test/postgres/canonical-research.test.ts
Normal file
424
test/postgres/canonical-research.test.ts
Normal file
|
|
@ -0,0 +1,424 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import {
|
||||
canonicalResearchSettingsSchema,
|
||||
canonicalRunRequestSchema,
|
||||
} 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 { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
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 { 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 { canonicalDailyDataset, canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('canonical-admission');
|
||||
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(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_canonical_api_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
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',
|
||||
]) {
|
||||
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 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 = () =>
|
||||
catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision: 'approve', reason: 'Reviewed retained builtin' },
|
||||
'operator'
|
||||
);
|
||||
const execute = async (id: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Canonical execution must never load provider data');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: new PostgresBacktestRunRepository(postgres),
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
await runner.runQueued(id);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
}
|
||||
};
|
||||
return {
|
||||
pool,
|
||||
schema,
|
||||
api,
|
||||
catalog,
|
||||
pkg,
|
||||
version,
|
||||
draft,
|
||||
definition,
|
||||
dataset,
|
||||
approve,
|
||||
execute,
|
||||
app: new Hono().route('/', createBacktestV2Routes(container)),
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('canonical research admission and saved evidence', () => {
|
||||
test('approved exact artifact/policy/dataset admission, receipt replay and native results survive template and review changes', async () => {
|
||||
const f = await fixture();
|
||||
expect((await f.api.canonicalCapability(f.draft.id)).available).toBe(false);
|
||||
await expect(f.api.createRun({ backtestId: f.draft.id })).rejects.toThrow('approve');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
await f.approve();
|
||||
expect(await f.api.canonicalCapability(f.draft.id)).toEqual({ available: true, reason: null });
|
||||
const receipt = { principal: 'operator' as const, key: 'original' };
|
||||
const run = await f.api.createRun({ backtestId: f.draft.id }, receipt);
|
||||
const frozen = (
|
||||
await f.pool.query('SELECT request_snapshot,dataset_hash FROM runs WHERE id=$1', [run.id])
|
||||
).rows[0];
|
||||
const request = canonicalRunRequestSchema.parse(frozen.request_snapshot);
|
||||
expect(request.strategy.package).toEqual(f.pkg);
|
||||
expect(request.datasetHash).toBe(f.dataset.manifest.hash);
|
||||
expect(frozen.dataset_hash).toBe(request.datasetHash);
|
||||
expect(run.dataset.state).toBe('pinned');
|
||||
expect(String(request.policy.matching.risk.ledger.initialCapital)).toBe('10000.00000000');
|
||||
await f.api.updateBacktest(f.draft.id, {
|
||||
name: 'Changed',
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 5 },
|
||||
});
|
||||
await f.catalog.reviewVersion(
|
||||
f.version.id,
|
||||
{ decision: 'revoke', reason: 'Block new admissions' },
|
||||
'operator'
|
||||
);
|
||||
await f.api.archiveBacktest(f.draft.id, true);
|
||||
expect((await f.api.createRun({ backtestId: f.draft.id }, receipt)).id).toBe(run.id);
|
||||
await expect(f.api.createRun({ backtestId: f.draft.id })).rejects.toThrow('archived');
|
||||
await f.execute(run.id);
|
||||
const result = await f.api.getRunResults(run.id);
|
||||
expect(result && 'kind' in result && result.kind).toBe('canonical-result/v1');
|
||||
if (!result || !('kind' in result)) {
|
||||
throw new Error('Missing canonical result');
|
||||
}
|
||||
expect(result.request).toEqual(request);
|
||||
expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000');
|
||||
expect(result.financial.projection.fills).toHaveLength(2);
|
||||
expect(result.analytics.metrics.roundTripCount).toBeNull();
|
||||
expect(result.analytics.unavailable.roundTripCount).toBe('unsupported-round-trips');
|
||||
expect(await f.api.getRunResults(run.id)).toEqual(result);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1);
|
||||
await expect(
|
||||
f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [{}, run.id])
|
||||
).rejects.toThrow('Retained');
|
||||
});
|
||||
|
||||
test('exact non-midnight daily bounds and retained DST account boundaries are frozen', async () => {
|
||||
const f = await fixture(canonicalDailyDataset());
|
||||
await f.approve();
|
||||
const run = await f.api.createRun({ backtestId: f.draft.id });
|
||||
const request = canonicalRunRequestSchema.parse(
|
||||
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id])).rows[0]
|
||||
.request_snapshot
|
||||
);
|
||||
expect(request.policy.matching.risk.ledger.riskSession.startsAt).toBe(
|
||||
Date.parse('2024-03-08T14:30:00Z')
|
||||
);
|
||||
expect(request.policy.risk_boundaries[0]?.startsAt).toBe(Date.parse('2024-03-11T13:30:00Z'));
|
||||
expect((await f.api.getBacktest(f.draft.id))?.startDate.toISOString()).toBe(
|
||||
'2024-03-11T13:30:00.000Z'
|
||||
);
|
||||
await expect(
|
||||
f.api.updateBacktest(f.draft.id, { startDate: '2024-03-08T00:00:00Z' })
|
||||
).rejects.toThrow('exact trade bounds');
|
||||
await f.execute(run.id);
|
||||
const result = await f.api.getRunResults(run.id);
|
||||
if (!result || !('kind' in result)) {
|
||||
throw new Error('Missing canonical result');
|
||||
}
|
||||
expect(result.analytics.metrics.exposureTime).toBe(0);
|
||||
expect(result.analytics.metrics.totalReturn).toBe(0);
|
||||
});
|
||||
|
||||
test('candidates, legacy settings, wrong asset/timeframe, multi-asset datasets and pacing never admit work', async () => {
|
||||
const f = await fixture();
|
||||
await f.approve();
|
||||
const clone = await f.catalog.cloneVersion(
|
||||
f.version.id,
|
||||
{ name: 'Candidate' },
|
||||
'operator',
|
||||
'candidate'
|
||||
);
|
||||
await f.catalog.reviewVersion(
|
||||
clone.version.id,
|
||||
{ decision: 'approve', reason: 'Still untrusted' },
|
||||
'operator'
|
||||
);
|
||||
const candidate = await f.api.createBacktest(
|
||||
{ ...f.definition, strategyVersionId: clone.version.id },
|
||||
{ autoStart: false }
|
||||
);
|
||||
await expect(f.api.createRun({ backtestId: candidate.id })).rejects.toThrow('candidates');
|
||||
await expect(f.api.createRun({ backtestId: f.draft.id, speedMultiplier: 2 })).rejects.toThrow(
|
||||
'maximum speed'
|
||||
);
|
||||
for (const change of [
|
||||
{ symbols: ['Y.US'] },
|
||||
{ config: { ...f.definition.config, commission: 0.1 } },
|
||||
{ config: { ...f.definition.config, dataFrequency: '1d' } },
|
||||
]) {
|
||||
await expect(f.api.updateBacktest(f.draft.id, change)).rejects.toThrow();
|
||||
}
|
||||
const multi = nativeReplayFixture(5, 2).dataset;
|
||||
await retainResearchDataset(f.pool, multi);
|
||||
await expect(
|
||||
f.api.updateBacktest(f.draft.id, {
|
||||
config: { ...f.definition.config, datasetHash: multi.manifest.hash },
|
||||
})
|
||||
).rejects.toThrow('one execution asset');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
||||
});
|
||||
|
||||
test('offline import is repeat-safe and rejects corruption; direct SQL cannot bypass snapshot/version binding', async () => {
|
||||
const f = await fixture();
|
||||
await f.approve();
|
||||
await retainResearchDataset(f.pool, f.dataset);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rowCount).toBe(1);
|
||||
const changed = {
|
||||
...f.dataset,
|
||||
bars: f.dataset.bars.map((bar, index) => ({
|
||||
...bar,
|
||||
volume: bar.volume + (index === 0 ? 1 : 0),
|
||||
})),
|
||||
};
|
||||
await expect(retainResearchDataset(f.pool, changed)).rejects.toThrow();
|
||||
await expect(
|
||||
f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES($1,$2,1)', [
|
||||
randomUUID(),
|
||||
f.draft.id,
|
||||
])
|
||||
).rejects.toThrow('canonical request');
|
||||
const run = await f.api.createRun({ backtestId: f.draft.id });
|
||||
const snapshot = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id]))
|
||||
.rows[0].request_snapshot;
|
||||
const id = randomUUID();
|
||||
snapshot.runId = id;
|
||||
snapshot.strategy.package.artifact.content += '\n/* forged */';
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'INSERT INTO runs(id,backtest_id,run_number,request_snapshot,dataset_hash,speed_multiplier) VALUES($1,$2,2,$3,$4,NULL)',
|
||||
[id, f.draft.id, snapshot, f.dataset.manifest.hash]
|
||||
)
|
||||
).rejects.toThrow('exact approved');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
||||
});
|
||||
|
||||
test('extra series and malformed financial settings reject before saving or dispatching', async () => {
|
||||
const f = await fixture();
|
||||
await f.approve();
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
f.dataset.manifest;
|
||||
const extraId = 'X0.US:aux';
|
||||
const extra = createDatasetV2({
|
||||
metadata: {
|
||||
calendars,
|
||||
series: [...series, { ...series[0]!, id: extraId }],
|
||||
executionSeries,
|
||||
bounds,
|
||||
universe,
|
||||
corporateActions,
|
||||
},
|
||||
bars: f.dataset.bars.flatMap(
|
||||
({
|
||||
instrumentId: _instrument,
|
||||
eventTime: _event,
|
||||
intervalEnd: _end,
|
||||
intervalStart,
|
||||
...bar
|
||||
}) => [
|
||||
{ ...bar, timestamp: intervalStart },
|
||||
{ ...bar, seriesId: extraId, timestamp: intervalStart },
|
||||
]
|
||||
),
|
||||
});
|
||||
await retainResearchDataset(f.pool, extra);
|
||||
await expect(
|
||||
f.api.updateBacktest(f.draft.id, {
|
||||
config: { ...f.definition.config, datasetHash: extra.manifest.hash },
|
||||
})
|
||||
).rejects.toThrow('one retained series');
|
||||
for (const change of [
|
||||
{ config: { ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '1e-3' } } },
|
||||
{
|
||||
config: { ...f.definition.config, canonical: { ...canonicalSettings, ownerBudget: 'wat' } },
|
||||
},
|
||||
{ initialCapital: 1e22 },
|
||||
{
|
||||
config: {
|
||||
...f.definition.config,
|
||||
canonical: { ...canonicalSettings, halfSpreadRate: '1' },
|
||||
},
|
||||
},
|
||||
{
|
||||
config: { ...f.definition.config, canonical: { ...canonicalSettings, slippageRate: '1' } },
|
||||
},
|
||||
]) {
|
||||
const response = await f.app.request(`/api/v2/backtests/${f.draft.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(change),
|
||||
});
|
||||
expect(response.status).toBe(400);
|
||||
}
|
||||
for (const key of ['halfSpreadRate', 'slippageRate'] as const) {
|
||||
expect(
|
||||
canonicalResearchSettingsSchema.safeParse({ ...canonicalSettings, [key]: '0.99999999' })
|
||||
.success
|
||||
).toBe(true);
|
||||
}
|
||||
expect((await f.api.getBacktest(f.draft.id))?.config).toEqual(f.draft.config);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
});
|
||||
|
||||
test('concurrent approval revocation and admission follow the same family lock in either ordering', async () => {
|
||||
for (const revokeFirst of [true, false]) {
|
||||
const f = await fixture();
|
||||
await f.approve();
|
||||
const held = await f.pool.connect();
|
||||
await held.query('BEGIN');
|
||||
await held.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.version.strategyId]);
|
||||
const waiters = async (count: number) => {
|
||||
const deadline = Date.now() + 5000;
|
||||
while (Date.now() < deadline) {
|
||||
const waiting = await f.pool.query(
|
||||
"SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
|
||||
[f.schema]
|
||||
);
|
||||
if (waiting.rows[0].count >= count) {
|
||||
return;
|
||||
}
|
||||
await Bun.sleep(10);
|
||||
}
|
||||
throw new Error('Expected family row lock waiters');
|
||||
};
|
||||
const revoke = () =>
|
||||
f.catalog.reviewVersion(
|
||||
f.version.id,
|
||||
{ decision: 'revoke', reason: 'Concurrent review' },
|
||||
'operator'
|
||||
);
|
||||
const admit = () => f.api.createRun({ backtestId: f.draft.id });
|
||||
const first = (revokeFirst ? revoke() : admit()).then(
|
||||
value => ({ value }),
|
||||
error => ({ error })
|
||||
);
|
||||
try {
|
||||
await waiters(1);
|
||||
const second = (revokeFirst ? admit() : revoke()).then(
|
||||
value => ({ value }),
|
||||
error => ({ error })
|
||||
);
|
||||
await waiters(2);
|
||||
await held.query('COMMIT');
|
||||
const outcomes = await Promise.all([first, second]);
|
||||
const admission = outcomes[revokeFirst ? 1 : 0]!;
|
||||
const revocation = outcomes[revokeFirst ? 0 : 1]!;
|
||||
expect('error' in revocation).toBe(false);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
|
||||
[f.version.id]
|
||||
)
|
||||
).rows[0].decision
|
||||
).toBe('revoke');
|
||||
expect('error' in admission).toBe(revokeFirst);
|
||||
if (revokeFirst && 'error' in admission) {
|
||||
expect(String(admission.error)).toContain('approve');
|
||||
}
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(revokeFirst ? 0 : 1);
|
||||
if (!revokeFirst && 'value' in admission) {
|
||||
await f.execute(admission.value.id);
|
||||
expect((await f.api.getRun(admission.value.id))?.status).toBe('completed');
|
||||
}
|
||||
} finally {
|
||||
await held.query('ROLLBACK');
|
||||
held.release();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -99,6 +99,7 @@ async function fixture() {
|
|||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ async function fixture() {
|
|||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -83,6 +83,7 @@ async function fixture() {
|
|||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ const migrations = [
|
|||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -20,7 +20,11 @@ const cleanup: (() => Promise<void>)[] = [];
|
|||
const sql = (name: string) =>
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8');
|
||||
const retention =
|
||||
sql('17-research-retention.sql') + '\n' + sql('18-backtest-strategy-versions.sql');
|
||||
sql('17-research-retention.sql') +
|
||||
'\n' +
|
||||
sql('18-backtest-strategy-versions.sql') +
|
||||
'\n' +
|
||||
sql('19-canonical-research.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@ async function fixture() {
|
|||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -401,7 +401,7 @@ describe.skipIf(!url)('immutable strategy catalog on real PostgreSQL', () => {
|
|||
reviewStatus: 'pending',
|
||||
runnable: false,
|
||||
});
|
||||
expect(seeded[0]!.reason).toContain('R05');
|
||||
expect(seeded[0]!.reason).toContain('approve');
|
||||
expect(await f.api.listStrategies()).toHaveLength(1);
|
||||
await expect(f.api.seedBuiltin('Fake builtin', candidate(), 'fake')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue