Look-ahead bias: one door between a backtest and the future
Why look-ahead bias survives code review, and what kairos builds against it: one bisect access path, append-only writes, a close-of-day cutoff, a clock check.
Look-ahead bias is the backtest bug where a decision uses information that did not exist yet at the moment the decision would have been made. The kairos lab page shows its simplest form: one index slips and a random walk turns into a money machine. This note is about the harder forms, the ones that do not look like an index bug at all. And about the design kairos uses against it in the place where it matters most: where the reasoning layer reads market perception.
Why review does not catch it
Three things make look-ahead hard to find by reading code. It is directional: it always flatters the result, so nothing looks broken. It hides in the meaning of a lookup: “give me the data for 2024-05-10” looks equally innocent whether the vendor returns what was known that day or a later revision. And it can be shorter than a day: a cutoff at the start of the session instead of the end shifts a whole session and trips no assertion.
kairos makes this concrete. Its reasoning layer (System 2) is a multi-agent LLM debate that decides “as of a trade date”; its perception layer (System 1) reads the order book. Every tool the agents call is a potential leak. The conclusion the repo draws: look-ahead safety has to be a property of the access path, not of the caller’s discipline.
One door, and it only opens backwards
System 2 reaches microstructure perception only through a CausalPerceptionBus. Writes go through record, reads through as_of, window_before and aggregate_before; there is no other sanctioned door. The bus keeps two parallel lists: the percepts and their sorted timestamps. A read is a single bisect:
def as_of(self, query: float | int | str | date | datetime) -> Percept | None:
"""The most recent percept at or before ``query``. ``None`` if the
causal history is empty at that cutoff. Never returns the future."""
cutoff = self._cutoff(query)
idx = bisect.bisect_right(self._ts, cutoff) - 1
if idx < 0:
return None
p = self._percepts[idx]
if self._strict and p.ts > cutoff:
raise LookAheadError(f"as_of returned ts={p.ts} > cutoff={cutoff}")
return p
src/kairos/bridge/causal_bus.py, lines 163–173bisect_right returns the position just past every timestamp less than or equal to the cutoff; one less is the most recent percept at or before the cutoff. The future is not filtered out here, it is unreachable: as long as the timestamps are sorted and the cutoff is a real number, no idx this code can produce points past the cutoff. The strict check after it is a tripwire for a bug in the bus itself. A genuine gap in the data is not an error; it returns None.
The “real number” condition is not decoration. At this commit a NaN cutoff (as_of("nan") or float("nan")) walks through this door: every comparison with NaN is false, bisect_right returns the end of the list, idx points at the newest percept, and the p.ts > cutoff check is false too, so it does not fire. Maximal look-ahead, silently. The fix that forces the cutoff to be a finite number landed on kairos’s main on 25 November 2026 (9a6feb7).
as_of cannot reach percepts after the cutoff; bisect_right fixes the reachable prefix and one less is the newest valid percept. Bottom: a bare date. datetime.fromisoformat puts it at the start of the day (red); kairos recognises it with a regex first and maps it to the last microsecond of the day (gold).Sortedness is the write side’s job. record refuses a percept older than the last one (“the causal bus models a forward-only stream”); equal timestamps are accepted. That gives the second invariant, append-independence: percepts recorded later can never change the answer to an earlier query, because new entries always land behind every position an earlier cutoff could reach. This is what defeats revised data structurally: a correction recorded later is simply invisible to a query about the past.
What does “as of a date” mean?
Daily reasoning says “trade on 2024-05-10”. kairos maps a bare date to the last microsecond of that UTC day, 23:59:59.999999: the whole session is in-sample, nothing from the 11th is. The trap is in the standard library: datetime.fromisoformat("2024-05-10") is a valid call and returns midnight, the start of the day. Hand it the date string and the cutoff silently moves by a whole session; the bus then behaves correctly for the wrong cutoff, and no assertion fires. So bare dates are recognised with a regex before fromisoformat is ever called:
if isinstance(query, str):
s = query.strip()
try: # a stringified number is a numeric-clock value
return float(s), "numeric"
except ValueError:
pass
if _DATE_ONLY.match(s): # "YYYY-MM-DD" -> close of that day, UTC
d = date.fromisoformat(s)
return (datetime(d.year, d.month, d.day, 23, 59, 59, 999999,
tzinfo=timezone.utc).timestamp(), "epoch")
dt = datetime.fromisoformat(s) # has a time component
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.timestamp(), "epoch"
src/kairos/bridge/causal_bus.py, lines 89–102Which way the error goes depends on how the rest of the run is wired: a start-of-day cutoff can hide the day’s data from a decision that was meant to see it, or, if the execution window is aligned to the other convention, overlap with it. Either way it is silent. A test pins it down: a mid-day percept on the 10th is visible to as_of("2024-05-10"), one at 01:00 on the 11th is not. Timestamps without a time zone are taken as UTC too, so the same string does not mean a different instant on a different machine.
When the invariant holds and the answer is still wrong
An adversarial review of the bus found a subtler hole. Synthetic and replayed sessions often stamp percepts with a step index (0, 8, 16, … up to about 4000); real instruments use UNIX epoch seconds (about 1.7 billion). Ask an index-clocked bus for as_of("2024-05-10"): the date becomes an epoch, every step index is smaller than it, and the bisect returns the newest percept. Maximal look-ahead, and the ts ≤ cutoff check does not fire, because 4000 ≤ 1.7×10⁹ is true. The invariant held; the clock was wrong.
The fix gives the bus a clock domain, inferred from the first recorded timestamp: 10⁷ or more means epoch. 10⁷ seconds is about 116 days after 1970; far above any plausible step count, far below any real market timestamp. Each query is classified as numeric or epoch, and a wall-clock query against an index-clocked bus raises ClockDomainError instead of getting an answer:
def _cutoff(self, query) -> float:
"""Resolve a query to a numeric cutoff, refusing a cross-clock query."""
value, domain = resolve_cutoff(query)
if domain == "epoch" and self._clock == "index":
raise ClockDomainError(
f"date/datetime query ({query!r} -> epoch {value:.0f}) against an "
"index-clocked bus. A wall-clock cutoff on step-index percepts would "
"return the newest percept (look-ahead). Query with the same clock the "
"percepts use, or build the bus with real epoch timestamps."
)
return value
src/kairos/bridge/causal_bus.py, lines 131–141Numeric queries stay clock-agnostic, so querying a synthetic run by step number still works. That small distinction turns a guarantee that holds within one clock into one that cannot be fooled across clocks either.
Keeping the door the only door
All of this binds only if the reasoning code actually goes through the door. The bus also has a latest property and its raw lists; harmless for bookkeeping, fatal in a reasoning tool. kairos has a small “constitution” script that runs in CI. Its Rule 5 scans the two reasoning-facing bridge files for .latest, ._percepts or ._ts outside comments; a match fails the build.
To be precise about what that is: a regex over two files is a tripwire, not a proof. A getattr with a string walks past it. Its job is to stop the easy mistake, someone “just grabbing .latest” in a new tool, and it does that cheaply.
Tests that state the invariants
The bus’s tests are written as statements of the two invariants rather than as examples: against timestamps 0–99, every cutoff from −5 to 104 never returns the future; snapshots of 50 past queries are unchanged after 150 future percepts are appended; 200 random buses with random increasing timestamps and 30 random queries each never leak in strict mode. That is evidence over many inputs; the actual argument for safety is the bisect itself. The tests are there so that a future change to the bus has to break something visible.
The same rule, elsewhere
The bus is the part with a name, but the same rule shows up in smaller places. The paper fill simulator fills the quote posted on the previous step against this step’s trades, so a quote never benefits from flow it could not have seen. The cognitive loop forms its decision from the first part of a session and executes it only on the rest, the forward window.
What the honest version earns
With the leak closed, the results are modest, and the README says so. On benign, range-bound synthetic markets kairos’s loop beats naive always-long on all five seeds the reproduce script tries. On trending or toxic markets naive directional exposure often wins; a market maker pays adverse selection there, and that is a property of the market, not a bug. The reproduce script asserts only what holds across seeds, never profit in every regime. All of it is on synthetic or replayed data. This is what a backtest looks like when it cannot see its own future: less exciting, and believable.