374 lines
16 KiB
TypeScript
374 lines
16 KiB
TypeScript
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',
|
|
'21-run-reproduction.sql',
|
|
'22-experiments.sql',
|
|
'23-experiment-retries.sql',
|
|
'24-chronological-validation.sql',
|
|
'25-walk-forward.sql',
|
|
'26-cost-sensitivity.sql',
|
|
]) {
|
|
await pool.query(
|
|
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
|
);
|
|
}
|
|
const postgres = new PostgreSQLClient(
|
|
{ host: 'unused', port: 5432, database: 'unused', 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);
|
|
});
|
|
}
|
|
});
|