stock-bot/docs/backtest-datasets.md

99 lines
5.4 KiB
Markdown

# Backtest dataset preparation
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.
## Loading and replay
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.
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
`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 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.
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 operations. The batch
size controls event-loop yielding only; it is not an input limit.
## 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.
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 |
| --- | --- | --- | --- | --- |
| 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. This optional diagnostic remains
available; it does not impose input limits or change v1 content identity.
## Stored EOD preparation across declared sessions (v2)
In backtest **Settings → Prepare dataset from source export**, choose **Stored EOD —
declared sessions only** and upload the complete v2 metadata JSON. The panel displays
the selected series' declared session windows, clipped to the warmup/evaluation bounds,
in UTC. Preview reads these windows sequentially; retain saves the captured input and
hash without querying the mutable source again.
The reads are not an atomic database snapshot; the captured rows define the retained
dataset. Cancellation prevents subsequent reads/results but does not interrupt an
already dispatched Mongo query.
The existing API opts in explicitly:
```json
{ "metadata": { "...": "complete v2 metadata" }, "selection": "declared-sessions" }
```
Send this to `POST /api/v2/datasets/canonical/stored-source`. The response echoes
`selection` alongside `input` and `preparation`; retain uses that exact `input` and
`preparation.hash`. Omitting `selection` preserves the continuous-range query.
Empty selected sessions, invalid selected rows, duplicates and bars crossing a session
boundary fail preparation. Rows outside the declared windows are never read. Sessions,
corporate-action coverage and source timing remain explicit operator declarations:
successful preparation does not certify them or establish gap-free data. The source
inspector diagnoses its own selected range independently of these capture windows.
## Verification
`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.