feat(research): cut over canonical runtime and enforce agent budgets
This commit is contained in:
parent
ab08db82fd
commit
bbf0dd4453
103 changed files with 6138 additions and 3112 deletions
|
|
@ -10,10 +10,12 @@ import { HandlerRegistry } from '@stock-bot/handler-registry';
|
|||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { Queue } from '@stock-bot/queue';
|
||||
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
backtestRequestFromDefinition,
|
||||
parseBacktestRequest,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
|
|
@ -28,6 +30,8 @@ import {
|
|||
RunSubmissionConflictError,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('durable-backtest-test');
|
||||
|
|
@ -35,19 +39,23 @@ const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
|||
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
async function until(check: () => Promise<boolean>, timeoutMs = 3_000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if (await check()) return;
|
||||
if (await check()) {
|
||||
return;
|
||||
}
|
||||
await sleep(20);
|
||||
}
|
||||
throw new Error('Timed out waiting for durable workflow');
|
||||
}
|
||||
|
||||
async function fixture() {
|
||||
async function fixture(historical = false) {
|
||||
if (
|
||||
!url ||
|
||||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
|
||||
|
|
@ -59,7 +67,11 @@ async function fixture() {
|
|||
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
options: `-c search_path=${schema}`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
|
|
@ -96,7 +108,7 @@ async function fixture() {
|
|||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
|
|
@ -124,20 +136,23 @@ async function fixture() {
|
|||
const api = new BacktestServiceV2({ postgres, logger }, async () => {
|
||||
throw new Error('No HTTP execution dispatch allowed');
|
||||
});
|
||||
const definition = await api.createBacktest(
|
||||
{
|
||||
name: 'Durable fixture',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 },
|
||||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
// A response DTO includes nullable catalog markers; legacy input deliberately omits them.
|
||||
const definitionInput = {
|
||||
const legacyDefinition = historical
|
||||
? await api.createBacktest(
|
||||
{
|
||||
name: 'Durable fixture',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 },
|
||||
},
|
||||
{ autoStart: false }
|
||||
)
|
||||
: undefined;
|
||||
const canonical = historical ? undefined : await canonicalAdmissionFixture(pool, postgres, false);
|
||||
const definition = canonical?.draft ?? legacyDefinition!;
|
||||
const definitionInput = canonical?.definition ?? {
|
||||
name: definition.name,
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
|
|
@ -146,6 +161,25 @@ async function fixture() {
|
|||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
};
|
||||
// This raw insertion represents already accepted pre-cutover history. It is
|
||||
// deliberately not exposed through a service or production admission switch.
|
||||
const historicalRun = async (_request: { backtestId: string }) => {
|
||||
if (!historical) {
|
||||
throw new Error('Historical fixture only');
|
||||
}
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(definitionInput, {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
});
|
||||
await pool.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,request_snapshot)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3 FROM runs WHERE backtest_id=$2`,
|
||||
[runId, definition.id, snapshot]
|
||||
);
|
||||
await pool.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
|
||||
return { id: runId };
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
|
||||
const history = { reads: 0, unavailable: false };
|
||||
const storage = {
|
||||
|
|
@ -200,10 +234,27 @@ async function fixture() {
|
|||
return worker;
|
||||
};
|
||||
const snapshot = async (runId: string) =>
|
||||
BacktestConfigSchema.parse(
|
||||
canonicalRunRequestSchema.parse(
|
||||
(await pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [runId])).rows[0]
|
||||
.request_snapshot
|
||||
);
|
||||
const legacySnapshot = async (runId: string) =>
|
||||
BacktestConfigSchema.parse(
|
||||
(await pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
|
||||
.request_snapshot
|
||||
);
|
||||
const report = async (request: CanonicalRunRequest): Promise<CanonicalRunResult> => ({
|
||||
kind: 'canonical-result/v1',
|
||||
runId: request.runId,
|
||||
backtestId: request.backtestId,
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
executionTime: 1,
|
||||
financialEngine: 'rust',
|
||||
strategyExecution: 'typescript-retained-builtin/v1',
|
||||
request,
|
||||
...(await engine.runCanonical(request, async () => canonical!.dataset)),
|
||||
});
|
||||
const expire = async (runId: string) => {
|
||||
await pool.query(
|
||||
"UPDATE runs SET lease_expires_at = NOW() - INTERVAL '1 second' WHERE id = $1",
|
||||
|
|
@ -224,6 +275,10 @@ async function fixture() {
|
|||
dispatcher,
|
||||
enqueueWorker,
|
||||
snapshot,
|
||||
legacySnapshot,
|
||||
historicalRun,
|
||||
report,
|
||||
canonical,
|
||||
expire,
|
||||
history,
|
||||
storage,
|
||||
|
|
@ -246,7 +301,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const original = await f.snapshot(runs[0]!.id);
|
||||
await f.api.updateBacktest(f.definition.id, {
|
||||
initialCapital: 12345,
|
||||
config: { fastPeriod: 4, slowPeriod: 9 },
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 4 },
|
||||
});
|
||||
expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe(
|
||||
runs[0]!.id
|
||||
|
|
@ -282,17 +337,27 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
[f.definition.id, second.id].map(backtestId => f.api.createRun({ backtestId }, submission))
|
||||
);
|
||||
try {
|
||||
// Both parent-row locks are held, neither run exists yet, and both transactions
|
||||
// are inside their INSERT. Releasing shared waiters forces the unique-index race.
|
||||
// Both requests passed their initial receipt lookup and hold distinct parent
|
||||
// locks. One waits inside INSERT; the other waits on the shared strategy
|
||||
// family lock. The stale second receipt lookup must still conflict after
|
||||
// the first transaction commits, rather than returning its unrelated run.
|
||||
await until(
|
||||
async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int AS count FROM pg_locks WHERE locktype = 'advisory' AND classid = 40303 AND objid = $1 AND NOT granted",
|
||||
[barrierKey]
|
||||
"SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
|
||||
[f.schema]
|
||||
)
|
||||
).rows[0].count === 2
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int AS count FROM pg_locks WHERE locktype='advisory' AND classid=40303 AND objid=$1 AND NOT granted",
|
||||
[barrierKey]
|
||||
)
|
||||
).rows[0].count
|
||||
).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
} finally {
|
||||
await barrier.query('SELECT pg_advisory_unlock(40303, $1)', [barrierKey]);
|
||||
|
|
@ -313,7 +378,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
);
|
||||
});
|
||||
|
||||
test('different principals can reuse keys; concurrent distinct and legacy submissions preserve run numbering', async () => {
|
||||
test('different principals can reuse keys; concurrent distinct and unkeyed submissions preserve run numbering', async () => {
|
||||
const f = await fixture();
|
||||
const runs = await Promise.all([
|
||||
f.api.createRun({ backtestId: f.definition.id }, { principal: 'operator', key: 'shared' }),
|
||||
|
|
@ -354,7 +419,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('save_only route honors autoStart; authenticated keyed submissions return202/Location or409', async () => {
|
||||
test('save_only catalog route requires explicit false; authenticated keyed submissions return202/Location or409', async () => {
|
||||
const f = await fixture();
|
||||
const app = new Hono();
|
||||
createHttpSecurity({ disabled: true, environment: 'test' }).mount(app);
|
||||
|
|
@ -387,11 +452,14 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
expect(response.headers.get('Location')).toBe(`/api/v2/runs/${run.id}`);
|
||||
expect((await (await post({ speedMultiplier: null })).json()).id).toBe(run.id);
|
||||
expect((await post({ speedMultiplier: 2 })).status).toBe(409);
|
||||
const legacy = await app.request('/api/v2/backtests', {
|
||||
const saveOnly = await app.request('/api/v2/backtests', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...body, autoStart: undefined }),
|
||||
});
|
||||
expect(await f.api.listRuns((await legacy.json()).id)).toHaveLength(1);
|
||||
expect(saveOnly.status).toBe(400);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM backtests')).rows[0].count).toBe(
|
||||
2
|
||||
);
|
||||
});
|
||||
|
||||
test('cookie renewal and admin bearer replay the same operator submission while service keys are separate', async () => {
|
||||
|
|
@ -442,9 +510,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const f = await fixture(true);
|
||||
const run = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const config = await f.legacySnapshot(run.id);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
|
|
@ -461,51 +529,40 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
.dataset_hash
|
||||
).toBeNull();
|
||||
});
|
||||
test('prepared snapshots survive owner loss and replay through JSONB without provider reads', async () => {
|
||||
test('retained canonical inputs survive owner loss and replay without provider reads', async () => {
|
||||
const f = await fixture();
|
||||
const parameters = {
|
||||
...f.definition.config,
|
||||
dataFrequency: '1d',
|
||||
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
||||
};
|
||||
await f.api.updateBacktest(f.definition.id, { config: parameters });
|
||||
const first = await f.runner.runQueued(
|
||||
(await f.api.createRun({ backtestId: f.definition.id })).id
|
||||
);
|
||||
const baseline = (await f.api.getRunResults(first.runId))!;
|
||||
expect(baseline.config.parameters).toEqual(parameters);
|
||||
const first = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.runner.runQueued(first.id);
|
||||
const baseline = await f.api.getRunResults(first.id);
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const old = await f.repository.start(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.loadDataset(
|
||||
const old = await f.repository.startCanonical(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.loadCanonicalDataset(
|
||||
run.id,
|
||||
old.attemptId,
|
||||
baseline.config.dataset!.hash
|
||||
f.canonical!.dataset.manifest.hash
|
||||
);
|
||||
expect(frozen?.bars).toHaveLength(70);
|
||||
await f.expire(run.id);
|
||||
await expect(f.repository.loadDataset(run.id, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
await expect(f.repository.freezeDataset(run.id, old.attemptId, frozen!)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
const reads = f.history.reads;
|
||||
await expect(
|
||||
f.repository.loadCanonicalDataset(run.id, old.attemptId, frozen.manifest.hash)
|
||||
).rejects.toBeInstanceOf(BacktestLeaseLostError);
|
||||
f.history.unavailable = true;
|
||||
await f.dispatcher.tick();
|
||||
await f.runner.runQueued(run.id);
|
||||
const replay = (await f.api.getRunResults(run.id))!;
|
||||
expect(f.history.reads).toBe(reads);
|
||||
expect(replay.config.dataset).toEqual(baseline.config.dataset);
|
||||
expect(replay.config.parameters).toEqual(parameters);
|
||||
expect(replay.trades).toEqual(baseline.trades);
|
||||
expect(replay.metrics).toEqual(baseline.metrics);
|
||||
const replay = await f.api.getRunResults(run.id);
|
||||
if (!baseline || !replay || !('financial' in baseline) || !('financial' in replay)) {
|
||||
throw new Error('Canonical results required');
|
||||
}
|
||||
expect(f.history.reads).toBe(0);
|
||||
expect(replay.financial.projection.valuation).toEqual(baseline.financial.projection.valuation);
|
||||
expect(replay.financial.projection.fills).toEqual(baseline.financial.projection.fills);
|
||||
expect(replay.analytics).toEqual(baseline.analytics);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('snapshot insertion and the run pointer roll back together; frozen inputs cannot be replaced', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const f = await fixture(true);
|
||||
const run = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const config = await f.legacySnapshot(run.id);
|
||||
const claim = await f.repository.start(config);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
await f.pool
|
||||
|
|
@ -536,9 +593,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('cancellation after snapshot insertion aborts preparation and rolls back the run pointer and payload', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const f = await fixture(true);
|
||||
const run = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const config = await f.legacySnapshot(run.id);
|
||||
const claim = await f.repository.start(config);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
const controller = new AbortController();
|
||||
|
|
@ -549,10 +606,14 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
work(
|
||||
new Proxy(client, {
|
||||
get(target, key) {
|
||||
if (key !== 'query') return Reflect.get(target, key);
|
||||
if (key !== 'query') {
|
||||
return Reflect.get(target, key);
|
||||
}
|
||||
return async (sql: string, params?: unknown[]) => {
|
||||
const result = await target.query(sql, params);
|
||||
if (sql.startsWith('INSERT INTO backtest_datasets')) controller.abort(reason);
|
||||
if (sql.startsWith('INSERT INTO backtest_datasets')) {
|
||||
controller.abort(reason);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
},
|
||||
|
|
@ -574,9 +635,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('restored snapshots are revalidated rather than trusted by their content-addressed key', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const f = await fixture(true);
|
||||
const run = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const config = await f.legacySnapshot(run.id);
|
||||
const claim = await f.repository.start(config);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
// Model corrupt historical storage at initial insertion; retained evidence cannot be edited.
|
||||
|
|
@ -595,14 +656,15 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
await expect(f.runner.runQueued(run.id)).rejects.toThrow('hash/content');
|
||||
expect((await f.runner.runQueued(run.id)).status).toBe('failed');
|
||||
expect((await f.api.getRun(run.id))?.error).toContain('Legacy backtest execution is retired');
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('failed');
|
||||
expect(await f.api.getRunResults(run.id)).toBeNull();
|
||||
expect(f.history.reads).toBe(reads);
|
||||
});
|
||||
|
||||
test('a missing retained dataset fails a historical request without provider fallback', async () => {
|
||||
const f = await fixture();
|
||||
const f = await fixture(true);
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(
|
||||
{ ...f.definitionInput, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
|
||||
|
|
@ -615,56 +677,38 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
);
|
||||
await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]);
|
||||
f.history.unavailable = true;
|
||||
await expect(f.runner.runQueued(runId)).rejects.toThrow('Frozen dataset not found');
|
||||
expect((await f.runner.runQueued(runId)).status).toBe('failed');
|
||||
expect((await f.api.getRun(runId))?.error).toContain('Legacy backtest execution is retired');
|
||||
expect(f.history.reads).toBe(0);
|
||||
expect((await f.api.getRun(runId))?.status).toBe('failed');
|
||||
expect(await f.api.getRunResults(runId)).toBeNull();
|
||||
});
|
||||
|
||||
test('an explicit dataset replay rejects a different listing or date range', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.runner.runQueued(run.id);
|
||||
const result = (await f.api.getRunResults(run.id))!;
|
||||
await expect(
|
||||
f.runner.runBacktest({
|
||||
...(await f.snapshot(run.id)),
|
||||
runId: undefined,
|
||||
endDate: '2024-03-16T00:00:00.000Z',
|
||||
datasetHash: result.config.dataset!.hash,
|
||||
})
|
||||
).rejects.toThrow('does not match');
|
||||
});
|
||||
test('API acceptance uses the runner contract before writing a run or dispatch intent', async () => {
|
||||
test('canonical admission rejects template ranges inconsistent with its retained dataset', async () => {
|
||||
const f = await fixture();
|
||||
await expect(
|
||||
f.api.updateBacktest(f.definition.id, { config: { commission: -1 } })
|
||||
).rejects.toThrow('commission');
|
||||
expect((await f.api.getBacktest(f.definition.id))?.config).toEqual(f.definition.config);
|
||||
// Model malformed historical configuration that bypassed today's API validator.
|
||||
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
|
||||
f.api.updateBacktest(f.definition.id, { endDate: '2025-01-01T00:00:00.000Z' })
|
||||
).rejects.toThrow('trade bounds');
|
||||
await f.pool.query('UPDATE backtests SET end_date=$2 WHERE id=$1', [
|
||||
f.definition.id,
|
||||
JSON.stringify({ ...f.definition.config, slippage: 0.2 }),
|
||||
'2025-01-01T00:00:00.000Z',
|
||||
]);
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow('slippage');
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow();
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
||||
});
|
||||
test('canonical admission rejects malformed policy and legacy pacing before run/outbox writes', async () => {
|
||||
const f = await fixture();
|
||||
await expect(
|
||||
f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 })
|
||||
).rejects.toThrow('maximum speed');
|
||||
await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [
|
||||
f.definition.id,
|
||||
{ ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '-1' } },
|
||||
]);
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow();
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0);
|
||||
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
|
||||
f.definition.id,
|
||||
JSON.stringify(f.definition.config),
|
||||
]);
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 });
|
||||
const snapshot = (
|
||||
await f.pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
|
||||
).rows[0].request_snapshot;
|
||||
const expected = backtestRequestFromDefinition(f.definitionInput, {
|
||||
runId: run.id,
|
||||
backtestId: f.definition.id,
|
||||
speedMultiplier: 7,
|
||||
});
|
||||
expect(parseBacktestRequest(snapshot)).toEqual(expected);
|
||||
expect(snapshot.speed).toBe('5x');
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => {
|
||||
|
|
@ -691,8 +735,8 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [run.id])).rows
|
||||
).toHaveLength(1);
|
||||
await f.api.updateBacktest(f.definition.id, {
|
||||
config: { fastPeriod: 999 },
|
||||
symbols: ['MUTATED.TEST'],
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 4 },
|
||||
name: 'Mutated after admission',
|
||||
});
|
||||
// A fresh dispatcher models an API restart after SQL commit but before the first publish.
|
||||
const restarted = new BacktestDispatcher(f.postgres, f.queue, logger);
|
||||
|
|
@ -701,8 +745,12 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
f.enqueueWorker();
|
||||
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
|
||||
const result = await f.api.getRunResults(run.id);
|
||||
expect(result?.config.symbols).toEqual(['FIXTURE.TEST']);
|
||||
expect(result?.config.parameters.fastPeriod).toBe(3);
|
||||
expect(result).toHaveProperty('kind', 'canonical-result/v1');
|
||||
if (!result || !('request' in result)) {
|
||||
throw new Error('Canonical result required');
|
||||
}
|
||||
expect(result.request.strategy.selection.instrumentId).toBe(f.definition.symbols[0]!);
|
||||
expect(result.request.strategy.selection.parameters).toMatchObject({ fastPeriod: 2 });
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
|
||||
});
|
||||
|
||||
|
|
@ -711,8 +759,8 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const claims = await Promise.allSettled([
|
||||
f.repository.start(config),
|
||||
f.repository.start(config),
|
||||
f.repository.startCanonical(config),
|
||||
f.repository.startCanonical(config),
|
||||
]);
|
||||
expect(claims.filter(result => result.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(claims.filter(result => result.status === 'rejected')).toHaveLength(1);
|
||||
|
|
@ -736,14 +784,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
|
||||
test('expired owners cannot heartbeat, write progress/control/failure/cancellation, or commit a stale result', async () => {
|
||||
const f = await fixture();
|
||||
const baseline = await f.runner.runBacktest({
|
||||
...(await f.snapshot((await f.api.createRun({ backtestId: f.definition.id })).id)),
|
||||
});
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const old = await f.repository.start(await f.snapshot(run.id));
|
||||
const request = await f.snapshot(run.id);
|
||||
const old = await f.repository.startCanonical(request);
|
||||
const result = await f.report(request);
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
const replacement = await f.repository.start(await f.snapshot(run.id));
|
||||
const replacement = await f.repository.startCanonical(await f.snapshot(run.id));
|
||||
await expect(f.repository.heartbeat(run.id, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
|
|
@ -757,13 +804,12 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
BacktestLeaseLostError
|
||||
);
|
||||
await f.repository.fail(run.id, 'stale failure', old.attemptId);
|
||||
const result = { ...baseline, runId: run.id };
|
||||
await expect(f.repository.complete(result, old.attemptId)).rejects.toBeInstanceOf(
|
||||
await expect(f.repository.completeCanonical(result, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('running');
|
||||
await f.repository.loadDataset(run.id, replacement.attemptId, baseline.config.dataset!.hash);
|
||||
await f.repository.complete(result, replacement.attemptId);
|
||||
await f.repository.loadCanonicalDataset(run.id, replacement.attemptId, request.datasetHash);
|
||||
await f.repository.completeCanonical(result, replacement.attemptId);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows
|
||||
).toHaveLength(1);
|
||||
|
|
@ -773,7 +819,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const shortLease = new PostgresBacktestRunRepository(f.postgres, 300);
|
||||
const claim = await shortLease.start(await f.snapshot(run.id));
|
||||
const claim = await shortLease.startCanonical(await f.snapshot(run.id));
|
||||
await sleep(200);
|
||||
await shortLease.heartbeat(run.id, claim.attemptId);
|
||||
await sleep(150);
|
||||
|
|
@ -792,7 +838,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const shortLease = new PostgresBacktestRunRepository(f.postgres, 300);
|
||||
const claim = await shortLease.start(await f.snapshot(run.id));
|
||||
const claim = await shortLease.startCanonical(await f.snapshot(run.id));
|
||||
const lock = await f.pool.connect();
|
||||
let renewal: Promise<unknown> | undefined;
|
||||
try {
|
||||
|
|
@ -813,20 +859,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
test('cancellation wins against late completion and expires an abandoned cancelled owner truthfully', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const claim = await f.repository.startCanonical(await f.snapshot(run.id));
|
||||
const result = await f.report(await f.snapshot(run.id));
|
||||
await f.api.cancelRun(run.id);
|
||||
expect((await f.repository.heartbeat(run.id, claim.attemptId)).cancelRequested).toBe(true);
|
||||
await expect(
|
||||
f.repository.complete(
|
||||
{
|
||||
runId: run.id,
|
||||
backtestId: f.definition.id,
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
} as never,
|
||||
claim.attemptId
|
||||
)
|
||||
).rejects.toBeInstanceOf(BacktestCancelledError);
|
||||
await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestCancelledError
|
||||
);
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('cancelled');
|
||||
|
|
@ -837,7 +876,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
await f.repository.start(await f.snapshot(run.id));
|
||||
await f.repository.startCanonical(await f.snapshot(run.id));
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe(attempt === 3 ? 'failed' : 'pending');
|
||||
|
|
@ -874,7 +913,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
child.once('error', reject);
|
||||
child.once('exit', code => {
|
||||
clearTimeout(timeout);
|
||||
if (code) reject(new Error(`Crash owner exited: ${code}`));
|
||||
if (code) {
|
||||
reject(new Error(`Crash owner exited: ${code}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('running');
|
||||
|
|
@ -934,7 +975,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('invalid persisted snapshots become failed instead of remaining stranded pending', async () => {
|
||||
const f = await fixture();
|
||||
const f = await fixture(true);
|
||||
const run = { id: randomUUID() };
|
||||
// A legacy malformed snapshot is inserted as found, not fabricated by editing retained evidence.
|
||||
await f.pool.query(
|
||||
|
|
@ -948,15 +989,15 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
|
||||
test('migration replay preserves leased owners, backfills legacy pending snapshots, and fails ownerless legacy runs', async () => {
|
||||
const f = await fixture();
|
||||
const f = await fixture(true);
|
||||
const pending = { id: randomUUID() };
|
||||
await f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES ($1,$2,1)', [
|
||||
pending.id,
|
||||
f.definition.id,
|
||||
]);
|
||||
const active = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const oldActive = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(active.id));
|
||||
const active = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const oldActive = await f.historicalRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.legacySnapshot(active.id));
|
||||
await f.pool.query("UPDATE runs SET status = 'running' WHERE id = $1", [oldActive.id]);
|
||||
const migration = readFileSync(
|
||||
new URL('../../database/postgres/init/10-durable-backtest-dispatch.sql', import.meta.url),
|
||||
|
|
@ -964,13 +1005,16 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
);
|
||||
await f.pool.query(migration);
|
||||
await f.pool.query(migration);
|
||||
expect((await f.snapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z');
|
||||
expect((await f.legacySnapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z');
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [pending.id])).rows
|
||||
).toHaveLength(1);
|
||||
expect((await f.api.getRun(oldActive.id))?.status).toBe('failed');
|
||||
expect((await f.repository.heartbeat(active.id, claim.attemptId)).cancelRequested).toBe(false);
|
||||
await f.runner.runQueued(pending.id);
|
||||
expect((await f.api.getRun(pending.id))?.status).toBe('completed');
|
||||
expect((await f.api.getRun(pending.id))?.status).toBe('failed');
|
||||
expect((await f.api.getRun(pending.id))?.error).toContain(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue