94 lines
5.5 KiB
Markdown
94 lines
5.5 KiB
Markdown
# 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.
|