feat(research): run durable backtests in a bounded worker pool

This commit is contained in:
Boki 2026-10-24 17:41:00 -04:00
parent bbf0dd4453
commit 26b97265c6
15 changed files with 1730 additions and 129 deletions

View file

@ -139,7 +139,7 @@ describe('canonical production workflow and legacy retirement', () => {
});
test('observer errors cannot relabel committed success and SSE detaches on completion', async () => {
const f = setup();
const response = await routes(f).request('/api/backtest/stream');
const response = await routes(f).request(`/api/backtest/stream?runId=${f.request.runId}`);
const reader = response.body!.getReader();
expect((await f.runner.runQueued(f.request.runId)).status).toBe('completed');
expect(new TextDecoder().decode((await reader.read()).value)).toContain('"event":"complete"');

View file

@ -0,0 +1,396 @@
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { createBacktestRoutes } from '../../apps/stock/orchestrator/src/api/rest/backtest';
import {
BacktestCancelledError,
type BacktestExecutionEngine,
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { ResearchBacktestPool } from '../../apps/stock/orchestrator/src/backtest/ResearchBacktestPool';
import { canonicalRunnerFixture, deferred } from '../fixtures/canonical-runner';
import { logger } from '../fixtures/execution';
const cleanup: (() => Promise<unknown>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
function fixture(count: 1 | 2 | 4 = 2) {
const slots = Array.from({ length: count }, () => {
const f = canonicalRunnerFixture();
const entered = deferred<void>(),
release = deferred<void>();
const execute = f.engine.runCanonical;
f.engine.runCanonical = async (...args) => {
entered.resolve();
await release.promise;
return execute(...args);
};
f.engine.stopBacktest = async () => release.reject(new BacktestCancelledError());
return { ...f, entered, release };
});
const pool = new ResearchBacktestPool({ runners: slots.map(f => f.runner), logger });
cleanup.push(() => pool.shutdown().catch(() => {}));
const app = new Hono().route(
'/backtest',
createBacktestRoutes({ logger, custom: { BacktestRunner: pool } })
);
return { slots, pool, app };
}
async function post(app: Hono, path: string, body: unknown = {}) {
return app.request(`/backtest/${path}`, { method: 'POST', body: JSON.stringify(body) });
}
async function started(f: ReturnType<typeof fixture>) {
const work = f.slots.map(slot =>
f.pool.runQueued(slot.request.runId).catch(error => error as Error)
);
await Promise.all(f.slots.map(slot => slot.entered.promise));
return work;
}
describe('bounded independent research runners', () => {
test.each([0, 3, 5, 8])('rejects %s slots', count => {
const runner = canonicalRunnerFixture().runner;
expect(
() =>
new ResearchBacktestPool({ runners: Array.from({ length: count }, () => runner), logger })
).toThrow('1, 2, or 4');
});
test('rejects duplicate mutable runner instances', () => {
const runner = canonicalRunnerFixture().runner;
expect(() => new ResearchBacktestPool({ runners: [runner, runner], logger })).toThrow(
'distinct'
);
});
test.each([1, 2, 4] as const)(
'reserves %s slots before the first await; overflow never loads or claims',
async count => {
const f = fixture(count);
const loads = f.slots.map(() => deferred<void>());
f.slots.forEach((slot, i) => {
const load = slot.repo.load;
slot.repo.load = async id => {
await loads[i]!.promise;
return load(id);
};
});
const work = f.slots.map(slot => f.pool.runQueued(slot.request.runId));
expect(f.slots.every(slot => slot.events.length === 0)).toBe(true);
await expect(f.pool.runQueued(randomUUID())).rejects.toThrow('occupied');
expect(f.slots.every(slot => slot.events.length === 0)).toBe(true);
loads.forEach(gate => gate.resolve());
await Promise.all(f.slots.map(slot => slot.entered.promise));
// Deliberately finish in the reverse submission order.
for (let i = count - 1; i >= 0; i--) {
f.slots[i]!.release.resolve();
expect(await work[i]).toEqual({ runId: f.slots[i]!.request.runId, status: 'completed' });
}
expect(f.slots.map(slot => slot.events.filter(event => event === 'claim').length)).toEqual(
Array(count).fill(1)
);
expect(f.pool.getStatus().isRunning).toBe(false);
}
);
test('duplicate deliveries, including UUID casing, join the original exact promise', async () => {
const f = fixture(1),
slot = f.slots[0]!;
const first = f.pool.runQueued(slot.request.runId);
expect(f.pool.runQueued(slot.request.runId.toUpperCase())).toBe(first);
await slot.entered.promise;
expect(f.pool.runQueued(slot.request.runId)).toBe(first);
slot.release.resolve();
await first;
expect(slot.events.filter(event => event === 'claim')).toHaveLength(1);
// Terminal redelivery is still read/acknowledged by the durable runner.
expect(await f.pool.runQueued(slot.request.runId)).toEqual({
runId: slot.request.runId,
status: 'completed',
});
expect(slot.events.filter(event => event === 'claim')).toHaveLength(1);
});
test('a reservation does not turn an unclaimed pending row into a local cancellation', async () => {
const f = fixture(1),
slot = f.slots[0]!,
gate = deferred<void>();
const load = slot.repo.load;
slot.repo.load = async id => {
await gate.promise;
return load(id);
};
const work = f.pool.runQueued(slot.request.runId);
await expect(f.pool.stopBacktest(slot.request.runId)).rejects.toThrow('No matching active');
expect(slot.events).toEqual([]);
gate.resolve();
await slot.entered.promise;
slot.release.resolve();
await work;
});
test('reused slot status never exposes the prior run while the new reservation loads', async () => {
const f = fixture(1),
slot = f.slots[0]!;
const previous = f.pool.runQueued(slot.request.runId);
await slot.entered.promise;
slot.release.resolve();
await previous;
slot.engine.getStatus = () => ({
isRunning: false,
isPaused: true,
progress: 100,
currentTime: 123456,
});
const nextId = randomUUID(),
gate = deferred<void>();
const nextRequest = structuredClone(slot.request);
nextRequest.runId = nextId;
nextRequest.policy.matching.risk.ledger.sessionId = nextId;
nextRequest.policy.matching.risk.ledger.accountId = `research:${nextId}`;
slot.repo.load = async () => {
await gate.promise;
return { status: 'pending', config: nextRequest };
};
const next = f.pool.runQueued(nextId).catch(error => error as Error);
expect(f.pool.getStatus(nextId)).toEqual({
isRunning: false,
isPaused: false,
progress: 0,
currentTime: 0,
runId: nextId,
});
const closed = f.pool.shutdown();
gate.resolve();
expect(String(await next)).toContain('shutting down');
await expect(closed).resolves.toBeUndefined();
});
test('targeted cancellation leaves the other run active and commits only its own outcome', async () => {
const f = fixture(),
work = await started(f),
[a, b] = f.slots;
await f.pool.stopBacktest(a!.request.runId);
expect(await work[0]).toBeInstanceOf(BacktestCancelledError);
expect(a!.events).toContain('cancel');
expect(b!.events).not.toContain('cancel');
expect(f.pool.getStatus().runId).toBe(b!.request.runId);
b!.release.resolve();
expect(await work[1]).toEqual({ runId: b!.request.runId, status: 'completed' });
});
test('failure publishes the captured ID once, releases just that slot, and preserves the other run', async () => {
const f = fixture(),
errors: unknown[] = [];
f.pool.on('error', event => errors.push(event));
const work = await started(f),
[a, b] = f.slots;
const error = new Error('isolated worker failure');
a!.release.reject(error);
expect(await work[0]).toBe(error);
expect(errors).toEqual([{ runId: a!.request.runId, error }]);
expect(b!.events).not.toContain('fail');
expect(f.pool.getStatus().runId).toBe(b!.request.runId);
b!.release.resolve();
await work[1];
});
test('load failure is routed without leaving a reservation or listener behind', async () => {
const f = fixture(1),
slot = f.slots[0]!,
errors: unknown[] = [];
slot.repo.load = async () => {
throw new Error('unavailable database');
};
f.pool.on('error', event => errors.push(event));
await expect(f.pool.runQueued(slot.request.runId)).rejects.toThrow('unavailable database');
expect(errors).toHaveLength(1);
expect(errors[0]).toHaveProperty('runId', slot.request.runId);
expect(f.pool.getStatus().isRunning).toBe(false);
for (const event of ['progress', 'complete', 'cancelled']) {
expect(slot.runner.listenerCount(event)).toBe(0);
}
});
test('observer failure cannot change committed success', async () => {
const f = fixture(1),
slot = f.slots[0]!;
f.pool.on('complete', () => {
throw new Error('observer');
});
const work = await started(f);
slot.release.resolve();
expect(await work[0]).toEqual({ runId: slot.request.runId, status: 'completed' });
expect(slot.events).not.toContain('fail');
});
test('shutdown closes admission synchronously, drains all slots and is idempotent', async () => {
const f = fixture(),
work = await started(f);
const shutdown = f.pool.shutdown();
expect(f.pool.shutdown()).toBe(shutdown);
await expect(f.pool.runQueued(randomUUID())).rejects.toThrow('shutting down');
await shutdown;
for (const result of await Promise.all(work)) {
expect(result).toBeInstanceOf(BacktestCancelledError);
}
expect(f.slots.every(slot => slot.events.includes('cancel'))).toBe(true);
});
test('shutdown waits for a pending load and never claims after closure', async () => {
const f = fixture(1),
slot = f.slots[0]!,
gate = deferred<void>();
const load = slot.repo.load;
slot.repo.load = async id => {
await gate.promise;
return load(id);
};
const work = f.pool.runQueued(slot.request.runId).catch(error => error as Error);
const shutdown = f.pool.shutdown();
gate.resolve();
expect(String(await work)).toContain('shutting down');
await expect(shutdown).resolves.toBeUndefined();
expect(slot.events).not.toContain('claim');
});
test('one failing shutdown cannot skip any other runner shutdown', async () => {
const f = fixture(),
closed: number[] = [];
f.slots.forEach((slot, index) => {
slot.runner.shutdown = async () => {
closed.push(index);
if (index === 0) {
throw new Error('close failed');
}
};
});
await expect(f.pool.shutdown()).rejects.toThrow('drain');
expect(closed).toEqual([0, 1]);
});
});
describe('run-scoped controls and event streams', () => {
test('unknown explicit ID never reads or controls another run; empty status stays idle', async () => {
const f = fixture(1);
expect((await f.app.request('/backtest/progress')).status).toBe(200);
expect((await f.app.request(`/backtest/progress?runId=${randomUUID()}`)).status).toBe(409);
const work = await started(f);
expect((await f.app.request(`/backtest/progress?runId=${randomUUID()}`)).status).toBe(409);
expect((await post(f.app, 'stop', { runId: randomUUID() })).status).toBe(409);
expect((await post(f.app, 'stop')).status).toBe(200);
await work[0];
});
test('multiple active runs require a run ID on all legacy controls/progress/stream', async () => {
const f = fixture(),
work = await started(f);
for (const action of ['stop', 'pause', 'resume', 'speed']) {
expect((await post(f.app, action)).status).toBe(409);
}
for (const action of ['progress', 'stream']) {
expect((await f.app.request(`/backtest/${action}`)).status).toBe(409);
}
expect(
(await f.app.request(`/backtest/progress?runId=${f.slots[1]!.request.runId}`)).status
).toBe(200);
f.slots.forEach(slot => slot.release.resolve());
await Promise.all(work);
});
test('malformed explicit IDs and JSON fail closed, never become an omitted target', async () => {
const f = fixture(1),
work = await started(f);
for (const action of ['stop', 'pause', 'resume', 'speed']) {
expect((await post(f.app, action, { runId: 'bad' })).status).toBe(400);
expect(
(await f.app.request(`/backtest/${action}`, { method: 'POST', body: '{' })).status
).toBe(400);
}
expect((await f.app.request('/backtest/progress?runId=bad')).status).toBe(400);
expect((await f.app.request('/backtest/stream?runId=bad')).status).toBe(400);
f.slots[0]!.release.resolve();
await work[0];
});
test('exactly one active run retains no-ID pause/resume/speed controls', async () => {
const f = fixture(1),
work = await started(f),
controls: unknown[] = [],
slot = f.slots[0]!;
slot.engine.pauseBacktest = async () => {
controls.push('pause');
};
slot.engine.resumeBacktest = async () => {
controls.push('resume');
};
(slot.engine as BacktestExecutionEngine).setSpeedMultiplier = speed => {
controls.push(speed);
};
for (const action of ['pause', 'resume']) {
expect((await post(f.app, action)).status).toBe(200);
}
expect((await post(f.app, 'speed', { speed: null })).status).toBe(200);
expect(controls).toEqual(['pause', 'resume', null]);
slot.release.resolve();
await work[0];
});
test('SSE captures one ID, ignores unrelated completion, and detaches on its own completion', async () => {
const f = fixture(),
[a, b] = f.slots;
// An explicit ID can subscribe before admission is claimed; no global idle subscription.
expect((await f.app.request('/backtest/stream')).status).toBe(409);
const response = await f.app.request(`/backtest/stream?runId=${b!.request.runId}`);
const reader = response.body!.getReader(),
work = await started(f);
a!.release.resolve();
await work[0];
b!.engine.emit('progress', { progress: 25 });
const progress = new TextDecoder().decode((await reader.read()).value);
expect(progress).toContain(b!.request.runId);
expect(progress).toContain('25');
expect(progress).not.toContain(a!.request.runId);
b!.release.resolve();
await work[1];
expect(new TextDecoder().decode((await reader.read()).value)).toContain('"event":"complete"');
expect((await reader.read()).done).toBe(true);
for (const event of ['progress', 'complete', 'error', 'cancelled']) {
expect(f.pool.listenerCount(event)).toBe(0);
}
});
test('no-ID stream freezes sole active identity even after another slot starts', async () => {
const f = fixture(),
[a, b] = f.slots;
const first = f.pool.runQueued(a!.request.runId);
await a!.entered.promise;
const response = await f.app.request('/backtest/stream'),
reader = response.body!.getReader();
const second = f.pool.runQueued(b!.request.runId);
await b!.entered.promise;
b!.release.resolve();
await second;
a!.release.resolve();
await first;
const body = new TextDecoder().decode((await reader.read()).value);
expect(body).toContain(a!.request.runId);
expect(body).not.toContain(b!.request.runId);
expect((await reader.read()).done).toBe(true);
});
test('SSE error and cancellation belong to their captured run; abort removes all listeners', async () => {
const f = fixture(),
[a, b] = f.slots;
const reader = (
await f.app.request(`/backtest/stream?runId=${a!.request.runId}`)
).body!.getReader();
const cancelled = (
await f.app.request(`/backtest/stream?runId=${b!.request.runId}`)
).body!.getReader();
const work = await started(f);
a!.release.reject(new Error('isolated failure'));
await work[0];
const message = new TextDecoder().decode((await reader.read()).value);
expect(message).toContain('isolated failure');
expect(message).toContain(a!.request.runId);
expect((await reader.read()).done).toBe(true);
await f.pool.stopBacktest(b!.request.runId);
await work[1];
expect(new TextDecoder().decode((await cancelled.read()).value)).toContain(
'"event":"cancelled"'
);
expect((await cancelled.read()).done).toBe(true);
const abort = new AbortController();
const response = await f.app.request(`/backtest/stream?runId=${randomUUID()}`, {
signal: abort.signal,
});
abort.abort();
expect((await response.body!.getReader().read()).done).toBe(true);
expect(f.pool.listenerCount('progress')).toBe(0);
});
});

View file

@ -2,7 +2,8 @@ import { asFunction, asValue, createContainer as createDiContainer } from 'awili
import { afterEach, describe, expect, test } from 'bun:test';
import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { stockAppSchema } from '../../apps/stock/config/src/schemas/stock-app.schema';
import { ResearchBacktestPool } from '../../apps/stock/orchestrator/src/backtest/ResearchBacktestPool';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes';
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
@ -15,7 +16,10 @@ afterEach(async () => {
await close();
}
});
async function compose(options: Parameters<typeof registerOrchestratorServices>[1] = {}) {
async function compose(
options: Parameters<typeof registerOrchestratorServices>[1] = {},
queues?: unknown[]
) {
const container = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
@ -28,6 +32,11 @@ async function compose(options: Parameters<typeof registerOrchestratorServices>[
})
.build();
const services: OrchestratorServices = { logger };
if (queues) {
Object.defineProperty(services, 'queueManager', {
value: { getQueue: (name: string, options: unknown) => queues.push({ name, options }) },
});
}
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container, options);
cleanup.push(async () => {
@ -88,8 +97,9 @@ describe('canonical research-only default composition', () => {
'default and explicit research compose one canonical engine without any account/feed/mode gateway',
async options => {
const { services, container } = await compose(options);
expect(services.custom!.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
expect(services.custom!.BacktestRunner).toBeInstanceOf(ResearchBacktestPool);
for (const key of [
'BacktestEngine',
'ModeManager',
'ExecutionService',
'MarketDataService',
@ -118,6 +128,37 @@ describe('canonical research-only default composition', () => {
});
}
);
test.each([1, 2, 4] as const)(
'composition uses one BullMQ consumer with concurrency %s',
async maxConcurrent => {
const calls: unknown[] = [];
const { services } = await compose({ maxConcurrent }, calls);
expect(calls).toEqual([
{ name: 'orchestrator', options: { workers: 1, concurrency: maxConcurrent } },
]);
expect(services.custom!.BacktestRunner!.getStatus().isRunning).toBe(false);
}
);
test('default composition and schema select one slot; invalid values fail before resolving services/connections', async () => {
const calls: unknown[] = [];
await compose({}, calls);
expect(calls).toEqual([{ name: 'orchestrator', options: { workers: 1, concurrency: 1 } }]);
const schema = stockAppSchema.shape.services
.unwrap()
.shape.orchestrator.unwrap()
.shape.backtesting.unwrap();
expect(schema.parse({}).maxConcurrent).toBe(1);
for (const maxConcurrent of [null, 0, 3, 5, 1.5, '2', NaN, Infinity]) {
expect(schema.safeParse({ maxConcurrent }).success).toBe(false);
const container = createDiContainer<ServiceCradle>();
await expect(
registerOrchestratorServices(container, { maxConcurrent } as never)
).rejects.toThrow('1, 2, or 4');
await expect(
createContainer({ services: { orchestrator: { backtesting: { maxConcurrent } } } } as never)
).rejects.toThrow('1, 2, or 4');
}
});
test('cannot overlay the canonical graph on a legacy account runtime', async () => {
const container = createDiContainer<ServiceCradle>();
container.register({ serviceContainer: asValue({ logger, custom: { ExecutionService: {} } }) });