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
10
README.md
10
README.md
|
|
@ -313,12 +313,10 @@ history. Runs capture data at execution preparation, **not HTTP acceptance time*
|
||||||
Reproducibility assumes the same engine/strategy code and configuration; the snapshot
|
Reproducibility assumes the same engine/strategy code and configuration; the snapshot
|
||||||
is not an engine binary archive or a point-in-time constituent universe. Direct backend
|
is not an engine binary archive or a point-in-time constituent universe. Direct backend
|
||||||
calls can load data for diagnostics, but durable replay/persistence requires the runner.
|
calls can load data for diagnostics, but durable replay/persistence requires the runner.
|
||||||
Dataset preparation enforces configurable instrument, bar-count, JSON/IPC and stored-JSONB
|
Dataset preparation has no application-level instrument, bar-count or payload-size caps.
|
||||||
budgets. Internal handoffs reuse deeply frozen validated inputs; restored snapshots are
|
Internal handoffs reuse deeply frozen validated inputs; restored snapshots are always
|
||||||
always content-checked. Existing v1 hashes and replay identities are unchanged.
|
content-checked. Existing v1 hashes and replay identities are unchanged. Snapshots remain
|
||||||
See [dataset limits and preparation benchmarks](docs/backtest-datasets.md).
|
JSONB and load in memory. See [dataset preparation](docs/backtest-datasets.md).
|
||||||
Snapshots are still JSONB and load in memory; large tick datasets need chunked storage
|
|
||||||
and an explicit retention policy before scaling beyond these budgets.
|
|
||||||
|
|
||||||
## Simulation order execution
|
## Simulation order execution
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,20 +9,6 @@ import {
|
||||||
import { featuresSchema } from './features.schema';
|
import { featuresSchema } from './features.schema';
|
||||||
import { providersSchema } from './providers.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
|
* Stock trading application configuration schema
|
||||||
*/
|
*/
|
||||||
|
|
@ -107,7 +93,6 @@ export const stockAppSchema = baseAppSchema.extend({
|
||||||
maxConcurrent: z.number().default(5),
|
maxConcurrent: z.number().default(5),
|
||||||
useRustEngine: z.boolean().default(true),
|
useRustEngine: z.boolean().default(true),
|
||||||
executionTimeoutMs: z.number().int().positive().max(2_147_483_647).default(300_000),
|
executionTimeoutMs: z.number().int().positive().max(2_147_483_647).default(300_000),
|
||||||
datasetLimits: backtestDatasetLimitsSchema.optional(),
|
|
||||||
allowSyntheticData: z.boolean().default(false),
|
allowSyntheticData: z.boolean().default(false),
|
||||||
syntheticSeed: z.number().int().default(42),
|
syntheticSeed: z.number().int().default(42),
|
||||||
defaultSpeed: z.string().default('max'),
|
defaultSpeed: z.string().default('max'),
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ import { randomUUID } from 'node:crypto';
|
||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import { defined } from '@stock-bot/invariants';
|
import { defined } from '@stock-bot/invariants';
|
||||||
import { DataManager } from '../data/DataManager';
|
import { DataManager } from '../data/DataManager';
|
||||||
import { datasetLimits, type DatasetLimits } from '../data/dataset-limits';
|
|
||||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||||
import { amount, decimal } from '../execution/model';
|
import { amount, decimal } from '../execution/model';
|
||||||
import type { StorageService } from '../services/StorageService';
|
import type { StorageService } from '../services/StorageService';
|
||||||
|
|
@ -25,16 +24,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
||||||
private active?: Promise<BacktestResult>;
|
private active?: Promise<BacktestResult>;
|
||||||
private completedReport?: BacktestReport;
|
private completedReport?: BacktestReport;
|
||||||
private closing = false;
|
private closing = false;
|
||||||
private readonly datasetLimits: Readonly<DatasetLimits>;
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly container: OrchestratorServices,
|
private readonly container: OrchestratorServices,
|
||||||
private readonly storageService: StorageService,
|
private readonly storageService: StorageService,
|
||||||
private readonly strategyManager: StrategyManager,
|
private readonly strategyManager: StrategyManager
|
||||||
options: { datasetLimits?: Partial<DatasetLimits> } = {}
|
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
this.datasetLimits = datasetLimits(options.datasetLimits);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async runBacktest(input: unknown, resolver?: DatasetResolver): Promise<BacktestResult> {
|
async runBacktest(input: unknown, resolver?: DatasetResolver): Promise<BacktestResult> {
|
||||||
|
|
@ -65,10 +61,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
||||||
const plan = backtestStrategies(config, 'typescript');
|
const plan = backtestStrategies(config, 'typescript');
|
||||||
this.container.logger.info('Starting TypeScript backtest', { symbols: config.symbols });
|
this.container.logger.info('Starting TypeScript backtest', { symbols: config.symbols });
|
||||||
const dataset = await playback.read(() =>
|
const dataset = await playback.read(() =>
|
||||||
resolveDataset(this.storageService, config, resolver, {
|
resolveDataset(this.storageService, config, resolver, playback.signal)
|
||||||
limits: this.datasetLimits,
|
|
||||||
signal: playback.signal,
|
|
||||||
})
|
|
||||||
);
|
);
|
||||||
playback.assertRunning();
|
playback.assertRunning();
|
||||||
const dataManager = new DataManager(this.storageService);
|
const dataManager = new DataManager(this.storageService);
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import { z } from 'zod';
|
||||||
import type { Logger } from '@stock-bot/services';
|
import type { Logger } from '@stock-bot/services';
|
||||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||||
import { validateHistoricalDataRequest } 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 { dataPolicy, prepareDataset } from '../data/historical-dataset';
|
||||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||||
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
|
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
|
||||||
|
|
@ -37,7 +36,6 @@ export class BacktestRunner extends EventEmitter {
|
||||||
private closing = false;
|
private closing = false;
|
||||||
private phase: 'preparing' | 'executing' | 'persisting' = 'preparing';
|
private phase: 'preparing' | 'executing' | 'persisting' = 'preparing';
|
||||||
private execution: Promise<BacktestRunResult> | undefined;
|
private execution: Promise<BacktestRunResult> | undefined;
|
||||||
private readonly datasetLimits: Readonly<DatasetLimits>;
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly dependencies: {
|
private readonly dependencies: {
|
||||||
|
|
@ -47,12 +45,10 @@ export class BacktestRunner extends EventEmitter {
|
||||||
logger: Pick<Logger, 'error'>;
|
logger: Pick<Logger, 'error'>;
|
||||||
heartbeatMs?: number;
|
heartbeatMs?: number;
|
||||||
heartbeatTimeoutMs?: number;
|
heartbeatTimeoutMs?: number;
|
||||||
datasetLimits?: Partial<DatasetLimits>;
|
|
||||||
prepare?: (config: BacktestConfig) => Promise<void>;
|
prepare?: (config: BacktestConfig) => Promise<void>;
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
this.datasetLimits = datasetLimits(dependencies.datasetLimits);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async runBacktest(input: unknown): Promise<BacktestRunResult> {
|
async runBacktest(input: unknown): Promise<BacktestRunResult> {
|
||||||
|
|
@ -213,10 +209,7 @@ export class BacktestRunner extends EventEmitter {
|
||||||
executionConfig.datasetHash,
|
executionConfig.datasetHash,
|
||||||
signal
|
signal
|
||||||
);
|
);
|
||||||
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, {
|
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, signal);
|
||||||
limits: this.datasetLimits,
|
|
||||||
signal,
|
|
||||||
});
|
|
||||||
signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
const frozen =
|
const frozen =
|
||||||
saved ??
|
saved ??
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import type { PoolClient } from 'pg';
|
||||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||||
import type { PostgresClient } from '@stock-bot/services';
|
import type { PostgresClient } from '@stock-bot/services';
|
||||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||||
import { assertDatasetLimit, datasetLimits, type DatasetLimits } from '../data/dataset-limits';
|
|
||||||
import { prepareDataset } from '../data/historical-dataset';
|
import { prepareDataset } from '../data/historical-dataset';
|
||||||
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
import { BacktestConfigSchema, type BacktestConfig } from '../types';
|
||||||
import { BacktestCancelledError } from './execution-engine';
|
import { BacktestCancelledError } from './execution-engine';
|
||||||
|
|
@ -16,13 +15,10 @@ import {
|
||||||
|
|
||||||
/** The attempt UUID is a fencing token. PostgreSQL time, not worker clocks, defines ownership. */
|
/** The attempt UUID is a fencing token. PostgreSQL time, not worker clocks, defines ownership. */
|
||||||
export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
||||||
private readonly datasetLimits: Readonly<DatasetLimits>;
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly postgres: Pick<PostgresClient, 'transaction'>,
|
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) {
|
if (!Number.isInteger(leaseMs) || leaseMs < 100) {
|
||||||
throw new Error('Invalid execution lease duration');
|
throw new Error('Invalid execution lease duration');
|
||||||
}
|
}
|
||||||
|
|
@ -177,7 +173,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
||||||
input: HistoricalDataset,
|
input: HistoricalDataset,
|
||||||
signal?: AbortSignal
|
signal?: AbortSignal
|
||||||
): Promise<HistoricalDataset> {
|
): 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 => {
|
return this.ownedTransaction(runId, async client => {
|
||||||
const owned = await client.query(
|
const owned = await client.query(
|
||||||
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
|
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
|
||||||
|
|
@ -218,21 +214,14 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
||||||
signal?: AbortSignal
|
signal?: AbortSignal
|
||||||
): Promise<HistoricalDataset> {
|
): Promise<HistoricalDataset> {
|
||||||
signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
// Never transfer/parse an oversized JSONB document into the application process.
|
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
|
||||||
const saved = await client.query(
|
hash,
|
||||||
`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];
|
const row = saved.rows[0];
|
||||||
if (!row) {
|
if (!row) {
|
||||||
throw new Error('Frozen dataset not found');
|
throw new Error('Frozen dataset not found');
|
||||||
}
|
}
|
||||||
assertDatasetLimit(this.datasetLimits, 'maxStoredBytes', Number(row.payload_bytes));
|
const dataset = await prepareDataset(row.payload, undefined, signal);
|
||||||
const dataset = await prepareDataset(row.payload, undefined, {
|
|
||||||
limits: this.datasetLimits,
|
|
||||||
signal,
|
|
||||||
});
|
|
||||||
if (dataset.manifest.hash !== hash) {
|
if (dataset.manifest.hash !== hash) {
|
||||||
throw new Error('Stored dataset identity mismatch');
|
throw new Error('Stored dataset identity mismatch');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,6 @@
|
||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import {
|
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||||
datasetLimits,
|
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
||||||
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 { StorageService } from '../services/StorageService';
|
||||||
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
|
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
|
||||||
import {
|
import {
|
||||||
|
|
@ -29,7 +20,6 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
||||||
private readonly storageService: StorageService;
|
private readonly storageService: StorageService;
|
||||||
private readonly worker: NativeBacktestWorker;
|
private readonly worker: NativeBacktestWorker;
|
||||||
private readonly timeoutMs: number;
|
private readonly timeoutMs: number;
|
||||||
private readonly datasetLimits: Readonly<DatasetLimits>;
|
|
||||||
private active: { controller: AbortController; finished: Promise<void> } | undefined;
|
private active: { controller: AbortController; finished: Promise<void> } | undefined;
|
||||||
private closing = false;
|
private closing = false;
|
||||||
private progress = 0;
|
private progress = 0;
|
||||||
|
|
@ -37,10 +27,9 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly container: OrchestratorServices,
|
private readonly container: OrchestratorServices,
|
||||||
options: { timeoutMs?: number; workerUrl?: URL; datasetLimits?: Partial<DatasetLimits> } = {}
|
options: { timeoutMs?: number; workerUrl?: URL } = {}
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
this.datasetLimits = datasetLimits(options.datasetLimits);
|
|
||||||
this.timeoutMs = options.timeoutMs ?? 300_000;
|
this.timeoutMs = options.timeoutMs ?? 300_000;
|
||||||
if (
|
if (
|
||||||
!Number.isInteger(this.timeoutMs) ||
|
!Number.isInteger(this.timeoutMs) ||
|
||||||
|
|
@ -128,10 +117,8 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
||||||
resolver?: DatasetResolver
|
resolver?: DatasetResolver
|
||||||
): Promise<NativeWorkerRequest['data']> {
|
): Promise<NativeWorkerRequest['data']> {
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
const options = { limits: this.datasetLimits, signal };
|
const dataset = await resolveDataset(this.storageService, config, resolver, signal);
|
||||||
const dataset = await resolveDataset(this.storageService, config, resolver, options);
|
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
assertNativeDatasetBudget(dataset, config, options);
|
|
||||||
const data: NativeWorkerRequest['data'] = [];
|
const data: NativeWorkerRequest['data'] = [];
|
||||||
for (const bar of dataset.bars) {
|
for (const bar of dataset.bars) {
|
||||||
data.push({ ...bar, type: 'bar' });
|
data.push({ ...bar, type: 'bar' });
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRep
|
||||||
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
|
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
|
||||||
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
|
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
|
||||||
import { ModeManager } from './core/ModeManager';
|
import { ModeManager } from './core/ModeManager';
|
||||||
import { datasetLimits, type DatasetLimits } from './data/dataset-limits';
|
|
||||||
import { BacktestHandler } from './handlers/backtest/backtest.handler';
|
import { BacktestHandler } from './handlers/backtest/backtest.handler';
|
||||||
import { PaperTradingManager } from './paper/PaperTradingManager';
|
import { PaperTradingManager } from './paper/PaperTradingManager';
|
||||||
import { AnalyticsService } from './services/AnalyticsService';
|
import { AnalyticsService } from './services/AnalyticsService';
|
||||||
|
|
@ -30,10 +29,8 @@ export async function registerOrchestratorServices(
|
||||||
syntheticSeed?: number;
|
syntheticSeed?: number;
|
||||||
nativeExecutionTimeoutMs?: number;
|
nativeExecutionTimeoutMs?: number;
|
||||||
strategyRegistry?: StrategyRegistry;
|
strategyRegistry?: StrategyRegistry;
|
||||||
datasetLimits?: Partial<DatasetLimits>;
|
|
||||||
} = {}
|
} = {}
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const limits = datasetLimits(options.datasetLimits);
|
|
||||||
// Create a service adapter that provides the expected interface
|
// Create a service adapter that provides the expected interface
|
||||||
const services = container.resolve('serviceContainer') as IServiceContainer;
|
const services = container.resolve('serviceContainer') as IServiceContainer;
|
||||||
const custom = services.custom ?? {};
|
const custom = services.custom ?? {};
|
||||||
|
|
@ -59,9 +56,8 @@ export async function registerOrchestratorServices(
|
||||||
const backtestEngine = options.useRustEngine
|
const backtestEngine = options.useRustEngine
|
||||||
? new RustBacktestAdapter(services, {
|
? new RustBacktestAdapter(services, {
|
||||||
timeoutMs: options.nativeExecutionTimeoutMs,
|
timeoutMs: options.nativeExecutionTimeoutMs,
|
||||||
datasetLimits: limits,
|
|
||||||
})
|
})
|
||||||
: new BacktestEngine(services, storageService, strategyManager, { datasetLimits: limits });
|
: new BacktestEngine(services, storageService, strategyManager);
|
||||||
const paperTradingManager = new PaperTradingManager(
|
const paperTradingManager = new PaperTradingManager(
|
||||||
services,
|
services,
|
||||||
storageService,
|
storageService,
|
||||||
|
|
@ -79,10 +75,9 @@ export async function registerOrchestratorServices(
|
||||||
engine: backtestEngine,
|
engine: backtestEngine,
|
||||||
engineName: options.useRustEngine ? 'native' : 'typescript',
|
engineName: options.useRustEngine ? 'native' : 'typescript',
|
||||||
repository: services.postgres
|
repository: services.postgres
|
||||||
? new PostgresBacktestRunRepository(services.postgres, undefined, limits)
|
? new PostgresBacktestRunRepository(services.postgres)
|
||||||
: new UnavailableBacktestRunRepository(),
|
: new UnavailableBacktestRunRepository(),
|
||||||
logger: services.logger,
|
logger: services.logger,
|
||||||
datasetLimits: limits,
|
|
||||||
prepare: options.useRustEngine ? undefined : config => modeManager.initializeMode(config),
|
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,
|
type HistoricalDataset,
|
||||||
} from '@stock-bot/types';
|
} from '@stock-bot/types';
|
||||||
import { datasetBarSchema, datasetManifestSchema } from '../contracts/historical';
|
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 type { BacktestConfig } from '../types';
|
||||||
import {
|
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from './preparation';
|
||||||
assertDatasetLimit,
|
|
||||||
DatasetLimitError,
|
|
||||||
datasetLimits,
|
|
||||||
PREPARATION_BATCH_SIZE,
|
|
||||||
preparationCheckpoint,
|
|
||||||
type DatasetPreparationOptions,
|
|
||||||
} from './dataset-limits';
|
|
||||||
|
|
||||||
export type DatasetResolver = (
|
export type DatasetResolver = (
|
||||||
load: () => Promise<HistoricalDataset>,
|
load: () => Promise<HistoricalDataset>,
|
||||||
signal?: AbortSignal
|
signal?: AbortSignal
|
||||||
) => Promise<HistoricalDataset>;
|
) => Promise<HistoricalDataset>;
|
||||||
interface DatasetSize {
|
|
||||||
serializedBytes: number;
|
|
||||||
barsBytes: number;
|
|
||||||
}
|
|
||||||
// Only detached, deeply frozen values enter this cache. Mutable caller objects never do.
|
// 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(
|
export function dataPolicy(
|
||||||
config: Pick<BacktestConfig, 'dataFrequency' | 'dataPolicy'>
|
config: Pick<BacktestConfig, 'dataFrequency' | 'dataPolicy'>
|
||||||
|
|
@ -60,17 +49,12 @@ function matchRequest(dataset: HistoricalDataset, config?: BacktestConfig): void
|
||||||
function* canonicalize(
|
function* canonicalize(
|
||||||
input: unknown,
|
input: unknown,
|
||||||
config: BacktestConfig | undefined,
|
config: BacktestConfig | undefined,
|
||||||
options: DatasetPreparationOptions,
|
signal?: AbortSignal,
|
||||||
assignHash = false
|
assignHash = false
|
||||||
): Generator<void, HistoricalDataset> {
|
): Generator<void, HistoricalDataset> {
|
||||||
const limits = datasetLimits(options.limits);
|
signal?.throwIfAborted();
|
||||||
options.signal?.throwIfAborted();
|
|
||||||
if (input && typeof input === 'object' && prepared.has(input as HistoricalDataset)) {
|
if (input && typeof input === 'object' && prepared.has(input as HistoricalDataset)) {
|
||||||
const dataset = 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);
|
matchRequest(dataset, config);
|
||||||
return dataset;
|
return dataset;
|
||||||
}
|
}
|
||||||
|
|
@ -86,24 +70,6 @@ function* canonicalize(
|
||||||
) {
|
) {
|
||||||
throw new Error('Invalid historical dataset');
|
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 m = datasetManifestSchema.parse(input.manifest);
|
||||||
const ids = m.instruments.map(i => i.id);
|
const ids = m.instruments.map(i => i.id);
|
||||||
const idSet = new Set(ids);
|
const idSet = new Set(ids);
|
||||||
|
|
@ -132,14 +98,11 @@ function* canonicalize(
|
||||||
const { hash: _hash, ...manifest } = m;
|
const { hash: _hash, ...manifest } = m;
|
||||||
// Identical bytes to v1 JSON.stringify({ manifest, bars }), without one giant string.
|
// Identical bytes to v1 JSON.stringify({ manifest, bars }), without one giant string.
|
||||||
const hash = createHash('sha256').update(`{"manifest":${JSON.stringify(manifest)},"bars":[`);
|
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 = '';
|
let chunk = '';
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
let previous: HistoricalDataset['bars'][number] | undefined;
|
let previous: HistoricalDataset['bars'][number] | undefined;
|
||||||
assertDatasetLimit(limits, 'maxSerializedBytes', envelopeBytes + barsBytes);
|
|
||||||
for (let i = 0; i < input.bars.length; i++) {
|
for (let i = 0; i < input.bars.length; i++) {
|
||||||
options.signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
const bar = datasetBarSchema.parse(input.bars[i]);
|
const bar = datasetBarSchema.parse(input.bars[i]);
|
||||||
if (
|
if (
|
||||||
!idSet.has(bar.symbol) ||
|
!idSet.has(bar.symbol) ||
|
||||||
|
|
@ -155,8 +118,6 @@ function* canonicalize(
|
||||||
throw new Error('Invalid or unordered dataset bars');
|
throw new Error('Invalid or unordered dataset bars');
|
||||||
}
|
}
|
||||||
const json = (i ? ',' : '') + JSON.stringify(bar);
|
const json = (i ? ',' : '') + JSON.stringify(bar);
|
||||||
barsBytes += Buffer.byteLength(json);
|
|
||||||
assertDatasetLimit(limits, 'maxSerializedBytes', envelopeBytes + barsBytes);
|
|
||||||
chunk += json;
|
chunk += json;
|
||||||
if (chunk.length >= 64 * 1024) {
|
if (chunk.length >= 64 * 1024) {
|
||||||
hash.update(chunk);
|
hash.update(chunk);
|
||||||
|
|
@ -187,7 +148,7 @@ function* canonicalize(
|
||||||
Object.freeze(m);
|
Object.freeze(m);
|
||||||
Object.freeze(dataset.bars);
|
Object.freeze(dataset.bars);
|
||||||
Object.freeze(dataset);
|
Object.freeze(dataset);
|
||||||
prepared.set(dataset, Object.freeze({ serializedBytes: envelopeBytes + barsBytes, barsBytes }));
|
prepared.add(dataset);
|
||||||
return dataset;
|
return dataset;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -195,9 +156,9 @@ function* canonicalize(
|
||||||
export function validateDataset(
|
export function validateDataset(
|
||||||
input: unknown,
|
input: unknown,
|
||||||
config?: BacktestConfig,
|
config?: BacktestConfig,
|
||||||
options: DatasetPreparationOptions = {}
|
signal?: AbortSignal
|
||||||
): HistoricalDataset {
|
): HistoricalDataset {
|
||||||
const work = canonicalize(input, config, options);
|
const work = canonicalize(input, config, signal);
|
||||||
let step = work.next();
|
let step = work.next();
|
||||||
while (!step.done) {
|
while (!step.done) {
|
||||||
step = work.next();
|
step = work.next();
|
||||||
|
|
@ -218,104 +179,33 @@ async function finishPreparation(work: Generator<void, HistoricalDataset>, signa
|
||||||
export function prepareDataset(
|
export function prepareDataset(
|
||||||
input: unknown,
|
input: unknown,
|
||||||
config?: BacktestConfig,
|
config?: BacktestConfig,
|
||||||
options: DatasetPreparationOptions = {}
|
signal?: AbortSignal
|
||||||
): Promise<HistoricalDataset> {
|
): Promise<HistoricalDataset> {
|
||||||
return finishPreparation(canonicalize(input, config, options), options.signal);
|
return finishPreparation(canonicalize(input, config, signal), 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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadDataset(
|
export async function loadDataset(
|
||||||
storage: Pick<StorageService, 'getHistoricalBars'>,
|
storage: Pick<StorageService, 'getHistoricalBars'>,
|
||||||
config: BacktestConfig,
|
config: BacktestConfig,
|
||||||
options: DatasetPreparationOptions = {}
|
signal?: AbortSignal
|
||||||
): Promise<HistoricalDataset> {
|
): Promise<HistoricalDataset> {
|
||||||
const limits = datasetLimits(options.limits);
|
signal?.throwIfAborted();
|
||||||
options.signal?.throwIfAborted();
|
|
||||||
assertDatasetLimit(limits, 'maxInstruments', config.symbols.length);
|
|
||||||
validateHistoricalDataRequest(config);
|
validateHistoricalDataRequest(config);
|
||||||
const instruments = [...config.symbols].sort().map(parseInstrumentId);
|
const instruments = [...config.symbols].sort().map(parseInstrumentId);
|
||||||
const policy = dataPolicy(config);
|
const policy = dataPolicy(config);
|
||||||
const bars: HistoricalDataset['bars'] = [];
|
const bars: HistoricalDataset['bars'] = [];
|
||||||
const sources: HistoricalDataset['manifest']['sources'] = [];
|
const sources: HistoricalDataset['manifest']['sources'] = [];
|
||||||
let barBytes = 2;
|
|
||||||
for (const instrument of instruments) {
|
for (const instrument of instruments) {
|
||||||
options.signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
const remaining = limits.maxBars - bars.length;
|
const rows = await storage.getHistoricalBars(
|
||||||
if (!remaining) {
|
instrument.id,
|
||||||
assertDatasetLimit(limits, 'maxBars', bars.length + 1);
|
new Date(config.startDate),
|
||||||
}
|
new Date(config.endDate),
|
||||||
// A numeric field occupies at least one JSON byte. This conservative lower bound
|
config.dataFrequency,
|
||||||
// also bounds the query when the byte budget is much tighter than the bar budget.
|
policy,
|
||||||
const minimumBarBytes = Buffer.byteLength(
|
signal
|
||||||
JSON.stringify({
|
|
||||||
symbol: instrument.id,
|
|
||||||
timestamp: 0,
|
|
||||||
open: 1,
|
|
||||||
high: 1,
|
|
||||||
low: 1,
|
|
||||||
close: 1,
|
|
||||||
volume: 0,
|
|
||||||
vwap: 1,
|
|
||||||
})
|
|
||||||
);
|
);
|
||||||
const byteBound = Math.floor(
|
signal?.throwIfAborted();
|
||||||
(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);
|
|
||||||
const source = rows[0]?.source;
|
const source = rows[0]?.source;
|
||||||
if (!source) {
|
if (!source) {
|
||||||
throw new Error('Historical source provenance is missing or mixed');
|
throw new Error('Historical source provenance is missing or mixed');
|
||||||
|
|
@ -339,15 +229,13 @@ export async function loadDataset(
|
||||||
volume: bar.volume,
|
volume: bar.volume,
|
||||||
vwap: bar.vwap ?? (bar.high + bar.low + bar.close) / 3,
|
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);
|
bars.push(value);
|
||||||
if (bars.length % PREPARATION_BATCH_SIZE === 0) {
|
if (bars.length % PREPARATION_BATCH_SIZE === 0) {
|
||||||
await preparationCheckpoint(options.signal);
|
await preparationCheckpoint(signal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
options.signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
bars.sort(
|
bars.sort(
|
||||||
(a, b) => a.timestamp - b.timestamp || (a.symbol < b.symbol ? -1 : a.symbol > b.symbol ? 1 : 0)
|
(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,
|
bars,
|
||||||
};
|
};
|
||||||
return finishPreparation(canonicalize(dataset, config, options, true), options.signal);
|
return finishPreparation(canonicalize(dataset, config, signal, true), signal);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function resolveDataset(
|
export async function resolveDataset(
|
||||||
storage: Pick<StorageService, 'getHistoricalBars'>,
|
storage: Pick<StorageService, 'getHistoricalBars'>,
|
||||||
config: BacktestConfig,
|
config: BacktestConfig,
|
||||||
resolver?: DatasetResolver,
|
resolver?: DatasetResolver,
|
||||||
options: DatasetPreparationOptions = {}
|
signal?: AbortSignal
|
||||||
) {
|
) {
|
||||||
const limits = datasetLimits(options.limits);
|
signal?.throwIfAborted();
|
||||||
options.signal?.throwIfAborted();
|
|
||||||
assertDatasetLimit(limits, 'maxInstruments', config.symbols.length);
|
|
||||||
if (config.datasetHash && !resolver) {
|
if (config.datasetHash && !resolver) {
|
||||||
throw new Error('Dataset replay requires the durable backtest runner');
|
throw new Error('Dataset replay requires the durable backtest runner');
|
||||||
}
|
}
|
||||||
const load = () => loadDataset(storage, config, options);
|
const load = () => loadDataset(storage, config, signal);
|
||||||
return prepareDataset(
|
return prepareDataset(await (resolver ? resolver(load, signal) : load()), config, signal);
|
||||||
await (resolver ? resolver(load, options.signal) : load()),
|
|
||||||
config,
|
|
||||||
options
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
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,
|
QuestDBClient,
|
||||||
} from '@stock-bot/services';
|
} from '@stock-bot/services';
|
||||||
import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types';
|
import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types';
|
||||||
import {
|
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
||||||
assertDatasetLimit,
|
|
||||||
datasetLimits,
|
|
||||||
PREPARATION_BATCH_SIZE,
|
|
||||||
preparationCheckpoint,
|
|
||||||
} from '../data/dataset-limits';
|
|
||||||
import type { MarketData, ModeConfig, PerformanceMetrics } from '../types';
|
import type { MarketData, ModeConfig, PerformanceMetrics } from '../types';
|
||||||
|
|
||||||
export interface HistoricalReadOptions {
|
|
||||||
maxBars?: number;
|
|
||||||
signal?: AbortSignal;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HistoricalBar {
|
export interface HistoricalBar {
|
||||||
symbol: string;
|
symbol: string;
|
||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
|
|
@ -186,10 +176,9 @@ export class StorageService {
|
||||||
adjustment: 'raw',
|
adjustment: 'raw',
|
||||||
timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant',
|
timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant',
|
||||||
},
|
},
|
||||||
options: HistoricalReadOptions = {}
|
signal?: AbortSignal
|
||||||
): Promise<HistoricalBar[]> {
|
): Promise<HistoricalBar[]> {
|
||||||
const limits = datasetLimits({ maxBars: options.maxBars ?? datasetLimits().maxBars });
|
signal?.throwIfAborted();
|
||||||
options.signal?.throwIfAborted();
|
|
||||||
parseInstrumentId(symbol);
|
parseInstrumentId(symbol);
|
||||||
if (
|
if (
|
||||||
!Number.isFinite(startTime.getTime()) ||
|
!Number.isFinite(startTime.getTime()) ||
|
||||||
|
|
@ -210,15 +199,8 @@ export class StorageService {
|
||||||
'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants'
|
'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const rows = await this.readHistoricalBars(
|
const rows = await this.readHistoricalBars(symbol, startTime, endTime, interval);
|
||||||
symbol,
|
signal?.throwIfAborted();
|
||||||
startTime,
|
|
||||||
endTime,
|
|
||||||
interval,
|
|
||||||
limits.maxBars
|
|
||||||
);
|
|
||||||
options.signal?.throwIfAborted();
|
|
||||||
assertDatasetLimit(limits, 'maxBars', rows.length);
|
|
||||||
const bars: HistoricalBar[] = [];
|
const bars: HistoricalBar[] = [];
|
||||||
let processed = 0;
|
let processed = 0;
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
|
|
@ -276,10 +258,10 @@ export class StorageService {
|
||||||
bars.push({ ...row, symbol, timestamp, open, high, low, close, volume, vwap });
|
bars.push({ ...row, symbol, timestamp, open, high, low, close, volume, vwap });
|
||||||
}
|
}
|
||||||
if (++processed % PREPARATION_BATCH_SIZE === 0) {
|
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());
|
bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
||||||
if (!bars.length) {
|
if (!bars.length) {
|
||||||
throw new Error(`No historical data for ${symbol}`);
|
throw new Error(`No historical data for ${symbol}`);
|
||||||
|
|
@ -299,8 +281,7 @@ export class StorageService {
|
||||||
symbol: string,
|
symbol: string,
|
||||||
startTime: Date,
|
startTime: Date,
|
||||||
endTime: Date,
|
endTime: Date,
|
||||||
interval: string,
|
interval: string
|
||||||
maxBars: number
|
|
||||||
): Promise<HistoricalBar[]> {
|
): Promise<HistoricalBar[]> {
|
||||||
// If QuestDB is available, use real data
|
// If QuestDB is available, use real data
|
||||||
if (this.questdb) {
|
if (this.questdb) {
|
||||||
|
|
@ -308,10 +289,9 @@ export class StorageService {
|
||||||
throw new Error('Unsupported historical interval');
|
throw new Error('Unsupported historical interval');
|
||||||
}
|
}
|
||||||
const result = await this.questdb.query<HistoricalBar>(
|
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`,
|
`SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`,
|
||||||
[symbol, startTime, endTime, maxBars + 1]
|
[symbol, startTime, endTime]
|
||||||
);
|
);
|
||||||
assertDatasetLimit(datasetLimits({ maxBars }), 'maxBars', result.rows.length);
|
|
||||||
return result.rows.map(row => ({ ...row, source: 'questdb' }));
|
return result.rows.map(row => ({ ...row, source: 'questdb' }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -343,7 +323,6 @@ export class StorageService {
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
sort: { date: 1 },
|
sort: { date: 1 },
|
||||||
limit: maxBars + 1,
|
|
||||||
projection: {
|
projection: {
|
||||||
symbol: 1,
|
symbol: 1,
|
||||||
exchange: 1,
|
exchange: 1,
|
||||||
|
|
@ -359,7 +338,6 @@ export class StorageService {
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
assertDatasetLimit(datasetLimits({ maxBars }), 'maxBars', prices.length);
|
|
||||||
return prices.map(price => {
|
return prices.map(price => {
|
||||||
if (
|
if (
|
||||||
price.eodSearchCode !== identity.id ||
|
price.eodSearchCode !== identity.id ||
|
||||||
|
|
@ -393,11 +371,6 @@ export class StorageService {
|
||||||
'No historical data store configured; synthetic data requires explicit opt-in'
|
'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 => ({
|
return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({
|
||||||
...bar,
|
...bar,
|
||||||
source: 'synthetic',
|
source: 'synthetic',
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,6 @@ export async function createContainer(config: StockAppConfig) {
|
||||||
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
|
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
|
||||||
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
|
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
|
||||||
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
|
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
|
||||||
datasetLimits: config.services?.orchestrator?.backtesting?.datasetLimits,
|
|
||||||
});
|
});
|
||||||
return container.resolve('serviceContainer') as OrchestratorServices;
|
return container.resolve('serviceContainer') as OrchestratorServices;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,43 +1,21 @@
|
||||||
# Bounded backtest dataset preparation
|
# Backtest dataset preparation
|
||||||
|
|
||||||
Both backends use the same historical-data preparation boundary. Defaults are per run:
|
Both backends use the same historical-data preparation boundary. There are no
|
||||||
|
application-level instrument, bar-count, JSON/IPC-size or stored-snapshot-size caps,
|
||||||
|
and no dataset-limit configuration. Runs load the complete requested historical range
|
||||||
|
into memory; they are not silently truncated. Runtime, database and available-memory
|
||||||
|
constraints still apply. No environment-file changes or database migrations are required.
|
||||||
|
|
||||||
| Budget | Default | Enforcement |
|
## Loading and replay
|
||||||
| --- | --- | --- |
|
|
||||||
| `maxInstruments` | 100 | Before invoking storage or the replay resolver |
|
|
||||||
| `maxBars` | 1,000,000 | Aggregate remaining allowance, storage query and snapshot parsing |
|
|
||||||
| `maxSerializedBytes` | 256 MiB | Exact UTF-8 canonical dataset JSON, and separately the complete native IPC request |
|
|
||||||
| `maxStoredBytes` | 512 MiB | PostgreSQL JSONB text, before transferring the payload into the application |
|
|
||||||
|
|
||||||
Configure partial overrides at `services.orchestrator.backtesting.datasetLimits` in the
|
QuestDB and Mongo queries retain their instrument and exclusive date-range filters,
|
||||||
stock application configuration, or inject `datasetLimits` through
|
but have no application row limit. Mongo queries still project historical fields only.
|
||||||
`registerOrchestratorServices(container, options)`. Composition passes the same ceilings
|
Synthetic data still requires explicit opt-in and a stable seed.
|
||||||
to the runner, repository and selected backend. Defaults live only in `dataset-limits.ts`;
|
|
||||||
configuration schemas validate overrides without duplicating default values. Invalid,
|
|
||||||
zero, non-integer and unknown limits fail; there is no unlimited sentinel.
|
|
||||||
Direct backend/repository constructors also accept overrides for isolated workloads/tests.
|
|
||||||
No environment-file changes or database migrations are required.
|
|
||||||
|
|
||||||
## Admission and loading
|
Replay loads the stored JSONB snapshot and validates it before execution. Invalid prices,
|
||||||
|
duplicate or unordered bars, missing listings, incompatible requests and corrupted hashes
|
||||||
QuestDB and Mongo queries request at most the remaining bar allowance plus one overflow
|
remain errors. Failed snapshot preparation rolls back insertion and the run pointer
|
||||||
sentinel. Overflow is an error, **not a truncated backtest**. Mongo queries project only
|
together; the fencing/lease/cancellation predicates are unchanged.
|
||||||
historical fields. A conservative minimum encoded-row size further reduces the query
|
|
||||||
allowance for tight byte budgets. Actual normalized bar bytes are counted during loading;
|
|
||||||
the final canonical boundary includes all manifest overhead. Synthetic fixtures are
|
|
||||||
counted before generation and still require explicit opt-in.
|
|
||||||
|
|
||||||
Replay uses a SQL `CASE` expression to omit oversized stored JSONB payloads from query
|
|
||||||
results. Stored text has a separate ceiling because JSONB adds whitespace and expands
|
|
||||||
some number representations. Application-side canonical byte and content checks still
|
|
||||||
apply after this transport guard. Failed snapshot preparation rolls back insertion and
|
|
||||||
the run pointer together; the fencing/lease/cancellation predicates are unchanged.
|
|
||||||
|
|
||||||
These are admission budgets, **not heap-memory guarantees**. Database drivers still
|
|
||||||
materialize bounded result sets; sorting, JSONB persistence and IPC serialization still
|
|
||||||
need memory. A custom storage adapter must honor the read allowance before allocating its
|
|
||||||
results. The loader rejects an adapter's overflow too, but cannot undo its allocations.
|
|
||||||
No count-only database preflight is used, avoiding a count/read race.
|
|
||||||
|
|
||||||
## Canonical preparation and compatibility
|
## Canonical preparation and compatibility
|
||||||
|
|
||||||
|
|
@ -49,7 +27,7 @@ does not change identity. Prices, timestamp ties and adjustment policies are unc
|
||||||
Returned datasets are detached from caller inputs and deeply frozen, including nested
|
Returned datasets are detached from caller inputs and deeply frozen, including nested
|
||||||
manifest metadata and every bar. A private weak cache recognizes only these prepared
|
manifest metadata and every bar. A private weak cache recognizes only these prepared
|
||||||
objects. Internal handoffs reuse them without another array reconstruction/content hash;
|
objects. Internal handoffs reuse them without another array reconstruction/content hash;
|
||||||
request compatibility and the current ceilings are still checked. Raw database, resolver
|
request compatibility is still checked. Raw database, resolver
|
||||||
and caller objects always pass the full boundary. Clone a prepared value before editing
|
and caller objects always pass the full boundary. Clone a prepared value before editing
|
||||||
it; altered content requires a new valid hash, not mutation of a pinned snapshot.
|
it; altered content requires a new valid hash, not mutation of a pinned snapshot.
|
||||||
|
|
||||||
|
|
@ -58,7 +36,8 @@ calls. Runtime loading/restoration uses the asynchronous driver, yielding every
|
||||||
bars so cancellation, execution deadlines and lease heartbeats can run. Abort signals
|
bars so cancellation, execution deadlines and lease heartbeats can run. Abort signals
|
||||||
propagate through loading, resolver callbacks and repository preparation; cancelled late
|
propagate through loading, resolver callbacks and repository preparation; cancelled late
|
||||||
reads cannot dispatch a worker. Driver queries already in flight are not forcibly killed.
|
reads cannot dispatch a worker. Driver queries already in flight are not forcibly killed.
|
||||||
Sorting and final persistence/IPC serialization remain synchronous bounded operations.
|
Sorting and final persistence/IPC serialization remain synchronous operations. The batch
|
||||||
|
size controls event-loop yielding only; it is not an input limit.
|
||||||
|
|
||||||
## Reproducible preparation benchmark
|
## Reproducible preparation benchmark
|
||||||
|
|
||||||
|
|
@ -72,7 +51,8 @@ hashes must match. Timing excludes fixture creation. Peak RSS includes fixture c
|
||||||
and the runtime, so it is not an allocation counter or an incremental heap measurement.
|
and the runtime, so it is not an allocation counter or an incremental heap measurement.
|
||||||
This is not an end-to-end backtest/database/native-worker benchmark or a CI threshold.
|
This is not an end-to-end backtest/database/native-worker benchmark or a CI threshold.
|
||||||
|
|
||||||
One local Bun 1.2.17 run:
|
Historical Bun 1.2.17 sample, recorded before removal of the size-limit machinery
|
||||||
|
(not a claim about current timings):
|
||||||
|
|
||||||
| Bars / instruments | Previous time | Prepared time | Previous peak RSS | Prepared peak RSS |
|
| Bars / instruments | Previous time | Prepared time | Previous peak RSS | Prepared peak RSS |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
|
|
@ -80,15 +60,13 @@ One local Bun 1.2.17 run:
|
||||||
| 100,000 / 10 | 565 ms | 191 ms | 258 MiB | 176 MiB |
|
| 100,000 / 10 | 565 ms | 191 ms | 258 MiB | 176 MiB |
|
||||||
| 1,000,000 / 100 | 6,190 ms | 2,559 ms | 1,545 MiB | 695 MiB |
|
| 1,000,000 / 100 | 6,190 ms | 2,559 ms | 1,545 MiB | 695 MiB |
|
||||||
|
|
||||||
Results vary with machine load and garbage collection. The remaining memory footprint
|
Results vary with machine load and garbage collection. This optional diagnostic remains
|
||||||
supports retaining conservative budgets. Larger workloads should next measure a chunked
|
available; it does not impose input limits or change v1 content identity.
|
||||||
immutable snapshot reader and native transfer protocol; do not weaken validation or
|
|
||||||
change v1 content identity to increase throughput.
|
|
||||||
|
|
||||||
## Verification
|
## Verification
|
||||||
|
|
||||||
`bun run check` includes limit boundaries, immutable reuse, v1 hash compatibility,
|
`bun run check` includes complete-range reads without row caps, acceptance beyond the
|
||||||
deterministic replay, CPU cancellation, backend admission and overflow-query regressions.
|
former listing ceiling, immutable reuse, v1 hash compatibility, deterministic replay,
|
||||||
The disposable PostgreSQL/Redis suite additionally verifies stored-size rejection,
|
invalid-data rejection and CPU cancellation. The disposable PostgreSQL/Redis suite
|
||||||
tamper detection, cancellation/overflow rollback and existing lease/owner-loss replay.
|
additionally verifies tamper detection, cancellation rollback and lease/owner-loss replay.
|
||||||
See the root README for safety-suite setup; never use development trading databases.
|
See the root README for safety-suite setup; never use development trading databases.
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { expect, test } from 'bun:test';
|
import { expect, test } from 'bun:test';
|
||||||
import { createExampleRuntime } from '../../apps/stock/orchestrator/examples/example-runtime';
|
import { createExampleRuntime } from '../../apps/stock/orchestrator/examples/example-runtime';
|
||||||
import { backtestDatasetLimitsSchema } from '../../apps/stock/config/src/schemas/stock-app.schema';
|
|
||||||
|
|
||||||
test('offline examples use the shared DI graph without starting a real-time feed', async () => {
|
test('offline examples use the shared DI graph without starting a real-time feed', async () => {
|
||||||
const runtime = await createExampleRuntime();
|
const runtime = await createExampleRuntime();
|
||||||
|
|
@ -11,12 +10,3 @@ test('offline examples use the shared DI graph without starting a real-time feed
|
||||||
expect(runtime.modeManager.getConfig()).toBeNull();
|
expect(runtime.modeManager.getConfig()).toBeNull();
|
||||||
expect(() => runtime.modeManager.getTradingEngine()).toThrow('Trading engine not initialized');
|
expect(() => runtime.modeManager.getTradingEngine()).toThrow('Trading engine not initialized');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('dataset configuration accepts partial budgets and rejects invalid or misspelled ceilings', () => {
|
|
||||||
expect(backtestDatasetLimitsSchema.parse({ maxBars: 1000 })).toEqual({ maxBars: 1000 });
|
|
||||||
expect(backtestDatasetLimitsSchema.parse({})).toEqual({});
|
|
||||||
for (const maxBars of [0, -1, 1.5, Infinity, Number.MAX_SAFE_INTEGER]) {
|
|
||||||
expect(backtestDatasetLimitsSchema.safeParse({ maxBars }).success).toBe(false);
|
|
||||||
}
|
|
||||||
expect(backtestDatasetLimitsSchema.safeParse({ maxBar: 1000 }).success).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
|
||||||
|
|
@ -70,12 +70,6 @@ async function fixture(
|
||||||
impure: true,
|
impure: true,
|
||||||
implementation: () => new Date(),
|
implementation: () => new Date(),
|
||||||
});
|
});
|
||||||
db.public.registerFunction({
|
|
||||||
name: 'octet_length',
|
|
||||||
args: [DataType.text],
|
|
||||||
returns: DataType.integer,
|
|
||||||
implementation: (value: string) => Buffer.byteLength(value),
|
|
||||||
});
|
|
||||||
db.public
|
db.public
|
||||||
.none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
.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,
|
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
|
||||||
|
|
|
||||||
|
|
@ -3,17 +3,9 @@ import { setImmediate } from 'node:timers/promises';
|
||||||
import { describe, expect, test } from 'bun:test';
|
import { describe, expect, test } from 'bun:test';
|
||||||
import type { MongoDBClient, QuestDBClient } from '@stock-bot/services';
|
import type { MongoDBClient, QuestDBClient } from '@stock-bot/services';
|
||||||
import { parseInstrumentId, type HistoricalDataset } from '@stock-bot/types';
|
import { parseInstrumentId, type HistoricalDataset } from '@stock-bot/types';
|
||||||
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
|
||||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
|
||||||
import { datasetSchema } from '../../apps/stock/orchestrator/src/contracts/historical';
|
import { datasetSchema } from '../../apps/stock/orchestrator/src/contracts/historical';
|
||||||
import {
|
import {
|
||||||
DatasetLimitError,
|
|
||||||
datasetLimits,
|
|
||||||
} from '../../apps/stock/orchestrator/src/data/dataset-limits';
|
|
||||||
import {
|
|
||||||
assertNativeDatasetBudget,
|
|
||||||
datasetSize,
|
|
||||||
loadDataset,
|
loadDataset,
|
||||||
prepareDataset,
|
prepareDataset,
|
||||||
resolveDataset,
|
resolveDataset,
|
||||||
|
|
@ -23,7 +15,6 @@ import {
|
||||||
StorageService,
|
StorageService,
|
||||||
type HistoricalBar,
|
type HistoricalBar,
|
||||||
} from '../../apps/stock/orchestrator/src/services/StorageService';
|
} from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||||
import type { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
|
||||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||||
import { logger } from '../fixtures/execution';
|
import { logger } from '../fixtures/execution';
|
||||||
|
|
||||||
|
|
@ -96,7 +87,7 @@ function legacyFixture(count = 3): HistoricalDataset {
|
||||||
return dataset;
|
return dataset;
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('bounded historical dataset preparation', () => {
|
describe('historical dataset preparation', () => {
|
||||||
test('preserves v1 whole-JSON hashes and canonical key ordering, including Unicode metadata', async () => {
|
test('preserves v1 whole-JSON hashes and canonical key ordering, including Unicode metadata', async () => {
|
||||||
const expected = legacyFixture();
|
const expected = legacyFixture();
|
||||||
const loaded = await loadDataset(
|
const loaded = await loadDataset(
|
||||||
|
|
@ -121,7 +112,6 @@ describe('bounded historical dataset preparation', () => {
|
||||||
.digest('hex');
|
.digest('hex');
|
||||||
const result = validateDataset(expected, config);
|
const result = validateDataset(expected, config);
|
||||||
expect(result.manifest.hash).toBe(expected.manifest.hash);
|
expect(result.manifest.hash).toBe(expected.manifest.hash);
|
||||||
expect(datasetSize(result).serializedBytes).toBe(Buffer.byteLength(JSON.stringify(expected)));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('only deeply immutable detached preparations are reused; mutable inputs are always rechecked', async () => {
|
test('only deeply immutable detached preparations are reused; mutable inputs are always rechecked', async () => {
|
||||||
|
|
@ -150,7 +140,6 @@ describe('bounded historical dataset preparation', () => {
|
||||||
dataset.manifest.instruments[0],
|
dataset.manifest.instruments[0],
|
||||||
dataset.manifest.sources,
|
dataset.manifest.sources,
|
||||||
dataset.manifest.sources[0],
|
dataset.manifest.sources[0],
|
||||||
datasetSize(dataset),
|
|
||||||
]) {
|
]) {
|
||||||
expect(Object.isFrozen(value)).toBe(true);
|
expect(Object.isFrozen(value)).toBe(true);
|
||||||
}
|
}
|
||||||
|
|
@ -165,15 +154,8 @@ describe('bounded historical dataset preparation', () => {
|
||||||
expect(dataset.bars[0]?.volume).toBe(0);
|
expect(dataset.bars[0]?.volume).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('cached preparations still enforce tighter budgets and request identity', async () => {
|
test('cached preparations still enforce request identity', async () => {
|
||||||
const dataset = await prepareDataset(legacyFixture());
|
const dataset = await prepareDataset(legacyFixture());
|
||||||
expect(() => validateDataset(dataset, config, { limits: { maxBars: 5 } })).toThrow('maxBars');
|
|
||||||
expect(() => validateDataset(dataset, config, { limits: { maxInstruments: 1 } })).toThrow(
|
|
||||||
'maxInstruments'
|
|
||||||
);
|
|
||||||
expect(() => validateDataset(dataset, config, { limits: { maxSerializedBytes: 1 } })).toThrow(
|
|
||||||
'maxSerializedBytes'
|
|
||||||
);
|
|
||||||
expect(() => validateDataset(dataset, { ...config, symbols: ['A.US'] })).toThrow(
|
expect(() => validateDataset(dataset, { ...config, symbols: ['A.US'] })).toThrow(
|
||||||
'does not match'
|
'does not match'
|
||||||
);
|
);
|
||||||
|
|
@ -182,44 +164,25 @@ describe('bounded historical dataset preparation', () => {
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('admission rejects excessive instruments before invoking storage or a resolver', async () => {
|
test('all requested instruments and bars are retained without a listing ceiling', async () => {
|
||||||
let calls = 0;
|
const request = { ...config, symbols: Array.from({ length: 101 }, (_, i) => `S${i}.US`) };
|
||||||
const storage = {
|
const loaded = await loadDataset(
|
||||||
async getHistoricalBars() {
|
{
|
||||||
calls++;
|
async getHistoricalBars(symbol) {
|
||||||
return [];
|
return rows(symbol);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
request
|
||||||
const resolver = async () => {
|
|
||||||
calls++;
|
|
||||||
return legacyFixture();
|
|
||||||
};
|
|
||||||
await expect(
|
|
||||||
resolveDataset(storage, config, resolver, { limits: { maxInstruments: 1 } })
|
|
||||||
).rejects.toBeInstanceOf(DatasetLimitError);
|
|
||||||
await expect(loadDataset(storage, config, { limits: { maxInstruments: 1 } })).rejects.toThrow(
|
|
||||||
'maxInstruments'
|
|
||||||
);
|
);
|
||||||
expect(calls).toBe(0);
|
expect(loaded.manifest.instruments).toHaveLength(101);
|
||||||
|
expect(loaded.bars).toHaveLength(303);
|
||||||
|
expect(loaded.manifest.barCount).toBe(303);
|
||||||
|
expect(await prepareDataset(structuredClone(loaded), request)).toEqual(loaded);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('untrusted array sizes fail before individual bars are parsed', () => {
|
test('resolver and storage reads receive the same cancellation signal directly', async () => {
|
||||||
const dataset = legacyFixture();
|
const controller = new AbortController();
|
||||||
Object.defineProperty(dataset.bars, 0, {
|
const seen: string[] = [];
|
||||||
get() {
|
|
||||||
throw new Error('should not inspect bar');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(() => validateDataset(dataset, undefined, { limits: { maxBars: 5 } })).toThrow(
|
|
||||||
'maxBars'
|
|
||||||
);
|
|
||||||
const hugeSources = legacyFixture();
|
|
||||||
hugeSources.manifest.sources = new Array(101);
|
|
||||||
expect(() => validateDataset(hugeSources)).toThrow('maxInstruments');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('aggregate bar allowance shrinks across instruments and fails without truncation', async () => {
|
|
||||||
const allowances: number[] = [];
|
|
||||||
const storage = {
|
const storage = {
|
||||||
async getHistoricalBars(
|
async getHistoricalBars(
|
||||||
symbol: string,
|
symbol: string,
|
||||||
|
|
@ -227,31 +190,32 @@ describe('bounded historical dataset preparation', () => {
|
||||||
_end: Date,
|
_end: Date,
|
||||||
_interval?: string,
|
_interval?: string,
|
||||||
_policy?: unknown,
|
_policy?: unknown,
|
||||||
options?: { maxBars?: number }
|
signal?: AbortSignal
|
||||||
) {
|
) {
|
||||||
allowances.push(options!.maxBars!);
|
expect(signal).toBe(controller.signal);
|
||||||
|
seen.push(symbol);
|
||||||
return rows(symbol);
|
return rows(symbol);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
await expect(loadDataset(storage, config, { limits: { maxBars: 5 } })).rejects.toThrow(
|
const dataset = await resolveDataset(
|
||||||
'maxBars'
|
storage,
|
||||||
|
config,
|
||||||
|
async (load, signal) => {
|
||||||
|
expect(signal).toBe(controller.signal);
|
||||||
|
return load();
|
||||||
|
},
|
||||||
|
controller.signal
|
||||||
);
|
);
|
||||||
expect(allowances).toEqual([5, 2]);
|
expect(seen).toEqual(config.symbols);
|
||||||
expect((await loadDataset(storage, config, { limits: { maxBars: 6 } })).bars).toHaveLength(6);
|
expect(dataset).toEqual(legacyFixture());
|
||||||
});
|
});
|
||||||
|
|
||||||
test('QuestDB requests one overflow sentinel and rejects overflow rather than replaying a prefix', async () => {
|
test('QuestDB reads the full requested range without a row cap', async () => {
|
||||||
let count = 2;
|
|
||||||
const questdb = {
|
const questdb = {
|
||||||
async query(sql: string, parameters: unknown[]) {
|
async query(sql: string, parameters: unknown[]) {
|
||||||
expect(sql).toContain('LIMIT $4');
|
expect(sql).not.toContain('LIMIT');
|
||||||
expect(parameters).toEqual([
|
expect(parameters).toEqual(['A.US', new Date(config.startDate), new Date(config.endDate)]);
|
||||||
'A.US',
|
return { rows: rows('A.US', 5) };
|
||||||
new Date(config.startDate),
|
|
||||||
new Date(config.endDate),
|
|
||||||
3,
|
|
||||||
]);
|
|
||||||
return { rows: rows('A.US', count) };
|
|
||||||
},
|
},
|
||||||
} as unknown as QuestDBClient;
|
} as unknown as QuestDBClient;
|
||||||
const storage = new StorageService({ logger }, null, null, questdb);
|
const storage = new StorageService({ logger }, null, null, questdb);
|
||||||
|
|
@ -260,35 +224,17 @@ describe('bounded historical dataset preparation', () => {
|
||||||
'A.US',
|
'A.US',
|
||||||
new Date(config.startDate),
|
new Date(config.startDate),
|
||||||
new Date(config.endDate),
|
new Date(config.endDate),
|
||||||
'1m',
|
'1m'
|
||||||
undefined,
|
|
||||||
{ maxBars: 2 }
|
|
||||||
)
|
)
|
||||||
).toHaveLength(2);
|
).toHaveLength(5);
|
||||||
count = 3;
|
|
||||||
await expect(
|
|
||||||
storage.getHistoricalBars(
|
|
||||||
'A.US',
|
|
||||||
new Date(config.startDate),
|
|
||||||
new Date(config.endDate),
|
|
||||||
'1m',
|
|
||||||
undefined,
|
|
||||||
{ maxBars: 2 }
|
|
||||||
)
|
|
||||||
).rejects.toThrow('maxBars');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Mongo reads are projected and row-bounded before normalization', async () => {
|
test('Mongo reads retain their historical-field projection without a row cap', async () => {
|
||||||
let count = 2;
|
|
||||||
const mongodb = {
|
const mongodb = {
|
||||||
async find(
|
async find(_collection: string, _filter: unknown, options: { projection: unknown }) {
|
||||||
_collection: string,
|
expect(options).not.toHaveProperty('limit');
|
||||||
_filter: unknown,
|
|
||||||
options: { limit: number; projection: unknown }
|
|
||||||
) {
|
|
||||||
expect(options.limit).toBe(3);
|
|
||||||
expect(options.projection).toHaveProperty('eodSearchCode', 1);
|
expect(options.projection).toHaveProperty('eodSearchCode', 1);
|
||||||
return Array.from({ length: count }, (_, i) => ({
|
return Array.from({ length: 5 }, (_, i) => ({
|
||||||
symbol: 'A',
|
symbol: 'A',
|
||||||
exchange: 'US',
|
exchange: 'US',
|
||||||
eodSearchCode: 'A.US',
|
eodSearchCode: 'A.US',
|
||||||
|
|
@ -303,73 +249,8 @@ describe('bounded historical dataset preparation', () => {
|
||||||
} as unknown as MongoDBClient;
|
} as unknown as MongoDBClient;
|
||||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||||
const read = () =>
|
const read = () =>
|
||||||
storage.getHistoricalBars(
|
storage.getHistoricalBars('A.US', new Date(config.startDate), new Date(config.endDate), '1d');
|
||||||
'A.US',
|
expect(await read()).toHaveLength(5);
|
||||||
new Date(config.startDate),
|
|
||||||
new Date(config.endDate),
|
|
||||||
'1d',
|
|
||||||
undefined,
|
|
||||||
{ maxBars: 2 }
|
|
||||||
);
|
|
||||||
expect(await read()).toHaveLength(2);
|
|
||||||
count = 3;
|
|
||||||
await expect(read()).rejects.toThrow('maxBars');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a tight byte budget bounds the database query and reports the byte resource', async () => {
|
|
||||||
const questdb = {
|
|
||||||
async query(_sql: string, parameters: unknown[]) {
|
|
||||||
expect(parameters[3]).toBeLessThan(10);
|
|
||||||
return { rows: rows('A.US', Number(parameters[3])) };
|
|
||||||
},
|
|
||||||
} as unknown as QuestDBClient;
|
|
||||||
const storage = new StorageService({ logger }, null, null, questdb);
|
|
||||||
await expect(
|
|
||||||
loadDataset(storage, config, { limits: { maxSerializedBytes: 500 } })
|
|
||||||
).rejects.toThrow('maxSerializedBytes');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('synthetic histories are counted and rejected before generation', async () => {
|
|
||||||
const storage = new StorageService({ logger }, null, null, null, { allowSyntheticData: true });
|
|
||||||
await expect(
|
|
||||||
storage.getHistoricalBars(
|
|
||||||
'A.US',
|
|
||||||
new Date(config.startDate),
|
|
||||||
new Date(config.endDate),
|
|
||||||
'1m',
|
|
||||||
undefined,
|
|
||||||
{ maxBars: 2 }
|
|
||||||
)
|
|
||||||
).rejects.toThrow('maxBars');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('exact UTF-8 payload boundaries include manifest overhead and the complete native request', async () => {
|
|
||||||
const dataset = await prepareDataset(legacyFixture());
|
|
||||||
const bytes = Buffer.byteLength(JSON.stringify(dataset));
|
|
||||||
expect(validateDataset(dataset, config, { limits: { maxSerializedBytes: bytes } })).toBe(
|
|
||||||
dataset
|
|
||||||
);
|
|
||||||
expect(() =>
|
|
||||||
validateDataset(legacyFixture(), config, { limits: { maxSerializedBytes: bytes - 1 } })
|
|
||||||
).toThrow('maxSerializedBytes');
|
|
||||||
const nativeConfig = { ...config, config: { notes: '市場'.repeat(1000) } };
|
|
||||||
const nativeBytes = Buffer.byteLength(
|
|
||||||
JSON.stringify({
|
|
||||||
type: 'run',
|
|
||||||
config: nativeConfig,
|
|
||||||
data: dataset.bars.map(bar => ({ ...bar, type: 'bar' })),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
expect(() =>
|
|
||||||
assertNativeDatasetBudget(dataset, nativeConfig, {
|
|
||||||
limits: { maxSerializedBytes: nativeBytes },
|
|
||||||
})
|
|
||||||
).not.toThrow();
|
|
||||||
expect(() =>
|
|
||||||
assertNativeDatasetBudget(dataset, nativeConfig, {
|
|
||||||
limits: { maxSerializedBytes: nativeBytes - 1 },
|
|
||||||
})
|
|
||||||
).toThrow('maxSerializedBytes');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('unknown resolver values still pass the full content boundary and replay requires durability', async () => {
|
test('unknown resolver values still pass the full content boundary and replay requires durability', async () => {
|
||||||
|
|
@ -404,11 +285,11 @@ describe('bounded historical dataset preparation', () => {
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
const work = loadDataset(storage, config, { signal: controller.signal });
|
const work = loadDataset(storage, config, controller.signal);
|
||||||
controller.abort(reason);
|
controller.abort(reason);
|
||||||
release(rows('A.US'));
|
release(rows('A.US'));
|
||||||
expect(await work.catch(error => error)).toBe(reason);
|
expect(await work.catch(error => error)).toBe(reason);
|
||||||
await expect(loadDataset(storage, config, { signal: controller.signal })).rejects.toBe(reason);
|
await expect(loadDataset(storage, config, controller.signal)).rejects.toBe(reason);
|
||||||
expect(reads).toBe(1);
|
expect(reads).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -422,43 +303,49 @@ describe('bounded historical dataset preparation', () => {
|
||||||
throw new Error('read after cancellation');
|
throw new Error('read after cancellation');
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const work = prepareDataset(input, config, { signal: controller.signal });
|
const work = prepareDataset(input, config, controller.signal);
|
||||||
await setImmediate();
|
await setImmediate();
|
||||||
controller.abort(reason);
|
controller.abort(reason);
|
||||||
expect(await work.catch(error => error)).toBe(reason);
|
expect(await work.catch(error => error)).toBe(reason);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('both backends reject oversized requests before strategy setup or native worker spawn', async () => {
|
test('removing size limits does not permit invalid bars, manifests or request identities', async () => {
|
||||||
const storage = new StorageService({ logger }, null, null, null, { allowSyntheticData: true });
|
for (const change of [
|
||||||
const manager = {} as StrategyManager; // Any strategy setup would fail this fixture.
|
(dataset: HistoricalDataset) => {
|
||||||
const engine = new BacktestEngine({ logger }, storage, manager, {
|
dataset.bars[0]!.volume = -1;
|
||||||
datasetLimits: { maxInstruments: 1 },
|
},
|
||||||
});
|
(dataset: HistoricalDataset) => {
|
||||||
await expect(engine.runBacktest(config)).rejects.toThrow('maxInstruments');
|
dataset.bars[0]!.close = NaN;
|
||||||
expect(engine.getStatus().isRunning).toBe(false);
|
},
|
||||||
const native = new RustBacktestAdapter(
|
(dataset: HistoricalDataset) => {
|
||||||
{ logger, custom: { StorageService: storage } },
|
dataset.bars.reverse();
|
||||||
{
|
},
|
||||||
datasetLimits: { maxSerializedBytes: 3000 },
|
(dataset: HistoricalDataset) => {
|
||||||
workerUrl: new URL('file:///must-not-spawn-dataset-test.ts'),
|
dataset.manifest.barCount++;
|
||||||
}
|
},
|
||||||
);
|
(dataset: HistoricalDataset) => {
|
||||||
const short = {
|
dataset.manifest.sources.pop();
|
||||||
...config,
|
},
|
||||||
symbols: ['A.US'],
|
]) {
|
||||||
endDate: new Date(start + 120000).toISOString(),
|
const dataset = legacyFixture();
|
||||||
name: 'x'.repeat(5000),
|
change(dataset);
|
||||||
};
|
await expect(prepareDataset(dataset)).rejects.toThrow();
|
||||||
await expect(native.runBacktest(short)).rejects.toThrow('maxSerializedBytes');
|
|
||||||
await expect(native.runBacktest(short)).rejects.toThrow('maxSerializedBytes');
|
|
||||||
expect(native.getStatus().isRunning).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('invalid budgets fail closed instead of disabling limits', () => {
|
|
||||||
for (const maxBars of [0, -1, NaN, Infinity, 1.5, Number.MAX_SAFE_INTEGER]) {
|
|
||||||
expect(() => datasetLimits({ maxBars })).toThrow('Invalid dataset limit');
|
|
||||||
}
|
}
|
||||||
expect(() => datasetLimits({ unexpected: 1 } as never)).toThrow('Invalid dataset limit');
|
let reads = 0;
|
||||||
expect(Object.isFrozen(datasetLimits())).toBe(true);
|
await expect(
|
||||||
|
loadDataset(
|
||||||
|
{
|
||||||
|
async getHistoricalBars() {
|
||||||
|
reads++;
|
||||||
|
return [];
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...config,
|
||||||
|
symbols: ['A.US', 'A.US'],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
).rejects.toThrow('distinct');
|
||||||
|
expect(reads).toBe(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,6 @@ import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backte
|
||||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||||
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||||
import { DatasetLimitError } from '../../apps/stock/orchestrator/src/data/dataset-limits';
|
|
||||||
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||||
|
|
@ -295,36 +294,6 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('oversized snapshots fail before pinning and persisted JSONB size is checked before transfer', async () => {
|
|
||||||
const f = await fixture();
|
|
||||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
|
||||||
const config = await f.snapshot(run.id);
|
|
||||||
const claim = await f.repository.start(config);
|
|
||||||
const dataset = await loadDataset(f.storage, config);
|
|
||||||
const small = new PostgresBacktestRunRepository(f.postgres, 2000, { maxBars: 1 });
|
|
||||||
await expect(small.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toBeInstanceOf(
|
|
||||||
DatasetLimitError
|
|
||||||
);
|
|
||||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0);
|
|
||||||
expect(
|
|
||||||
(await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0]
|
|
||||||
.dataset_hash
|
|
||||||
).toBeNull();
|
|
||||||
// A stored-text overflow during freeze must roll back both insertion and pinning too.
|
|
||||||
const storedBudget = new PostgresBacktestRunRepository(f.postgres, 2000, { maxStoredBytes: 1 });
|
|
||||||
await expect(
|
|
||||||
storedBudget.freezeDataset(run.id, claim.attemptId, dataset)
|
|
||||||
).rejects.toBeInstanceOf(DatasetLimitError);
|
|
||||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0);
|
|
||||||
await f.repository.freezeDataset(run.id, claim.attemptId, dataset);
|
|
||||||
await expect(storedBudget.loadDataset(run.id, claim.attemptId)).rejects.toBeInstanceOf(
|
|
||||||
DatasetLimitError
|
|
||||||
);
|
|
||||||
expect((await f.repository.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe(
|
|
||||||
dataset.manifest.hash
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('cancellation after snapshot insertion aborts preparation and rolls back the run pointer and payload', async () => {
|
test('cancellation after snapshot insertion aborts preparation and rolls back the run pointer and payload', async () => {
|
||||||
const f = await fixture();
|
const f = await fixture();
|
||||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue