432 lines
17 KiB
TypeScript
432 lines
17 KiB
TypeScript
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',
|
|
'21-run-reproduction.sql',
|
|
'22-experiments.sql',
|
|
'23-experiment-retries.sql',
|
|
'24-chronological-validation.sql',
|
|
'25-walk-forward.sql',
|
|
'26-cost-sensitivity.sql',
|
|
]) {
|
|
await pool.query(
|
|
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
|
);
|
|
}
|
|
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('undeclared 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(
|
|
'Candidate requires a retained isolated execution declaration'
|
|
);
|
|
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();
|
|
}
|
|
}
|
|
});
|
|
});
|