more stuff
This commit is contained in:
parent
c3cb36c8d6
commit
7dec0be3b4
26 changed files with 1394 additions and 275 deletions
|
|
@ -24,11 +24,14 @@ repository-check:
|
|||
services:
|
||||
- name: postgres:16-alpine
|
||||
alias: postgres
|
||||
- name: redis:7-alpine
|
||||
alias: redis
|
||||
variables:
|
||||
POSTGRES_DB: stock_bot_safety
|
||||
POSTGRES_USER: fixture
|
||||
POSTGRES_PASSWORD: fixture
|
||||
PIPELINE_TEST_DATABASE_URL: postgres://fixture:fixture@postgres:5432/stock_bot_safety
|
||||
BACKTEST_TEST_REDIS_URL: redis://redis:6379/15
|
||||
before_script:
|
||||
- apt-get update && apt-get install -y --no-install-recommends nodejs unzip
|
||||
- curl -fsSL https://bun.sh/install | bash -s "bun-v1.2.17"
|
||||
|
|
|
|||
57
README.md
57
README.md
|
|
@ -101,9 +101,10 @@ schema or execution path. Strategy parameters and exact run configuration are pr
|
|||
All historical readers delegate to the same storage policy; simulated fills do not enter
|
||||
the trading ledger. Shared adapters are closed by DI, not by a backtest mode transition.
|
||||
|
||||
Deployment requires the additive migration
|
||||
`database/postgres/init/09-backtest-run-contract.sql`, after the existing runs migration.
|
||||
The web API's migration allowlist includes it. It adds configuration/provenance columns and
|
||||
Deployment requires the additive migrations
|
||||
`database/postgres/init/09-backtest-run-contract.sql` and `10-durable-backtest-dispatch.sql`,
|
||||
after the existing runs migration. The web API's migration allowlist includes both.
|
||||
The first adds configuration/provenance columns and
|
||||
a unique result-per-run index without deleting history. Existing duplicate result rows must
|
||||
be reconciled before applying that index. Historical rows without snapshots remain readable
|
||||
and are explicitly marked `legacy`; their configuration is reconstructed from the definition.
|
||||
|
|
@ -135,7 +136,47 @@ The integration suite covers both real engines, REST/job parity, V1/V2 dispatch
|
|||
reads, missing data, duplicate/concurrent requests, failed persistence/rollback, controls,
|
||||
responsive requests/streams, worker crashes, deadlines, cancellation, and cleanup. SQL tests
|
||||
use an in-process PostgreSQL emulator and the real transaction manager, not a live database.
|
||||
Durable queued dispatch and recovery after an orchestrator crash remain follow-up work.
|
||||
|
||||
### Durable dispatch and recovery
|
||||
|
||||
`POST /api/v2/backtests/:id/runs` returns **202** with a pending run ID and a `Location`
|
||||
header. In one PostgreSQL transaction it stores the run, its immutable execution request,
|
||||
and a `backtest_dispatch` intent. No Redis/HTTP call is needed to accept the run. Editing
|
||||
a definition later does not change an accepted run. The V1 facade uses the same workflow.
|
||||
The orchestrator's direct synchronous REST execution routes remain compatibility endpoints.
|
||||
|
||||
The web API runs a producer-only dispatcher (zero workers) every five seconds. It reserves
|
||||
due intents with `FOR UPDATE SKIP LOCKED` and publishes identity-only notifications to the
|
||||
existing `{orchestrator_orchestrator}` queue. Stable job IDs deduplicate outstanding jobs;
|
||||
pending intents are republished every 30 seconds, including after a lost Redis job or a
|
||||
publisher restart. Redis outages leave accepted runs pending; they do not falsely fail them.
|
||||
The queue clients honor explicit Redis endpoints and reconnect after transient outages.
|
||||
|
||||
Each orchestrator consumes one job at a time. It atomically claims a pending run with a new
|
||||
attempt UUID and a 30-second PostgreSQL-clock lease, renewed every five seconds. Progress,
|
||||
controls, failure, cancellation, and terminal result writes are fenced by that attempt and
|
||||
an unexpired lease. A lost heartbeat stops the local execution and leaves recovery to the
|
||||
dispatcher. Expired owners are retried from their saved request, up to three execution
|
||||
attempts; exhaustion becomes `failed`. Terminal redelivery is acknowledged without rerunning.
|
||||
Computation is at-least-once, not exactly-once; only an owned result can commit, atomically
|
||||
with terminal status, and the unique result-per-run constraint remains the final guard.
|
||||
Recovery also depends on BullMQ detecting stalled jobs and the API dispatcher being available.
|
||||
|
||||
Cancellation is durable: queued runs become `cancelled` before a claim; active runs record
|
||||
`cancel_requested` for their owner to observe, stop, and acknowledge. The V2 cancel endpoint
|
||||
returns **202**, not a claim that execution already stopped. A cancelled abandoned lease
|
||||
becomes `cancelled`, without a result. The dashboard keeps polling until persisted terminal
|
||||
state; WebSocket updates are read from committed SQL state, not an in-memory dispatch request.
|
||||
Native pause/resume/speed remain unsupported; those compatibility controls still require
|
||||
the HTTP request to reach the owning instance.
|
||||
|
||||
Before applying migration 10, **stop all older orchestrators**, start the migrated web API,
|
||||
then start lease-aware orchestrators. Legacy pending runs receive a one-time snapshot of
|
||||
their current definition; legacy active runs with no owner token are marked failed rather
|
||||
than pretending they are recoverable. Existing results are preserved. Infrastructure should
|
||||
supervise the orchestrator process tree: SIGKILL of a parent cannot guarantee reaping a child
|
||||
blocked in native code, though a stale child cannot persist a result through the fenced parent.
|
||||
No migration or restart is performed against your existing local databases by the tests.
|
||||
|
||||
## HTTP access and secrets
|
||||
|
||||
|
|
@ -200,5 +241,9 @@ incremental/batch parity; no synthetic D values are produced before warm-up comp
|
|||
`bun run test:postgres` additionally requires `PIPELINE_TEST_DATABASE_URL` pointing to a
|
||||
**disposable database whose name starts with `stock_bot_safety`**. It creates/drops isolated
|
||||
test schemas and verifies real rollback, foreign-key constraints, idempotency, and competing
|
||||
transaction locking. CI provisions that database and runs this additional gate. It is
|
||||
separate from the infrastructure-free `check`; never point tests at production.
|
||||
transaction locking. Set `BACKTEST_TEST_REDIS_URL` to a dedicated Redis fixture using database
|
||||
15 as well; queue names are unique per test. The durability tests cover HTTP acceptance,
|
||||
outbox rollback, immutable requests, migration replay, hard-killed owners, stale-write fencing,
|
||||
cancellation races, retry exhaustion, disconnected publishing, and lost-job redelivery with
|
||||
the real native engine. CI provisions PostgreSQL and Redis and runs this additional gate.
|
||||
It is separate from the infrastructure-free `check`; never point tests at production.
|
||||
|
|
|
|||
|
|
@ -7,8 +7,9 @@ import { BacktestCancelledError, type BacktestExecutionEngine } from './executio
|
|||
import { normalizeBacktestResult } from './result';
|
||||
import {
|
||||
BacktestConflictError,
|
||||
BacktestLeaseLostError,
|
||||
type BacktestRunRepository,
|
||||
type RunIdentity,
|
||||
type RunClaim,
|
||||
} from './run-repository';
|
||||
|
||||
export function parseBacktestRequest(input: unknown): BacktestConfig {
|
||||
|
|
@ -24,7 +25,8 @@ export function parseBacktestRequest(input: unknown): BacktestConfig {
|
|||
/** One application workflow for HTTP, jobs, and both execution backends. */
|
||||
export class BacktestRunner extends EventEmitter {
|
||||
private busy = false;
|
||||
private active: RunIdentity | undefined;
|
||||
private active: RunClaim | undefined;
|
||||
private leaseFailure: BacktestLeaseLostError | undefined;
|
||||
private cancelled = false;
|
||||
private progressWrites: Promise<void> = Promise.resolve();
|
||||
private closing = false;
|
||||
|
|
@ -37,6 +39,8 @@ export class BacktestRunner extends EventEmitter {
|
|||
engineName: Exclude<BacktestRunResult['engine'], 'legacy'>;
|
||||
repository: BacktestRunRepository;
|
||||
logger: Pick<Logger, 'error'>;
|
||||
heartbeatMs?: number;
|
||||
heartbeatTimeoutMs?: number;
|
||||
prepare?: (config: BacktestConfig) => Promise<void>;
|
||||
}
|
||||
) {
|
||||
|
|
@ -53,14 +57,78 @@ export class BacktestRunner extends EventEmitter {
|
|||
}
|
||||
this.busy = true;
|
||||
this.cancelled = false;
|
||||
this.leaseFailure = undefined;
|
||||
this.phase = 'preparing';
|
||||
this.execution = this.execute(config);
|
||||
return this.execution;
|
||||
}
|
||||
|
||||
/** Queue redelivery is an acknowledgement for terminal runs, never a second execution. */
|
||||
async runQueued(runId: string) {
|
||||
const run = await this.dependencies.repository.load(runId);
|
||||
if (!run) {
|
||||
return { runId, status: 'missing' };
|
||||
}
|
||||
if (['completed', 'cancelled', 'failed'].includes(run.status)) {
|
||||
return { runId, status: run.status };
|
||||
}
|
||||
let snapshot: BacktestConfig;
|
||||
try {
|
||||
snapshot = parseBacktestRequest(run.config);
|
||||
} catch (error) {
|
||||
await this.dependencies.repository.rejectPending(
|
||||
runId,
|
||||
'Invalid persisted execution configuration'
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
const result = await this.runBacktest({ ...snapshot, runId });
|
||||
return { runId, status: result.status };
|
||||
}
|
||||
|
||||
private async execute(config: BacktestConfig): Promise<BacktestRunResult> {
|
||||
const started = performance.now();
|
||||
this.progressWrites = Promise.resolve();
|
||||
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let heartbeatWork: Promise<void> | undefined;
|
||||
const heartbeat = async () => {
|
||||
const active = this.active;
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
let deadline: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const state = await Promise.race([
|
||||
this.dependencies.repository.heartbeat(active.runId, active.attemptId),
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
deadline = setTimeout(
|
||||
() => reject(new Error('Execution heartbeat timed out')),
|
||||
this.dependencies.heartbeatTimeoutMs ?? 5_000
|
||||
);
|
||||
}),
|
||||
]);
|
||||
if (!state.cancelRequested) {
|
||||
return;
|
||||
}
|
||||
this.cancelled = true;
|
||||
} catch (error) {
|
||||
this.leaseFailure = new BacktestLeaseLostError(
|
||||
'Could not renew execution lease; abandoning attempt',
|
||||
{ cause: error }
|
||||
);
|
||||
} finally {
|
||||
if (deadline) {
|
||||
clearTimeout(deadline);
|
||||
}
|
||||
}
|
||||
if (this.phase === 'executing') {
|
||||
try {
|
||||
await this.dependencies.engine.stopBacktest();
|
||||
} catch (error) {
|
||||
this.dependencies.logger.error('Could not stop abandoned/cancelled execution', { error });
|
||||
}
|
||||
}
|
||||
};
|
||||
const onProgress = (data: unknown) => {
|
||||
const active = this.active;
|
||||
if (
|
||||
|
|
@ -81,7 +149,14 @@ export class BacktestRunner extends EventEmitter {
|
|||
? data.currentDate
|
||||
: undefined;
|
||||
this.progressWrites = this.progressWrites
|
||||
.then(() => this.dependencies.repository.updateProgress(active.runId, progress, date))
|
||||
.then(() =>
|
||||
this.dependencies.repository.updateProgress(
|
||||
active.runId,
|
||||
progress,
|
||||
date,
|
||||
active.attemptId
|
||||
)
|
||||
)
|
||||
.catch(error => {
|
||||
this.dependencies.logger.error('Could not persist backtest progress', { error });
|
||||
});
|
||||
|
|
@ -90,13 +165,38 @@ export class BacktestRunner extends EventEmitter {
|
|||
this.dependencies.engine.on('progress', onProgress);
|
||||
try {
|
||||
this.active = await this.dependencies.repository.start(config);
|
||||
const executionConfig = { ...config, ...this.active };
|
||||
const executionConfig = parseBacktestRequest({
|
||||
...this.active.config,
|
||||
runId: this.active.runId,
|
||||
backtestId: this.active.backtestId,
|
||||
});
|
||||
heartbeatTimer = setInterval(() => {
|
||||
if (!heartbeatWork) {
|
||||
heartbeatWork = heartbeat().finally(() => {
|
||||
heartbeatWork = undefined;
|
||||
});
|
||||
}
|
||||
}, this.dependencies.heartbeatMs ?? 5_000);
|
||||
heartbeatTimer.unref();
|
||||
await heartbeat();
|
||||
if (this.leaseFailure) {
|
||||
throw this.leaseFailure;
|
||||
}
|
||||
if (this.cancelled) {
|
||||
throw new BacktestCancelledError();
|
||||
}
|
||||
await this.dependencies.prepare?.(executionConfig);
|
||||
if (this.leaseFailure) {
|
||||
throw this.leaseFailure;
|
||||
}
|
||||
if (this.cancelled) {
|
||||
throw new BacktestCancelledError();
|
||||
}
|
||||
this.phase = 'executing';
|
||||
const raw = await this.dependencies.engine.runBacktest(executionConfig);
|
||||
if (this.leaseFailure) {
|
||||
throw this.leaseFailure;
|
||||
}
|
||||
this.phase = 'persisting';
|
||||
let result: BacktestRunResult;
|
||||
try {
|
||||
|
|
@ -112,21 +212,25 @@ export class BacktestRunner extends EventEmitter {
|
|||
throw new Error('Backtest engine returned an invalid result', { cause: error });
|
||||
}
|
||||
await this.progressWrites;
|
||||
await this.dependencies.repository.complete(result);
|
||||
if (this.leaseFailure) {
|
||||
throw this.leaseFailure;
|
||||
}
|
||||
await this.dependencies.repository.complete(result, this.active.attemptId);
|
||||
// Observers cannot turn a committed success into a failed run.
|
||||
this.publish('complete', result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
await this.progressWrites;
|
||||
let failure = error;
|
||||
if (this.active) {
|
||||
let failure = this.leaseFailure ?? error;
|
||||
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
|
||||
try {
|
||||
if (error instanceof BacktestCancelledError) {
|
||||
await this.dependencies.repository.cancel(this.active.runId);
|
||||
await this.dependencies.repository.cancel(this.active.runId, this.active.attemptId);
|
||||
} else {
|
||||
await this.dependencies.repository.fail(
|
||||
this.active.runId,
|
||||
error instanceof Error ? error.message : String(error)
|
||||
error instanceof Error ? error.message : String(error),
|
||||
this.active.attemptId
|
||||
);
|
||||
}
|
||||
} catch (persistenceError) {
|
||||
|
|
@ -138,12 +242,20 @@ export class BacktestRunner extends EventEmitter {
|
|||
}
|
||||
}
|
||||
if (failure instanceof BacktestCancelledError) {
|
||||
this.publish('cancelled', { ...this.active, status: 'cancelled' });
|
||||
this.publish('cancelled', {
|
||||
runId: this.active?.runId,
|
||||
backtestId: this.active?.backtestId,
|
||||
status: 'cancelled',
|
||||
});
|
||||
} else if (this.listenerCount('error')) {
|
||||
this.publish('error', failure);
|
||||
}
|
||||
throw failure;
|
||||
} finally {
|
||||
if (heartbeatTimer) {
|
||||
clearInterval(heartbeatTimer);
|
||||
}
|
||||
await heartbeatWork;
|
||||
this.dependencies.engine.off('progress', onProgress);
|
||||
this.active = undefined;
|
||||
this.busy = false;
|
||||
|
|
@ -211,12 +323,20 @@ export class BacktestRunner extends EventEmitter {
|
|||
async pauseBacktest(runId?: string) {
|
||||
const active = this.requireActive(runId);
|
||||
await this.dependencies.engine.pauseBacktest();
|
||||
await this.dependencies.repository.updateControl(active.runId, { status: 'paused' });
|
||||
await this.dependencies.repository.updateControl(
|
||||
active.runId,
|
||||
{ status: 'paused' },
|
||||
active.attemptId
|
||||
);
|
||||
}
|
||||
async resumeBacktest(runId?: string) {
|
||||
const active = this.requireActive(runId);
|
||||
await this.dependencies.engine.resumeBacktest();
|
||||
await this.dependencies.repository.updateControl(active.runId, { status: 'running' });
|
||||
await this.dependencies.repository.updateControl(
|
||||
active.runId,
|
||||
{ status: 'running' },
|
||||
active.attemptId
|
||||
);
|
||||
}
|
||||
async setSpeedMultiplier(speed: number | null, runId?: string) {
|
||||
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
|
||||
|
|
@ -224,7 +344,11 @@ export class BacktestRunner extends EventEmitter {
|
|||
}
|
||||
const active = this.requireActive(runId);
|
||||
this.dependencies.engine.setSpeedMultiplier(speed);
|
||||
await this.dependencies.repository.updateControl(active.runId, { speedMultiplier: speed });
|
||||
await this.dependencies.repository.updateControl(
|
||||
active.runId,
|
||||
{ speedMultiplier: speed },
|
||||
active.attemptId
|
||||
);
|
||||
}
|
||||
getStatus() {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -1,33 +1,64 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||
import { BacktestCancelledError } from './execution-engine';
|
||||
import {
|
||||
BacktestConflictError,
|
||||
BacktestLeaseLostError,
|
||||
type BacktestRunRepository,
|
||||
type RunIdentity,
|
||||
type RunClaim,
|
||||
} from './run-repository';
|
||||
|
||||
/** Uses the existing backtests/runs schema; never commits completion without the result. */
|
||||
/** The attempt UUID is a fencing token. PostgreSQL time, not worker clocks, defines ownership. */
|
||||
export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
||||
constructor(private readonly postgres: Pick<PostgresClient, 'transaction'>) {}
|
||||
constructor(
|
||||
private readonly postgres: Pick<PostgresClient, 'transaction'>,
|
||||
private readonly leaseMs = 30_000
|
||||
) {
|
||||
if (!Number.isInteger(leaseMs) || leaseMs < 100) {
|
||||
throw new Error('Invalid execution lease duration');
|
||||
}
|
||||
}
|
||||
|
||||
async start(config: BacktestConfig): Promise<RunIdentity> {
|
||||
async load(runId: string) {
|
||||
return this.postgres.transaction(async client => {
|
||||
const result = await client.query('SELECT status, request_snapshot FROM runs WHERE id = $1', [
|
||||
runId,
|
||||
]);
|
||||
const row = result.rows[0];
|
||||
return row ? { status: String(row.status), config: row.request_snapshot as unknown } : null;
|
||||
});
|
||||
}
|
||||
|
||||
async start(config: BacktestConfig): Promise<RunClaim> {
|
||||
const attemptId = randomUUID();
|
||||
return this.postgres.transaction(async client => {
|
||||
if (config.runId) {
|
||||
const claimed = await client.query<{ id: string; backtest_id: string }>(
|
||||
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [config.runId]);
|
||||
const claimed = await client.query(
|
||||
`UPDATE runs SET status = 'running', progress = 0, error = NULL,
|
||||
started_at = NOW(), completed_at = NULL, updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('pending', 'failed')
|
||||
started_at = NOW(), completed_at = NULL, paused_at = NULL, updated_at = NOW(),
|
||||
attempt_id = $3, attempt_number = attempt_number + 1,
|
||||
lease_expires_at = clock_timestamp() + $4::interval
|
||||
WHERE id = $1 AND status = 'pending' AND NOT cancel_requested
|
||||
AND request_snapshot IS NOT NULL
|
||||
AND ($2::uuid IS NULL OR backtest_id = $2::uuid)
|
||||
RETURNING id, backtest_id`,
|
||||
[config.runId, config.backtestId ?? null]
|
||||
RETURNING id, backtest_id, request_snapshot`,
|
||||
[config.runId, config.backtestId ?? null, attemptId, `${this.leaseMs} milliseconds`]
|
||||
);
|
||||
const run = claimed.rows[0];
|
||||
if (!run) {
|
||||
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
|
||||
}
|
||||
return { runId: run.id, backtestId: run.backtest_id };
|
||||
const snapshot = BacktestConfigSchema.parse(run.request_snapshot);
|
||||
return {
|
||||
runId: String(run.id),
|
||||
backtestId: String(run.backtest_id),
|
||||
attemptId,
|
||||
config: snapshot,
|
||||
};
|
||||
}
|
||||
|
||||
const backtestId = config.backtestId ?? randomUUID();
|
||||
|
|
@ -53,7 +84,6 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
]
|
||||
);
|
||||
}
|
||||
// Serialize run numbering on the parent rather than racing MAX(run_number).
|
||||
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
backtestId,
|
||||
]);
|
||||
|
|
@ -61,9 +91,12 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
throw new Error('Backtest definition not found');
|
||||
}
|
||||
const runId = randomUUID();
|
||||
const snapshot = { ...config, runId, backtestId };
|
||||
await client.query(
|
||||
`INSERT INTO runs (id, backtest_id, run_number, status, started_at, speed_multiplier)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, 'running'::run_status, NOW(), $3
|
||||
`INSERT INTO runs (id, backtest_id, run_number, status, started_at, speed_multiplier,
|
||||
request_snapshot, attempt_id, attempt_number, lease_expires_at)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, 'running'::run_status, NOW(), $3,
|
||||
$4::jsonb, $5::uuid, 1, clock_timestamp() + $6::interval
|
||||
FROM runs WHERE backtest_id = $2`,
|
||||
[
|
||||
runId,
|
||||
|
|
@ -73,22 +106,70 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
: config.speed === 'realtime'
|
||||
? 1
|
||||
: Number.parseFloat(config.speed),
|
||||
JSON.stringify(snapshot),
|
||||
attemptId,
|
||||
`${this.leaseMs} milliseconds`,
|
||||
]
|
||||
);
|
||||
return { runId, backtestId };
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
return { runId, backtestId, attemptId, config: snapshot };
|
||||
});
|
||||
}
|
||||
|
||||
async complete(result: BacktestRunResult): Promise<void> {
|
||||
async rejectPending(runId: string, error: string) {
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
`UPDATE runs SET status = 'failed', error = $2,
|
||||
completed_at = NOW(), updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
|
||||
[runId, error]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Lock first, then evaluate the lease against real DB time. UPDATE can evaluate its
|
||||
* predicate before waiting on a row lock, even when the predicate uses clock_timestamp(). */
|
||||
private ownedTransaction<T>(runId: string, work: TransactionCallback<T>): Promise<T> {
|
||||
return this.postgres.transaction(async client => {
|
||||
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [runId]);
|
||||
return work(client);
|
||||
});
|
||||
}
|
||||
|
||||
async heartbeat(runId: string, attemptId: string) {
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const result = await client.query(
|
||||
`UPDATE runs SET lease_expires_at = clock_timestamp() + $3::interval, updated_at = NOW()
|
||||
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp()
|
||||
AND status IN ('running', 'paused') RETURNING cancel_requested`,
|
||||
[runId, attemptId, `${this.leaseMs} milliseconds`]
|
||||
);
|
||||
if (!result.rows[0]) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost');
|
||||
}
|
||||
return { cancelRequested: result.rows[0].cancel_requested === true };
|
||||
});
|
||||
}
|
||||
|
||||
async complete(result: BacktestRunResult, attemptId: string): Promise<void> {
|
||||
await this.ownedTransaction(result.runId, async client => {
|
||||
const updated = await client.query(
|
||||
`UPDATE runs SET status = $2, progress = CASE WHEN $2 = 'completed' THEN 100 ELSE progress END,
|
||||
completed_at = $3, updated_at = NOW(), error = NULL
|
||||
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused') RETURNING id`,
|
||||
[result.runId, result.status, result.completedAt, result.backtestId]
|
||||
`UPDATE runs SET status = $2::run_status, progress = CASE WHEN $2::run_status = 'completed' THEN 100 ELSE progress END,
|
||||
completed_at = $3, updated_at = NOW(), error = NULL, lease_expires_at = NULL
|
||||
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused')
|
||||
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id`,
|
||||
[result.runId, result.status, result.completedAt, result.backtestId, attemptId]
|
||||
);
|
||||
if (!updated.rows.length) {
|
||||
throw new BacktestConflictError('Run no longer belongs to this execution');
|
||||
const cancellation = await client.query(
|
||||
`SELECT id FROM runs
|
||||
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp()
|
||||
AND status IN ('running', 'paused') AND cancel_requested`,
|
||||
[result.runId, attemptId]
|
||||
);
|
||||
if (cancellation.rows.length) {
|
||||
throw new BacktestCancelledError();
|
||||
}
|
||||
throw new BacktestLeaseLostError('Execution lease lost');
|
||||
}
|
||||
await client.query(
|
||||
`INSERT INTO backtest_results
|
||||
|
|
@ -111,59 +192,73 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
async updateProgress(runId: string, progress: number, currentDate?: string): Promise<void> {
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
async updateProgress(
|
||||
runId: string,
|
||||
progress: number,
|
||||
currentDate: string | undefined,
|
||||
attemptId: string
|
||||
) {
|
||||
await this.ownedTransaction(runId, async client => {
|
||||
const result = await client.query(
|
||||
`UPDATE runs SET progress = GREATEST(progress, $2),
|
||||
current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused')`,
|
||||
[runId, progress, currentDate ?? null]
|
||||
WHERE id = $1 AND attempt_id = $4 AND lease_expires_at > clock_timestamp()
|
||||
AND status IN ('running', 'paused') RETURNING id`,
|
||||
[runId, progress, currentDate ?? null, attemptId]
|
||||
);
|
||||
if (!result.rows.length) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async updateControl(
|
||||
runId: string,
|
||||
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null }
|
||||
): Promise<void> {
|
||||
await this.postgres.transaction(async client => {
|
||||
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null },
|
||||
attemptId: string
|
||||
) {
|
||||
await this.ownedTransaction(runId, async client => {
|
||||
const result = await client.query(
|
||||
`UPDATE runs SET status = COALESCE($2::run_status, status),
|
||||
paused_at = CASE WHEN $2 = 'paused' THEN NOW() ELSE paused_at END,
|
||||
speed_multiplier = CASE WHEN $3 THEN $4 ELSE speed_multiplier END, updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') RETURNING id`,
|
||||
WHERE id = $1 AND attempt_id = $5 AND lease_expires_at > clock_timestamp()
|
||||
AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`,
|
||||
[
|
||||
runId,
|
||||
update.status ?? null,
|
||||
update.speedMultiplier !== undefined,
|
||||
update.speedMultiplier ?? null,
|
||||
attemptId,
|
||||
]
|
||||
);
|
||||
if (!result.rows.length) {
|
||||
throw new BacktestConflictError('No matching active run');
|
||||
throw new BacktestLeaseLostError('No matching owned active run');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fail(runId: string, error: string): Promise<void> {
|
||||
await this.postgres.transaction(async client => {
|
||||
async fail(runId: string, error: string, attemptId: string) {
|
||||
await this.ownedTransaction(runId, async client => {
|
||||
await client.query(
|
||||
`UPDATE runs SET status = 'failed', error = $2, completed_at = NOW(), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused')`,
|
||||
[runId, error]
|
||||
`UPDATE runs SET status = CASE WHEN cancel_requested THEN 'cancelled'::run_status ELSE 'failed'::run_status END,
|
||||
error = CASE WHEN cancel_requested THEN NULL ELSE $2 END,
|
||||
completed_at = NOW(), lease_expires_at = NULL, updated_at = NOW()
|
||||
WHERE id = $1 AND attempt_id = $3 AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused')`,
|
||||
[runId, error, attemptId]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async cancel(runId: string): Promise<void> {
|
||||
await this.postgres.transaction(async client => {
|
||||
async cancel(runId: string, attemptId: string) {
|
||||
await this.ownedTransaction(runId, async client => {
|
||||
const result = await client.query(
|
||||
`UPDATE runs SET status = 'cancelled', error = NULL, completed_at = NOW(), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') RETURNING id`,
|
||||
[runId]
|
||||
`UPDATE runs SET status = 'cancelled', error = NULL, completed_at = NOW(), lease_expires_at = NULL, updated_at = NOW()
|
||||
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') RETURNING id`,
|
||||
[runId, attemptId]
|
||||
);
|
||||
if (!result.rows.length) {
|
||||
throw new BacktestConflictError('No matching active run to cancel');
|
||||
throw new BacktestLeaseLostError('No matching owned active run to cancel');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,39 +5,65 @@ export interface RunIdentity {
|
|||
runId: string;
|
||||
backtestId: string;
|
||||
}
|
||||
export interface RunClaim extends RunIdentity {
|
||||
attemptId: string;
|
||||
config: BacktestConfig;
|
||||
}
|
||||
|
||||
/** The runner owns this lifecycle. Results and terminal status must commit atomically. */
|
||||
/** Every execution write must prove ownership of an unexpired attempt. */
|
||||
export interface BacktestRunRepository {
|
||||
start(config: BacktestConfig): Promise<RunIdentity>;
|
||||
complete(result: BacktestRunResult): Promise<void>;
|
||||
updateProgress(runId: string, progress: number, currentDate?: string): Promise<void>;
|
||||
fail(runId: string, error: string): Promise<void>;
|
||||
cancel(runId: string): Promise<void>;
|
||||
start(config: BacktestConfig): Promise<RunClaim>;
|
||||
load(runId: string): Promise<{ status: string; config: unknown } | null>;
|
||||
rejectPending(runId: string, error: string): Promise<void>;
|
||||
heartbeat(runId: string, attemptId: string): Promise<{ cancelRequested: boolean }>;
|
||||
complete(result: BacktestRunResult, attemptId: string): Promise<void>;
|
||||
updateProgress(
|
||||
runId: string,
|
||||
progress: number,
|
||||
currentDate: string | undefined,
|
||||
attemptId: string
|
||||
): Promise<void>;
|
||||
fail(runId: string, error: string, attemptId: string): Promise<void>;
|
||||
cancel(runId: string, attemptId: string): Promise<void>;
|
||||
updateControl(
|
||||
runId: string,
|
||||
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null }
|
||||
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null },
|
||||
attemptId: string
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
export class BacktestConflictError extends Error {}
|
||||
export class BacktestLeaseLostError extends BacktestConflictError {}
|
||||
|
||||
/** No database is never a license to execute an unowned job. */
|
||||
export class UnavailableBacktestRunRepository implements BacktestRunRepository {
|
||||
async start(_config: BacktestConfig): Promise<RunIdentity> {
|
||||
private unavailable(): never {
|
||||
throw new Error('Backtest execution requires a PostgreSQL run repository');
|
||||
}
|
||||
async complete(_result: BacktestRunResult): Promise<void> {
|
||||
throw new Error('Backtest run repository is unavailable');
|
||||
async start(_config: BacktestConfig): Promise<RunClaim> {
|
||||
return this.unavailable();
|
||||
}
|
||||
async load(_runId: string): Promise<null> {
|
||||
return this.unavailable();
|
||||
}
|
||||
async rejectPending(_runId: string, _error: string): Promise<void> {
|
||||
this.unavailable();
|
||||
}
|
||||
async heartbeat(_runId: string, _attemptId: string): Promise<{ cancelRequested: boolean }> {
|
||||
return this.unavailable();
|
||||
}
|
||||
async complete(_result: BacktestRunResult, _attemptId: string): Promise<void> {
|
||||
this.unavailable();
|
||||
}
|
||||
async updateProgress(): Promise<void> {
|
||||
throw new Error('Backtest run repository is unavailable');
|
||||
this.unavailable();
|
||||
}
|
||||
async updateControl(): Promise<void> {
|
||||
throw new Error('Backtest run repository is unavailable');
|
||||
this.unavailable();
|
||||
}
|
||||
async fail(_runId: string, _error: string): Promise<void> {
|
||||
throw new Error('Backtest run repository is unavailable');
|
||||
async fail(_runId: string, _error: string, _attemptId: string): Promise<void> {
|
||||
this.unavailable();
|
||||
}
|
||||
async cancel(_runId: string): Promise<void> {
|
||||
throw new Error('Backtest run repository is unavailable');
|
||||
async cancel(_runId: string, _attemptId: string): Promise<void> {
|
||||
this.unavailable();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -136,7 +136,7 @@ export async function registerOrchestratorServices(
|
|||
await modeManager.initializeMode({ mode: 'paper', startingCapital: 100000 });
|
||||
}
|
||||
// Start job consumption only after the shared graph and initial mode are ready.
|
||||
services.queueManager?.getQueue('orchestrator');
|
||||
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
|
||||
}
|
||||
|
||||
// For backward compatibility, export a container getter
|
||||
|
|
|
|||
|
|
@ -17,6 +17,11 @@ export class BacktestHandler extends BaseHandler<OrchestratorServices> {
|
|||
if (typeof payload !== 'object' || payload === null) {
|
||||
throw new Error('Invalid backtest job');
|
||||
}
|
||||
// Durable notifications carry identity only; execution always uses the SQL snapshot.
|
||||
if ('runId' in payload && !('strategy' in payload)) {
|
||||
const { runId } = z.object({ runId: z.string().uuid() }).parse(payload);
|
||||
return this.runner.runQueued(runId);
|
||||
}
|
||||
// Old jobs omitted these fields. Normalize the envelope, never the execution result.
|
||||
const config = { mode: 'backtest', dataFrequency: '1d', ...payload };
|
||||
const results = await this.runner.runBacktest(config);
|
||||
|
|
|
|||
|
|
@ -41,7 +41,11 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
|
||||
const files = readdirSync(migrationsDir)
|
||||
.filter(
|
||||
f => f.endsWith('.sql') && (f.startsWith('001_') || f === '09-backtest-run-contract.sql')
|
||||
f =>
|
||||
f.endsWith('.sql') &&
|
||||
(f.startsWith('001_') ||
|
||||
f === '09-backtest-run-contract.sql' ||
|
||||
f === '10-durable-backtest-dispatch.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { Hono } from 'hono';
|
|||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
||||
|
|
@ -90,7 +89,8 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
backtestId: c.req.param('backtestId'),
|
||||
speedMultiplier: body.speedMultiplier,
|
||||
});
|
||||
return c.json(run, 201);
|
||||
c.header('Location', `/api/v2/runs/${run.id}`);
|
||||
return c.json(run, 202);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
return c.json({ error: 'Failed to create run' }, 500);
|
||||
|
|
@ -146,7 +146,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
app.post('/api/v2/runs/:id/cancel', async c => {
|
||||
try {
|
||||
await backtestService.cancelRun(c.req.param('id'));
|
||||
return c.json({ message: 'Run cancelled' });
|
||||
return c.json({ message: 'Cancellation requested' }, 202);
|
||||
} catch (error) {
|
||||
logger.error('Failed to cancel run', error);
|
||||
return c.json({ error: 'Failed to cancel run' }, 500);
|
||||
|
|
@ -169,20 +169,18 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
try {
|
||||
const runId = c.req.param('id');
|
||||
const body = await c.req.json();
|
||||
const { progress, currentDate } = body;
|
||||
const { progress, currentDate, attemptId } = body;
|
||||
if (typeof attemptId !== 'string') {
|
||||
return c.json({ error: 'Execution attempt ID required' }, 400);
|
||||
}
|
||||
|
||||
// Update run progress in database
|
||||
await backtestService.updateRunProgress(runId, {
|
||||
progress,
|
||||
currentDate,
|
||||
attemptId,
|
||||
});
|
||||
|
||||
// Broadcast via WebSocket if handler is available
|
||||
const wsHandler = getWebSocketHandler();
|
||||
if (wsHandler) {
|
||||
wsHandler.sendProgressUpdate(runId, progress, currentDate);
|
||||
}
|
||||
|
||||
return c.json({ message: 'Progress updated' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to update run progress', error);
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { getLogger } from '@stock-bot/logger';
|
|||
import { initializeStockConfig } from '@stock-bot/stock-config';
|
||||
import { createRoutes } from './routes/create-routes';
|
||||
import { createWebSocketRoute, handleWebSocketConnection } from './routes/websocket.routes';
|
||||
import { BacktestDispatcher } from './services/BacktestDispatcher';
|
||||
import { getWebSocketHandler, type RunSocketData } from './websocket/run-updates';
|
||||
|
||||
// Initialize configuration with service-specific overrides
|
||||
|
|
@ -65,6 +66,15 @@ export async function startServerWithWebSocket() {
|
|||
const diContainer = await createContainer(config);
|
||||
container = diContainer.resolve('serviceContainer');
|
||||
|
||||
if (!container.postgres || !container.queueManager) {
|
||||
throw new Error('Durable backtest dispatch requires PostgreSQL and Redis queues');
|
||||
}
|
||||
const dispatcher = new BacktestDispatcher(
|
||||
container.postgres,
|
||||
container.queueManager.getQueue('{orchestrator_orchestrator}', { workers: 0 }),
|
||||
logger
|
||||
);
|
||||
|
||||
// Create HTTP routes
|
||||
const routes = createRoutes(container, security);
|
||||
|
||||
|
|
@ -125,15 +135,29 @@ export async function startServerWithWebSocket() {
|
|||
}
|
||||
|
||||
logger.info(`Web API service with WebSocket support started on port ${server.port}`);
|
||||
dispatcher.start();
|
||||
logger.info(`WebSocket endpoint available at ws://localhost:${server.port}/ws`);
|
||||
|
||||
// Handle shutdown
|
||||
process.on('SIGINT', async () => {
|
||||
let shuttingDown = false;
|
||||
const shutdown = async () => {
|
||||
if (shuttingDown) {
|
||||
return;
|
||||
}
|
||||
shuttingDown = true;
|
||||
logger.info('Shutting down server...');
|
||||
const deadline = setTimeout(() => process.exit(1), 10_000);
|
||||
deadline.unref();
|
||||
await dispatcher.shutdown();
|
||||
getWebSocketHandler()?.cleanup();
|
||||
await server.stop(true);
|
||||
await container?.queueManager?.shutdown();
|
||||
await diContainer.dispose();
|
||||
clearTimeout(deadline);
|
||||
process.exit(0);
|
||||
});
|
||||
};
|
||||
process.on('SIGINT', () => void shutdown());
|
||||
process.on('SIGTERM', () => void shutdown());
|
||||
} catch (error) {
|
||||
logger.fatal('Failed to start web API service', { error });
|
||||
process.exit(1);
|
||||
|
|
|
|||
105
apps/stock/web-api/src/services/BacktestDispatcher.ts
Normal file
105
apps/stock/web-api/src/services/BacktestDispatcher.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
import type { Logger, PostgresClient, Queue } from '@stock-bot/services';
|
||||
|
||||
/** PostgreSQL is the source of truth; Redis jobs are repeatable delivery notifications. */
|
||||
export class BacktestDispatcher {
|
||||
private timer?: ReturnType<typeof setInterval>;
|
||||
private inFlight?: Promise<void>;
|
||||
private closing = false;
|
||||
|
||||
constructor(
|
||||
private readonly postgres: Pick<PostgresClient, 'transaction'>,
|
||||
private readonly queue: Pick<Queue, 'add'>,
|
||||
private readonly logger: Pick<Logger, 'error'>,
|
||||
private readonly options = { intervalMs: 5_000, republishMs: 30_000, maxAttempts: 3 }
|
||||
) {}
|
||||
|
||||
start() {
|
||||
this.timer ??= setInterval(
|
||||
() =>
|
||||
void this.tick().catch(error => {
|
||||
this.logger.error('Backtest dispatch/recovery failed; will retry', { error });
|
||||
}),
|
||||
this.options.intervalMs
|
||||
);
|
||||
this.timer.unref();
|
||||
void this.tick().catch(error =>
|
||||
this.logger.error('Initial backtest dispatch failed; will retry', { error })
|
||||
);
|
||||
}
|
||||
|
||||
tick(): Promise<void> {
|
||||
if (this.closing) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return (this.inFlight ??= this.dispatch().finally(() => {
|
||||
this.inFlight = undefined;
|
||||
}));
|
||||
}
|
||||
|
||||
async shutdown() {
|
||||
this.closing = true;
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer);
|
||||
}
|
||||
await this.inFlight;
|
||||
}
|
||||
|
||||
private async dispatch() {
|
||||
// Recovery is independent of Redis availability. Every terminal write fences the old owner.
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
`UPDATE runs SET
|
||||
status = CASE WHEN cancel_requested THEN 'cancelled'::run_status
|
||||
WHEN attempt_number >= $1 THEN 'failed'::run_status ELSE 'pending'::run_status END,
|
||||
error = CASE WHEN cancel_requested THEN NULL
|
||||
WHEN attempt_number >= $1 THEN 'Execution lease expired; retry limit reached' ELSE NULL END,
|
||||
completed_at = CASE WHEN cancel_requested OR attempt_number >= $1 THEN NOW() ELSE NULL END,
|
||||
attempt_id = NULL, lease_expires_at = NULL, updated_at = NOW()
|
||||
WHERE status IN ('running', 'paused') AND lease_expires_at <= clock_timestamp()`,
|
||||
[this.options.maxAttempts]
|
||||
);
|
||||
});
|
||||
|
||||
// Reserve a small batch in SQL, then publish outside the transaction. A crash between these
|
||||
// steps only delays redelivery; it cannot lose the intent or hold DB locks during a Redis outage.
|
||||
const rows = await this.postgres.transaction(async client => {
|
||||
const due = await client.query<{ run_id: string }>(`SELECT d.run_id
|
||||
FROM backtest_dispatch d JOIN runs r ON r.id = d.run_id
|
||||
WHERE r.status = 'pending' AND NOT r.cancel_requested AND d.next_publish_at <= NOW()
|
||||
ORDER BY d.next_publish_at LIMIT 20 FOR UPDATE OF d SKIP LOCKED`);
|
||||
for (const row of due.rows) {
|
||||
await client.query(
|
||||
`UPDATE backtest_dispatch
|
||||
SET next_publish_at = NOW() + $2::interval
|
||||
WHERE run_id = $1`,
|
||||
[row.run_id, `${this.options.republishMs} milliseconds`]
|
||||
);
|
||||
}
|
||||
return due.rows;
|
||||
});
|
||||
for (const row of rows) {
|
||||
await this.queue.add(
|
||||
'run-backtest',
|
||||
{
|
||||
handler: 'orchestrator',
|
||||
operation: 'run-backtest',
|
||||
payload: { runId: row.run_id },
|
||||
},
|
||||
{
|
||||
jobId: `backtest-${row.run_id}`,
|
||||
attempts: 3,
|
||||
backoff: { type: 'fixed', delay: 1_000 },
|
||||
removeOnComplete: true,
|
||||
removeOnFail: true,
|
||||
}
|
||||
);
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
`UPDATE backtest_dispatch
|
||||
SET last_published_at = NOW(), publish_count = publish_count + 1 WHERE run_id = $1`,
|
||||
[row.run_id]
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -49,6 +49,8 @@ export interface Run {
|
|||
completedAt?: Date;
|
||||
pausedAt?: Date;
|
||||
progress: number;
|
||||
cancelRequested: boolean;
|
||||
attemptNumber: number;
|
||||
currentDate?: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
|
|
@ -200,29 +202,69 @@ export class BacktestServiceV2 {
|
|||
async createRun(request: RunRequest): Promise<Run> {
|
||||
const runId = uuidv4();
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
const parent = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
request.backtestId,
|
||||
]);
|
||||
if (!parent.rows.length) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||
const multiplier = request.speedMultiplier ?? null;
|
||||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||
throw new Error('Speed multiplier must be positive or null');
|
||||
}
|
||||
const snapshot = {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
name: definition.name,
|
||||
mode: 'backtest',
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
dataFrequency: definition.config.dataFrequency ?? '1d',
|
||||
commission: definition.config.commission ?? 0.001,
|
||||
slippage: definition.config.slippage ?? 0.0001,
|
||||
speed:
|
||||
multiplier === null
|
||||
? 'max'
|
||||
: multiplier >= 10
|
||||
? '10x'
|
||||
: multiplier >= 5
|
||||
? '5x'
|
||||
: multiplier >= 2
|
||||
? '2x'
|
||||
: 'realtime',
|
||||
};
|
||||
if (
|
||||
!snapshot.strategy ||
|
||||
!Array.isArray(snapshot.symbols) ||
|
||||
!snapshot.symbols.length ||
|
||||
snapshot.symbols.some(symbol => typeof symbol !== 'string' || !symbol.length) ||
|
||||
!Number.isFinite(snapshot.initialCapital) ||
|
||||
snapshot.initialCapital <= 0 ||
|
||||
Date.parse(snapshot.endDate) <= Date.parse(snapshot.startDate) ||
|
||||
!['1m', '5m', '15m', '1h', '1d'].includes(String(snapshot.dataFrequency)) ||
|
||||
typeof snapshot.commission !== 'number' ||
|
||||
!Number.isFinite(snapshot.commission) ||
|
||||
typeof snapshot.slippage !== 'number' ||
|
||||
!Number.isFinite(snapshot.slippage)
|
||||
) {
|
||||
throw new Error('Invalid backtest execution configuration');
|
||||
}
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb
|
||||
FROM runs WHERE backtest_id = $2 RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
request.backtestId,
|
||||
request.speedMultiplier === undefined ? null : request.speedMultiplier,
|
||||
]
|
||||
[runId, request.backtestId, multiplier, JSON.stringify(snapshot)]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
return at(result.rows, 0);
|
||||
});
|
||||
const run = this.mapRun(row);
|
||||
// startRun handles dispatch failures; the runner owns execution and terminal persistence.
|
||||
void this.startRun(run);
|
||||
return run;
|
||||
return this.mapRun(row);
|
||||
}
|
||||
|
||||
async getRun(id: string): Promise<Run | null> {
|
||||
|
|
@ -248,14 +290,17 @@ export class BacktestServiceV2 {
|
|||
|
||||
async updateRunProgress(
|
||||
id: string,
|
||||
updates: { progress?: number; currentDate?: Date }
|
||||
updates: { progress?: number; currentDate?: Date; attemptId: string }
|
||||
): Promise<void> {
|
||||
const result = await this.container.postgres.query(
|
||||
const result = await this.container.postgres.transaction(async client => {
|
||||
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [id]);
|
||||
return client.query(
|
||||
`UPDATE runs
|
||||
SET progress = COALESCE($2, progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') RETURNING status`,
|
||||
[id, updates.progress ?? null, updates.currentDate ?? null]
|
||||
SET progress = GREATEST(COALESCE($2::numeric, progress), progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') AND attempt_id = $4 AND lease_expires_at > clock_timestamp() RETURNING status`,
|
||||
[id, updates.progress ?? null, updates.currentDate ?? null, updates.attemptId]
|
||||
);
|
||||
});
|
||||
const row = result.rows[0];
|
||||
if (row) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
|
|
@ -273,7 +318,21 @@ export class BacktestServiceV2 {
|
|||
await this.sendControl(id, 'resume');
|
||||
}
|
||||
async cancelRun(id: string): Promise<void> {
|
||||
await this.sendControl(id, 'stop');
|
||||
const result = await this.container.postgres.query(
|
||||
`UPDATE runs SET cancel_requested = TRUE,
|
||||
status = CASE WHEN status = 'pending' THEN 'cancelled'::run_status ELSE status END,
|
||||
completed_at = CASE WHEN status = 'pending' THEN NOW() ELSE completed_at END, updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('pending', 'running', 'paused', 'cancelled') RETURNING status`,
|
||||
[id]
|
||||
);
|
||||
const row = result.rows[0];
|
||||
if (!row) {
|
||||
throw new Error('No cancellable run found');
|
||||
}
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
type: 'run_update',
|
||||
data: { status: row.status, cancelRequested: true, timestamp: new Date().toISOString() },
|
||||
});
|
||||
}
|
||||
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
|
||||
await this.sendControl(id, 'speed', { speed: speedMultiplier });
|
||||
|
|
@ -394,94 +453,6 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
// Private methods
|
||||
private async startRun(run: Run): Promise<void> {
|
||||
try {
|
||||
const backtest = await this.getBacktest(run.backtestId);
|
||||
if (!backtest) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
this.getWebSocketHandler()?.sendProgressUpdate(run.id, 0);
|
||||
const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
runId: run.id,
|
||||
backtestId: backtest.id,
|
||||
name: backtest.name,
|
||||
mode: 'backtest',
|
||||
startDate: backtest.startDate.toISOString(),
|
||||
endDate: backtest.endDate.toISOString(),
|
||||
symbols: backtest.symbols,
|
||||
strategy: backtest.strategy,
|
||||
initialCapital: backtest.initialCapital,
|
||||
config: backtest.config,
|
||||
dataFrequency: backtest.config.dataFrequency ?? '1d',
|
||||
commission: backtest.config.commission ?? 0.001,
|
||||
slippage: backtest.config.slippage ?? 0.0001,
|
||||
speed:
|
||||
run.speedMultiplier === null
|
||||
? 'max'
|
||||
: run.speedMultiplier >= 10
|
||||
? '10x'
|
||||
: run.speedMultiplier >= 5
|
||||
? '5x'
|
||||
: run.speedMultiplier >= 2
|
||||
? '2x'
|
||||
: 'realtime',
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
if (response.status === 409) {
|
||||
const outcome: unknown = await response
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => null);
|
||||
if (
|
||||
outcome &&
|
||||
typeof outcome === 'object' &&
|
||||
'status' in outcome &&
|
||||
outcome.status === 'cancelled' &&
|
||||
(await this.getRun(run.id))?.status === 'cancelled'
|
||||
) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(run.id, {
|
||||
type: 'run_update',
|
||||
data: { status: 'cancelled', timestamp: new Date().toISOString() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error(`Orchestrator returned ${response.status}: ${await response.text()}`);
|
||||
}
|
||||
const result: BacktestRunResult = await response.json();
|
||||
if (
|
||||
result.runId !== run.id ||
|
||||
result.backtestId !== backtest.id ||
|
||||
!['completed', 'cancelled'].includes(result.status)
|
||||
) {
|
||||
throw new Error('Invalid orchestrator run response');
|
||||
}
|
||||
// Results and terminal state are already committed by the orchestrator.
|
||||
this.getWebSocketHandler()?.sendCompletion(run.id, result);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logger.error('Backtest dispatch failed', { runId: run.id, error });
|
||||
// A broken HTTP connection must not overwrite a claimed or completed execution.
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`UPDATE runs SET status = 'failed', error = $2,
|
||||
completed_at = NOW(), updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
|
||||
[run.id, message]
|
||||
);
|
||||
} catch (persistenceError) {
|
||||
logger.error('Could not record backtest dispatch failure', {
|
||||
runId: run.id,
|
||||
persistenceError,
|
||||
});
|
||||
}
|
||||
this.getWebSocketHandler()?.sendError(run.id, message);
|
||||
}
|
||||
}
|
||||
|
||||
private mapBacktest(row: QueryResultRow): Backtest {
|
||||
return {
|
||||
id: row.id,
|
||||
|
|
@ -515,6 +486,8 @@ export class BacktestServiceV2 {
|
|||
completedAt: row.completed_at,
|
||||
pausedAt: row.paused_at,
|
||||
progress: parseFloat(row.progress),
|
||||
cancelRequested: row.cancel_requested === true,
|
||||
attemptNumber: Number(row.attempt_number ?? 0),
|
||||
currentDate: row.current_simulation_date,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
|
|
|
|||
|
|
@ -13,15 +13,29 @@ export interface RunUpdateMessage {
|
|||
data: unknown;
|
||||
}
|
||||
|
||||
export function createWebSocketHandler(_container: IServiceContainer) {
|
||||
export function createWebSocketHandler(container: IServiceContainer) {
|
||||
const connections = new Map<string, Set<RunSocket>>();
|
||||
const completionTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const snapshots = new Map<string, string>();
|
||||
let pollTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let polling: Promise<void> | undefined;
|
||||
let stopped = false;
|
||||
return {
|
||||
handleConnection(ws: RunSocket, runId: string) {
|
||||
const clients = connections.get(runId) ?? new Set<RunSocket>();
|
||||
clients.add(ws);
|
||||
connections.set(runId, clients);
|
||||
ws.send(JSON.stringify({ type: 'connected', runId, timestamp: new Date().toISOString() }));
|
||||
if (container.postgres && !pollTimer) {
|
||||
pollTimer = setInterval(
|
||||
() =>
|
||||
void this.refreshRunUpdates().catch(error => {
|
||||
logger.warn('Could not refresh persisted run updates', { error });
|
||||
}),
|
||||
1000
|
||||
);
|
||||
pollTimer.unref();
|
||||
}
|
||||
},
|
||||
handleMessage(ws: RunSocket, payload: string | Buffer) {
|
||||
try {
|
||||
|
|
@ -44,7 +58,60 @@ export function createWebSocketHandler(_container: IServiceContainer) {
|
|||
clients?.delete(ws);
|
||||
if (clients?.size === 0) {
|
||||
connections.delete(runId);
|
||||
snapshots.delete(runId);
|
||||
if (!connections.size && pollTimer) {
|
||||
clearInterval(pollTimer);
|
||||
pollTimer = undefined;
|
||||
}
|
||||
}
|
||||
},
|
||||
/** Notifications are a projection of committed SQL state, independent of the executor process. */
|
||||
refreshRunUpdates(): Promise<void> {
|
||||
if (stopped || !container.postgres || !connections.size) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
const postgres = container.postgres;
|
||||
return (polling ??= (async () => {
|
||||
const result = await postgres.query(
|
||||
`SELECT id, status, progress, current_simulation_date,
|
||||
error, cancel_requested, attempt_number, updated_at FROM runs WHERE id::text = ANY($1::text[])`,
|
||||
[[...connections.keys()]]
|
||||
);
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
for (const row of result.rows) {
|
||||
const fingerprint = JSON.stringify(row);
|
||||
if (snapshots.get(row.id) === fingerprint) {
|
||||
continue;
|
||||
}
|
||||
snapshots.set(row.id, fingerprint);
|
||||
this.broadcastRunUpdate(row.id, {
|
||||
data: {
|
||||
status: row.status,
|
||||
progress: Number(row.progress),
|
||||
currentDate: row.current_simulation_date,
|
||||
cancelRequested: row.cancel_requested,
|
||||
attemptNumber: row.attempt_number,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
// Terminal rows do not change after commit, so these events are emitted once per subscription.
|
||||
if (row.status === 'completed') {
|
||||
this.sendCompletion(row.id);
|
||||
} else if (row.status === 'failed') {
|
||||
this.sendError(row.id, String(row.error ?? 'Backtest failed'));
|
||||
} else if (row.status === 'running' || row.status === 'paused') {
|
||||
this.sendProgressUpdate(
|
||||
row.id,
|
||||
Number(row.progress),
|
||||
row.current_simulation_date?.toISOString()
|
||||
);
|
||||
}
|
||||
}
|
||||
})().finally(() => {
|
||||
polling = undefined;
|
||||
}));
|
||||
},
|
||||
broadcastRunUpdate(runId: string, update: Partial<RunUpdateMessage>) {
|
||||
const message: RunUpdateMessage = {
|
||||
|
|
@ -94,6 +161,12 @@ export function createWebSocketHandler(_container: IServiceContainer) {
|
|||
return connections.get(runId)?.size ?? 0;
|
||||
},
|
||||
cleanup() {
|
||||
stopped = true;
|
||||
if (pollTimer) {
|
||||
clearInterval(pollTimer);
|
||||
}
|
||||
pollTimer = undefined;
|
||||
snapshots.clear();
|
||||
for (const timer of completionTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -215,14 +215,16 @@ export function useBacktestV2(): UseBacktestV2Return {
|
|||
}, [currentRun]);
|
||||
|
||||
const cancelRun = useCallback(async () => {
|
||||
if (!currentRun || (currentRun.status !== 'running' && currentRun.status !== 'paused')) {
|
||||
if (!currentRun || !['pending', 'running', 'paused'].includes(currentRun.status)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await backtestApiV2.cancelRun(currentRun.id);
|
||||
setCurrentRun(prev => (prev ? { ...prev, status: 'cancelled' } : null));
|
||||
stopMonitoringRun();
|
||||
// Acceptance is not completion: keep monitoring the owner's persisted acknowledgement.
|
||||
const updated = await backtestApiV2.getRun(currentRun.id);
|
||||
setCurrentRun(updated);
|
||||
setRuns(prev => prev.map(run => (run.id === updated.id ? updated : run)));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to cancel run');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,8 @@ export interface Run {
|
|||
completedAt?: string;
|
||||
pausedAt?: string;
|
||||
progress: number;
|
||||
cancelRequested?: boolean;
|
||||
attemptNumber?: number;
|
||||
currentSimulationDate?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
|
|
|
|||
43
database/postgres/init/10-durable-backtest-dispatch.sql
Normal file
43
database/postgres/init/10-durable-backtest-dispatch.sql
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
-- Additive migration. Stop old orchestrators before deploying lease-aware workers.
|
||||
ALTER TABLE runs ADD COLUMN IF NOT EXISTS request_snapshot JSONB;
|
||||
ALTER TABLE runs ADD COLUMN IF NOT EXISTS attempt_id UUID;
|
||||
ALTER TABLE runs ADD COLUMN IF NOT EXISTS attempt_number INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE runs ADD COLUMN IF NOT EXISTS lease_expires_at TIMESTAMPTZ;
|
||||
ALTER TABLE runs ADD COLUMN IF NOT EXISTS cancel_requested BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS backtest_dispatch (
|
||||
run_id UUID PRIMARY KEY REFERENCES runs(id) ON DELETE CASCADE,
|
||||
next_publish_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
last_published_at TIMESTAMPTZ,
|
||||
publish_count INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS backtest_dispatch_due ON backtest_dispatch(next_publish_at);
|
||||
CREATE INDEX IF NOT EXISTS runs_expired_lease ON runs(lease_expires_at)
|
||||
WHERE status IN ('running', 'paused');
|
||||
|
||||
-- Legacy pending runs did not capture a snapshot. Freeze their current definition once.
|
||||
UPDATE runs r SET request_snapshot = jsonb_build_object(
|
||||
'mode', 'backtest', 'runId', r.id, 'backtestId', b.id, 'name', b.name,
|
||||
'strategy', b.strategy, 'symbols', b.symbols,
|
||||
'startDate', to_char(b.start_date AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
|
||||
'endDate', to_char(b.end_date AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
|
||||
'initialCapital', b.initial_capital,
|
||||
'config', COALESCE(b.config, '{}'::jsonb),
|
||||
'dataFrequency', COALESCE(b.config->>'dataFrequency', '1d'),
|
||||
'commission', COALESCE(b.config->'commission', '0.001'::jsonb),
|
||||
'slippage', COALESCE(b.config->'slippage', '0.0001'::jsonb),
|
||||
'speed', CASE WHEN r.speed_multiplier IS NULL THEN 'max'
|
||||
WHEN r.speed_multiplier >= 10 THEN '10x'
|
||||
WHEN r.speed_multiplier >= 5 THEN '5x'
|
||||
WHEN r.speed_multiplier >= 2 THEN '2x' ELSE 'realtime' END
|
||||
) FROM backtests b WHERE b.id = r.backtest_id AND r.status = 'pending'
|
||||
AND r.request_snapshot IS NULL;
|
||||
|
||||
-- There is no safe way to identify the owner of a pre-lease active execution.
|
||||
UPDATE runs SET status = 'failed', completed_at = NOW(), updated_at = NOW(),
|
||||
error = 'Legacy execution has no lease; create a new run after deployment'
|
||||
WHERE status IN ('running', 'paused') AND attempt_id IS NULL;
|
||||
|
||||
INSERT INTO backtest_dispatch (run_id)
|
||||
SELECT id FROM runs WHERE status = 'pending' AND request_snapshot IS NOT NULL
|
||||
ON CONFLICT (run_id) DO NOTHING;
|
||||
|
|
@ -73,8 +73,8 @@ export function registerApplicationServices(
|
|||
db: config.redis.db,
|
||||
},
|
||||
defaultQueueOptions: {
|
||||
workers: defined(config.queue).workers || 1,
|
||||
concurrency: defined(config.queue).concurrency || 1,
|
||||
workers: defined(config.queue).workers ?? 1,
|
||||
concurrency: defined(config.queue).concurrency ?? 1,
|
||||
defaultJobOptions: defined(config.queue).defaultJobOptions,
|
||||
},
|
||||
enableScheduledJobs: defined(config.queue).enableScheduledJobs ?? true,
|
||||
|
|
|
|||
|
|
@ -554,8 +554,8 @@ export class QueueManager {
|
|||
}
|
||||
}
|
||||
|
||||
const workerCount = this.config.defaultQueueOptions?.workers || 1;
|
||||
const concurrency = this.config.defaultQueueOptions?.concurrency || 1;
|
||||
const workerCount = this.config.defaultQueueOptions?.workers ?? 1;
|
||||
const concurrency = this.config.defaultQueueOptions?.concurrency ?? 1;
|
||||
|
||||
if (workerCount > 0) {
|
||||
queue.startWorkersManually(workerCount, concurrency);
|
||||
|
|
|
|||
|
|
@ -56,7 +56,8 @@ export class Queue {
|
|||
|
||||
// Initialize BullMQ queue
|
||||
this.bullQueue = new BullQueue(queueName, {
|
||||
connection,
|
||||
// Publishing must fail promptly during outages; durable producers retain their intent.
|
||||
connection: { ...connection, maxRetriesPerRequest: 1, enableOfflineQueue: false },
|
||||
defaultJobOptions: {
|
||||
removeOnComplete: 100,
|
||||
removeOnFail: 100,
|
||||
|
|
@ -68,6 +69,9 @@ export class Queue {
|
|||
...defaultJobOptions,
|
||||
},
|
||||
});
|
||||
this.bullQueue.on('error', error =>
|
||||
this.logger.error('Queue connection error', { queueName, error })
|
||||
);
|
||||
|
||||
// Initialize queue events if workers will be used
|
||||
if (config.workers && config.workers > 0) {
|
||||
|
|
|
|||
|
|
@ -1,39 +1,14 @@
|
|||
import type { RedisConfig } from './types';
|
||||
|
||||
/**
|
||||
* Get Redis connection configuration with retry settings
|
||||
*/
|
||||
/** Honor the explicit endpoint, including isolated test Redis instances. */
|
||||
export function getRedisConnection(config: RedisConfig) {
|
||||
const isTest = process.env.NODE_ENV === 'test' || process.env['BUNIT'] === '1';
|
||||
|
||||
// In test mode, always use localhost
|
||||
const testConfig = isTest
|
||||
? {
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
}
|
||||
: config;
|
||||
|
||||
const baseConfig = {
|
||||
host: testConfig.host,
|
||||
port: testConfig.port,
|
||||
password: testConfig.password,
|
||||
db: testConfig.db,
|
||||
maxRetriesPerRequest: null, // Required by BullMQ
|
||||
return {
|
||||
...config,
|
||||
maxRetriesPerRequest: null, // Workers must survive transient outages.
|
||||
enableReadyCheck: false,
|
||||
connectTimeout: isTest ? 1000 : 3000,
|
||||
lazyConnect: false, // Changed from true to ensure connection is established immediately
|
||||
keepAlive: true, // Changed from false to maintain persistent connections
|
||||
retryStrategy: (times: number) => {
|
||||
const maxRetries = isTest ? 1 : 3;
|
||||
if (times > maxRetries) {
|
||||
return null; // Stop retrying
|
||||
}
|
||||
const delay = isTest ? 100 : Math.min(times * 100, 3000);
|
||||
return delay;
|
||||
},
|
||||
connectTimeout: 3000,
|
||||
lazyConnect: false,
|
||||
keepAlive: 10000,
|
||||
retryStrategy: (times: number) => Math.min(times * 100, 3000),
|
||||
};
|
||||
|
||||
// In non-test mode, spread config first to preserve additional properties, then override with our settings
|
||||
return isTest ? baseConfig : { ...config, ...baseConfig };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ export interface JobData<T = unknown> {
|
|||
* Queue job options
|
||||
*/
|
||||
export interface JobOptions {
|
||||
/** Stable identity for idempotent publication (BullMQ IDs cannot contain colons). */
|
||||
jobId?: string;
|
||||
priority?: number;
|
||||
delay?: number;
|
||||
attempts?: number;
|
||||
|
|
|
|||
|
|
@ -4,6 +4,10 @@ if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
|||
'Set PIPELINE_TEST_DATABASE_URL to a disposable stock_bot_safety database; tests create/drop isolated schemas'
|
||||
);
|
||||
}
|
||||
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
if (!redisUrl || new URL(redisUrl).pathname !== '/15') {
|
||||
throw new Error('Set BACKTEST_TEST_REDIS_URL to a dedicated Redis fixture using database 15');
|
||||
}
|
||||
const child = Bun.spawn([process.execPath, 'test', 'test/postgres/'], {
|
||||
stdin: 'inherit',
|
||||
stdout: 'inherit',
|
||||
|
|
|
|||
51
scripts/test/durable-notifications.test.ts
Normal file
51
scripts/test/durable-notifications.test.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import type { ServerWebSocket } from 'bun';
|
||||
import { expect, test } from 'bun:test';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import {
|
||||
createWebSocketHandler,
|
||||
type RunSocketData,
|
||||
} from '../../apps/stock/web-api/src/websocket/run-updates';
|
||||
|
||||
test('dashboard notifications reflect committed state across owners and emit completion once', async () => {
|
||||
const id = '39b3ad03-361c-4ea2-8f5e-2fd702fa3f20';
|
||||
const messages: { type: string; data?: Record<string, unknown> }[] = [];
|
||||
let row = {
|
||||
id,
|
||||
status: 'running',
|
||||
progress: '17',
|
||||
attempt_number: 2,
|
||||
cancel_requested: false,
|
||||
current_simulation_date: new Date('2024-01-02'),
|
||||
updated_at: new Date(),
|
||||
};
|
||||
const postgres = {
|
||||
async query(_sql: string, params: unknown[]) {
|
||||
expect(params).toEqual([[id]]);
|
||||
return { rows: [row] };
|
||||
},
|
||||
} as unknown as PostgresClient;
|
||||
const handler = createWebSocketHandler({ logger: getLogger('notification-test'), postgres });
|
||||
const ws = {
|
||||
data: { runId: id },
|
||||
send(message: string) {
|
||||
messages.push(JSON.parse(message));
|
||||
},
|
||||
close() {},
|
||||
} as unknown as ServerWebSocket<RunSocketData>;
|
||||
try {
|
||||
handler.handleConnection(ws, id);
|
||||
await handler.refreshRunUpdates();
|
||||
expect(messages.find(message => message.type === 'run_update')?.data).toMatchObject({
|
||||
status: 'running',
|
||||
attemptNumber: 2,
|
||||
progress: 17,
|
||||
});
|
||||
row = { ...row, status: 'completed', progress: '100' };
|
||||
await handler.refreshRunUpdates();
|
||||
await handler.refreshRunUpdates();
|
||||
expect(messages.filter(message => message.type === 'completed')).toHaveLength(1);
|
||||
} finally {
|
||||
handler.cleanup();
|
||||
}
|
||||
});
|
||||
40
test/fixtures/backtest-crash-owner.ts
vendored
Normal file
40
test/fixtures/backtest-crash-owner.ts
vendored
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
/** Dedicated fixture process: claim a real SQL run, heartbeat, then await a hard kill. */
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const schema = process.env.BACKTEST_FIXTURE_SCHEMA;
|
||||
const runId = process.env.BACKTEST_FIXTURE_RUN_ID;
|
||||
if (
|
||||
!url ||
|
||||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
|
||||
!schema ||
|
||||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
|
||||
!runId
|
||||
)
|
||||
throw new Error('Unsafe crash fixture target');
|
||||
const logger = getLogger('crash-owner');
|
||||
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 500);
|
||||
const runner = new BacktestRunner({
|
||||
engine: new RustBacktestAdapter({ logger }),
|
||||
engineName: 'native',
|
||||
repository,
|
||||
logger,
|
||||
heartbeatMs: 50,
|
||||
prepare: async () => {
|
||||
process.send?.({ type: 'claimed' });
|
||||
await new Promise<void>(() => {});
|
||||
},
|
||||
});
|
||||
await runner.runQueued(runId);
|
||||
|
|
@ -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');
|
||||
|
|
|
|||
494
test/postgres/durable-backtest.test.ts
Normal file
494
test/postgres/durable-backtest.test.ts
Normal file
|
|
@ -0,0 +1,494 @@
|
|||
import { fork } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
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 { 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';
|
||||
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
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 { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('durable-backtest-test');
|
||||
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();
|
||||
});
|
||||
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;
|
||||
await sleep(20);
|
||||
}
|
||||
throw new Error('Timed out waiting for durable workflow');
|
||||
}
|
||||
|
||||
async function fixture() {
|
||||
if (
|
||||
!url ||
|
||||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
|
||||
!redisUrl ||
|
||||
new URL(redisUrl).pathname !== '/15'
|
||||
) {
|
||||
throw new Error('Dedicated stock_bot_safety database and Redis database 15 required');
|
||||
}
|
||||
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}` });
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text NOT NULL, strategy text NOT NULL, symbols jsonb NOT NULL,
|
||||
start_date timestamptz NOT NULL, end_date timestamptz NOT NULL, initial_capital numeric NOT NULL, config jsonb,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
|
||||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id) ON DELETE CASCADE, 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,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id) ON DELETE CASCADE, completed_at timestamptz,
|
||||
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb, execution_time numeric);`);
|
||||
for (const filename of ['09-backtest-run-contract.sql', '10-durable-backtest-dispatch.sql']) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const endpoint = new URL(redisUrl);
|
||||
const redis = {
|
||||
host: endpoint.hostname,
|
||||
port: Number(endpoint.port || 6379),
|
||||
db: 15,
|
||||
...(endpoint.password ? { password: decodeURIComponent(endpoint.password) } : {}),
|
||||
};
|
||||
const queueName = `stock-bot-safety-${randomUUID()}`;
|
||||
const queue = new Queue(queueName, redis, {}, { workers: 0 }, logger);
|
||||
await queue.getBullQueue().waitUntilReady();
|
||||
cleanup.push(async () => {
|
||||
await queue.getBullQueue().obliterate({ force: true });
|
||||
await queue.close();
|
||||
});
|
||||
const dispatcher = new BacktestDispatcher(postgres, queue, logger, {
|
||||
intervalMs: 20,
|
||||
republishMs: 50,
|
||||
maxAttempts: 3,
|
||||
});
|
||||
cleanup.push(() => dispatcher.shutdown());
|
||||
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'],
|
||||
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 }
|
||||
);
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
|
||||
const engine = new RustBacktestAdapter(
|
||||
{
|
||||
logger,
|
||||
custom: {
|
||||
StorageService: {
|
||||
async getHistoricalBars() {
|
||||
return Array.from({ length: 70 }, (_, i) => {
|
||||
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
|
||||
return {
|
||||
timestamp: new Date(Date.parse(definition.startDate.toISOString()) + i * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
},
|
||||
} as unknown as StorageService,
|
||||
},
|
||||
},
|
||||
{ timeoutMs: 5_000 }
|
||||
);
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository,
|
||||
logger,
|
||||
heartbeatMs: 50,
|
||||
});
|
||||
cleanup.push(() => runner.shutdown());
|
||||
const enqueueWorker = () => {
|
||||
const registry = new HandlerRegistry();
|
||||
registry.registerConfiguration({
|
||||
name: 'orchestrator',
|
||||
operations: {
|
||||
'run-backtest': async payload => runner.runQueued((payload as { runId: string }).runId),
|
||||
},
|
||||
});
|
||||
const worker = new Queue(
|
||||
queueName,
|
||||
redis,
|
||||
{},
|
||||
{ workers: 1, concurrency: 1, handlerRegistry: registry },
|
||||
logger
|
||||
);
|
||||
cleanup.push(async () => {
|
||||
await runner.shutdown();
|
||||
await worker.close();
|
||||
});
|
||||
return worker;
|
||||
};
|
||||
const snapshot = async (runId: string) =>
|
||||
BacktestConfigSchema.parse(
|
||||
(await pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [runId])).rows[0]
|
||||
.request_snapshot
|
||||
);
|
||||
const expire = async (runId: string) => {
|
||||
await pool.query(
|
||||
"UPDATE runs SET lease_expires_at = NOW() - INTERVAL '1 second' WHERE id = $1",
|
||||
[runId]
|
||||
);
|
||||
};
|
||||
return {
|
||||
schema,
|
||||
pool,
|
||||
postgres,
|
||||
api,
|
||||
definition,
|
||||
repository,
|
||||
runner,
|
||||
engine,
|
||||
queue,
|
||||
dispatcher,
|
||||
enqueueWorker,
|
||||
snapshot,
|
||||
expire,
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => {
|
||||
test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => {
|
||||
const f = await fixture();
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION reject_dispatch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
RAISE EXCEPTION 'injected outbox failure'; END $$;
|
||||
CREATE TRIGGER reject_dispatch BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_dispatch();`);
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow(
|
||||
'injected outbox'
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
await f.pool.query('DROP TRIGGER reject_dispatch ON backtest_dispatch');
|
||||
const response = await createBacktestV2Routes({ postgres: f.postgres, logger }).request(
|
||||
`/api/v2/backtests/${f.definition.id}/runs`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }
|
||||
);
|
||||
expect(response.status).toBe(202);
|
||||
const run = (await response.json()) as { id: string; status: string };
|
||||
expect(response.headers.get('location')).toBe(`/api/v2/runs/${run.id}`);
|
||||
expect(f.queue.getWorkerCount()).toBe(0);
|
||||
expect(run.status).toBe('pending');
|
||||
expect(
|
||||
(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'],
|
||||
});
|
||||
// A fresh dispatcher models an API restart after SQL commit but before the first publish.
|
||||
const restarted = new BacktestDispatcher(f.postgres, f.queue, logger);
|
||||
await restarted.tick();
|
||||
await restarted.shutdown();
|
||||
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']);
|
||||
expect(result?.config.parameters.fastPeriod).toBe(3);
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
|
||||
});
|
||||
|
||||
test('duplicate deliveries and competing claims execute once and persist exactly one result', async () => {
|
||||
const f = await fixture();
|
||||
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),
|
||||
]);
|
||||
expect(claims.filter(result => result.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(claims.filter(result => result.status === 'rejected')).toHaveLength(1);
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
f.enqueueWorker();
|
||||
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
|
||||
await f.runner.runQueued(run.id);
|
||||
await f.runner.runQueued(run.id);
|
||||
await f.queue.add('duplicate', {
|
||||
handler: 'orchestrator',
|
||||
operation: 'run-backtest',
|
||||
payload: { runId: run.id },
|
||||
});
|
||||
await until(async () => (await f.queue.getStats()).completed > 0);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows
|
||||
).toHaveLength(1);
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2);
|
||||
});
|
||||
|
||||
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));
|
||||
await f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
const replacement = await f.repository.start(await f.snapshot(run.id));
|
||||
await expect(f.repository.heartbeat(run.id, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
await expect(
|
||||
f.repository.updateProgress(run.id, 99, undefined, old.attemptId)
|
||||
).rejects.toBeInstanceOf(BacktestLeaseLostError);
|
||||
await expect(
|
||||
f.repository.updateControl(run.id, { status: 'paused' }, old.attemptId)
|
||||
).rejects.toBeInstanceOf(BacktestLeaseLostError);
|
||||
await expect(f.repository.cancel(run.id, old.attemptId)).rejects.toBeInstanceOf(
|
||||
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(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('running');
|
||||
await f.repository.complete(result, replacement.attemptId);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('healthy heartbeats prevent reclamation; cancellation before claim never executes', async () => {
|
||||
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));
|
||||
await sleep(200);
|
||||
await shortLease.heartbeat(run.id, claim.attemptId);
|
||||
await sleep(150);
|
||||
await f.dispatcher.tick();
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('running');
|
||||
const queued = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.api.cancelRun(queued.id);
|
||||
await f.api.cancelRun(queued.id);
|
||||
expect((await f.runner.runQueued(queued.id)).status).toBe('cancelled');
|
||||
expect((await f.api.getRun(queued.id))?.attemptNumber).toBe(0);
|
||||
expect(await f.api.getRunResults(queued.id)).toBeNull();
|
||||
});
|
||||
|
||||
test('a heartbeat blocked behind a row lock cannot resurrect an expired lease using transaction-start time', async () => {
|
||||
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 lock = await f.pool.connect();
|
||||
let renewal: Promise<unknown> | undefined;
|
||||
try {
|
||||
await lock.query('BEGIN');
|
||||
await lock.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [run.id]);
|
||||
renewal = shortLease.heartbeat(run.id, claim.attemptId).catch(error => error);
|
||||
await sleep(400);
|
||||
await lock.query('COMMIT');
|
||||
expect(await renewal).toBeInstanceOf(BacktestLeaseLostError);
|
||||
} finally {
|
||||
await lock.query('ROLLBACK');
|
||||
lock.release();
|
||||
}
|
||||
await f.dispatcher.tick();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('pending');
|
||||
});
|
||||
|
||||
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));
|
||||
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 f.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('cancelled');
|
||||
expect(await f.api.getRunResults(run.id)).toBeNull();
|
||||
});
|
||||
|
||||
test('expired attempts retry at most three times, then become failed without a result', async () => {
|
||||
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.expire(run.id);
|
||||
await f.dispatcher.tick();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe(attempt === 3 ? 'failed' : 'pending');
|
||||
}
|
||||
expect((await f.api.getRun(run.id))?.error).toContain('retry limit');
|
||||
expect((await f.runner.runQueued(run.id)).status).toBe('failed');
|
||||
expect(await f.api.getRunResults(run.id)).toBeNull();
|
||||
});
|
||||
|
||||
test('a hard-killed execution process is recovered by a fresh dispatcher and owner', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const child = fork(
|
||||
fileURLToPath(new URL('../fixtures/backtest-crash-owner.ts', import.meta.url)),
|
||||
[],
|
||||
{
|
||||
execPath: process.execPath,
|
||||
execArgv: [],
|
||||
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
||||
env: { ...process.env, BACKTEST_FIXTURE_SCHEMA: f.schema, BACKTEST_FIXTURE_RUN_ID: run.id },
|
||||
}
|
||||
);
|
||||
const closed = new Promise<void>(resolve => child.once('close', () => resolve()));
|
||||
cleanup.push(async () => {
|
||||
child.kill('SIGKILL');
|
||||
await closed;
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => reject(new Error('Crash owner did not claim')), 3_000);
|
||||
child.once('message', () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
});
|
||||
child.once('error', reject);
|
||||
child.once('exit', code => {
|
||||
clearTimeout(timeout);
|
||||
if (code) reject(new Error(`Crash owner exited: ${code}`));
|
||||
});
|
||||
});
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('running');
|
||||
child.kill('SIGKILL');
|
||||
await closed;
|
||||
// Wait for the real lease; do not alter the crashed owner's SQL state.
|
||||
await sleep(550);
|
||||
await f.dispatcher.tick();
|
||||
f.enqueueWorker();
|
||||
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('publication failure retains intent; a restarted publisher recovers the same accepted run', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const connection = await f.queue.getBullQueue().client;
|
||||
connection.disconnect();
|
||||
await expect(f.dispatcher.tick()).rejects.toThrow();
|
||||
// Only this fixture producer's socket is disconnected; no shared Redis data is touched.
|
||||
await connection.connect();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('pending');
|
||||
await sleep(60);
|
||||
await f.dispatcher.tick();
|
||||
f.enqueueWorker();
|
||||
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
|
||||
});
|
||||
|
||||
test('lost Redis notifications are republished; concurrent publishers reserve each SQL intent once', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const second = new BacktestDispatcher(f.postgres, f.queue, logger, {
|
||||
intervalMs: 20,
|
||||
republishMs: 50,
|
||||
maxAttempts: 3,
|
||||
});
|
||||
await Promise.all([f.dispatcher.tick(), second.tick()]);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query('SELECT publish_count FROM backtest_dispatch WHERE run_id = $1', [
|
||||
run.id,
|
||||
])
|
||||
).rows[0].publish_count
|
||||
).toBe(1);
|
||||
const notification = await f.queue.getJob(`backtest-${run.id}`);
|
||||
await notification!.remove();
|
||||
await sleep(60);
|
||||
await second.tick();
|
||||
await second.shutdown();
|
||||
f.enqueueWorker();
|
||||
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
|
||||
});
|
||||
|
||||
test('invalid persisted snapshots become failed instead of remaining stranded pending', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.pool.query("UPDATE runs SET request_snapshot = '{}' WHERE id = $1", [run.id]);
|
||||
await expect(f.runner.runQueued(run.id)).rejects.toThrow();
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('failed');
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(0);
|
||||
});
|
||||
|
||||
test('migration replay preserves leased owners, backfills legacy pending snapshots, and fails ownerless legacy runs', async () => {
|
||||
const f = await fixture();
|
||||
const pending = await f.api.createRun({ backtestId: 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));
|
||||
await f.pool.query('DELETE FROM backtest_dispatch WHERE run_id = $1', [pending.id]);
|
||||
await f.pool.query('UPDATE runs SET request_snapshot = NULL WHERE id = $1', [pending.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),
|
||||
'utf8'
|
||||
);
|
||||
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.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');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue