diff --git a/README.md b/README.md index 59e2abc6..924f3778 100644 --- a/README.md +++ b/README.md @@ -313,8 +313,12 @@ history. Runs capture data at execution preparation, **not HTTP acceptance time* 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 calls can load data for diagnostics, but durable replay/persistence requires the runner. -Snapshots are currently JSONB and load in memory; large tick datasets need chunked storage -and an explicit retention policy before scaling. +Dataset preparation enforces configurable instrument, bar-count, JSON/IPC and stored-JSONB +budgets. Internal handoffs reuse deeply frozen validated inputs; restored snapshots are +always content-checked. Existing v1 hashes and replay identities are unchanged. +See [dataset limits and preparation benchmarks](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 diff --git a/apps/stock/config/src/schemas/stock-app.schema.ts b/apps/stock/config/src/schemas/stock-app.schema.ts index cd187800..87c82f86 100644 --- a/apps/stock/config/src/schemas/stock-app.schema.ts +++ b/apps/stock/config/src/schemas/stock-app.schema.ts @@ -9,6 +9,20 @@ 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 */ @@ -93,6 +107,7 @@ 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'), diff --git a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts index ac59f602..fa4046e6 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'; import { EventEmitter } from 'node:events'; import { defined } from '@stock-bot/invariants'; import { DataManager } from '../data/DataManager'; +import { datasetLimits, type DatasetLimits } from '../data/dataset-limits'; import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; import { amount, decimal } from '../execution/model'; import type { StorageService } from '../services/StorageService'; @@ -24,13 +25,16 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng private active?: Promise; private completedReport?: BacktestReport; private closing = false; + private readonly datasetLimits: Readonly; constructor( private readonly container: OrchestratorServices, private readonly storageService: StorageService, - private readonly strategyManager: StrategyManager + private readonly strategyManager: StrategyManager, + options: { datasetLimits?: Partial } = {} ) { super(); + this.datasetLimits = datasetLimits(options.datasetLimits); } async runBacktest(input: unknown, resolver?: DatasetResolver): Promise { @@ -61,7 +65,10 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng const plan = backtestStrategies(config, 'typescript'); this.container.logger.info('Starting TypeScript backtest', { symbols: config.symbols }); const dataset = await playback.read(() => - resolveDataset(this.storageService, config, resolver) + resolveDataset(this.storageService, config, resolver, { + limits: this.datasetLimits, + signal: playback.signal, + }) ); playback.assertRunning(); const dataManager = new DataManager(this.storageService); diff --git a/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts b/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts index db85f909..bfb18848 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts @@ -39,6 +39,10 @@ export class BacktestPlayback { this.controller.signal.throwIfAborted(); } + get signal(): AbortSignal { + return this.controller.signal; + } + /** Only race side-effect-free reads; late reads must never resume execution. */ async read(load: () => Promise): Promise { this.assertRunning(); diff --git a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts index a04f6ba2..a9a1f4ad 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts @@ -3,7 +3,8 @@ import { z } from 'zod'; import type { Logger } from '@stock-bot/services'; import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types'; import { validateHistoricalDataRequest } from '@stock-bot/types'; -import { dataPolicy, validateDataset } from '../data/historical-dataset'; +import { datasetLimits, type DatasetLimits } from '../data/dataset-limits'; +import { dataPolicy, prepareDataset } from '../data/historical-dataset'; import { BacktestConfigSchema, type BacktestConfig } from '../types'; import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine'; import { normalizeBacktestResult } from './result'; @@ -36,6 +37,7 @@ export class BacktestRunner extends EventEmitter { private closing = false; private phase: 'preparing' | 'executing' | 'persisting' = 'preparing'; private execution: Promise | undefined; + private readonly datasetLimits: Readonly; constructor( private readonly dependencies: { @@ -45,10 +47,12 @@ export class BacktestRunner extends EventEmitter { logger: Pick; heartbeatMs?: number; heartbeatTimeoutMs?: number; + datasetLimits?: Partial; prepare?: (config: BacktestConfig) => Promise; } ) { super(); + this.datasetLimits = datasetLimits(dependencies.datasetLimits); } async runBacktest(input: unknown): Promise { @@ -199,19 +203,34 @@ export class BacktestRunner extends EventEmitter { this.phase = 'executing'; let manifest: HistoricalDatasetManifest | undefined; const claim = this.active; - const raw = await this.dependencies.engine.runBacktest(executionConfig, async load => { - const saved = await this.dependencies.repository.loadDataset( - claim.runId, - claim.attemptId, - executionConfig.datasetHash - ); - const dataset = validateDataset(saved ?? (await load()), executionConfig); - const frozen = - saved ?? - (await this.dependencies.repository.freezeDataset(claim.runId, claim.attemptId, dataset)); - manifest = frozen.manifest; - return frozen; - }); + const raw = await this.dependencies.engine.runBacktest( + executionConfig, + async (load, signal) => { + signal?.throwIfAborted(); + const saved = await this.dependencies.repository.loadDataset( + claim.runId, + claim.attemptId, + executionConfig.datasetHash, + signal + ); + const dataset = await prepareDataset(saved ?? (await load()), executionConfig, { + limits: this.datasetLimits, + signal, + }); + signal?.throwIfAborted(); + const frozen = + saved ?? + (await this.dependencies.repository.freezeDataset( + claim.runId, + claim.attemptId, + dataset, + signal + )); + signal?.throwIfAborted(); + manifest = frozen.manifest; + return frozen; + } + ); if (!manifest) { throw new Error('Backtest engine did not resolve frozen execution inputs'); } diff --git a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts index 56e2a8af..94a390ac 100644 --- a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts +++ b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts @@ -1,8 +1,10 @@ import { randomUUID } from 'node:crypto'; +import type { PoolClient } from 'pg'; import type { TransactionCallback } from '@stock-bot/postgres'; import type { PostgresClient } from '@stock-bot/services'; import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types'; -import { validateDataset } from '../data/historical-dataset'; +import { assertDatasetLimit, datasetLimits, type DatasetLimits } from '../data/dataset-limits'; +import { prepareDataset } from '../data/historical-dataset'; import { BacktestConfigSchema, type BacktestConfig } from '../types'; import { BacktestCancelledError } from './execution-engine'; import { @@ -14,10 +16,13 @@ import { /** The attempt UUID is a fencing token. PostgreSQL time, not worker clocks, defines ownership. */ export class PostgresBacktestRunRepository implements BacktestRunRepository { + private readonly datasetLimits: Readonly; constructor( private readonly postgres: Pick, - private readonly leaseMs = 30_000 + private readonly leaseMs = 30_000, + limits?: Partial ) { + this.datasetLimits = datasetLimits(limits); if (!Number.isInteger(leaseMs) || leaseMs < 100) { throw new Error('Invalid execution lease duration'); } @@ -130,8 +135,10 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { async loadDataset( runId: string, attemptId: string, - requestedHash?: string + requestedHash?: string, + signal?: AbortSignal ): Promise { + signal?.throwIfAborted(); return this.ownedTransaction(runId, async client => { const owned = await client.query( `SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2 @@ -148,16 +155,8 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { if (requestedHash && requestedHash !== hash) { throw new BacktestConflictError('Run dataset is already frozen'); } - const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [ - hash, - ]); - if (!saved.rows[0]) { - throw new Error('Frozen dataset not found'); - } - const dataset = validateDataset(saved.rows[0].payload); - if (dataset.manifest.hash !== hash) { - throw new Error('Stored dataset identity mismatch'); - } + const dataset = await this.readDataset(client, String(hash), signal); + signal?.throwIfAborted(); const pinned = await client.query( `UPDATE runs SET dataset_hash = $2 WHERE id = $1 AND attempt_id = $3 AND lease_expires_at > clock_timestamp() @@ -167,6 +166,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { if (!pinned.rows.length) { throw new BacktestLeaseLostError('Execution lease lost while pinning dataset'); } + signal?.throwIfAborted(); return dataset; }); } @@ -174,9 +174,10 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { async freezeDataset( runId: string, attemptId: string, - input: HistoricalDataset + input: HistoricalDataset, + signal?: AbortSignal ): Promise { - const dataset = validateDataset(input); + const dataset = await prepareDataset(input, undefined, { limits: this.datasetLimits, signal }); return this.ownedTransaction(runId, async client => { const owned = await client.query( `SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2 @@ -190,17 +191,13 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { if (owned.rows[0].dataset_hash && owned.rows[0].dataset_hash !== hash) { throw new BacktestConflictError('Run dataset is already frozen'); } + signal?.throwIfAborted(); await client.query( 'INSERT INTO backtest_datasets (hash, payload) VALUES ($1, $2::jsonb) ON CONFLICT (hash) DO NOTHING', [hash, JSON.stringify(dataset)] ); - const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [ - hash, - ]); - const frozen = validateDataset(saved.rows[0]?.payload); - if (frozen.manifest.hash !== hash) { - throw new Error('Stored dataset identity mismatch'); - } + const frozen = await this.readDataset(client, hash, signal); + signal?.throwIfAborted(); const pinned = await client.query( `UPDATE runs SET dataset_hash = $2 WHERE id = $1 AND attempt_id = $3 AND lease_expires_at > clock_timestamp() @@ -210,10 +207,38 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { if (!pinned.rows.length) { throw new BacktestLeaseLostError('Execution lease lost while pinning dataset'); } + signal?.throwIfAborted(); return frozen; }); } + private async readDataset( + client: PoolClient, + hash: string, + signal?: AbortSignal + ): Promise { + signal?.throwIfAborted(); + // Never transfer/parse an oversized JSONB document into the application process. + const saved = await client.query( + `SELECT CASE WHEN octet_length(payload::text) <= $2 THEN payload ELSE NULL END AS payload, + octet_length(payload::text) AS payload_bytes FROM backtest_datasets WHERE hash = $1`, + [hash, this.datasetLimits.maxStoredBytes] + ); + const row = saved.rows[0]; + if (!row) { + throw new Error('Frozen dataset not found'); + } + assertDatasetLimit(this.datasetLimits, 'maxStoredBytes', Number(row.payload_bytes)); + const dataset = await prepareDataset(row.payload, undefined, { + limits: this.datasetLimits, + signal, + }); + if (dataset.manifest.hash !== hash) { + throw new Error('Stored dataset identity mismatch'); + } + return dataset; + } + /** Lock first, then evaluate the lease against real DB time. UPDATE can evaluate its * predicate before waiting on a row lock, even when the predicate uses clock_timestamp(). */ private ownedTransaction(runId: string, work: TransactionCallback): Promise { diff --git a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts index 20a30451..1a9cf7e1 100644 --- a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts +++ b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts @@ -1,5 +1,15 @@ import { EventEmitter } from 'node:events'; -import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; +import { + datasetLimits, + PREPARATION_BATCH_SIZE, + preparationCheckpoint, + type DatasetLimits, +} from '../data/dataset-limits'; +import { + assertNativeDatasetBudget, + resolveDataset, + type DatasetResolver, +} from '../data/historical-dataset'; import { StorageService } from '../services/StorageService'; import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types'; import { @@ -19,6 +29,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti private readonly storageService: StorageService; private readonly worker: NativeBacktestWorker; private readonly timeoutMs: number; + private readonly datasetLimits: Readonly; private active: { controller: AbortController; finished: Promise } | undefined; private closing = false; private progress = 0; @@ -26,9 +37,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti constructor( private readonly container: OrchestratorServices, - options: { timeoutMs?: number; workerUrl?: URL } = {} + options: { timeoutMs?: number; workerUrl?: URL; datasetLimits?: Partial } = {} ) { super(); + this.datasetLimits = datasetLimits(options.datasetLimits); this.timeoutMs = options.timeoutMs ?? 300_000; if ( !Number.isInteger(this.timeoutMs) || @@ -116,9 +128,19 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti resolver?: DatasetResolver ): Promise { signal.throwIfAborted(); - const dataset = await resolveDataset(this.storageService, config, resolver); + const options = { limits: this.datasetLimits, signal }; + const dataset = await resolveDataset(this.storageService, config, resolver, options); signal.throwIfAborted(); - return dataset.bars.map(bar => ({ ...bar, type: 'bar' })); + assertNativeDatasetBudget(dataset, config, options); + const data: NativeWorkerRequest['data'] = []; + for (const bar of dataset.bars) { + data.push({ ...bar, type: 'bar' }); + if (data.length % PREPARATION_BATCH_SIZE === 0) { + await preparationCheckpoint(signal); + } + } + signal.throwIfAborted(); + return data; } private publish(event: string, data: unknown): void { diff --git a/apps/stock/orchestrator/src/backtest/run-repository.ts b/apps/stock/orchestrator/src/backtest/run-repository.ts index c929b49a..c14f6b04 100644 --- a/apps/stock/orchestrator/src/backtest/run-repository.ts +++ b/apps/stock/orchestrator/src/backtest/run-repository.ts @@ -19,12 +19,14 @@ export interface BacktestRunRepository { loadDataset( runId: string, attemptId: string, - requestedHash?: string + requestedHash?: string, + signal?: AbortSignal ): Promise; freezeDataset( runId: string, attemptId: string, - dataset: HistoricalDataset + dataset: HistoricalDataset, + signal?: AbortSignal ): Promise; complete(result: BacktestRunResult, attemptId: string): Promise; updateProgress( diff --git a/apps/stock/orchestrator/src/container.ts b/apps/stock/orchestrator/src/container.ts index 0670acbf..d80e8f8c 100644 --- a/apps/stock/orchestrator/src/container.ts +++ b/apps/stock/orchestrator/src/container.ts @@ -7,6 +7,7 @@ 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'; @@ -29,8 +30,10 @@ export async function registerOrchestratorServices( syntheticSeed?: number; nativeExecutionTimeoutMs?: number; strategyRegistry?: StrategyRegistry; + datasetLimits?: Partial; } = {} ): Promise { + 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 ?? {}; @@ -54,8 +57,11 @@ export async function registerOrchestratorServices( const strategyManager = new StrategyManager(services, options.strategyRegistry); Object.assign(custom, { StorageService: storageService }); const backtestEngine = options.useRustEngine - ? new RustBacktestAdapter(services, { timeoutMs: options.nativeExecutionTimeoutMs }) - : new BacktestEngine(services, storageService, strategyManager); + ? new RustBacktestAdapter(services, { + timeoutMs: options.nativeExecutionTimeoutMs, + datasetLimits: limits, + }) + : new BacktestEngine(services, storageService, strategyManager, { datasetLimits: limits }); const paperTradingManager = new PaperTradingManager( services, storageService, @@ -73,9 +79,10 @@ export async function registerOrchestratorServices( engine: backtestEngine, engineName: options.useRustEngine ? 'native' : 'typescript', repository: services.postgres - ? new PostgresBacktestRunRepository(services.postgres) + ? new PostgresBacktestRunRepository(services.postgres, undefined, limits) : new UnavailableBacktestRunRepository(), logger: services.logger, + datasetLimits: limits, prepare: options.useRustEngine ? undefined : config => modeManager.initializeMode(config), }); diff --git a/apps/stock/orchestrator/src/data/dataset-limits.ts b/apps/stock/orchestrator/src/data/dataset-limits.ts new file mode 100644 index 00000000..c29cd07e --- /dev/null +++ b/apps/stock/orchestrator/src/data/dataset-limits.ts @@ -0,0 +1,67 @@ +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 = 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; + 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 = {}): Readonly { + 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, + 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 { + signal?.throwIfAborted(); + await setImmediate(); + signal?.throwIfAborted(); +} diff --git a/apps/stock/orchestrator/src/data/historical-dataset.ts b/apps/stock/orchestrator/src/data/historical-dataset.ts index 95f2611c..6d776489 100644 --- a/apps/stock/orchestrator/src/data/historical-dataset.ts +++ b/apps/stock/orchestrator/src/data/historical-dataset.ts @@ -5,13 +5,29 @@ import { type HistoricalDataPolicy, type HistoricalDataset, } from '@stock-bot/types'; -import { datasetSchema } from '../contracts/historical'; -import type { StorageService } from '../services/StorageService'; +import { datasetBarSchema, datasetManifestSchema } from '../contracts/historical'; +import type { HistoricalBar, StorageService } from '../services/StorageService'; import type { BacktestConfig } from '../types'; +import { + assertDatasetLimit, + DatasetLimitError, + datasetLimits, + PREPARATION_BATCH_SIZE, + preparationCheckpoint, + type DatasetPreparationOptions, +} from './dataset-limits'; export type DatasetResolver = ( - load: () => Promise + load: () => Promise, + signal?: AbortSignal ) => Promise; +interface DatasetSize { + serializedBytes: number; + barsBytes: number; +} +// Only detached, deeply frozen values enter this cache. Mutable caller objects never do. +const prepared = new WeakMap>(); + export function dataPolicy( config: Pick ): HistoricalDataPolicy { @@ -25,17 +41,70 @@ export function dataPolicy( return policy; } -function hashDataset(dataset: HistoricalDataset): string { - const { hash: _hash, ...manifest } = dataset.manifest; - return createHash('sha256') - .update(JSON.stringify({ manifest, bars: dataset.bars })) - .digest('hex'); +function matchRequest(dataset: HistoricalDataset, config?: BacktestConfig): void { + const m = dataset.manifest; + if ( + config && + (JSON.stringify([...config.symbols].sort()) !== JSON.stringify(m.instruments.map(i => i.id)) || + new Date(config.startDate).toISOString() !== m.startDate || + new Date(config.endDate).toISOString() !== m.endDate || + config.dataFrequency !== m.interval || + JSON.stringify(dataPolicy(config)) !== JSON.stringify(m.policy) || + (config.datasetHash && config.datasetHash !== m.hash)) + ) { + throw new Error('Frozen dataset does not match the backtest request'); + } } -/** Parsing reconstructs a fixed property order before hashing, independent of JSONB key order. */ -export function validateDataset(input: unknown, config?: BacktestConfig): HistoricalDataset { - const dataset = datasetSchema.parse(input); - const m = dataset.manifest; +/** One canonical parse/order/hash boundary, driven synchronously or in cancellable batches. */ +function* canonicalize( + input: unknown, + config: BacktestConfig | undefined, + options: DatasetPreparationOptions, + assignHash = false +): Generator { + const limits = datasetLimits(options.limits); + options.signal?.throwIfAborted(); + if (input && typeof input === 'object' && prepared.has(input as HistoricalDataset)) { + const dataset = input as HistoricalDataset; + const size = prepared.get(dataset) as Readonly; + assertDatasetLimit(limits, 'maxInstruments', dataset.manifest.instruments.length); + assertDatasetLimit(limits, 'maxBars', dataset.bars.length); + assertDatasetLimit(limits, 'maxSerializedBytes', size.serializedBytes); + matchRequest(dataset, config); + return dataset; + } + if ( + !input || + typeof input !== 'object' || + Array.isArray(input) || + Object.keys(input).length !== 2 || + !('manifest' in input) || + !('bars' in input) || + !Array.isArray(input.bars) || + !input.bars.length + ) { + 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); const sortedIds = [...ids].sort(); @@ -54,13 +123,24 @@ export function validateDataset(input: unknown, config?: BacktestConfig): Histor m.instruments.some(i => JSON.stringify(i) !== JSON.stringify(parseInstrumentId(i.id))) || m.sources.length !== ids.length || m.sources.some((s, i) => s.instrumentId !== ids[i]) || - m.barCount !== dataset.bars.length + m.barCount !== input.bars.length ) { throw new Error('Invalid dataset manifest'); } + const dataset: HistoricalDataset = { manifest: m, bars: [] }; + matchRequest(dataset, assignHash ? undefined : config); + 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(); let previous: HistoricalDataset['bars'][number] | undefined; - for (const bar of dataset.bars) { + assertDatasetLimit(limits, 'maxSerializedBytes', envelopeBytes + barsBytes); + for (let i = 0; i < input.bars.length; i++) { + options.signal?.throwIfAborted(); + const bar = datasetBarSchema.parse(input.bars[i]); if ( !idSet.has(bar.symbol) || bar.timestamp < start || @@ -74,44 +154,170 @@ export function validateDataset(input: unknown, config?: BacktestConfig): Histor ) { 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); + chunk = ''; + } + dataset.bars.push(Object.freeze(bar)); seen.add(bar.symbol); previous = bar; + if ((i + 1) % PREPARATION_BATCH_SIZE === 0) { + yield; + } } - if (seen.size !== ids.length || hashDataset(dataset) !== m.hash) { + const digest = hash.update(chunk).update(']}').digest('hex'); + if (seen.size !== ids.length || (!assignHash && digest !== m.hash)) { throw new Error('Dataset hash/content mismatch'); } - if ( - config && - (JSON.stringify([...config.symbols].sort()) !== JSON.stringify(ids) || - new Date(config.startDate).toISOString() !== m.startDate || - new Date(config.endDate).toISOString() !== m.endDate || - config.dataFrequency !== m.interval || - JSON.stringify(dataPolicy(config)) !== JSON.stringify(m.policy) || - (config.datasetHash && config.datasetHash !== m.hash)) - ) { - throw new Error('Frozen dataset does not match the backtest request'); + m.hash = digest; + matchRequest(dataset, config); + for (const identity of m.instruments) { + Object.freeze(identity); } + for (const source of m.sources) { + Object.freeze(source); + } + Object.freeze(m.instruments); + Object.freeze(m.sources); + Object.freeze(m.policy); + Object.freeze(m); + Object.freeze(dataset.bars); + Object.freeze(dataset); + prepared.set(dataset, Object.freeze({ serializedBytes: envelopeBytes + barsBytes, barsBytes })); return dataset; } -export async function loadDataset( - storage: StorageService, - config: BacktestConfig +/** Untrusted values are detached and fully checked; only prepared immutable values are reused. */ +export function validateDataset( + input: unknown, + config?: BacktestConfig, + options: DatasetPreparationOptions = {} +): HistoricalDataset { + const work = canonicalize(input, config, options); + let step = work.next(); + while (!step.done) { + step = work.next(); + } + return step.value; +} + +async function finishPreparation(work: Generator, signal?: AbortSignal) { + let step = work.next(); + while (!step.done) { + await preparationCheckpoint(signal); + step = work.next(); + } + signal?.throwIfAborted(); + return step.value; +} + +export function prepareDataset( + input: unknown, + config?: BacktestConfig, + options: DatasetPreparationOptions = {} ): Promise { + return finishPreparation(canonicalize(input, config, options), options.signal); +} + +export function datasetSize(dataset: HistoricalDataset): Readonly { + 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( + storage: Pick, + config: BacktestConfig, + options: DatasetPreparationOptions = {} +): Promise { + const limits = datasetLimits(options.limits); + options.signal?.throwIfAborted(); + assertDatasetLimit(limits, 'maxInstruments', config.symbols.length); + 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) { - const rows = await storage.getHistoricalBars( - instrument.id, - new Date(config.startDate), - new Date(config.endDate), - config.dataFrequency, - policy + 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, + }) ); + 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); const source = rows[0]?.source; - if (!source || rows.some(row => row.source !== source)) { + if (!source) { throw new Error('Historical source provenance is missing or mixed'); } sources.push({ @@ -120,7 +326,10 @@ export async function loadDataset( revision: 'historical-normalization-v1', }); for (const bar of rows) { - bars.push({ + if (bar.source !== source) { + throw new Error('Historical source provenance is missing or mixed'); + } + const value = { symbol: instrument.id, timestamp: bar.timestamp.getTime(), open: bar.open, @@ -129,9 +338,16 @@ export async function loadDataset( close: bar.close, 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); + } } } + options.signal?.throwIfAborted(); bars.sort( (a, b) => a.timestamp - b.timestamp || (a.symbol < b.symbol ? -1 : a.symbol > b.symbol ? 1 : 0) ); @@ -151,22 +367,25 @@ export async function loadDataset( }, bars, }; - // Canonicalize before hashing, including metadata key order. - const canonical = datasetSchema.parse(dataset); - canonical.manifest.hash = hashDataset(canonical); - return validateDataset(canonical, config); + return finishPreparation(canonicalize(dataset, config, options, true), options.signal); } export async function resolveDataset( - storage: StorageService, + storage: Pick, config: BacktestConfig, - resolver?: DatasetResolver + resolver?: DatasetResolver, + options: DatasetPreparationOptions = {} ) { + const limits = datasetLimits(options.limits); + options.signal?.throwIfAborted(); + assertDatasetLimit(limits, 'maxInstruments', config.symbols.length); if (config.datasetHash && !resolver) { throw new Error('Dataset replay requires the durable backtest runner'); } - return validateDataset( - await (resolver ? resolver(() => loadDataset(storage, config)) : loadDataset(storage, config)), - config + const load = () => loadDataset(storage, config, options); + return prepareDataset( + await (resolver ? resolver(load, options.signal) : load()), + config, + options ); } diff --git a/apps/stock/orchestrator/src/services/StorageService.ts b/apps/stock/orchestrator/src/services/StorageService.ts index 1227e8cb..47ce2a9e 100644 --- a/apps/stock/orchestrator/src/services/StorageService.ts +++ b/apps/stock/orchestrator/src/services/StorageService.ts @@ -5,8 +5,19 @@ 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 type { MarketData, ModeConfig, PerformanceMetrics } from '../types'; +export interface HistoricalReadOptions { + maxBars?: number; + signal?: AbortSignal; +} + export interface HistoricalBar { symbol: string; timestamp: Date; @@ -174,8 +185,11 @@ export class StorageService { policy: HistoricalDataPolicy = { adjustment: 'raw', timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant', - } + }, + options: HistoricalReadOptions = {} ): Promise { + const limits = datasetLimits({ maxBars: options.maxBars ?? datasetLimits().maxBars }); + options.signal?.throwIfAborted(); parseInstrumentId(symbol); if ( !Number.isFinite(startTime.getTime()) || @@ -196,63 +210,77 @@ 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); - const bars = rows - .map(row => { - if (row.symbol !== symbol) { - throw new Error(`Historical instrument identity mismatch for ${symbol}`); + const rows = await this.readHistoricalBars( + symbol, + startTime, + endTime, + interval, + limits.maxBars + ); + options.signal?.throwIfAborted(); + assertDatasetLimit(limits, 'maxBars', rows.length); + const bars: HistoricalBar[] = []; + let processed = 0; + for (const row of rows) { + if (row.symbol !== symbol) { + throw new Error(`Historical instrument identity mismatch for ${symbol}`); + } + if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) { + throw new Error('Historical instants require an explicit UTC offset'); + } + const timestamp = new Date(row.timestamp); + const numeric = (value: unknown) => + typeof value === 'number' + ? value + : typeof value === 'string' && value.trim() + ? Number(value) + : NaN; + let open = numeric(row.open), + high = numeric(row.high), + low = numeric(row.low), + close = numeric(row.close); + const volume = numeric(row.volume); + if ( + !Number.isFinite(timestamp.getTime()) || + ![open, high, low, close, volume].every(Number.isFinite) || + low <= 0 || + high < Math.max(open, close) || + low > Math.min(open, close) || + volume < 0 || + (interval === '1d' && timestamp.getTime() % 86400000 !== 0) + ) { + throw new Error(`Invalid historical OHLCV data for ${symbol}`); + } + let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap); + if (policy.adjustment === 'provider-adjusted') { + const adjustedClose = numeric(row.adjustedClose); + if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) { + throw new Error(`Provider-adjusted prices unavailable for ${symbol}`); } - if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) { - throw new Error('Historical instants require an explicit UTC offset'); + const factor = adjustedClose / close; + open *= factor; + high *= factor; + low *= factor; + close = adjustedClose; + if (vwap !== undefined) { + vwap *= factor; } - const timestamp = new Date(row.timestamp); - const numeric = (value: unknown) => - typeof value === 'number' - ? value - : typeof value === 'string' && value.trim() - ? Number(value) - : NaN; - let open = numeric(row.open), - high = numeric(row.high), - low = numeric(row.low), - close = numeric(row.close); - const volume = numeric(row.volume); - if ( - !Number.isFinite(timestamp.getTime()) || - ![open, high, low, close, volume].every(Number.isFinite) || - low <= 0 || - high < Math.max(open, close) || - low > Math.min(open, close) || - volume < 0 || - (interval === '1d' && timestamp.getTime() % 86400000 !== 0) - ) { - throw new Error(`Invalid historical OHLCV data for ${symbol}`); - } - let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap); - if (policy.adjustment === 'provider-adjusted') { - const adjustedClose = numeric(row.adjustedClose); - if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) { - throw new Error(`Provider-adjusted prices unavailable for ${symbol}`); - } - const factor = adjustedClose / close; - open *= factor; - high *= factor; - low *= factor; - close = adjustedClose; - if (vwap !== undefined) { - vwap *= factor; - } - } - if ( - ![open, high, low, close].every(value => Number.isFinite(value) && value > 0) || - (vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0)) - ) { - throw new Error(`Invalid adjusted historical data for ${symbol}`); - } - return { ...row, symbol, timestamp, open, high, low, close, volume, vwap }; - }) - .filter(bar => bar.timestamp >= startTime && bar.timestamp < endTime) - .sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()); + } + if ( + ![open, high, low, close].every(value => Number.isFinite(value) && value > 0) || + (vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0)) + ) { + throw new Error(`Invalid adjusted historical data for ${symbol}`); + } + if (timestamp >= startTime && timestamp < endTime) { + bars.push({ ...row, symbol, timestamp, open, high, low, close, volume, vwap }); + } + if (++processed % PREPARATION_BATCH_SIZE === 0) { + await preparationCheckpoint(options.signal); + } + } + options.signal?.throwIfAborted(); + bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()); if (!bars.length) { throw new Error(`No historical data for ${symbol}`); } @@ -271,7 +299,8 @@ export class StorageService { symbol: string, startTime: Date, endTime: Date, - interval: string = '1m' + interval: string, + maxBars: number ): Promise { // If QuestDB is available, use real data if (this.questdb) { @@ -279,9 +308,10 @@ export class StorageService { throw new Error('Unsupported historical interval'); } const result = await this.questdb.query( - `SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`, - [symbol, startTime, endTime] + `SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp LIMIT $4`, + [symbol, startTime, endTime, maxBars + 1] ); + assertDatasetLimit(datasetLimits({ maxBars }), 'maxBars', result.rows.length); return result.rows.map(row => ({ ...row, source: 'questdb' })); } @@ -311,8 +341,25 @@ export class StorageService { $lt: endTime.toISOString().slice(0, 10), }, }, - { sort: { date: 1 } } + { + sort: { date: 1 }, + limit: maxBars + 1, + projection: { + symbol: 1, + exchange: 1, + eodSearchCode: 1, + providerExchange: 1, + date: 1, + open: 1, + high: 1, + low: 1, + close: 1, + volume: 1, + adjustedClose: 1, + }, + } ); + assertDatasetLimit(datasetLimits({ maxBars }), 'maxBars', prices.length); return prices.map(price => { if ( price.eodSearchCode !== identity.id || @@ -346,6 +393,11 @@ 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', diff --git a/apps/stock/orchestrator/src/simple-container.ts b/apps/stock/orchestrator/src/simple-container.ts index 8b44cf5f..0c98f1d9 100644 --- a/apps/stock/orchestrator/src/simple-container.ts +++ b/apps/stock/orchestrator/src/simple-container.ts @@ -22,6 +22,7 @@ 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; } diff --git a/docs/backtest-datasets.md b/docs/backtest-datasets.md new file mode 100644 index 00000000..9b016df7 --- /dev/null +++ b/docs/backtest-datasets.md @@ -0,0 +1,94 @@ +# Bounded backtest dataset preparation + +Both backends use the same historical-data preparation boundary. Defaults are per run: + +| Budget | Default | Enforcement | +| --- | --- | --- | +| `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 +stock application configuration, or inject `datasetLimits` through +`registerOrchestratorServices(container, options)`. Composition passes the same ceilings +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 + +QuestDB and Mongo queries request at most the remaining bar allowance plus one overflow +sentinel. Overflow is an error, **not a truncated backtest**. Mongo queries project only +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 + +`prepareDataset` parses each bar, validates identities/provenance/ranges/OHLC/order, and +incrementally hashes bounded JSON chunks. It produces the exact same v1 digest bytes as +`JSON.stringify({ manifest: manifestWithoutHash, bars })`; property reordering by JSONB +does not change identity. Prices, timestamp ties and adjustment policies are unchanged. + +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 +objects. Internal handoffs reuse them without another array reconstruction/content hash; +request compatibility and the current ceilings are still checked. Raw database, resolver +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. + +The synchronous `validateDataset` facade uses the same validator for small diagnostic +calls. Runtime loading/restoration uses the asynchronous driver, yielding every 2,048 +bars so cancellation, execution deadlines and lease heartbeats can run. Abort signals +propagate through loading, resolver callbacks and repository preparation; cancelled late +reads cannot dispatch a worker. Driver queries already in flight are not forcibly killed. +Sorting and final persistence/IPC serialization remain synchronous bounded operations. + +## Reproducible preparation benchmark + +```sh +bun run benchmark:dataset +``` + +The script compares four in-process validation handoffs of one valid dataset against the +pre-refactor whole-schema/whole-JSON hash path. Each mode runs in a separate process; +hashes must match. Timing excludes fixture creation. Peak RSS includes fixture creation +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. + +One local Bun 1.2.17 run: + +| Bars / instruments | Previous time | Prepared time | Previous peak RSS | Prepared peak RSS | +| --- | --- | --- | --- | --- | +| 10,000 / 1 | 62 ms | 28 ms | 126 MiB | 107 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 | + +Results vary with machine load and garbage collection. The remaining memory footprint +supports retaining conservative budgets. Larger workloads should next measure a chunked +immutable snapshot reader and native transfer protocol; do not weaken validation or +change v1 content identity to increase throughput. + +## Verification + +`bun run check` includes limit boundaries, immutable reuse, v1 hash compatibility, +deterministic replay, CPU cancellation, backend admission and overflow-query regressions. +The disposable PostgreSQL/Redis suite additionally verifies stored-size rejection, +tamper detection, cancellation/overflow rollback and existing lease/owner-loss replay. +See the root README for safety-suite setup; never use development trading databases. diff --git a/package.json b/package.json index bd2eee7e..8ef13163 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,7 @@ "clean:fresh": "./scripts/clean.sh --fresh", "clean:fresh:force": "./scripts/clean.sh --fresh --force", "backtest": "turbo run backtest", + "benchmark:dataset": "bun run scripts/benchmark-dataset.ts", "docker:start": "./scripts/docker.sh start", "docker:stop": "./scripts/docker.sh stop", "docker:restart": "./scripts/docker.sh restart", diff --git a/scripts/benchmark-dataset.ts b/scripts/benchmark-dataset.ts new file mode 100644 index 00000000..d5360784 --- /dev/null +++ b/scripts/benchmark-dataset.ts @@ -0,0 +1,162 @@ +/** Reproducible CPU/peak-RSS comparison. No DB, native engine, credentials or network. */ +import { createHash } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; +import { + parseInstrumentId, + validateHistoricalDataRequest, + type HistoricalDataset, +} from '@stock-bot/types'; +import { datasetSchema } from '../apps/stock/orchestrator/src/contracts/historical'; +import { prepareDataset } from '../apps/stock/orchestrator/src/data/historical-dataset'; + +function hash(dataset: HistoricalDataset): string { + const { hash: _hash, ...manifest } = dataset.manifest; + return createHash('sha256') + .update(JSON.stringify({ manifest, bars: dataset.bars })) + .digest('hex'); +} + +/** Pre-refactor v1 validation, retained here solely as the benchmark baseline. */ +function legacyValidate(input: unknown): HistoricalDataset { + const dataset = datasetSchema.parse(input); + const m = dataset.manifest; + const ids = m.instruments.map(i => i.id), + sorted = [...ids].sort(), + idSet = new Set(ids); + const rangeStart = Date.parse(m.startDate), + rangeEnd = Date.parse(m.endDate); + validateHistoricalDataRequest({ + symbols: ids, + startDate: m.startDate, + endDate: m.endDate, + dataFrequency: m.interval, + dataPolicy: m.policy, + datasetHash: m.hash, + }); + if ( + ids.some((id, i) => id !== sorted[i]) || + m.instruments.some(i => JSON.stringify(i) !== JSON.stringify(parseInstrumentId(i.id))) || + m.sources.length !== ids.length || + m.sources.some((s, i) => s.instrumentId !== ids[i]) || + m.barCount !== dataset.bars.length + ) { + throw new Error('Invalid dataset manifest'); + } + const seen = new Set(); + let previous: HistoricalDataset['bars'][number] | undefined; + for (const bar of dataset.bars) { + if ( + !idSet.has(bar.symbol) || + bar.timestamp < rangeStart || + bar.timestamp >= rangeEnd || + bar.high < Math.max(bar.open, bar.close) || + bar.low > Math.min(bar.open, bar.close) || + (m.policy.timestamp === 'utc-session-date' && bar.timestamp % 86400000 !== 0) || + (previous && + (bar.timestamp < previous.timestamp || + (bar.timestamp === previous.timestamp && bar.symbol <= previous.symbol))) + ) { + throw new Error('Invalid or unordered dataset bars'); + } + seen.add(bar.symbol); + previous = bar; + } + if (seen.size !== ids.length || hash(dataset) !== m.hash) { + throw new Error('Dataset hash/content mismatch'); + } + return dataset; +} + +function fixture(barCount: number, instrumentCount: number): HistoricalDataset { + const instruments = Array.from({ length: instrumentCount }, (_, i) => + parseInstrumentId(`S${String(i).padStart(3, '0')}.US`) + ); + const start = Date.parse('2024-01-01T00:00:00.000Z'); + const bars: HistoricalDataset['bars'] = []; + for (let i = 0; i < barCount; i++) { + bars.push({ + symbol: instruments[i % instrumentCount]!.id, + timestamp: start + Math.floor(i / instrumentCount) * 60_000, + open: 100, + high: 102, + low: 99, + close: 101, + volume: i, + vwap: 100.5, + }); + } + const dataset: HistoricalDataset = { + manifest: { + version: 1, + hash: '0'.repeat(64), + instruments, + startDate: new Date(start).toISOString(), + endDate: new Date(start + (Math.ceil(barCount / instrumentCount) + 1) * 60_000).toISOString(), + interval: '1m', + policy: { adjustment: 'raw', timestamp: 'utc-instant' }, + volumePolicy: 'reported', + qualityPolicy: 'reject-invalid-no-interpolation', + sources: instruments.map(({ id }) => ({ + instrumentId: id, + provider: 'questdb', + revision: 'benchmark-v1', + })), + barCount, + }, + bars, + }; + dataset.manifest.hash = hash(dataset); + return dataset; +} + +const [mode, countArg, instrumentsArg] = process.argv.slice(2); +if (mode === 'legacy' || mode === 'prepared') { + const count = Number(countArg), + instruments = Number(instrumentsArg); + const source = fixture(count, instruments); + const expected = source.manifest.hash; + let dataset = source; + const start = performance.now(); + // Four in-process handoffs of the SAME content. Persistence/IPC boundary work is excluded. + for (let i = 0; i < 4; i++) { + dataset = mode === 'legacy' ? legacyValidate(dataset) : await prepareDataset(dataset); + } + if (dataset.manifest.hash !== expected) { + throw new Error('Benchmark changed content identity'); + } + process.stdout.write( + JSON.stringify({ + mode, + bars: count, + instruments, + milliseconds: Math.round(performance.now() - start), + peakRssMiB: Math.round(process.resourceUsage().maxRSS / 1024), + hash: expected, + }) + '\n' + ); +} else { + for (const [bars, instruments] of [ + [10_000, 1], + [100_000, 10], + [1_000_000, 100], + ]) { + const results = []; + for (const mode of ['legacy', 'prepared']) { + // Isolate peak RSS and garbage collector history for each measurement. + const child = Bun.spawn( + [process.execPath, fileURLToPath(import.meta.url), mode, String(bars), String(instruments)], + { stdout: 'pipe', stderr: 'inherit', env: { ...process.env, NODE_ENV: 'production' } } + ); + const output = await new Response(child.stdout).text(); + if ((await child.exited) !== 0) { + throw new Error(`Benchmark failed: ${mode} ${bars}`); + } + const result = JSON.parse(output); + results.push(result); + process.stdout.write(output); + } + if (results[0].hash !== results[1].hash) { + throw new Error('Baseline/prepared hash mismatch'); + } + } +} diff --git a/scripts/test/orchestrator-container.test.ts b/scripts/test/orchestrator-container.test.ts index 939aa19c..2e18b470 100644 --- a/scripts/test/orchestrator-container.test.ts +++ b/scripts/test/orchestrator-container.test.ts @@ -1,5 +1,6 @@ import { expect, test } from 'bun:test'; 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 () => { const runtime = await createExampleRuntime(); @@ -10,3 +11,12 @@ test('offline examples use the shared DI graph without starting a real-time feed expect(runtime.modeManager.getConfig()).toBeNull(); 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); +}); diff --git a/test/integration/backtest-workflow.test.ts b/test/integration/backtest-workflow.test.ts index 73807d5c..4275a3c7 100644 --- a/test/integration/backtest-workflow.test.ts +++ b/test/integration/backtest-workflow.test.ts @@ -70,6 +70,12 @@ async function fixture( impure: true, implementation: () => new Date(), }); + db.public.registerFunction({ + name: 'octet_length', + args: [DataType.text], + returns: DataType.integer, + implementation: (value: string) => Buffer.byteLength(value), + }); db.public .none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused'); CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb, @@ -742,6 +748,7 @@ describe('isolated native backtest workers', () => { await entered; await f.runner.stopBacktest(f.runner.getStatus().runId); expect(await cancelled).toBeInstanceOf(BacktestCancelledError); + expect((await f.postgres.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0); release(); await gate; f.storage.getHistoricalBars = read; diff --git a/test/integration/dataset-preparation.test.ts b/test/integration/dataset-preparation.test.ts new file mode 100644 index 00000000..8fd92011 --- /dev/null +++ b/test/integration/dataset-preparation.test.ts @@ -0,0 +1,464 @@ +import { createHash } from 'node:crypto'; +import { setImmediate } from 'node:timers/promises'; +import { describe, expect, test } from 'bun:test'; +import type { MongoDBClient, QuestDBClient } from '@stock-bot/services'; +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 { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; +import { datasetSchema } from '../../apps/stock/orchestrator/src/contracts/historical'; +import { + DatasetLimitError, + datasetLimits, +} from '../../apps/stock/orchestrator/src/data/dataset-limits'; +import { + assertNativeDatasetBudget, + datasetSize, + loadDataset, + prepareDataset, + resolveDataset, + validateDataset, +} from '../../apps/stock/orchestrator/src/data/historical-dataset'; +import { + StorageService, + type HistoricalBar, +} 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 { logger } from '../fixtures/execution'; + +const config = BacktestConfigSchema.parse({ + mode: 'backtest', + strategy: 'sma-crossover', + symbols: ['A.US', 'B.US'], + startDate: '2024-01-01T00:00:00.000Z', + endDate: '2025-01-01T00:00:00.000Z', + initialCapital: 10000, + dataFrequency: '1m', + speed: 'max', +}); +const start = Date.parse(config.startDate); + +function rows(symbol: string, count = 3): HistoricalBar[] { + return Array.from({ length: count }, (_, i) => ({ + symbol, + source: 'questdb', + timestamp: new Date(start + i * 60_000), + open: 100, + high: 102, + low: 99, + close: 100.25, + volume: i, + vwap: 100.125, + })); +} + +/** Independent pre-refactor v1 construction: whole-schema parse and whole-string SHA-256. */ +function legacyFixture(count = 3): HistoricalDataset { + const bars = config.symbols + .flatMap(symbol => + rows(symbol, count).map(bar => ({ + symbol, + timestamp: bar.timestamp.getTime(), + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + vwap: bar.vwap, + })) + ) + .sort((a, b) => a.timestamp - b.timestamp || (a.symbol < b.symbol ? -1 : 1)); + const dataset = datasetSchema.parse({ + manifest: { + version: 1, + hash: '0'.repeat(64), + instruments: config.symbols.map(parseInstrumentId), + startDate: config.startDate, + endDate: config.endDate, + interval: config.dataFrequency, + policy: { adjustment: 'raw', timestamp: 'utc-instant' }, + volumePolicy: 'reported', + qualityPolicy: 'reject-invalid-no-interpolation', + sources: config.symbols.map(instrumentId => ({ + instrumentId, + provider: 'questdb', + revision: 'historical-normalization-v1', + })), + barCount: bars.length, + }, + bars, + }); + const { hash: _hash, ...manifest } = dataset.manifest; + dataset.manifest.hash = createHash('sha256') + .update(JSON.stringify({ manifest, bars: dataset.bars })) + .digest('hex'); + return dataset; +} + +describe('bounded historical dataset preparation', () => { + test('preserves v1 whole-JSON hashes and canonical key ordering, including Unicode metadata', async () => { + const expected = legacyFixture(); + const loaded = await loadDataset( + { + async getHistoricalBars(symbol) { + return rows(symbol); + }, + }, + config + ); + expect(loaded).toEqual(expected); + const reordered = JSON.parse(JSON.stringify(expected), (_key, value) => + value && typeof value === 'object' && !Array.isArray(value) + ? Object.fromEntries(Object.entries(value).reverse()) + : value + ); + expect(await prepareDataset(reordered, config)).toEqual(expected); + expected.manifest.sources[0]!.revision = 'révision-市場'; + const { hash: _hash, ...manifest } = expected.manifest; + expected.manifest.hash = createHash('sha256') + .update(JSON.stringify({ manifest, bars: expected.bars })) + .digest('hex'); + const result = validateDataset(expected, config); + 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 () => { + const input = legacyFixture(); + const dataset = await prepareDataset(input, config); + expect(dataset).not.toBe(input); + expect(validateDataset(dataset, config)).toBe(dataset); + expect( + await resolveDataset( + { + getHistoricalBars: async () => { + throw new Error('must not load'); + }, + }, + config, + async () => dataset + ) + ).toBe(dataset); + for (const value of [ + dataset, + dataset.bars, + dataset.bars[0], + dataset.manifest, + dataset.manifest.policy, + dataset.manifest.instruments, + dataset.manifest.instruments[0], + dataset.manifest.sources, + dataset.manifest.sources[0], + datasetSize(dataset), + ]) { + expect(Object.isFrozen(value)).toBe(true); + } + expect(() => { + dataset.bars[0]!.close = 101; + }).toThrow(); + expect(() => { + dataset.manifest.policy.adjustment = 'provider-adjusted'; + }).toThrow(); + input.bars[0]!.volume++; + expect(() => validateDataset(input)).toThrow('hash/content'); + expect(dataset.bars[0]?.volume).toBe(0); + }); + + test('cached preparations still enforce tighter budgets and request identity', async () => { + 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( + 'does not match' + ); + expect(() => validateDataset(dataset, { ...config, datasetHash: 'f'.repeat(64) })).toThrow( + 'does not match' + ); + }); + + test('admission rejects excessive instruments before invoking storage or a resolver', async () => { + let calls = 0; + const storage = { + async getHistoricalBars() { + calls++; + return []; + }, + }; + 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); + }); + + test('untrusted array sizes fail before individual bars are parsed', () => { + const dataset = legacyFixture(); + Object.defineProperty(dataset.bars, 0, { + 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 = { + async getHistoricalBars( + symbol: string, + _start: Date, + _end: Date, + _interval?: string, + _policy?: unknown, + options?: { maxBars?: number } + ) { + allowances.push(options!.maxBars!); + return rows(symbol); + }, + }; + await expect(loadDataset(storage, config, { limits: { maxBars: 5 } })).rejects.toThrow( + 'maxBars' + ); + expect(allowances).toEqual([5, 2]); + expect((await loadDataset(storage, config, { limits: { maxBars: 6 } })).bars).toHaveLength(6); + }); + + test('QuestDB requests one overflow sentinel and rejects overflow rather than replaying a prefix', async () => { + let count = 2; + const questdb = { + async query(sql: string, parameters: unknown[]) { + expect(sql).toContain('LIMIT $4'); + expect(parameters).toEqual([ + 'A.US', + new Date(config.startDate), + new Date(config.endDate), + 3, + ]); + return { rows: rows('A.US', count) }; + }, + } as unknown as QuestDBClient; + const storage = new StorageService({ logger }, null, null, questdb); + expect( + await storage.getHistoricalBars( + 'A.US', + new Date(config.startDate), + new Date(config.endDate), + '1m', + undefined, + { maxBars: 2 } + ) + ).toHaveLength(2); + 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 () => { + let count = 2; + const mongodb = { + async find( + _collection: string, + _filter: unknown, + options: { limit: number; projection: unknown } + ) { + expect(options.limit).toBe(3); + expect(options.projection).toHaveProperty('eodSearchCode', 1); + return Array.from({ length: count }, (_, i) => ({ + symbol: 'A', + exchange: 'US', + eodSearchCode: 'A.US', + date: new Date(start + i * 86400000).toISOString().slice(0, 10), + open: 100, + high: 102, + low: 99, + close: 100, + volume: 1, + })); + }, + } as unknown as MongoDBClient; + const storage = new StorageService({ logger }, mongodb, null, null); + const read = () => + storage.getHistoricalBars( + 'A.US', + 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 () => { + const storage = { + async getHistoricalBars() { + throw new Error('must not load'); + }, + }; + const tampered = legacyFixture(); + tampered.bars[0]!.volume++; + await expect(resolveDataset(storage, config, async () => tampered)).rejects.toThrow( + 'hash/content' + ); + await expect( + resolveDataset(storage, { ...config, datasetHash: legacyFixture().manifest.hash }) + ).rejects.toThrow('durable'); + expect(() => validateDataset({ ...legacyFixture(), extra: 1 })).toThrow( + 'Invalid historical dataset' + ); + }); + + test('already-cancelled admission performs no reads; late database completion cannot resume preparation', async () => { + const controller = new AbortController(); + const reason = new BacktestCancelledError(); + let reads = 0; + let release!: (bars: HistoricalBar[]) => void; + const storage = { + async getHistoricalBars() { + reads++; + return new Promise(resolve => { + release = resolve; + }); + }, + }; + const work = loadDataset(storage, config, { signal: controller.signal }); + controller.abort(reason); + release(rows('A.US')); + expect(await work.catch(error => error)).toBe(reason); + await expect(loadDataset(storage, config, { signal: controller.signal })).rejects.toBe(reason); + expect(reads).toBe(1); + }); + + test('CPU preparation yields to cancellation before consuming the rest of a large snapshot', async () => { + const input = legacyFixture(5000); + const controller = new AbortController(); + const reason = new BacktestCancelledError(); + // If cancellation did not stop the next batch, this later bar would be inspected. + Object.defineProperty(input.bars, 4096, { + get() { + throw new Error('read after cancellation'); + }, + }); + const work = prepareDataset(input, config, { signal: controller.signal }); + await setImmediate(); + controller.abort(reason); + expect(await work.catch(error => error)).toBe(reason); + }); + + test('both backends reject oversized requests before strategy setup or native worker spawn', async () => { + const storage = new StorageService({ logger }, null, null, null, { allowSyntheticData: true }); + const manager = {} as StrategyManager; // Any strategy setup would fail this fixture. + const engine = new BacktestEngine({ logger }, storage, manager, { + datasetLimits: { maxInstruments: 1 }, + }); + await expect(engine.runBacktest(config)).rejects.toThrow('maxInstruments'); + expect(engine.getStatus().isRunning).toBe(false); + const native = new RustBacktestAdapter( + { logger, custom: { StorageService: storage } }, + { + datasetLimits: { maxSerializedBytes: 3000 }, + workerUrl: new URL('file:///must-not-spawn-dataset-test.ts'), + } + ); + const short = { + ...config, + symbols: ['A.US'], + endDate: new Date(start + 120000).toISOString(), + name: 'x'.repeat(5000), + }; + 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'); + expect(Object.isFrozen(datasetLimits())).toBe(true); + }); +}); diff --git a/test/postgres/durable-backtest.test.ts b/test/postgres/durable-backtest.test.ts index 1407a34c..1b5c536c 100644 --- a/test/postgres/durable-backtest.test.ts +++ b/test/postgres/durable-backtest.test.ts @@ -13,6 +13,7 @@ import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backte import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; +import { DatasetLimitError } from '../../apps/stock/orchestrator/src/data/dataset-limits'; import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; @@ -294,6 +295,88 @@ 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 () => { + 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 controller = new AbortController(); + const reason = new BacktestCancelledError(); + const repository = new PostgresBacktestRunRepository({ + transaction: work => + f.postgres.transaction(client => + work( + new Proxy(client, { + get(target, key) { + if (key !== 'query') return Reflect.get(target, key); + return async (sql: string, params?: unknown[]) => { + const result = await target.query(sql, params); + if (sql.startsWith('INSERT INTO backtest_datasets')) controller.abort(reason); + return result; + }; + }, + }) + ) + ), + }); + await expect( + repository.freezeDataset(run.id, claim.attemptId, dataset, controller.signal) + ).rejects.toBe(reason); + 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(); + await expect( + repository.loadDataset(run.id, claim.attemptId, undefined, controller.signal) + ).rejects.toBe(reason); + }); + + test('restored snapshots are revalidated rather than trusted by their content-addressed key', 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); + await f.repository.freezeDataset(run.id, claim.attemptId, dataset); + await f.pool.query( + "UPDATE backtest_datasets SET payload = jsonb_set(payload, '{bars,0,volume}', '0'::jsonb) WHERE hash = $1", + [dataset.manifest.hash] + ); + await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content'); + }); + test('an explicit dataset replay rejects a different listing or date range', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id });