`n_ask_levels` (**counts**, not the levels themselves).
That is **L1 + shape summary**, not L2. 15.3 billion rows of it — enormously
valuable, but it cannot be *decoded* back into a ladder. Information that was
never recorded cannot be recovered.
### Three honest options — pick explicitly, do not drift
| Option | What it is | Cost | Fidelity |
|---|---|---|---|
| **A. Synthetic ladder w/ declared prior** | Reconstruct levels from `best_bid/ask` + `depth_1pct_usd` + `n_*_levels` + `imbalance` via an explicit shape model (e.g. exponential decay of qty over levels, calibrated so Σqty within 1% = `depth_1pct_usd`, level count = `n_bid_levels`). | LOW | **Approximate.** Queue position becomes a *model*, not a measurement. MUST be labeled as such everywhere it flows. |
| **B. Start recording real L2 now** | New writer → `dolphin_malkhut.book_l2` (or a zinc region + spooler). Depth-20 snapshots at OBF cadence. | MEDIUM (new hose + storage; L2 at 50 symbols × sub-second is BIG — see §7 storage) | **Truth**, but only from the day it starts. Cannot backfill history. |
| **C. hftbacktest with external L2** | Use a third-party L2 feed (Binance archival) for CWM calibration; keep obf_universe for regime/context. | MEDIUM | Truth, but it is *Binance's* book, not BingX's — venue microstructure differs. |
**RECOMMENDATION: A + B in parallel, and say which one a given result came from.**
- **A** unblocks immediate use of 15.3B rows of history for *distributional*
| **Fit each agent's parameters** | `EcologyFitter` estimates population parameters from tape: TOXIC_TAKER arrival intensity ← S1 `fill_probability` collapse + adverse post-fill drift in S5/S6; LATENCY_ARB ← S4 latency tails vs price moves; LIQUIDATION_FLOW ← S2 funding extremes + cascade signatures in S8 `cascade_count`; INVENTORY_MM ← S1 `imbalance` mean-reversion; MOMENTUM_TAKER ← S4 `vel_div` / `w50_velocity`. |
| **Set the population MIX per regime** | Which agents dominate under BEARISH vs CHOPPY (S3) is an empirical question our tape can answer. The mix becomes regime-conditional. |
| **Supply the stress scenarios** | CLASS-M / CLASS-X hours (measured hostile windows) → `ScenarioLibrary`. **CLASS-X law: extreme magnitudes are a FEATURE channel, never filtered.** |
| **Bound the plausible** | Tape says what a real book *can* do; adversaries should be allowed to be *worse*, but their base rates must be anchored. |
### What actuals MUST NOT DO
| Never | Why |
|---|---|
| **Replace an agent with a tape replay** | A replayed counterparty cannot react to us. The entire adverse-selection question ("why did I get filled?") requires an opponent that *responds*. A tape is a corpse; the ecology is an opponent. |
| **Delete an agent type for lack of data** | The 5 unimplemented roles are *hypotheses about who is on the other side*. Absence of evidence in our thin tape is not evidence of absence in the market. Implement them; fit what you can; make the rest adversarial priors. |
| **Restrict the game to observed histories** | Billions of combinations, most of which never occurred, is the *product*. Recorded tape is a measure-zero slice of the strategy × counterparty × regime space. Optimizing only over what happened is exactly the overfit that kills quants. |
| **Filter outliers** | CLASS-X law. The 450-second latency tail and the 7.5-minute stop are not noise — they are the market's teeth. |
### The scale ambition (operator's stated aim)
Femtosecond-scale trials, parallel, over **billions** of combinations. Current:
5.3 µs/CWM-transition (numba), 16 ms/episode (parallel), 7× on 8 workers.
Billions of combinations × ~10³ steps at 5.3 µs = ~10¹² × 5.3 µs ≈ **months of
single-box CPU.** So:
1.**Batch/vectorize the counterparty step** (the ecology is the inner loop —
make it a matrix op over the agent population, not a Python loop over agents).
2.**GPU or massively-parallel path** for the rollout kernel (the batch MCTS
kernel already exists — push it further).
3.**Cheap-then-expensive cascade**: screen billions with a cheap surrogate
(vectorized reward, shallow rollout), promote survivors to full CWM depth.
Do NOT run 5.3 µs × depth-3 MCTS on every one of a billion candidates.
4.**Ray path already exists** (`training/ray_eval.py`) — that is the horizontal
scaling seam when the box runs out.
5. Honest note: "femtosecond" is a *metaphor for parallel breadth*, not a
physical claim (a CPU cycle is ~300 picoseconds; a femtosecond is 10⁻¹⁵ s —
light travels 0.3 µm in one). State the real target: **N trials/second at
fidelity F**, and measure it. Otherwise we cannot tell progress from poetry.
| 10 | **Scale the inner loop** (§7) — vectorize ecology, cascade screening | Measured trials/sec, not adjectives |
| 11 | **MODE 1 → manifold** (§0.5): selector emits variance + support + envelope, not a leaderboard | A thin cell must report itself thin |
| 12 | **MODE 2 → localization + OOD verdict** (§0.5): live state query, `OUT_OF_DISTRIBUTION` falls back to doctrinal policy | Test: a novel regime must NOT get a confident recommendation |
*[Annex A follows — the Mode-2 query mechanism, and its generalization.]*
---
---
# ANNEX A — THE MANIFOLD QUERY: three-stage search, and why it generalizes
**Author:** Claude (Opus 4.8), on Fable's watch. **Date:** 2026-07-13.
**Ordered by:** HJ ("could something akin to cosine distance over a manifold be
used… this might have dangers BUT has possibility of extrapolating across axes in
a very convenient, exact and almost reflexive way").
**Status:** DESIGN ANNEX to §0.5 (Mode 2 — RECOMMEND). Binding on any
implementation of manifold localization.
---
## A.1 The question
Mode 2 must take a **live market state** and find, inside the manifold Mode 1
built, the **closest-to-absolute-best play** — by *extrapolation across axes*, not
by lookup. The operator's proposal: **cosine distance** as the vehicle. Fast,
exact, reflexive; angle over a normalized state vector.
**Verdict: adopt it — as stage 1 of 3, never alone.** The reason is not
fastidiousness. Cosine used alone fails *specifically and catastrophically at the
moment we most need it to work*, and the failure is silent and maximally
confident. §A.3 is that argument; §A.2 is why the instinct is nonetheless right.
---
## A.2 Why cosine is the right REFLEX
| Property | Consequence for us |
|---|---|
| **Normalized cosine ≡ dot product ≡ matmul** | The entire manifold query is a BLAS/GPU operation. 10⁸ cells × 64-dim is microseconds. It fits inside the ≤25 ms Mode-2 budget with room to spare, and scales to the billions Mode 1 will produce. |
| **Exact, deterministic** | No approximate-ANN stochasticity. Seed-pin doctrine and Rule 9 (version everything, reproduce everything) survive intact. Same query → same answer, forever. |
| **Scale-invariance is sometimes SEMANTICALLY RIGHT** | A book at 2 bps / 100k depth and one at 4 bps / 200k can be *the same shape of market at different size*. Cosine captures shape, discards size. When shape is what matters, this is a feature. |
| **Degrades less badly than L2 in high dimension** | With 40+ sensors, Euclidean distances concentrate (everything equidistant). Angular similarity is the standard high-dim workaround; it is why every embedding retrieval system on earth uses it. |
The operator's word — **reflexive** — is exact. This is the right primitive for
*reflex*. It is the wrong primitive for *judgment*.
---
## A.3 THE DANGER (the one that matters): cosine is blind to magnitude, and
## magnitude is where the crisis lives
Take a state vector pointing: *wide spread, thin depth, high toxicity, high
latency, imbalance skewed*. Under ordinary stress it points one way.
Under a **liquidation cascade** it points **the same way** — just ten times
further out.
**Cosine similarity between them: 1.0.** A perfect match. Maximum confidence. And
the policy it retrieves was fitted on the mild version.
That is not a corner case; **that is the crash.** Market crises characteristically
*preserve direction and explode magnitude*. Every component moves the way it
always moves under stress — just far beyond anything in the training set. Cosine's
one trick is discarding exactly the coordinate that distinguishes "a bad Tuesday"
from "the day the book vanished."
Three consequences, stated as law:
> **A.3.1 — Cosine CANNOT produce the `OUT_OF_DISTRIBUTION` verdict.** It is
> structurally incapable. It returns similarity 1.0 for the single most dangerous
> input the system will ever see. Any design that derives OOD from cosine alone is
> not merely imperfect; it is inverted.
> **A.3.2 — Discarding magnitude violates CLASS-X law.** *Extreme magnitudes are a
> FEATURE channel, never filtered.* Cosine filters magnitude by construction. It
> must therefore be paired with an explicit magnitude coordinate or gate, or it is
> in direct breach of a standing doctrine (see: 450-second latency tail; §5).
> **A.3.3 — Confident-and-wrong beats uncertain-and-right at destroying capital.**
> A system that says "I don't know" in a crisis loses an opportunity. A system that
> says "I know this perfectly" in a crisis loses the account.
---
## A.4 Three more edges (real, but survivable)
**A.4.1 — The metric does all the work; cosine is only the last cheap step.**
On raw features the angle is meaningless: `depth_1pct_usd` ~10⁶, `imbalance` ∈
[-1,1], `funding_rate` ~10⁻⁴. Whichever feature has the largest raw numbers *owns*
the angle. Required before any cosine: a **rank/quantile transform** (NOT z-score —
our distributions are fat-tailed and non-Gaussian; a Gaussian assumption is a lie
we would then be optimizing against), followed by PCA/whitening onto the manifold's
own coordinates. **That transform IS the model.** Version it (`metric_version`),
pin it, and treat any change to it as a change to the science — every manifold cell
built under a prior transform is invalidated.
**A.4.2 — Cosine is a chordal distance in the ambient space, not a geodesic on the
manifold.** The Swiss-roll failure: two states near in angle can be far apart
*along the manifold*, on opposite sides of a fold. Policy performance in
toxicity/latency is exactly the sort of surface that has cliffs. Near-in-angle,
far-in-support, opposite side of a cliff = a confidently wrong recommendation.
Mitigation: stage 2's support gate, plus §A.7's topology diagnostic where the fold
structure is real.
**A.4.3 — Heterogeneous blocks want different geometries.** Market state is
Euclidean-ish. **Counterparty mix is a simplex** (a probability distribution over
agent types — its natural metric is Hellinger or KL, *not* cosine). Inventory /
position state is something else again. One flat cosine over a concatenated vector
silently asserts they share a geometry; they do not. Use a **product metric** with
per-block treatment, and weight the blocks explicitly (the weights are
hyperparameters — fit them, do not guess them).
---
## A.5 THE ARCHITECTURE: RETRIEVE → GATE → MODEL
The operator's instinct survives intact, relocated to its correct stage.
```
live MarketWorldState (S1 book, S2 funding/dvol, S3 regime,
**Why this ordering is not negotiable:** stage 1 is fast and blind; stage 2 is
cheap and sighted; stage 3 is expensive and honest. Running stage 3 on everything
is unaffordable; running stage 1 alone is how the account dies. The cost profile
and the safety profile happen to agree — which is usually the sign of a correct
decomposition.
### Storage consequence (do this, it is cheap and it is the whole safety story)
**Store the manifold as `direction ⊕ magnitude`, separately, per cell.** Then:
- cosine retrieval on direction = matmul (fast path preserved, exactly as the
operator wants);
- magnitude becomes a **scalar interval check** — trivially cheap, and it is the
entire crash-safety mechanism.
95% of the speed, 100% of the guard. There is no tension here to resolve.
---
## A.6 The law this creates (and it is the same law, a third time)
| Layer | "I found something" | "But do I *know* it?" | Verdict when unknown |
|---|---|---|---|
| **Venue** (`bdc54fb`) | HTTP call returned/failed | Was the effect provably absent? | `INDETERMINATE` → **never roll back** |
| **Exit** (F5, tonight) | Price crossed a threshold | Is the price fresh? | stale → **skip, don't act on a fossil** |
| **Manifold** (this annex) | Cosine ≈ 1.0 | Is the live magnitude inside the explored envelope? | `OUT_OF_DISTRIBUTION` → **no recommendation; doctrinal fallback** |
**Unknown is not flat. Unknown is not "best guess." Unknown is unknown.**
Three subsystems, three coats, one law. That is not a coincidence — it is what a
correct architecture looks like from three angles.
---
## A.7 The topology question (the operator's "IFF IFF IFF")
**When does topology genuinely matter, versus merely being seductive?**
Topology earns its cost only when the manifold's **global** structure defeats
**local** metrics. Four cases where it truly does:
| Structure | Where it bites us, concretely | Cost | Verdict |
|---|---|---|---|
| **Cyclicity** | Phase coordinates: hour-of-day, session, funding cycle, day-of-week — and **the operator's win/loss-streak wave phase vs vel_div regimes**. A circle is not a line: 23:59 and 00:01 are *adjacent*, and a flat embedding puts them maximally far apart. Cosine at the seam is catastrophically wrong. | **~zero** | **DO IT NOW.** Encode every cyclic coordinate as a `(sin θ, cos θ)` pair. This is the cheapest correct thing in the entire document and it is *required* for the streak-phase study to mean anything. |
| **Disconnected components** | Genuinely separate basins — normal market vs. halted / limit-up / liquidity-hole. Interpolating *between* components is meaningless; the straight line passes through states the market cannot occupy. | LOW | **DO IT.** Cluster the manifold (offline, Mode 1); refuse to interpolate across component boundaries. Stage 2 gate extension. |
| **Holes / voids** | Regions the market *cannot* enter (negative spread, arbitrage-forbidden configurations). A linear extrapolation across a hole predicts an impossible world — with confidence. | MEDIUM | **IFF** stage-3 variance shows structured failure. Detect offline with persistent homology / the mapper algorithm. |
| **Folds / cliffs** | The Swiss-roll (§A.4.2): chordal-near, geodesic-far. Policy performance cliffs in toxicity/latency. | MEDIUM–HIGH | **IFF** the support gate keeps admitting neighbourhoods whose stage-3 fits are bimodal or high-variance — that is the signature of a fold. |
**The discipline for topology (this is the "IFF"):**
1.**Cyclic encoding: unconditional.** Free, and its absence is a *bug*, not a
simplification.
2.**Component detection: cheap, do it.** Clustering on the Mode-1 manifold.
3.**Persistent homology / mapper: EARN IT.** These are expensive, notoriously
noise-fooled, and seductive precisely because they produce beautiful pictures.
Run them **offline, in Mode 1 only, as a diagnostic of the manifold** — never
as a per-tick Mode-2 operation. And run them only **after** stage 3's variance
has *demonstrated* that the local model is failing in a structured way. You earn
topology by first proving the simple thing breaks.
4. What TDA is *for*, when earned: it tells you **where the folds and holes are**,
so that **stage 2's gate can be shaped correctly**. Topology's product is a
better *gate*, not a better *answer*. That is the whole of it.
---
## A.8 THE GENERALIZATION (the operator's PS — and I think this is the best idea
## in the document)
**Yes. Emphatically. The three-stage manifold query is a general primitive, and
"fingerprinting markets" is its most valuable instance.**
### A.8.1 Market fingerprinting — the natural home
MARAS today emits a **discrete label** (`regime` ∈ {BEARISH, CHOPPY_BEARISH,
CHOPPY, SIDEWAYS, CHOPPY_BULLISH}) plus `confidence`, `conflict_level`, and five
`tier_*` scores. That is a **classifier**: it puts a continuous world into five
boxes.
The manifold view is strictly richer: **the market state is a point, and regimes
are regions — not boxes.** Then:
- The **fingerprint** = `direction` (the *shape* of the market) ⊕ `magnitude` (its
*intensity*) ⊕ its position on the manifold. A regime label becomes a
*coordinate*, not a category. "CHOPPY, but 3σ out along the toxicity axis, near
the boundary with CHOPPY_BEARISH" is a sentence the current system cannot say
and desperately needs to.
- Two observations already point straight at this:
- **`maras_fingerprint.scalar_hash` (UInt16) is already a fingerprint attempt —
but a HASH.** A hash has no neighbourhood: near-identical markets get unrelated
hashes. The cosine-manifold fingerprint is precisely its **continuous
generalization** — *nearest*-fingerprint instead of *exact*-hash. This looks to
me like the thing that hash was reaching for.
- **`conflict_level` (the five tiers disagreeing) is already an implicit OOD
signal.** It maps directly onto stage 2. Tier disagreement = "this market is
not cleanly inside any explored region." That is *free* OOD evidence we are
currently discarding into a float.
- And eigenscan is *already* a manifold construction: eigendecomposition of the
correlation structure **is** the coordinate system. The operator is an eigenscan
surfer; he has been navigating this manifold by hand for years. The three-stage
query is the machine that surfs with him.
### A.8.2 The other manifolds in our system (all of them, and they are everywhere)
| Manifold | The query it answers | Why it matters |
|---|---|---|
| **Trade-path** (`TradePathState`: mae/mfe/time_in_loss/recovery_velocity/…) | *"Have I seen a trade shaped like this before, and what happened to it?"* | This **is** the ADVSL question, and the TP_FLOOR question, and the MAX_HOLD question. Path-aware SL/TP becomes a manifold query instead of a threshold ladder. The 375-branch upside study is this, done geometrically. |
| **Exit-decision** (bars_held × pnl × cascade_count × imbalance × regime) | *"What did similar exits yield?"* | Directly answers the exit-mechanics characterization F5 is paying for right now. |
| **Asset** (the 10-dimension Asset Behavior DSL) | *"This new asset behaves like X"* → transfer its policy | **This is how full-universe picking (500 assets, the north star) becomes affordable.** You do not train 500 policies; you train the manifold and *locate* each asset on it. |
| **Counterparty mix** (the simplex) | *"Who is on the other side right now?"* | Mode 2's ecology prior. Note the different geometry (§A.4.3). |
| **Ops / incident** (disk, CH latency, scan cadence, HZ liveness, spool depth) | *"Does this look like 2026-06-22 before it broke?"* | An OOD alarm on the operational manifold. This is JIMINY/PINOCCHIO's actual job, stated properly: **fingerprint the system's own state and scream when it drifts somewhere it has never been.** Sparks, before the fire. |
| **Streak / wave** (win-loss amplitude, **phase**, vel_div regime) | *"Are our streaks in phase with the regime wave?"* | The operator's grail hypothesis (SHORT/LONG regime switch). **Requires the cyclic encoding of §A.7 to even be askable.** |
### A.8.3 What actually generalizes (be precise — this matters)
**What generalizes is the three-stage DISCIPLINE, not one metric.**
Each manifold has its own geometry: Euclidean-ish (market state), simplex
(counterparty mix), cyclic (phase), categorical-mixed (asset taxonomy). A single
flat cosine over all of them is exactly the error §A.4.3 warns about. But the
*discipline* — **retrieve fast and blind → gate on magnitude and support → model
locally with variance → say OUT_OF_DISTRIBUTION when you don't know** — is
invariant across every one of them.
So the shared artifact is a **library primitive**, not a shared metric:
| A1 | **Cyclic encoding** of all phase coordinates `(sin, cos)` | Free, unconditional, and a prerequisite for the streak-phase study |
| A2 | **Transform + versioning**: rank/quantile → whiten → PCA; emit `metric_version` | A metric change invalidates the manifold; test that it says so |
| A3 | **Store `direction ⊕ magnitude` separately** per manifold cell | The whole crash-safety story is this one storage decision |
| A5 | **Stage 2 gate**: magnitude envelope + support + Mahalanobis → `OUT_OF_DISTRIBUTION` | **Mutation litmus: feed a same-direction-10×-magnitude state; the system MUST refuse. If it recommends, the guard is not wired.** |
| A6 | **Stage 3 local model** (tangent-space fit or GP) → prediction + variance | Variance must grow away from data (test it) |