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
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