164 lines
9 KiB
Markdown
164 lines
9 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.
|
|
|
|
## Reusing a retained dataset in the web workbench
|
|
|
|
In **Settings → Canonical research setup**, use **Load more canonical datasets** to
|
|
browse beyond the newest 50 entries. A failed page can be retried without losing the
|
|
loaded choices or advancing past that page. **Refresh canonical datasets** reloads
|
|
the list and verifies the selected hash again.
|
|
|
|
If an AI workflow or earlier result gives you an exact hash, paste it into **Retained
|
|
dataset hash** and choose **Use dataset hash**. The existing catalog endpoint checks
|
|
the retained content and compatibility. A missing, unavailable or malformed hash lookup
|
|
cannot enable saving; a selected dataset outside the loaded page remains visible.
|
|
**Save canonical setup** saves the verified choice and its bounds without starting a run.
|
|
|
|
Settings are loaded on the first visit and stay in memory while switching tabs or
|
|
selecting another run of the same backtest. That includes source previews and an
|
|
unconfirmed retention retry's exact input/hash. Other tabs use the saved definition;
|
|
an unsaved settings draft does not change a run. Explicit discard, leaving this
|
|
backtest and reloading do not provide persistent draft recovery. Save settings and
|
|
resolve retention before leaving if you need to keep the work.
|
|
|
|
## Downloading a retained snapshot for local exploration
|
|
|
|
Choose **Download retained dataset** beneath a verified dataset in **Settings →
|
|
Canonical research setup**, or beside a saved canonical result's **Immutable configuration
|
|
and reporting policy**. The saved-result action uses that run's original dataset hash,
|
|
even if the editable backtest now selects another dataset. Downloading neither saves
|
|
settings nor starts a run.
|
|
|
|
The file is `dataset-<hash>.json`, containing the complete v2 `{manifest, bars}` snapshot.
|
|
The API validates retained content and identity before returning it; timestamps,
|
|
availability delays, source ordinals, null values and any parent hash are preserved.
|
|
This is identical dataset content, not a promise of original JSON formatting. The
|
|
manifest hash is the canonical dataset identity, not a checksum of downloaded file bytes.
|
|
|
|
Open the file in VS Code or a notebook, or give it to your local AI exploration tools.
|
|
For a quick TypeScript inspection with Bun:
|
|
|
|
```ts
|
|
const dataset = await Bun.file('/path/to/dataset-<hash>.json').json();
|
|
console.log(dataset.manifest);
|
|
console.table(dataset.bars.slice(0, 5));
|
|
```
|
|
|
|
Treat this as inspection of frozen observations, not validation of a trading hypothesis.
|
|
When testing features, respect each bar's `availableAt`; the file includes the entire
|
|
historical range, including observations unavailable to an earlier decision.
|
|
|
|
To retain the same file in another initialized research database, set
|
|
`RESEARCH_DATASET_DATABASE_URL` explicitly to that database and use the existing importer:
|
|
|
|
```sh
|
|
bun run scripts/import-research-dataset.ts --file '/path/to/dataset-<hash>.json'
|
|
```
|
|
|
|
The importer validates the full snapshot and repeats safely for an already retained hash.
|
|
This file is distinct from the source-input JSON accepted by **Prepare dataset from source
|
|
export**; use the importer for the complete retained snapshot.
|
|
|
|
Export supports the existing eligible single-asset canonical dataset selection. Missing,
|
|
corrupt and unsupported snapshots return an error instead of a file. A failed download
|
|
offers **Retry dataset download**; changing the selected hash cancels the pending action.
|
|
The endpoint is `GET /api/v2/datasets/canonical/:hash/export`, using existing read, operator,
|
|
service or browser-session access. Research-agent tokens remain unable to call dataset
|
|
routes; a user can supply the downloaded file to local tools explicitly.
|
|
|
|
## 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.
|