more stuff

This commit is contained in:
Boki 2026-10-20 20:11:40 -04:00
parent c3cb36c8d6
commit 7dec0be3b4
26 changed files with 1394 additions and 275 deletions

View file

@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
import { asValue } from 'awilix';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { newDb } from 'pg-mem';
import { DataType, newDb } from 'pg-mem';
import { ServiceContainerBuilder } from '@stock-bot/di';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
@ -17,6 +17,7 @@ import {
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { normalizeBacktestResult } from '../../apps/stock/orchestrator/src/backtest/result';
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager';
@ -60,6 +61,12 @@ async function fixture(
) {
// PostgreSQL protocol is replaced with an in-process database; SQL and transaction manager are real.
const db = newDb();
db.public.registerFunction({
name: 'clock_timestamp',
returns: DataType.timestamptz,
impure: true,
implementation: () => new Date(),
});
db.public
.none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
@ -68,7 +75,11 @@ async function fixture(
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,
request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0,
lease_expires_at timestamptz, cancel_requested boolean DEFAULT false,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
CREATE TABLE backtest_dispatch (run_id uuid PRIMARY KEY REFERENCES runs(id),
next_publish_at timestamptz DEFAULT NOW(), last_published_at timestamptz, publish_count integer DEFAULT 0);
CREATE TABLE backtest_results (run_id uuid PRIMARY KEY REFERENCES runs(id), completed_at timestamptz,
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
execution_time numeric, configuration jsonb, engine text);`);
@ -115,7 +126,14 @@ async function fixture(
engineOptions
);
const repository = new PostgresBacktestRunRepository(postgres);
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository,
logger,
heartbeatMs: 50,
heartbeatTimeoutMs: 500,
});
cleanup.unshift(() => runner.shutdown());
const services = { logger, postgres, custom: { BacktestRunner: runner } };
const routes = new Hono().route('/api/backtest', createBacktestRoutes(services));
@ -203,51 +221,39 @@ describe('one backtest execution workflow', () => {
test('V2 dispatch forwards strategy parameters and reads the runner-owned saved result', async () => {
const f = await fixture();
let finish!: () => void;
const finished = new Promise<void>(resolve => {
finish = resolve;
});
let forwarded: Record<string, unknown> = {};
const api = new BacktestServiceV2(f.services, async (url, init) => {
forwarded = JSON.parse(String(init?.body));
const response = await f.routes.request(new URL(url).pathname, init);
finish();
return response;
const api = new BacktestServiceV2(f.services, async () => {
throw new Error('Queued execution must not use HTTP dispatch');
});
const definition = await api.createBacktest(
{ ...config, name: config.name!, config: { ...config.config, commission: 0, slippage: 0 } },
{ autoStart: false }
);
const run = await api.createRun({ backtestId: definition.id, speedMultiplier: null });
await finished;
expect(forwarded.config).toMatchObject({ fastPeriod: 3, slowPeriod: 7 });
expect(forwarded.speed).toBe('max');
expect(run.status).toBe('pending');
const snapshot = (
await f.postgres.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
).rows[0]?.request_snapshot;
expect(snapshot.config).toMatchObject({ fastPeriod: 3, slowPeriod: 7 });
expect(snapshot.speed).toBe('max');
await f.runner.runQueued(run.id);
expect((await api.getRun(run.id))?.status).toBe('completed');
const saved = await api.getRunResults(run.id);
expect(saved?.config.parameters).toMatchObject({ fastPeriod: 3, slowPeriod: 7 });
expect(saved?.engine).toBe('native');
expect(saved?.trades.length).toBeGreaterThan(0);
await api.updateRunProgress(run.id, { progress: 2 });
await api.updateRunProgress(run.id, { progress: 2, attemptId: randomUUID() });
expect((await api.getRun(run.id))?.status).toBe('completed');
expect((await api.getRun(run.id))?.progress).toBe(100);
});
test('the V1 facade creates runs instead of writing removed backtest status columns', async () => {
const f = await fixture();
let finish!: () => void;
const finished = new Promise<void>(resolve => {
finish = resolve;
});
const api = new BacktestService(f.services, async (url, init) => {
const response = await f.routes.request(new URL(url).pathname, init);
finish();
return response;
});
const api = new BacktestService(f.services);
const created = await api.createBacktest({
...config,
config: { ...config.config, commission: 0, slippage: 0 },
});
await finished;
await f.runner.runQueued(created.runId!);
expect((await api.getBacktest(created.id))?.status).toBe('completed');
expect((await api.getBacktestResults(created.id))?.runId).toBe(created.runId);
});
@ -321,9 +327,9 @@ describe('one backtest execution workflow', () => {
},
}),
});
await expect(new PostgresBacktestRunRepository(postgres).complete(result)).rejects.toThrow(
'Insert failed'
);
await expect(
new PostgresBacktestRunRepository(postgres).complete(result, randomUUID())
).rejects.toThrow('Insert failed');
expect(statements[0]).toBe('BEGIN');
expect(statements.at(-1)).toBe('ROLLBACK');
expect(statements).not.toContain('COMMIT');
@ -357,7 +363,7 @@ describe('one backtest execution workflow', () => {
expect(JSON.parse(String(init?.body)).runId).toBe(result.runId);
return new Response('Unsupported', { status: 501 });
});
await expect(api.cancelRun(result.runId)).rejects.toThrow('was not acknowledged');
await expect(api.cancelRun(result.runId)).rejects.toThrow('No cancellable run');
expect((await api.getRun(result.runId))?.status).toBe('completed');
});
@ -619,10 +625,10 @@ describe('isolated native backtest workers', () => {
const gate = new Promise<void>(resolve => {
release = resolve;
});
f.repository.complete = async result => {
f.repository.complete = async (result, attemptId) => {
entered();
await gate;
await complete(result);
await complete(result, attemptId);
};
const running = f.runner.runBacktest(config);
await committing;
@ -675,6 +681,25 @@ describe('isolated native backtest workers', () => {
expect(result.engine).toBe('native');
});
test.each(['rejected', 'hung'])(
'%s heartbeat kills a blocking worker and leaves the abandoned attempt recoverable',
async behavior => {
const f = await fixture(false, { workerUrl });
const ready = workerReady(f.runner);
const execution = f.runner.runBacktest(blockingConfig).catch(error => error);
const { pid } = await ready;
f.repository.heartbeat = async () => {
if (behavior === 'hung') return new Promise(() => {});
throw new Error('Database unavailable');
};
expect(await execution).toBeInstanceOf(BacktestLeaseLostError);
expectWorkerExited(pid);
// Do not label a lost attempt failed/cancelled; the lease reaper owns its recovery.
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('running');
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
}
);
test('V2 cancellation publishes cancelled state, not a dispatch error or fabricated result', async () => {
const f = await fixture(false, { workerUrl });
const api = new BacktestServiceV2(f.services, (url, init) =>
@ -699,14 +724,16 @@ describe('isolated native backtest workers', () => {
);
const ready = workerReady(f.runner);
const run = await api.createRun({ backtestId: definition.id, speedMultiplier: null });
const execution = f.runner.runQueued(run.id).catch(error => error);
const { pid, runId } = await ready;
expect(runId).toBe(run.id);
await api.cancelRun(run.id);
await cancelled;
await execution;
expectWorkerExited(pid);
expect(notifications).toContainEqual({
type: 'run_update',
data: { status: 'cancelled', timestamp: expect.any(String) },
data: { status: 'running', cancelRequested: true, timestamp: expect.any(String) },
});
expect(notifications.some(update => update.type === 'error')).toBe(false);
expect((await api.getRun(run.id))?.status).toBe('cancelled');