Bound backtest dataset preparation and preserve replay identity

This commit is contained in:
Boki 2026-10-21 23:18:23 -04:00
parent cca5d71e6e
commit 6bd671d92a
20 changed files with 1420 additions and 155 deletions

View file

@ -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;

View file

@ -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<HistoricalBar[]>(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);
});
});

View file

@ -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 });