feat(backtests): separate saving from retry-safe run submission
This commit is contained in:
parent
5eb0985057
commit
9b9403e36b
18 changed files with 1200 additions and 226 deletions
|
|
@ -3,7 +3,9 @@ import { randomUUID } from 'node:crypto';
|
|||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
|
|
@ -21,7 +23,10 @@ import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-d
|
|||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
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 {
|
||||
BacktestServiceV2,
|
||||
RunSubmissionConflictError,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
|
|
@ -74,6 +79,7 @@ async function fixture() {
|
|||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
@ -204,6 +210,216 @@ async function fixture() {
|
|||
}
|
||||
|
||||
describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => {
|
||||
test('idempotent_submission_postgres_race: one snapshot/outbox, canonical null speed and stable original intent after edits', async () => {
|
||||
const f = await fixture();
|
||||
const submission = { principal: 'operator' as const, key: 'same-intent' };
|
||||
const runs = await Promise.all(
|
||||
Array.from({ length: 8 }, (_, i) =>
|
||||
f.api.createRun(
|
||||
{ backtestId: f.definition.id, ...(i % 2 ? { speedMultiplier: null } : {}) },
|
||||
submission
|
||||
)
|
||||
)
|
||||
);
|
||||
expect(new Set(runs.map(run => run.id)).size).toBe(1);
|
||||
const original = await f.snapshot(runs[0]!.id);
|
||||
await f.api.updateBacktest(f.definition.id, {
|
||||
initialCapital: 12345,
|
||||
config: { fastPeriod: 4, slowPeriod: 9 },
|
||||
});
|
||||
expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe(
|
||||
runs[0]!.id
|
||||
);
|
||||
expect(await f.snapshot(runs[0]!.id)).toEqual(original);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
await expect(
|
||||
f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 2 }, submission)
|
||||
).rejects.toBeInstanceOf(RunSubmissionConflictError);
|
||||
});
|
||||
|
||||
test('submission_key_conflict: different definitions racing for one principal/key cannot both commit', async () => {
|
||||
const f = await fixture();
|
||||
const second = await f.api.createBacktest(
|
||||
{
|
||||
...f.definition,
|
||||
startDate: f.definition.startDate.toISOString(),
|
||||
endDate: f.definition.endDate.toISOString(),
|
||||
name: 'Second',
|
||||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
const barrierKey = parseInt(randomUUID().slice(0, 7), 16);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION delay_submission() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
PERFORM pg_advisory_xact_lock_shared(40303, ${barrierKey}); RETURN NEW; END $$;
|
||||
CREATE TRIGGER delay_submission BEFORE INSERT ON runs FOR EACH ROW EXECUTE FUNCTION delay_submission()`);
|
||||
const submission = { principal: 'operator' as const, key: 'cross-definition' };
|
||||
const barrier = await f.pool.connect();
|
||||
await barrier.query('SELECT pg_advisory_lock(40303, $1)', [barrierKey]);
|
||||
const submissions = Promise.allSettled(
|
||||
[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.
|
||||
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]
|
||||
)
|
||||
).rows[0].count === 2
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
} finally {
|
||||
await barrier.query('SELECT pg_advisory_unlock(40303, $1)', [barrierKey]);
|
||||
barrier.release();
|
||||
}
|
||||
const outcomes = await submissions;
|
||||
expect(outcomes.filter(outcome => outcome.status === 'fulfilled')).toHaveLength(1);
|
||||
const rejection = outcomes.find(outcome => outcome.status === 'rejected');
|
||||
expect(rejection?.status === 'rejected' && rejection.reason).toBeInstanceOf(
|
||||
RunSubmissionConflictError
|
||||
);
|
||||
const committed = (await f.pool.query('SELECT * FROM runs')).rows;
|
||||
expect(committed).toHaveLength(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
const otherId = committed[0].backtest_id === f.definition.id ? second.id : f.definition.id;
|
||||
await expect(f.api.createRun({ backtestId: otherId }, submission)).rejects.toBeInstanceOf(
|
||||
RunSubmissionConflictError
|
||||
);
|
||||
});
|
||||
|
||||
test('different principals can reuse keys; concurrent distinct and legacy 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' }),
|
||||
f.api.createRun({ backtestId: f.definition.id }, { principal: 'service', key: 'shared' }),
|
||||
...Array.from({ length: 4 }, (_, i) =>
|
||||
f.api.createRun(
|
||||
{ backtestId: f.definition.id },
|
||||
{ principal: 'operator', key: `intent-${i}` }
|
||||
)
|
||||
),
|
||||
f.api.createRun({ backtestId: f.definition.id }),
|
||||
f.api.createRun({ backtestId: f.definition.id }),
|
||||
]);
|
||||
expect(new Set(runs.map(run => run.id)).size).toBe(8);
|
||||
expect(runs.map(run => run.runNumber).sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM runs WHERE submission_key IS NULL')).rows
|
||||
).toHaveLength(2);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(8);
|
||||
});
|
||||
|
||||
test('outbox failure rolls back the submission claim and retry creates exactly one run', async () => {
|
||||
const f = await fixture();
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION reject_submission_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
RAISE EXCEPTION 'injected submission outbox failure'; END $$;
|
||||
CREATE TRIGGER reject_submission_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_submission_outbox()`);
|
||||
const submission = { principal: 'operator' as const, key: 'retry-after-rollback' };
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id }, submission)).rejects.toThrow(
|
||||
'injected submission'
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
await f.pool.query('DROP TRIGGER reject_submission_outbox ON backtest_dispatch');
|
||||
const created = await f.api.createRun({ backtestId: f.definition.id }, submission);
|
||||
expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe(
|
||||
created.id
|
||||
);
|
||||
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 () => {
|
||||
const f = await fixture();
|
||||
const app = new Hono();
|
||||
createHttpSecurity({ disabled: true, environment: 'test' }).mount(app);
|
||||
app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger }));
|
||||
const body = { ...f.definition, autoStart: false };
|
||||
expect(
|
||||
(
|
||||
await app.request('/api/v2/backtests', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...body, autoStart: 'false' }),
|
||||
})
|
||||
).status
|
||||
).toBe(400);
|
||||
const saved = await app.request('/api/v2/backtests', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
expect(saved.status).toBe(201);
|
||||
const definition = await saved.json();
|
||||
expect(await f.api.listRuns(definition.id)).toHaveLength(0);
|
||||
const post = (payload: object) =>
|
||||
app.request(`/api/v2/backtests/${definition.id}/runs`, {
|
||||
method: 'POST',
|
||||
headers: { 'Idempotency-Key': 'route-retry' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const response = await post({});
|
||||
expect(response.status).toBe(202);
|
||||
const run = await response.json();
|
||||
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', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...body, autoStart: undefined }),
|
||||
});
|
||||
expect(await f.api.listRuns((await legacy.json()).id)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('cookie renewal and admin bearer replay the same operator submission while service keys are separate', async () => {
|
||||
const f = await fixture();
|
||||
const adminToken = 'submission-fixture-admin-not-a-secret-123456';
|
||||
const serviceToken = 'submission-fixture-service-not-a-secret-123456';
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken,
|
||||
serviceToken,
|
||||
browserSessions: true,
|
||||
origins: ['http://ui.test'],
|
||||
}).mount(app);
|
||||
app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger }));
|
||||
const submit = async (headers: Record<string, string>) => {
|
||||
const response = await app.request(`/api/v2/backtests/${f.definition.id}/runs`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Idempotency-Key': 'authenticated-intent',
|
||||
'X-Principal': 'spoofed',
|
||||
...headers,
|
||||
},
|
||||
body: '{}',
|
||||
});
|
||||
expect(response.status).toBe(202);
|
||||
return (await response.json()).id as string;
|
||||
};
|
||||
const original = await submit({ Authorization: `Bearer ${adminToken}` });
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const login = await app.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Origin: 'http://ui.test' },
|
||||
body: JSON.stringify({ token: adminToken }),
|
||||
});
|
||||
expect(login.status).toBe(200);
|
||||
expect(
|
||||
await submit({
|
||||
Cookie: login.headers.get('Set-Cookie')!.split(';')[0]!,
|
||||
Origin: 'http://ui.test',
|
||||
})
|
||||
).toBe(original);
|
||||
}
|
||||
expect(await submit({ Authorization: `Bearer ${serviceToken}` })).not.toBe(original);
|
||||
expect(
|
||||
(await f.pool.query('SELECT submission_principal FROM runs ORDER BY run_number')).rows
|
||||
).toEqual([{ submission_principal: 'operator' }, { submission_principal: 'service' }]);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(2);
|
||||
});
|
||||
|
||||
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 });
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ const migrations = [
|
|||
'11-simulation-execution-ledger.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
@ -130,6 +131,40 @@ async function fixture() {
|
|||
}
|
||||
|
||||
describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
||||
test('submission migration preserves legacy NULL-key runs and enforces complete key records', async () => {
|
||||
const f = await fixture();
|
||||
for (const filename of migrations.filter(name => name !== '14-backtest-submission.sql')) {
|
||||
await f.pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const backtestId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
await f.pool.query(
|
||||
`INSERT INTO backtests (id,name,strategy,symbols,start_date,end_date,initial_capital)
|
||||
VALUES ($1,'Legacy','sma-crossover','["A.US"]','2024-01-01','2024-02-01',10000)`,
|
||||
[backtestId]
|
||||
);
|
||||
await f.pool.query(
|
||||
"INSERT INTO runs (id,backtest_id,run_number,status,request_snapshot) VALUES ($1,$2,1,'completed','{\"legacy\":true}')",
|
||||
[runId, backtestId]
|
||||
);
|
||||
await f.startup().run();
|
||||
const row = (await f.pool.query('SELECT * FROM runs WHERE id = $1', [runId])).rows[0];
|
||||
expect(row.request_snapshot).toEqual({ legacy: true });
|
||||
expect(row.status).toBe('completed');
|
||||
expect([row.submission_principal, row.submission_key, row.submission_hash]).toEqual([
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
]);
|
||||
await expect(
|
||||
f.pool.query("UPDATE runs SET submission_key = 'incomplete' WHERE id = $1", [runId])
|
||||
).rejects.toThrow('runs_submission_complete');
|
||||
await f.startup().run();
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('two_concurrent_startups_same_client_lock and precheck_inside_lock', async () => {
|
||||
const f = await fixture();
|
||||
const firstAtPrecheck = gate();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue