Remove dataset input caps and simplify preparation

This commit is contained in:
Boki 2026-10-21 23:34:10 -04:00
parent 6bd671d92a
commit 007e35c747
17 changed files with 175 additions and 620 deletions

View file

@ -70,12 +70,6 @@ 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,

View file

@ -3,17 +3,9 @@ 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,
@ -23,7 +15,6 @@ 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';
@ -96,7 +87,7 @@ function legacyFixture(count = 3): HistoricalDataset {
return dataset;
}
describe('bounded historical dataset preparation', () => {
describe('historical dataset preparation', () => {
test('preserves v1 whole-JSON hashes and canonical key ordering, including Unicode metadata', async () => {
const expected = legacyFixture();
const loaded = await loadDataset(
@ -121,7 +112,6 @@ describe('bounded historical dataset preparation', () => {
.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 () => {
@ -150,7 +140,6 @@ describe('bounded historical dataset preparation', () => {
dataset.manifest.instruments[0],
dataset.manifest.sources,
dataset.manifest.sources[0],
datasetSize(dataset),
]) {
expect(Object.isFrozen(value)).toBe(true);
}
@ -165,15 +154,8 @@ describe('bounded historical dataset preparation', () => {
expect(dataset.bars[0]?.volume).toBe(0);
});
test('cached preparations still enforce tighter budgets and request identity', async () => {
test('cached preparations still enforce request identity', async () => {
const dataset = await prepareDataset(legacyFixture());
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'
);
@ -182,44 +164,25 @@ describe('bounded historical dataset preparation', () => {
);
});
test('admission rejects excessive instruments before invoking storage or a resolver', async () => {
let calls = 0;
const storage = {
async getHistoricalBars() {
calls++;
return [];
test('all requested instruments and bars are retained without a listing ceiling', async () => {
const request = { ...config, symbols: Array.from({ length: 101 }, (_, i) => `S${i}.US`) };
const loaded = await loadDataset(
{
async getHistoricalBars(symbol) {
return rows(symbol);
},
},
};
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'
request
);
expect(calls).toBe(0);
expect(loaded.manifest.instruments).toHaveLength(101);
expect(loaded.bars).toHaveLength(303);
expect(loaded.manifest.barCount).toBe(303);
expect(await prepareDataset(structuredClone(loaded), request)).toEqual(loaded);
});
test('untrusted array sizes fail before individual bars are parsed', () => {
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[] = [];
test('resolver and storage reads receive the same cancellation signal directly', async () => {
const controller = new AbortController();
const seen: string[] = [];
const storage = {
async getHistoricalBars(
symbol: string,
@ -227,31 +190,32 @@ describe('bounded historical dataset preparation', () => {
_end: Date,
_interval?: string,
_policy?: unknown,
options?: { maxBars?: number }
signal?: AbortSignal
) {
allowances.push(options!.maxBars!);
expect(signal).toBe(controller.signal);
seen.push(symbol);
return rows(symbol);
},
};
await expect(loadDataset(storage, config, { limits: { maxBars: 5 } })).rejects.toThrow(
'maxBars'
const dataset = await resolveDataset(
storage,
config,
async (load, signal) => {
expect(signal).toBe(controller.signal);
return load();
},
controller.signal
);
expect(allowances).toEqual([5, 2]);
expect((await loadDataset(storage, config, { limits: { maxBars: 6 } })).bars).toHaveLength(6);
expect(seen).toEqual(config.symbols);
expect(dataset).toEqual(legacyFixture());
});
test('QuestDB requests one overflow sentinel and rejects overflow rather than replaying a prefix', async () => {
let count = 2;
test('QuestDB reads the full requested range without a row cap', async () => {
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) };
expect(sql).not.toContain('LIMIT');
expect(parameters).toEqual(['A.US', new Date(config.startDate), new Date(config.endDate)]);
return { rows: rows('A.US', 5) };
},
} as unknown as QuestDBClient;
const storage = new StorageService({ logger }, null, null, questdb);
@ -260,35 +224,17 @@ describe('bounded historical dataset preparation', () => {
'A.US',
new Date(config.startDate),
new Date(config.endDate),
'1m',
undefined,
{ maxBars: 2 }
'1m'
)
).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');
).toHaveLength(5);
});
test('Mongo reads are projected and row-bounded before normalization', async () => {
let count = 2;
test('Mongo reads retain their historical-field projection without a row cap', async () => {
const mongodb = {
async find(
_collection: string,
_filter: unknown,
options: { limit: number; projection: unknown }
) {
expect(options.limit).toBe(3);
async find(_collection: string, _filter: unknown, options: { projection: unknown }) {
expect(options).not.toHaveProperty('limit');
expect(options.projection).toHaveProperty('eodSearchCode', 1);
return Array.from({ length: count }, (_, i) => ({
return Array.from({ length: 5 }, (_, i) => ({
symbol: 'A',
exchange: 'US',
eodSearchCode: 'A.US',
@ -303,73 +249,8 @@ describe('bounded historical dataset preparation', () => {
} 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');
storage.getHistoricalBars('A.US', new Date(config.startDate), new Date(config.endDate), '1d');
expect(await read()).toHaveLength(5);
});
test('unknown resolver values still pass the full content boundary and replay requires durability', async () => {
@ -404,11 +285,11 @@ describe('bounded historical dataset preparation', () => {
});
},
};
const work = loadDataset(storage, config, { signal: controller.signal });
const work = loadDataset(storage, config, controller.signal);
controller.abort(reason);
release(rows('A.US'));
expect(await work.catch(error => error)).toBe(reason);
await expect(loadDataset(storage, config, { signal: controller.signal })).rejects.toBe(reason);
await expect(loadDataset(storage, config, controller.signal)).rejects.toBe(reason);
expect(reads).toBe(1);
});
@ -422,43 +303,49 @@ describe('bounded historical dataset preparation', () => {
throw new Error('read after cancellation');
},
});
const work = prepareDataset(input, config, { signal: controller.signal });
const work = prepareDataset(input, config, 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');
test('removing size limits does not permit invalid bars, manifests or request identities', async () => {
for (const change of [
(dataset: HistoricalDataset) => {
dataset.bars[0]!.volume = -1;
},
(dataset: HistoricalDataset) => {
dataset.bars[0]!.close = NaN;
},
(dataset: HistoricalDataset) => {
dataset.bars.reverse();
},
(dataset: HistoricalDataset) => {
dataset.manifest.barCount++;
},
(dataset: HistoricalDataset) => {
dataset.manifest.sources.pop();
},
]) {
const dataset = legacyFixture();
change(dataset);
await expect(prepareDataset(dataset)).rejects.toThrow();
}
expect(() => datasetLimits({ unexpected: 1 } as never)).toThrow('Invalid dataset limit');
expect(Object.isFrozen(datasetLimits())).toBe(true);
let reads = 0;
await expect(
loadDataset(
{
async getHistoricalBars() {
reads++;
return [];
},
},
{
...config,
symbols: ['A.US', 'A.US'],
}
)
).rejects.toThrow('distinct');
expect(reads).toBe(0);
});
});

View file

@ -13,7 +13,6 @@ 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';
@ -295,36 +294,6 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
);
});
test('oversized snapshots fail before pinning and persisted JSONB size is checked before transfer', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const claim = await f.repository.start(config);
const dataset = await loadDataset(f.storage, config);
const small = new PostgresBacktestRunRepository(f.postgres, 2000, { maxBars: 1 });
await expect(small.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toBeInstanceOf(
DatasetLimitError
);
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0);
expect(
(await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0]
.dataset_hash
).toBeNull();
// A stored-text overflow during freeze must roll back both insertion and pinning too.
const storedBudget = new PostgresBacktestRunRepository(f.postgres, 2000, { maxStoredBytes: 1 });
await expect(
storedBudget.freezeDataset(run.id, claim.attemptId, dataset)
).rejects.toBeInstanceOf(DatasetLimitError);
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0);
await f.repository.freezeDataset(run.id, claim.attemptId, dataset);
await expect(storedBudget.loadDataset(run.id, claim.attemptId)).rejects.toBeInstanceOf(
DatasetLimitError
);
expect((await f.repository.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe(
dataset.manifest.hash
);
});
test('cancellation after snapshot insertion aborts preparation and rolls back the run pointer and payload', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });