Remove dataset input caps and simplify preparation
This commit is contained in:
parent
6bd671d92a
commit
007e35c747
17 changed files with 175 additions and 620 deletions
|
|
@ -9,20 +9,6 @@ import {
|
|||
import { featuresSchema } from './features.schema';
|
||||
import { providersSchema } from './providers.schema';
|
||||
|
||||
const datasetLimit = z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(Number.MAX_SAFE_INTEGER - 1);
|
||||
export const backtestDatasetLimitsSchema = z
|
||||
.object({
|
||||
maxInstruments: datasetLimit.optional(),
|
||||
maxBars: datasetLimit.optional(),
|
||||
maxSerializedBytes: datasetLimit.optional(),
|
||||
maxStoredBytes: datasetLimit.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/**
|
||||
* Stock trading application configuration schema
|
||||
*/
|
||||
|
|
@ -107,7 +93,6 @@ export const stockAppSchema = baseAppSchema.extend({
|
|||
maxConcurrent: z.number().default(5),
|
||||
useRustEngine: z.boolean().default(true),
|
||||
executionTimeoutMs: z.number().int().positive().max(2_147_483_647).default(300_000),
|
||||
datasetLimits: backtestDatasetLimitsSchema.optional(),
|
||||
allowSyntheticData: z.boolean().default(false),
|
||||
syntheticSeed: z.number().int().default(42),
|
||||
defaultSpeed: z.string().default('max'),
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ 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';
|
||||
|
|
@ -25,16 +24,13 @@ 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,
|
||||
options: { datasetLimits?: Partial<DatasetLimits> } = {}
|
||||
private readonly strategyManager: StrategyManager
|
||||
) {
|
||||
super();
|
||||
this.datasetLimits = datasetLimits(options.datasetLimits);
|
||||
}
|
||||
|
||||
async runBacktest(input: unknown, resolver?: DatasetResolver): Promise<BacktestResult> {
|
||||
|
|
@ -65,10 +61,7 @@ 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, {
|
||||
limits: this.datasetLimits,
|
||||
signal: playback.signal,
|
||||
})
|
||||
resolveDataset(this.storageService, config, resolver, playback.signal)
|
||||
);
|
||||
playback.assertRunning();
|
||||
const dataManager = new DataManager(this.storageService);
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ 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 { 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';
|
||||
|
|
@ -37,7 +36,6 @@ 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: {
|
||||
|
|
@ -47,12 +45,10 @@ 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> {
|
||||
|
|
@ -213,10 +209,7 @@ export class BacktestRunner extends EventEmitter {
|
|||
executionConfig.datasetHash,
|
||||
signal
|
||||
);
|
||||
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, {
|
||||
limits: this.datasetLimits,
|
||||
signal,
|
||||
});
|
||||
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, signal);
|
||||
signal?.throwIfAborted();
|
||||
const frozen =
|
||||
saved ??
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ 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 { 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';
|
||||
|
|
@ -16,13 +15,10 @@ 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,
|
||||
limits?: Partial<DatasetLimits>
|
||||
private readonly leaseMs = 30_000
|
||||
) {
|
||||
this.datasetLimits = datasetLimits(limits);
|
||||
if (!Number.isInteger(leaseMs) || leaseMs < 100) {
|
||||
throw new Error('Invalid execution lease duration');
|
||||
}
|
||||
|
|
@ -177,7 +173,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
input: HistoricalDataset,
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalDataset> {
|
||||
const dataset = await prepareDataset(input, undefined, { limits: this.datasetLimits, signal });
|
||||
const dataset = await prepareDataset(input, undefined, signal);
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const owned = await client.query(
|
||||
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
|
||||
|
|
@ -218,21 +214,14 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
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 saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
|
||||
hash,
|
||||
]);
|
||||
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,
|
||||
});
|
||||
const dataset = await prepareDataset(row.payload, undefined, signal);
|
||||
if (dataset.manifest.hash !== hash) {
|
||||
throw new Error('Stored dataset identity mismatch');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,6 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import {
|
||||
datasetLimits,
|
||||
PREPARATION_BATCH_SIZE,
|
||||
preparationCheckpoint,
|
||||
type DatasetLimits,
|
||||
} from '../data/dataset-limits';
|
||||
import {
|
||||
assertNativeDatasetBudget,
|
||||
resolveDataset,
|
||||
type DatasetResolver,
|
||||
} from '../data/historical-dataset';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
|
||||
import {
|
||||
|
|
@ -29,7 +20,6 @@ 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;
|
||||
|
|
@ -37,10 +27,9 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
|
||||
constructor(
|
||||
private readonly container: OrchestratorServices,
|
||||
options: { timeoutMs?: number; workerUrl?: URL; datasetLimits?: Partial<DatasetLimits> } = {}
|
||||
options: { timeoutMs?: number; workerUrl?: URL } = {}
|
||||
) {
|
||||
super();
|
||||
this.datasetLimits = datasetLimits(options.datasetLimits);
|
||||
this.timeoutMs = options.timeoutMs ?? 300_000;
|
||||
if (
|
||||
!Number.isInteger(this.timeoutMs) ||
|
||||
|
|
@ -128,10 +117,8 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
resolver?: DatasetResolver
|
||||
): Promise<NativeWorkerRequest['data']> {
|
||||
signal.throwIfAborted();
|
||||
const options = { limits: this.datasetLimits, signal };
|
||||
const dataset = await resolveDataset(this.storageService, config, resolver, options);
|
||||
const dataset = await resolveDataset(this.storageService, config, resolver, signal);
|
||||
signal.throwIfAborted();
|
||||
assertNativeDatasetBudget(dataset, config, options);
|
||||
const data: NativeWorkerRequest['data'] = [];
|
||||
for (const bar of dataset.bars) {
|
||||
data.push({ ...bar, type: 'bar' });
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRep
|
|||
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
|
||||
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
|
||||
import { ModeManager } from './core/ModeManager';
|
||||
import { datasetLimits, type DatasetLimits } from './data/dataset-limits';
|
||||
import { BacktestHandler } from './handlers/backtest/backtest.handler';
|
||||
import { PaperTradingManager } from './paper/PaperTradingManager';
|
||||
import { AnalyticsService } from './services/AnalyticsService';
|
||||
|
|
@ -30,10 +29,8 @@ export async function registerOrchestratorServices(
|
|||
syntheticSeed?: number;
|
||||
nativeExecutionTimeoutMs?: number;
|
||||
strategyRegistry?: StrategyRegistry;
|
||||
datasetLimits?: Partial<DatasetLimits>;
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const limits = datasetLimits(options.datasetLimits);
|
||||
// Create a service adapter that provides the expected interface
|
||||
const services = container.resolve('serviceContainer') as IServiceContainer;
|
||||
const custom = services.custom ?? {};
|
||||
|
|
@ -59,9 +56,8 @@ export async function registerOrchestratorServices(
|
|||
const backtestEngine = options.useRustEngine
|
||||
? new RustBacktestAdapter(services, {
|
||||
timeoutMs: options.nativeExecutionTimeoutMs,
|
||||
datasetLimits: limits,
|
||||
})
|
||||
: new BacktestEngine(services, storageService, strategyManager, { datasetLimits: limits });
|
||||
: new BacktestEngine(services, storageService, strategyManager);
|
||||
const paperTradingManager = new PaperTradingManager(
|
||||
services,
|
||||
storageService,
|
||||
|
|
@ -79,10 +75,9 @@ export async function registerOrchestratorServices(
|
|||
engine: backtestEngine,
|
||||
engineName: options.useRustEngine ? 'native' : 'typescript',
|
||||
repository: services.postgres
|
||||
? new PostgresBacktestRunRepository(services.postgres, undefined, limits)
|
||||
? new PostgresBacktestRunRepository(services.postgres)
|
||||
: new UnavailableBacktestRunRepository(),
|
||||
logger: services.logger,
|
||||
datasetLimits: limits,
|
||||
prepare: options.useRustEngine ? undefined : config => modeManager.initializeMode(config),
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,67 +0,0 @@
|
|||
import { setImmediate } from 'node:timers/promises';
|
||||
|
||||
/** Per-run admission budgets, not estimates of JavaScript heap usage. */
|
||||
export interface DatasetLimits {
|
||||
maxInstruments: number;
|
||||
maxBars: number;
|
||||
maxSerializedBytes: number;
|
||||
maxStoredBytes: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_DATASET_LIMITS: Readonly<DatasetLimits> = Object.freeze({
|
||||
maxInstruments: 100,
|
||||
maxBars: 1_000_000,
|
||||
maxSerializedBytes: 256 * 1024 * 1024,
|
||||
// PostgreSQL's JSONB text includes whitespace and can expand numeric exponents.
|
||||
maxStoredBytes: 512 * 1024 * 1024,
|
||||
});
|
||||
|
||||
export interface DatasetPreparationOptions {
|
||||
limits?: Partial<DatasetLimits>;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export class DatasetLimitError extends Error {
|
||||
constructor(
|
||||
readonly resource: keyof DatasetLimits,
|
||||
readonly limit: number,
|
||||
readonly actual: number
|
||||
) {
|
||||
super(`Historical dataset exceeds ${resource}: ${actual} > ${limit}`);
|
||||
this.name = 'DatasetLimitError';
|
||||
}
|
||||
}
|
||||
|
||||
export function datasetLimits(overrides: Partial<DatasetLimits> = {}): Readonly<DatasetLimits> {
|
||||
const limits = { ...DEFAULT_DATASET_LIMITS, ...overrides };
|
||||
for (const [key, value] of Object.entries(limits)) {
|
||||
if (
|
||||
!Object.hasOwn(DEFAULT_DATASET_LIMITS, key) ||
|
||||
!Number.isSafeInteger(value) ||
|
||||
value <= 0 ||
|
||||
value >= Number.MAX_SAFE_INTEGER
|
||||
) {
|
||||
throw new Error(`Invalid dataset limit: ${key}`);
|
||||
}
|
||||
}
|
||||
return Object.freeze(limits);
|
||||
}
|
||||
|
||||
export function assertDatasetLimit(
|
||||
limits: Readonly<DatasetLimits>,
|
||||
resource: keyof DatasetLimits,
|
||||
actual: number
|
||||
): void {
|
||||
if (actual > limits[resource]) {
|
||||
throw new DatasetLimitError(resource, limits[resource], actual);
|
||||
}
|
||||
}
|
||||
|
||||
export const PREPARATION_BATCH_SIZE = 2048;
|
||||
|
||||
/** Yield to cancellation, timeouts and lease heartbeats between bounded CPU batches. */
|
||||
export async function preparationCheckpoint(signal?: AbortSignal): Promise<void> {
|
||||
signal?.throwIfAborted();
|
||||
await setImmediate();
|
||||
signal?.throwIfAborted();
|
||||
}
|
||||
|
|
@ -6,27 +6,16 @@ import {
|
|||
type HistoricalDataset,
|
||||
} from '@stock-bot/types';
|
||||
import { datasetBarSchema, datasetManifestSchema } from '../contracts/historical';
|
||||
import type { HistoricalBar, StorageService } from '../services/StorageService';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import {
|
||||
assertDatasetLimit,
|
||||
DatasetLimitError,
|
||||
datasetLimits,
|
||||
PREPARATION_BATCH_SIZE,
|
||||
preparationCheckpoint,
|
||||
type DatasetPreparationOptions,
|
||||
} from './dataset-limits';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from './preparation';
|
||||
|
||||
export type DatasetResolver = (
|
||||
load: () => Promise<HistoricalDataset>,
|
||||
signal?: AbortSignal
|
||||
) => Promise<HistoricalDataset>;
|
||||
interface DatasetSize {
|
||||
serializedBytes: number;
|
||||
barsBytes: number;
|
||||
}
|
||||
// Only detached, deeply frozen values enter this cache. Mutable caller objects never do.
|
||||
const prepared = new WeakMap<HistoricalDataset, Readonly<DatasetSize>>();
|
||||
const prepared = new WeakSet<HistoricalDataset>();
|
||||
|
||||
export function dataPolicy(
|
||||
config: Pick<BacktestConfig, 'dataFrequency' | 'dataPolicy'>
|
||||
|
|
@ -60,17 +49,12 @@ function matchRequest(dataset: HistoricalDataset, config?: BacktestConfig): void
|
|||
function* canonicalize(
|
||||
input: unknown,
|
||||
config: BacktestConfig | undefined,
|
||||
options: DatasetPreparationOptions,
|
||||
signal?: AbortSignal,
|
||||
assignHash = false
|
||||
): Generator<void, HistoricalDataset> {
|
||||
const limits = datasetLimits(options.limits);
|
||||
options.signal?.throwIfAborted();
|
||||
signal?.throwIfAborted();
|
||||
if (input && typeof input === 'object' && prepared.has(input as HistoricalDataset)) {
|
||||
const dataset = input as HistoricalDataset;
|
||||
const size = prepared.get(dataset) as Readonly<DatasetSize>;
|
||||
assertDatasetLimit(limits, 'maxInstruments', dataset.manifest.instruments.length);
|
||||
assertDatasetLimit(limits, 'maxBars', dataset.bars.length);
|
||||
assertDatasetLimit(limits, 'maxSerializedBytes', size.serializedBytes);
|
||||
matchRequest(dataset, config);
|
||||
return dataset;
|
||||
}
|
||||
|
|
@ -86,24 +70,6 @@ function* canonicalize(
|
|||
) {
|
||||
throw new Error('Invalid historical dataset');
|
||||
}
|
||||
// Reject array sizes before schema parsing can allocate another complete copy.
|
||||
assertDatasetLimit(limits, 'maxBars', input.bars.length);
|
||||
if (
|
||||
input.manifest &&
|
||||
typeof input.manifest === 'object' &&
|
||||
'instruments' in input.manifest &&
|
||||
Array.isArray(input.manifest.instruments)
|
||||
) {
|
||||
assertDatasetLimit(limits, 'maxInstruments', input.manifest.instruments.length);
|
||||
}
|
||||
if (
|
||||
input.manifest &&
|
||||
typeof input.manifest === 'object' &&
|
||||
'sources' in input.manifest &&
|
||||
Array.isArray(input.manifest.sources)
|
||||
) {
|
||||
assertDatasetLimit(limits, 'maxInstruments', input.manifest.sources.length);
|
||||
}
|
||||
const m = datasetManifestSchema.parse(input.manifest);
|
||||
const ids = m.instruments.map(i => i.id);
|
||||
const idSet = new Set(ids);
|
||||
|
|
@ -132,14 +98,11 @@ function* canonicalize(
|
|||
const { hash: _hash, ...manifest } = m;
|
||||
// Identical bytes to v1 JSON.stringify({ manifest, bars }), without one giant string.
|
||||
const hash = createHash('sha256').update(`{"manifest":${JSON.stringify(manifest)},"bars":[`);
|
||||
const envelopeBytes = Buffer.byteLength(JSON.stringify({ manifest: m, bars: [] })) - 2;
|
||||
let barsBytes = 2;
|
||||
let chunk = '';
|
||||
const seen = new Set<string>();
|
||||
let previous: HistoricalDataset['bars'][number] | undefined;
|
||||
assertDatasetLimit(limits, 'maxSerializedBytes', envelopeBytes + barsBytes);
|
||||
for (let i = 0; i < input.bars.length; i++) {
|
||||
options.signal?.throwIfAborted();
|
||||
signal?.throwIfAborted();
|
||||
const bar = datasetBarSchema.parse(input.bars[i]);
|
||||
if (
|
||||
!idSet.has(bar.symbol) ||
|
||||
|
|
@ -155,8 +118,6 @@ function* canonicalize(
|
|||
throw new Error('Invalid or unordered dataset bars');
|
||||
}
|
||||
const json = (i ? ',' : '') + JSON.stringify(bar);
|
||||
barsBytes += Buffer.byteLength(json);
|
||||
assertDatasetLimit(limits, 'maxSerializedBytes', envelopeBytes + barsBytes);
|
||||
chunk += json;
|
||||
if (chunk.length >= 64 * 1024) {
|
||||
hash.update(chunk);
|
||||
|
|
@ -187,7 +148,7 @@ function* canonicalize(
|
|||
Object.freeze(m);
|
||||
Object.freeze(dataset.bars);
|
||||
Object.freeze(dataset);
|
||||
prepared.set(dataset, Object.freeze({ serializedBytes: envelopeBytes + barsBytes, barsBytes }));
|
||||
prepared.add(dataset);
|
||||
return dataset;
|
||||
}
|
||||
|
||||
|
|
@ -195,9 +156,9 @@ function* canonicalize(
|
|||
export function validateDataset(
|
||||
input: unknown,
|
||||
config?: BacktestConfig,
|
||||
options: DatasetPreparationOptions = {}
|
||||
signal?: AbortSignal
|
||||
): HistoricalDataset {
|
||||
const work = canonicalize(input, config, options);
|
||||
const work = canonicalize(input, config, signal);
|
||||
let step = work.next();
|
||||
while (!step.done) {
|
||||
step = work.next();
|
||||
|
|
@ -218,104 +179,33 @@ async function finishPreparation(work: Generator<void, HistoricalDataset>, signa
|
|||
export function prepareDataset(
|
||||
input: unknown,
|
||||
config?: BacktestConfig,
|
||||
options: DatasetPreparationOptions = {}
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalDataset> {
|
||||
return finishPreparation(canonicalize(input, config, options), options.signal);
|
||||
}
|
||||
|
||||
export function datasetSize(dataset: HistoricalDataset): Readonly<DatasetSize> {
|
||||
const size = prepared.get(dataset);
|
||||
if (!size) {
|
||||
throw new Error('Dataset has not passed preparation');
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
/** Exact JSON IPC request size, checked before allocating native bar copies or spawning. */
|
||||
export function assertNativeDatasetBudget(
|
||||
dataset: HistoricalDataset,
|
||||
config: BacktestConfig,
|
||||
options: DatasetPreparationOptions = {}
|
||||
): void {
|
||||
const limits = datasetLimits(options.limits);
|
||||
const bytes =
|
||||
Buffer.byteLength(JSON.stringify({ type: 'run', config, data: [] })) +
|
||||
datasetSize(dataset).barsBytes -
|
||||
2 +
|
||||
dataset.bars.length * Buffer.byteLength(',"type":"bar"');
|
||||
assertDatasetLimit(limits, 'maxSerializedBytes', bytes);
|
||||
return finishPreparation(canonicalize(input, config, signal), signal);
|
||||
}
|
||||
|
||||
export async function loadDataset(
|
||||
storage: Pick<StorageService, 'getHistoricalBars'>,
|
||||
config: BacktestConfig,
|
||||
options: DatasetPreparationOptions = {}
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalDataset> {
|
||||
const limits = datasetLimits(options.limits);
|
||||
options.signal?.throwIfAborted();
|
||||
assertDatasetLimit(limits, 'maxInstruments', config.symbols.length);
|
||||
signal?.throwIfAborted();
|
||||
validateHistoricalDataRequest(config);
|
||||
const instruments = [...config.symbols].sort().map(parseInstrumentId);
|
||||
const policy = dataPolicy(config);
|
||||
const bars: HistoricalDataset['bars'] = [];
|
||||
const sources: HistoricalDataset['manifest']['sources'] = [];
|
||||
let barBytes = 2;
|
||||
for (const instrument of instruments) {
|
||||
options.signal?.throwIfAborted();
|
||||
const remaining = limits.maxBars - bars.length;
|
||||
if (!remaining) {
|
||||
assertDatasetLimit(limits, 'maxBars', bars.length + 1);
|
||||
}
|
||||
// A numeric field occupies at least one JSON byte. This conservative lower bound
|
||||
// also bounds the query when the byte budget is much tighter than the bar budget.
|
||||
const minimumBarBytes = Buffer.byteLength(
|
||||
JSON.stringify({
|
||||
symbol: instrument.id,
|
||||
timestamp: 0,
|
||||
open: 1,
|
||||
high: 1,
|
||||
low: 1,
|
||||
close: 1,
|
||||
volume: 0,
|
||||
vwap: 1,
|
||||
})
|
||||
signal?.throwIfAborted();
|
||||
const rows = await storage.getHistoricalBars(
|
||||
instrument.id,
|
||||
new Date(config.startDate),
|
||||
new Date(config.endDate),
|
||||
config.dataFrequency,
|
||||
policy,
|
||||
signal
|
||||
);
|
||||
const byteBound = Math.floor(
|
||||
(limits.maxSerializedBytes - barBytes + (bars.length ? 0 : 1)) / (minimumBarBytes + 1)
|
||||
);
|
||||
if (byteBound < 1) {
|
||||
assertDatasetLimit(
|
||||
limits,
|
||||
'maxSerializedBytes',
|
||||
barBytes + minimumBarBytes + (bars.length ? 1 : 0)
|
||||
);
|
||||
}
|
||||
let rows: HistoricalBar[];
|
||||
try {
|
||||
rows = await storage.getHistoricalBars(
|
||||
instrument.id,
|
||||
new Date(config.startDate),
|
||||
new Date(config.endDate),
|
||||
config.dataFrequency,
|
||||
policy,
|
||||
{ maxBars: Math.min(remaining, byteBound), signal: options.signal }
|
||||
);
|
||||
} catch (error) {
|
||||
if (
|
||||
byteBound < remaining &&
|
||||
error instanceof DatasetLimitError &&
|
||||
error.resource === 'maxBars'
|
||||
) {
|
||||
throw new DatasetLimitError(
|
||||
'maxSerializedBytes',
|
||||
limits.maxSerializedBytes,
|
||||
barBytes + error.actual * (minimumBarBytes + 1) - (bars.length ? 0 : 1)
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
options.signal?.throwIfAborted();
|
||||
assertDatasetLimit(limits, 'maxBars', bars.length + rows.length);
|
||||
signal?.throwIfAborted();
|
||||
const source = rows[0]?.source;
|
||||
if (!source) {
|
||||
throw new Error('Historical source provenance is missing or mixed');
|
||||
|
|
@ -339,15 +229,13 @@ export async function loadDataset(
|
|||
volume: bar.volume,
|
||||
vwap: bar.vwap ?? (bar.high + bar.low + bar.close) / 3,
|
||||
};
|
||||
barBytes += Buffer.byteLength(JSON.stringify(value)) + (bars.length ? 1 : 0);
|
||||
assertDatasetLimit(limits, 'maxSerializedBytes', barBytes);
|
||||
bars.push(value);
|
||||
if (bars.length % PREPARATION_BATCH_SIZE === 0) {
|
||||
await preparationCheckpoint(options.signal);
|
||||
await preparationCheckpoint(signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
options.signal?.throwIfAborted();
|
||||
signal?.throwIfAborted();
|
||||
bars.sort(
|
||||
(a, b) => a.timestamp - b.timestamp || (a.symbol < b.symbol ? -1 : a.symbol > b.symbol ? 1 : 0)
|
||||
);
|
||||
|
|
@ -367,25 +255,19 @@ export async function loadDataset(
|
|||
},
|
||||
bars,
|
||||
};
|
||||
return finishPreparation(canonicalize(dataset, config, options, true), options.signal);
|
||||
return finishPreparation(canonicalize(dataset, config, signal, true), signal);
|
||||
}
|
||||
|
||||
export async function resolveDataset(
|
||||
storage: Pick<StorageService, 'getHistoricalBars'>,
|
||||
config: BacktestConfig,
|
||||
resolver?: DatasetResolver,
|
||||
options: DatasetPreparationOptions = {}
|
||||
signal?: AbortSignal
|
||||
) {
|
||||
const limits = datasetLimits(options.limits);
|
||||
options.signal?.throwIfAborted();
|
||||
assertDatasetLimit(limits, 'maxInstruments', config.symbols.length);
|
||||
signal?.throwIfAborted();
|
||||
if (config.datasetHash && !resolver) {
|
||||
throw new Error('Dataset replay requires the durable backtest runner');
|
||||
}
|
||||
const load = () => loadDataset(storage, config, options);
|
||||
return prepareDataset(
|
||||
await (resolver ? resolver(load, options.signal) : load()),
|
||||
config,
|
||||
options
|
||||
);
|
||||
const load = () => loadDataset(storage, config, signal);
|
||||
return prepareDataset(await (resolver ? resolver(load, signal) : load()), config, signal);
|
||||
}
|
||||
|
|
|
|||
10
apps/stock/orchestrator/src/data/preparation.ts
Normal file
10
apps/stock/orchestrator/src/data/preparation.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { setImmediate } from 'node:timers/promises';
|
||||
|
||||
export const PREPARATION_BATCH_SIZE = 2048;
|
||||
|
||||
/** Yield to cancellation, timeouts and lease heartbeats between bounded CPU batches. */
|
||||
export async function preparationCheckpoint(signal?: AbortSignal): Promise<void> {
|
||||
signal?.throwIfAborted();
|
||||
await setImmediate();
|
||||
signal?.throwIfAborted();
|
||||
}
|
||||
|
|
@ -5,19 +5,9 @@ import type {
|
|||
QuestDBClient,
|
||||
} from '@stock-bot/services';
|
||||
import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types';
|
||||
import {
|
||||
assertDatasetLimit,
|
||||
datasetLimits,
|
||||
PREPARATION_BATCH_SIZE,
|
||||
preparationCheckpoint,
|
||||
} from '../data/dataset-limits';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
||||
import type { MarketData, ModeConfig, PerformanceMetrics } from '../types';
|
||||
|
||||
export interface HistoricalReadOptions {
|
||||
maxBars?: number;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface HistoricalBar {
|
||||
symbol: string;
|
||||
timestamp: Date;
|
||||
|
|
@ -186,10 +176,9 @@ export class StorageService {
|
|||
adjustment: 'raw',
|
||||
timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant',
|
||||
},
|
||||
options: HistoricalReadOptions = {}
|
||||
signal?: AbortSignal
|
||||
): Promise<HistoricalBar[]> {
|
||||
const limits = datasetLimits({ maxBars: options.maxBars ?? datasetLimits().maxBars });
|
||||
options.signal?.throwIfAborted();
|
||||
signal?.throwIfAborted();
|
||||
parseInstrumentId(symbol);
|
||||
if (
|
||||
!Number.isFinite(startTime.getTime()) ||
|
||||
|
|
@ -210,15 +199,8 @@ export class StorageService {
|
|||
'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants'
|
||||
);
|
||||
}
|
||||
const rows = await this.readHistoricalBars(
|
||||
symbol,
|
||||
startTime,
|
||||
endTime,
|
||||
interval,
|
||||
limits.maxBars
|
||||
);
|
||||
options.signal?.throwIfAborted();
|
||||
assertDatasetLimit(limits, 'maxBars', rows.length);
|
||||
const rows = await this.readHistoricalBars(symbol, startTime, endTime, interval);
|
||||
signal?.throwIfAborted();
|
||||
const bars: HistoricalBar[] = [];
|
||||
let processed = 0;
|
||||
for (const row of rows) {
|
||||
|
|
@ -276,10 +258,10 @@ export class StorageService {
|
|||
bars.push({ ...row, symbol, timestamp, open, high, low, close, volume, vwap });
|
||||
}
|
||||
if (++processed % PREPARATION_BATCH_SIZE === 0) {
|
||||
await preparationCheckpoint(options.signal);
|
||||
await preparationCheckpoint(signal);
|
||||
}
|
||||
}
|
||||
options.signal?.throwIfAborted();
|
||||
signal?.throwIfAborted();
|
||||
bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
||||
if (!bars.length) {
|
||||
throw new Error(`No historical data for ${symbol}`);
|
||||
|
|
@ -299,8 +281,7 @@ export class StorageService {
|
|||
symbol: string,
|
||||
startTime: Date,
|
||||
endTime: Date,
|
||||
interval: string,
|
||||
maxBars: number
|
||||
interval: string
|
||||
): Promise<HistoricalBar[]> {
|
||||
// If QuestDB is available, use real data
|
||||
if (this.questdb) {
|
||||
|
|
@ -308,10 +289,9 @@ export class StorageService {
|
|||
throw new Error('Unsupported historical interval');
|
||||
}
|
||||
const result = await this.questdb.query<HistoricalBar>(
|
||||
`SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp LIMIT $4`,
|
||||
[symbol, startTime, endTime, maxBars + 1]
|
||||
`SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`,
|
||||
[symbol, startTime, endTime]
|
||||
);
|
||||
assertDatasetLimit(datasetLimits({ maxBars }), 'maxBars', result.rows.length);
|
||||
return result.rows.map(row => ({ ...row, source: 'questdb' }));
|
||||
}
|
||||
|
||||
|
|
@ -343,7 +323,6 @@ export class StorageService {
|
|||
},
|
||||
{
|
||||
sort: { date: 1 },
|
||||
limit: maxBars + 1,
|
||||
projection: {
|
||||
symbol: 1,
|
||||
exchange: 1,
|
||||
|
|
@ -359,7 +338,6 @@ export class StorageService {
|
|||
},
|
||||
}
|
||||
);
|
||||
assertDatasetLimit(datasetLimits({ maxBars }), 'maxBars', prices.length);
|
||||
return prices.map(price => {
|
||||
if (
|
||||
price.eodSearchCode !== identity.id ||
|
||||
|
|
@ -393,11 +371,6 @@ export class StorageService {
|
|||
'No historical data store configured; synthetic data requires explicit opt-in'
|
||||
);
|
||||
}
|
||||
assertDatasetLimit(
|
||||
datasetLimits({ maxBars }),
|
||||
'maxBars',
|
||||
Math.ceil((endTime.getTime() - startTime.getTime()) / this.getIntervalMilliseconds(interval))
|
||||
);
|
||||
return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({
|
||||
...bar,
|
||||
source: 'synthetic',
|
||||
|
|
|
|||
|
|
@ -22,7 +22,6 @@ export async function createContainer(config: StockAppConfig) {
|
|||
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
|
||||
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
|
||||
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
|
||||
datasetLimits: config.services?.orchestrator?.backtesting?.datasetLimits,
|
||||
});
|
||||
return container.resolve('serviceContainer') as OrchestratorServices;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue