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

@ -1,43 +1,21 @@
# Bounded backtest dataset preparation
# Backtest dataset preparation
Both backends use the same historical-data preparation boundary. Defaults are per run:
Both backends use the same historical-data preparation boundary. There are no
application-level instrument, bar-count, JSON/IPC-size or stored-snapshot-size caps,
and no dataset-limit configuration. Runs load the complete requested historical range
into memory; they are not silently truncated. Runtime, database and available-memory
constraints still apply. No environment-file changes or database migrations are required.
| Budget | Default | Enforcement |
| --- | --- | --- |
| `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 |
## Loading and replay
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.
QuestDB and Mongo queries retain their instrument and exclusive date-range filters,
but have no application row limit. Mongo queries still project historical fields only.
Synthetic data still requires explicit opt-in and a stable seed.
## 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.
Replay loads the stored JSONB snapshot and validates it before execution. Invalid prices,
duplicate or unordered bars, missing listings, incompatible requests and corrupted hashes
remain errors. Failed snapshot preparation rolls back insertion and the run pointer
together; the fencing/lease/cancellation predicates are unchanged.
## Canonical preparation and compatibility
@ -49,7 +27,7 @@ does not change identity. Prices, timestamp ties and adjustment policies are unc
Returned datasets are detached from caller inputs and deeply frozen, including nested
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
request compatibility is 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.
@ -58,7 +36,8 @@ calls. Runtime loading/restoration uses the asynchronous driver, yielding every
bars so cancellation, execution deadlines and lease heartbeats can run. Abort signals
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.
Sorting and final persistence/IPC serialization remain synchronous operations. The batch
size controls event-loop yielding only; it is not an input limit.
## Reproducible preparation benchmark
@ -72,7 +51,8 @@ hashes must match. Timing excludes fixture creation. Peak RSS includes fixture c
and the runtime, so it is not an allocation counter or an incremental heap measurement.
This is not an end-to-end backtest/database/native-worker benchmark or a CI threshold.
One local Bun 1.2.17 run:
Historical Bun 1.2.17 sample, recorded before removal of the size-limit machinery
(not a claim about current timings):
| Bars / instruments | Previous time | Prepared time | Previous peak RSS | Prepared peak RSS |
| --- | --- | --- | --- | --- |
@ -80,15 +60,13 @@ One local Bun 1.2.17 run:
| 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.
Results vary with machine load and garbage collection. This optional diagnostic remains
available; it does not impose input limits or change v1 content identity.
## 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.
`bun run check` includes complete-range reads without row caps, acceptance beyond the
former listing ceiling, immutable reuse, v1 hash compatibility, deterministic replay,
invalid-data rejection and CPU cancellation. The disposable PostgreSQL/Redis suite
additionally verifies tamper detection, cancellation rollback and lease/owner-loss replay.
See the root README for safety-suite setup; never use development trading databases.