Bound backtest dataset preparation and preserve replay identity
This commit is contained in:
parent
cca5d71e6e
commit
6bd671d92a
20 changed files with 1420 additions and 155 deletions
|
|
@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { DataManager } from '../data/DataManager';
|
||||
import { datasetLimits, type DatasetLimits } from '../data/dataset-limits';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { amount, decimal } from '../execution/model';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
|
|
@ -24,13 +25,16 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
private active?: Promise<BacktestResult>;
|
||||
private completedReport?: BacktestReport;
|
||||
private closing = false;
|
||||
private readonly datasetLimits: Readonly<DatasetLimits>;
|
||||
|
||||
constructor(
|
||||
private readonly container: OrchestratorServices,
|
||||
private readonly storageService: StorageService,
|
||||
private readonly strategyManager: StrategyManager
|
||||
private readonly strategyManager: StrategyManager,
|
||||
options: { datasetLimits?: Partial<DatasetLimits> } = {}
|
||||
) {
|
||||
super();
|
||||
this.datasetLimits = datasetLimits(options.datasetLimits);
|
||||
}
|
||||
|
||||
async runBacktest(input: unknown, resolver?: DatasetResolver): Promise<BacktestResult> {
|
||||
|
|
@ -61,7 +65,10 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
const plan = backtestStrategies(config, 'typescript');
|
||||
this.container.logger.info('Starting TypeScript backtest', { symbols: config.symbols });
|
||||
const dataset = await playback.read(() =>
|
||||
resolveDataset(this.storageService, config, resolver)
|
||||
resolveDataset(this.storageService, config, resolver, {
|
||||
limits: this.datasetLimits,
|
||||
signal: playback.signal,
|
||||
})
|
||||
);
|
||||
playback.assertRunning();
|
||||
const dataManager = new DataManager(this.storageService);
|
||||
|
|
|
|||
|
|
@ -39,6 +39,10 @@ export class BacktestPlayback {
|
|||
this.controller.signal.throwIfAborted();
|
||||
}
|
||||
|
||||
get signal(): AbortSignal {
|
||||
return this.controller.signal;
|
||||
}
|
||||
|
||||
/** Only race side-effect-free reads; late reads must never resume execution. */
|
||||
async read<T>(load: () => Promise<T>): Promise<T> {
|
||||
this.assertRunning();
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@ import { z } from 'zod';
|
|||
import type { Logger } from '@stock-bot/services';
|
||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||
import { validateHistoricalDataRequest } from '@stock-bot/types';
|
||||
import { dataPolicy, validateDataset } from '../data/historical-dataset';
|
||||
import { datasetLimits, type DatasetLimits } from '../data/dataset-limits';
|
||||
import { dataPolicy, prepareDataset } from '../data/historical-dataset';
|
||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
|
||||
import { normalizeBacktestResult } from './result';
|
||||
|
|
@ -36,6 +37,7 @@ export class BacktestRunner extends EventEmitter {
|
|||
private closing = false;
|
||||
private phase: 'preparing' | 'executing' | 'persisting' = 'preparing';
|
||||
private execution: Promise<BacktestRunResult> | undefined;
|
||||
private readonly datasetLimits: Readonly<DatasetLimits>;
|
||||
|
||||
constructor(
|
||||
private readonly dependencies: {
|
||||
|
|
@ -45,10 +47,12 @@ export class BacktestRunner extends EventEmitter {
|
|||
logger: Pick<Logger, 'error'>;
|
||||
heartbeatMs?: number;
|
||||
heartbeatTimeoutMs?: number;
|
||||
datasetLimits?: Partial<DatasetLimits>;
|
||||
prepare?: (config: BacktestConfig) => Promise<void>;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
this.datasetLimits = datasetLimits(dependencies.datasetLimits);
|
||||
}
|
||||
|
||||
async runBacktest(input: unknown): Promise<BacktestRunResult> {
|
||||
|
|
@ -199,19 +203,34 @@ export class BacktestRunner extends EventEmitter {
|
|||
this.phase = 'executing';
|
||||
let manifest: HistoricalDatasetManifest | undefined;
|
||||
const claim = this.active;
|
||||
const raw = await this.dependencies.engine.runBacktest(executionConfig, async load => {
|
||||
const saved = await this.dependencies.repository.loadDataset(
|
||||
claim.runId,
|
||||
claim.attemptId,
|
||||
executionConfig.datasetHash
|
||||
);
|
||||
const dataset = validateDataset(saved ?? (await load()), executionConfig);
|
||||
const frozen =
|
||||
saved ??
|
||||
(await this.dependencies.repository.freezeDataset(claim.runId, claim.attemptId, dataset));
|
||||
manifest = frozen.manifest;
|
||||
return frozen;
|
||||
});
|
||||
const raw = await this.dependencies.engine.runBacktest(
|
||||
executionConfig,
|
||||
async (load, signal) => {
|
||||
signal?.throwIfAborted();
|
||||
const saved = await this.dependencies.repository.loadDataset(
|
||||
claim.runId,
|
||||
claim.attemptId,
|
||||
executionConfig.datasetHash,
|
||||
signal
|
||||
);
|
||||
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, {
|
||||
limits: this.datasetLimits,
|
||||
signal,
|
||||
});
|
||||
signal?.throwIfAborted();
|
||||
const frozen =
|
||||
saved ??
|
||||
(await this.dependencies.repository.freezeDataset(
|
||||
claim.runId,
|
||||
claim.attemptId,
|
||||
dataset,
|
||||
signal
|
||||
));
|
||||
signal?.throwIfAborted();
|
||||
manifest = frozen.manifest;
|
||||
return frozen;
|
||||
}
|
||||
);
|
||||
if (!manifest) {
|
||||
throw new Error('Backtest engine did not resolve frozen execution inputs');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient } from 'pg';
|
||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import { validateDataset } from '../data/historical-dataset';
|
||||
import { assertDatasetLimit, datasetLimits, type DatasetLimits } from '../data/dataset-limits';
|
||||
import { prepareDataset } from '../data/historical-dataset';
|
||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||
import { BacktestCancelledError } from './execution-engine';
|
||||
import {
|
||||
|
|
@ -14,10 +16,13 @@ import {
|
|||
|
||||
/** The attempt UUID is a fencing token. PostgreSQL time, not worker clocks, defines ownership. */
|
||||
export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
||||
private readonly datasetLimits: Readonly<DatasetLimits>;
|
||||
constructor(
|
||||
private readonly postgres: Pick<PostgresClient, 'transaction'>,
|
||||
private readonly leaseMs = 30_000
|
||||
private readonly leaseMs = 30_000,
|
||||
limits?: Partial<DatasetLimits>
|
||||
) {
|
||||
this.datasetLimits = datasetLimits(limits);
|
||||
if (!Number.isInteger(leaseMs) || leaseMs < 100) {
|
||||
throw new Error('Invalid execution lease duration');
|
||||
}
|
||||
|
|
@ -130,8 +135,10 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
async loadDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
requestedHash?: string
|
||||
requestedHash?: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalDataset | null> {
|
||||
signal?.throwIfAborted();
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const owned = await client.query(
|
||||
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
|
||||
|
|
@ -148,16 +155,8 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
if (requestedHash && requestedHash !== hash) {
|
||||
throw new BacktestConflictError('Run dataset is already frozen');
|
||||
}
|
||||
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
|
||||
hash,
|
||||
]);
|
||||
if (!saved.rows[0]) {
|
||||
throw new Error('Frozen dataset not found');
|
||||
}
|
||||
const dataset = validateDataset(saved.rows[0].payload);
|
||||
if (dataset.manifest.hash !== hash) {
|
||||
throw new Error('Stored dataset identity mismatch');
|
||||
}
|
||||
const dataset = await this.readDataset(client, String(hash), signal);
|
||||
signal?.throwIfAborted();
|
||||
const pinned = await client.query(
|
||||
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
|
||||
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
|
||||
|
|
@ -167,6 +166,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
if (!pinned.rows.length) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
return dataset;
|
||||
});
|
||||
}
|
||||
|
|
@ -174,9 +174,10 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
async freezeDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
input: HistoricalDataset
|
||||
input: HistoricalDataset,
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalDataset> {
|
||||
const dataset = validateDataset(input);
|
||||
const dataset = await prepareDataset(input, undefined, { limits: this.datasetLimits, signal });
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const owned = await client.query(
|
||||
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
|
||||
|
|
@ -190,17 +191,13 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
if (owned.rows[0].dataset_hash && owned.rows[0].dataset_hash !== hash) {
|
||||
throw new BacktestConflictError('Run dataset is already frozen');
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
await client.query(
|
||||
'INSERT INTO backtest_datasets (hash, payload) VALUES ($1, $2::jsonb) ON CONFLICT (hash) DO NOTHING',
|
||||
[hash, JSON.stringify(dataset)]
|
||||
);
|
||||
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
|
||||
hash,
|
||||
]);
|
||||
const frozen = validateDataset(saved.rows[0]?.payload);
|
||||
if (frozen.manifest.hash !== hash) {
|
||||
throw new Error('Stored dataset identity mismatch');
|
||||
}
|
||||
const frozen = await this.readDataset(client, hash, signal);
|
||||
signal?.throwIfAborted();
|
||||
const pinned = await client.query(
|
||||
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
|
||||
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
|
||||
|
|
@ -210,10 +207,38 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
if (!pinned.rows.length) {
|
||||
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
return frozen;
|
||||
});
|
||||
}
|
||||
|
||||
private async readDataset(
|
||||
client: PoolClient,
|
||||
hash: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalDataset> {
|
||||
signal?.throwIfAborted();
|
||||
// Never transfer/parse an oversized JSONB document into the application process.
|
||||
const saved = await client.query(
|
||||
`SELECT CASE WHEN octet_length(payload::text) <= $2 THEN payload ELSE NULL END AS payload,
|
||||
octet_length(payload::text) AS payload_bytes FROM backtest_datasets WHERE hash = $1`,
|
||||
[hash, this.datasetLimits.maxStoredBytes]
|
||||
);
|
||||
const row = saved.rows[0];
|
||||
if (!row) {
|
||||
throw new Error('Frozen dataset not found');
|
||||
}
|
||||
assertDatasetLimit(this.datasetLimits, 'maxStoredBytes', Number(row.payload_bytes));
|
||||
const dataset = await prepareDataset(row.payload, undefined, {
|
||||
limits: this.datasetLimits,
|
||||
signal,
|
||||
});
|
||||
if (dataset.manifest.hash !== hash) {
|
||||
throw new Error('Stored dataset identity mismatch');
|
||||
}
|
||||
return dataset;
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,15 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import {
|
||||
datasetLimits,
|
||||
PREPARATION_BATCH_SIZE,
|
||||
preparationCheckpoint,
|
||||
type DatasetLimits,
|
||||
} from '../data/dataset-limits';
|
||||
import {
|
||||
assertNativeDatasetBudget,
|
||||
resolveDataset,
|
||||
type DatasetResolver,
|
||||
} from '../data/historical-dataset';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
|
||||
import {
|
||||
|
|
@ -19,6 +29,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
private readonly storageService: StorageService;
|
||||
private readonly worker: NativeBacktestWorker;
|
||||
private readonly timeoutMs: number;
|
||||
private readonly datasetLimits: Readonly<DatasetLimits>;
|
||||
private active: { controller: AbortController; finished: Promise<void> } | undefined;
|
||||
private closing = false;
|
||||
private progress = 0;
|
||||
|
|
@ -26,9 +37,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
|
||||
constructor(
|
||||
private readonly container: OrchestratorServices,
|
||||
options: { timeoutMs?: number; workerUrl?: URL } = {}
|
||||
options: { timeoutMs?: number; workerUrl?: URL; datasetLimits?: Partial<DatasetLimits> } = {}
|
||||
) {
|
||||
super();
|
||||
this.datasetLimits = datasetLimits(options.datasetLimits);
|
||||
this.timeoutMs = options.timeoutMs ?? 300_000;
|
||||
if (
|
||||
!Number.isInteger(this.timeoutMs) ||
|
||||
|
|
@ -116,9 +128,19 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
resolver?: DatasetResolver
|
||||
): Promise<NativeWorkerRequest['data']> {
|
||||
signal.throwIfAborted();
|
||||
const dataset = await resolveDataset(this.storageService, config, resolver);
|
||||
const options = { limits: this.datasetLimits, signal };
|
||||
const dataset = await resolveDataset(this.storageService, config, resolver, options);
|
||||
signal.throwIfAborted();
|
||||
return dataset.bars.map(bar => ({ ...bar, type: 'bar' }));
|
||||
assertNativeDatasetBudget(dataset, config, options);
|
||||
const data: NativeWorkerRequest['data'] = [];
|
||||
for (const bar of dataset.bars) {
|
||||
data.push({ ...bar, type: 'bar' });
|
||||
if (data.length % PREPARATION_BATCH_SIZE === 0) {
|
||||
await preparationCheckpoint(signal);
|
||||
}
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
return data;
|
||||
}
|
||||
|
||||
private publish(event: string, data: unknown): void {
|
||||
|
|
|
|||
|
|
@ -19,12 +19,14 @@ export interface BacktestRunRepository {
|
|||
loadDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
requestedHash?: string
|
||||
requestedHash?: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalDataset | null>;
|
||||
freezeDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
dataset: HistoricalDataset
|
||||
dataset: HistoricalDataset,
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalDataset>;
|
||||
complete(result: BacktestRunResult, attemptId: string): Promise<void>;
|
||||
updateProgress(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue