stock-bot/test/integration/research-pool.test.ts

394 lines
16 KiB
TypeScript

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 } 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('one active run preserves explicit rejection of unsupported playback controls', async () => {
const f = fixture(1),
work = await started(f),
slot = f.slots[0]!;
for (const [action, message] of [
['pause', 'Native backtests do not support pause'],
['resume', 'Native backtests do not support resume'],
['speed', 'Native backtests run at maximum speed'],
] as const) {
for (const runId of [undefined, slot.request.runId]) {
const response = await post(f.app, action, {
...(runId ? { runId } : {}),
...(action === 'speed' ? { speed: null } : {}),
});
expect(response.status).toBe(500);
expect(await response.json()).toMatchObject({ error: message });
}
}
expect(slot.runner.getStatus().isPaused).toBe(false);
expect(slot.events).not.toContain('complete');
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);
});
});