From a32e23c55a2c30c8de9e04de519b9640c7a12cee Mon Sep 17 00:00:00 2001 From: Alessandro <17289614+0x0f0f0f@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:08:43 +0100 Subject: [PATCH 1/4] perf(runtime): skip market masking that cannot mask a field With signal eligibility declared, RuntimeServices checked every market field of every asset on every bar, though a bar at the current timestamp is always published to the inclusive clock when no known-at, eligibility or instrument lifetime applies. On 2.2M daily bars of 1,164 assets this took 95 of 132 seconds; a run now takes 30. --- src/ml4t/backtest/runtime.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/ml4t/backtest/runtime.py b/src/ml4t/backtest/runtime.py index 514192e1..efdb9cad 100644 --- a/src/ml4t/backtest/runtime.py +++ b/src/ml4t/backtest/runtime.py @@ -1111,6 +1111,12 @@ def _advance(self, timestamp: datetime, data: dict[str, dict]) -> dict[str, dict if not self.known_at_cols and not signal_fields and self._assets is None: return data visible = {asset: dict(values) for asset, values in data.items()} + # A bar at the current timestamp is published to an inclusive clock. Without known-at or + # eligibility declarations, or instrument lifetimes for quotes, no market field can be + # masked, so the per-asset, per-field checks below are skipped. + masks_market = bool(market._known_at_cols or market._eligible_cols) or ( + market._quote_fields and self._assets is not None + ) for asset, values in visible.items(): if signal_fields: assert signal_view is not None @@ -1122,6 +1128,8 @@ def _advance(self, timestamp: datetime, data: dict[str, dict]) -> dict[str, dict if not view._available(field, signal): delivered[field] = None values["signals"] = delivered + if not masks_market: + continue row = market._row(asset, timestamp) if row is None: continue From c4d95dcf244817c6d3104962a9907573632d39c3 Mon Sep 17 00:00:00 2001 From: Alessandro <17289614+0x0f0f0f@users.noreply.github.com> Date: Sat, 21 Nov 2026 03:39:42 +0100 Subject: [PATCH 2/4] perf(runtime): index market views with Polars and skip signal checks between decisions MarketDataView built its asset/timestamp row index one Python row at a time and checked known-at timezones per row. It now groups row numbers by asset in Polars, shares one Python value per distinct instant, and checks timezone compatibility once per column. Duplicate and timezone errors are unchanged. RuntimeServices._advance looked up a signal row for every asset at every event although signal rows exist only at decisions. It now returns early at events with no signal row and nothing to mask, reads each signal row's masks from a table computed once in Polars (a row is read at its own timestamp, so its mask depends on the row alone), and checks an instrument lifetime once per asset instead of reading the bar and testing twelve fields. Measured on one monthly book over 1,165 assets x 2,264 sessions (2.2M bars): _bind 4.7 s -> 0.4 s, _advance 7.2 s -> 0.5 s, Engine.run 14.9 s -> 9.8 s, with identical fills and equity. --- src/ml4t/backtest/runtime.py | 158 ++++++++++++++++++++++++-------- tests/test_prepared_features.py | 42 +++++++++ 2 files changed, 160 insertions(+), 40 deletions(-) diff --git a/src/ml4t/backtest/runtime.py b/src/ml4t/backtest/runtime.py index efdb9cad..2e81ec23 100644 --- a/src/ml4t/backtest/runtime.py +++ b/src/ml4t/backtest/runtime.py @@ -15,7 +15,7 @@ from ._history_clock import expected_times, session_times from ._instruments import InstrumentSource, InstrumentView -from ._temporal import temporal_frame, temporal_row, temporal_rows +from ._temporal import temporal_frame, temporal_row, temporal_rows, timestamp_values from .auxiliary import AuxiliaryData from .execution.callbacks import SessionScheduler from .futures_lifecycle import FuturesLifecyclePolicy @@ -24,6 +24,22 @@ from .engine import Engine +_QUOTE_FIELDS = ( + "price", + "open", + "high", + "low", + "close", + "volume", + "vwap", + "bid", + "ask", + "mid", + "bid_size", + "ask_size", +) + + class PreparedHistory(Protocol): """Read interface for Data's causal prepared-history output.""" @@ -137,26 +153,41 @@ def __init__( self._frame.schema[column], pl.Datetime ): raise ValueError(f"Known-at column {column!r} must contain datetimes") - index_columns = list( - dict.fromkeys([self._timestamp_col, self._entity_col, *self._known_at_cols.values()]) + stamps = self._frame[self._timestamp_col] + for column in dict.fromkeys(self._known_at_cols.values()): + if self._frame[column].null_count() == self._frame.height: + continue + known_dtype = self._frame.schema[column] + if not isinstance(stamps.dtype, pl.Datetime) or ( + cast(pl.Datetime, known_dtype).time_zone is None + ) != (stamps.dtype.time_zone is None): + raise ValueError("Known-at and observation timezones must be compatible") + # One Python value per distinct instant, shared by every asset's index; rows are + # grouped by asset in Polars instead of being iterated one by one. + instants = stamps.unique().sort() + self._timestamps = timestamp_values(instants) + values = dict(zip(instants.to_physical().to_list(), self._timestamps, strict=True)) + index = self._frame.select( + pl.col(self._entity_col), pl.col(self._timestamp_col).to_physical().alias("__ml4t_key") + ).with_row_index("__ml4t_row") + repeated = index.filter( + pl.struct(self._entity_col, "__ml4t_key").is_first_distinct().not_() ) - for index, row in enumerate(temporal_rows(self._frame.select(index_columns), named=True)): - asset, timestamp = row[self._entity_col], row[self._timestamp_col] - rows = self._rows.setdefault(asset, {}) - if timestamp in rows: - raise ValueError(f"Duplicate market observation for {asset!r} at {timestamp}") - for column in self._known_at_cols.values(): - if row[column] is not None: - try: - _ = row[column] <= timestamp - except TypeError as exc: - raise ValueError( - "Known-at and observation timezones must be compatible" - ) from exc - rows[timestamp] = index + if repeated.height: + asset, key = repeated.row(0)[1:] + raise ValueError(f"Duplicate market observation for {asset!r} at {values[key]}") + for part in index.partition_by(self._entity_col, maintain_order=True): + self._rows[part[self._entity_col][0]] = dict( + zip( + map(values.__getitem__, part["__ml4t_key"].to_list()), + part["__ml4t_row"].to_list(), + strict=True, + ) + ) for asset, rows in self._rows.items(): self._times[asset] = sorted(rows) - self._timestamps = sorted({t for times in self._times.values() for t in times}) + self._timestamp_set = frozenset(self._timestamps) + self._hidden: dict[frozenset[str], dict[int, tuple[str, ...]]] = {} self._asof: datetime | None = None self._inclusive = False @@ -180,6 +211,47 @@ def _row(self, asset: str, timestamp: datetime) -> dict[str, Any] | None: index = self._rows.get(asset, {}).get(timestamp) return temporal_row(self._frame, index) if index is not None else None + def _hidden_at_own_time(self, fields: frozenset[str]) -> dict[int, tuple[str, ...]]: + """Row index -> the fields `_available` masks when the clock stands at that row's time. + + Valid only for views without quote fields: they read inclusively and carry no instrument + lifetime, so the mask of a row at its own timestamp depends on the row alone and is + computed once, in Polars, for every row. + """ + assert not self._quote_fields + cached = self._hidden.get(fields) + if cached is not None: + return cached + timestamp = pl.col(self._timestamp_col) + dtype = self._frame.schema[self._timestamp_col] + masks = [] + for field in sorted(fields): + declaration = self._known_at_cols.get(field) + hidden = ( + timestamp.is_null() + if declaration is None + else pl.col(declaration).is_null() | (pl.col(declaration).cast(dtype) > timestamp) + ) + eligible = self._eligible_cols.get(field) + if eligible is not None: + hidden = hidden | pl.col(eligible).fill_null(False).not_() + masks.append(pl.when(hidden).then(pl.lit(field))) + cached = ( + { + row: tuple(names) + for row, names in self._frame.select( + pl.concat_list(masks).list.drop_nulls().alias("hidden") + ) + .with_row_index("row") + .filter(pl.col("hidden").list.len() > 0) + .iter_rows() + } + if masks + else {} + ) + self._hidden[fields] = cached + return cached + def _column(self, field: str) -> str: return self._roles.get(field, field) @@ -1110,43 +1182,49 @@ def _advance(self, timestamp: datetime, data: dict[str, dict]) -> dict[str, dict ) if not self.known_at_cols and not signal_fields and self._assets is None: return data - visible = {asset: dict(values) for asset, values in data.items()} # A bar at the current timestamp is published to an inclusive clock. Without known-at or # eligibility declarations, or instrument lifetimes for quotes, no market field can be # masked, so the per-asset, per-field checks below are skipped. masks_market = bool(market._known_at_cols or market._eligible_cols) or ( market._quote_fields and self._assets is not None ) + check_signals = ( + signal_view is not None + and bool(signal_fields) + and timestamp in signal_view._timestamp_set + ) + if not masks_market and not check_signals: + return data # no signal row at this event and no market field to mask + # The clock stands at the signal rows' own timestamp, so their masks are precomputed. + hidden = ( + signal_view._hidden_at_own_time(frozenset(signal_fields)) + if check_signals and signal_view is not None + else {} + ) + visible = {asset: dict(values) for asset, values in data.items()} for asset, values in visible.items(): - if signal_fields: + if check_signals: assert signal_view is not None - view = signal_view - signal = view._row(asset, timestamp) - if signal is not None: + index = signal_view._rows.get(asset, {}).get(timestamp) + if index is not None: delivered = dict(values.get("signals", {})) - for field in signal_fields: - if not view._available(field, signal): - delivered[field] = None + delivered.update(dict.fromkeys(hidden.get(index, ()))) values["signals"] = delivered if not masks_market: continue + if not (market._known_at_cols or market._eligible_cols): + # Only an instrument's lifetime can mask this bar; it masks every field at once, + # so one membership check replaces reading the row and testing each field. + assert self._assets is not None + if timestamp in market._rows.get(asset, {}) and not self._assets._active_at( + asset, timestamp, timestamp + ): + values.update(dict.fromkeys(_QUOTE_FIELDS)) + continue row = market._row(asset, timestamp) if row is None: continue - for field in [ - "price", - "open", - "high", - "low", - "close", - "volume", - "vwap", - "bid", - "ask", - "mid", - "bid_size", - "ask_size", - ]: + for field in _QUOTE_FIELDS: raw = market._column(field) source = ( field diff --git a/tests/test_prepared_features.py b/tests/test_prepared_features.py index 1f9176d7..465cd6a5 100644 --- a/tests/test_prepared_features.py +++ b/tests/test_prepared_features.py @@ -3,6 +3,7 @@ import hashlib import json from copy import deepcopy +from datetime import timedelta from pathlib import Path import pandas as pd @@ -142,6 +143,47 @@ def on_data(self, timestamp, data, context, broker): assert panel["average"].to_list() == [2.0, 20.0, 3.0, 30.0] +@pytest.mark.parametrize("late", [False, True]) +def test_feature_values_reach_a_strategy_only_at_decisions_when_prices_have_events_between_them( + late, +): + panel = _panel() + if late: + panel = panel.with_columns( + pl.when(pl.col("asset") == "A") + .then(pl.col("decision_time") + pl.duration(seconds=1)) + .otherwise(pl.col("available_at")) + .alias("available_at") + ) + prices = _panel().select( + pl.col("decision_time").alias("timestamp"), "asset", pl.lit(100.0).alias("close") + ) + between = prices["timestamp"].min() + timedelta(hours=1) + extra = pl.select( + pl.lit(between, dtype=prices.schema["timestamp"]).alias("timestamp"), + pl.Series("asset", ["A", "B"]), + pl.lit(100.0).alias("close"), + ) + feed = DataFeed( + prices_df=pl.concat([prices, extra]).sort("timestamp", "asset"), + signals_df=panel, + feature_spec=MANIFEST["feature_spec"], + feed_spec={ + "time_contract_version": 2, + "calendar": None, + "timestamp_semantics": "event_time", + }, + ) + seen = [] + + class Read(Strategy): + def on_data(self, timestamp, data, context, broker): + seen.append((data["A"].get("signals") or {}).get("average")) + + Engine(feed, Read(), BacktestConfig(calendar=None)).run() + assert seen == ([None, None, None] if late else [2.0, None, 3.0]) + + def test_feature_metadata_is_a_defensive_copy_of_the_original_producer_contract(): feed = _feed() metadata = feed.feature_metadata From 04adb82b3073670e1a2f7d49becc32df22aa9c2a Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Mon, 23 Nov 2026 19:06:38 -0500 Subject: [PATCH 3/4] Preserve publication precision in cached prepared-feature masks --- src/ml4t/backtest/runtime.py | 11 ++++++-- tests/test_prepared_features.py | 47 +++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/ml4t/backtest/runtime.py b/src/ml4t/backtest/runtime.py index 2e81ec23..7e1f6ed0 100644 --- a/src/ml4t/backtest/runtime.py +++ b/src/ml4t/backtest/runtime.py @@ -223,14 +223,21 @@ def _hidden_at_own_time(self, fields: frozenset[str]) -> dict[int, tuple[str, .. if cached is not None: return cached timestamp = pl.col(self._timestamp_col) - dtype = self._frame.schema[self._timestamp_col] + units = {"ms": 1_000_000, "us": 1_000, "ns": 1} + stamp_dtype = cast(pl.Datetime, self._frame.schema[self._timestamp_col]) + observation_ns = timestamp.cast(pl.Int128) * units[stamp_dtype.time_unit] masks = [] for field in sorted(fields): declaration = self._known_at_cols.get(field) hidden = ( timestamp.is_null() if declaration is None - else pl.col(declaration).is_null() | (pl.col(declaration).cast(dtype) > timestamp) + else pl.col(declaration).is_null() + | ( + pl.col(declaration).cast(pl.Int128) + * units[cast(pl.Datetime, self._frame.schema[declaration]).time_unit] + > observation_ns + ) ) eligible = self._eligible_cols.get(field) if eligible is not None: diff --git a/tests/test_prepared_features.py b/tests/test_prepared_features.py index 465cd6a5..5da1c093 100644 --- a/tests/test_prepared_features.py +++ b/tests/test_prepared_features.py @@ -262,3 +262,50 @@ def test_captured_panel_can_be_rebuilt_by_the_actual_installed_engineer_producer actual = actual.collect() if isinstance(actual, pl.LazyFrame) else actual assert_frame_equal(actual, _panel()) assert _feed(actual, spec).feature_metadata["spec"] == spec.to_dict() + + +@pytest.mark.parametrize("unit", ["ms", "us", "ns"]) +@pytest.mark.parametrize("delay_ns", [0, 1]) +@pytest.mark.parametrize("append_future", [False, True]) +def test_prepared_feature_publication_keeps_nanosecond_causality_at_coarser_decision_clocks( + unit, delay_ns, append_future +): + panel = _panel().with_columns( + pl.col("decision_time").cast(pl.Datetime(unit, "UTC")), + ( + pl.col("decision_time").cast(pl.Datetime("ns", "UTC")) + + pl.duration(nanoseconds=delay_ns) + ).alias("available_at"), + ) + if append_future: + future = panel.tail(2).with_columns( + pl.col("timestamp") + pl.duration(days=1), + (pl.col("decision_time") + pl.duration(days=1, time_unit="ns")).cast( + panel.schema["decision_time"] + ), + pl.col("available_at") + pl.duration(days=1, time_unit="ns"), + pl.lit(99999.0).alias("average"), + ) + panel = pl.concat([panel, future]) + runtime = RuntimeServices(end=_panel()["decision_time"].max()) + seen = [] + + class Read(Strategy): + def on_data(self, timestamp, data, context, broker): + values = [(data.get(a, {}).get("signals") or {}).get("average") for a in ["A", "B"]] + current = runtime.signals.current(["A", "B"], ["average"])["average"].to_list() + assert current == values + seen.append(values) + if values[0] is not None: + broker.submit_order("A", 1) + + # Original two decision observations only. A future appended panel must not change them. + feed = _feed(panel) + result = Engine( + feed, + Read(), + BacktestConfig(calendar=None, execution_mode=ExecutionMode.SAME_BAR), + runtime=runtime, + ).run() + assert seen == ([[2.0, None], [3.0, None]] if delay_ns == 0 else [[None, None], [None, None]]) + assert [f.price for f in result.fills] == ([100.0, 100.0] if delay_ns == 0 else []) From f020987f55b5aa2cb790164facba7c0a5a355993 Mon Sep 17 00:00:00 2001 From: Stefan Jansen Date: Mon, 23 Nov 2026 19:36:04 -0500 Subject: [PATCH 4/4] Document causal RuntimeServices indexing changes --- CHANGELOG.md | 6 ++++++ release/changelog.json | 3 +++ 2 files changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 622267c8..9cec03c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,12 @@ - Retry transient external documentation-link failures with bounded backoff. Broken links and persistent service errors still fail qualification. +### Changed + +- Avoid redundant prepared-signal masking and per-row index construction in RuntimeServices. + Preserve exact publication timestamps, eligibility, missing observations and instrument + lifetimes. + ## 0.2.0 - 2026-10-22 ### Added diff --git a/release/changelog.json b/release/changelog.json index 30526e12..3eb919e3 100644 --- a/release/changelog.json +++ b/release/changelog.json @@ -20,6 +20,9 @@ "Update build and workflow dependencies and repair contributor-environment security locks. Require PyArrow 26.0.1 or later in the pinned installed successor qualification cohort.", "Correct the executable limit-order tutorial to match favorable opening fills and simplify documentation navigation. Keep public examples qualified against the built wheel.", "Retry transient external documentation-link failures with bounded backoff. Broken links and persistent service errors still fail qualification." + ], + "Changed": [ + "Avoid redundant prepared-signal masking and per-row index construction in RuntimeServices. Preserve exact publication timestamps, eligibility, missing observations and instrument lifetimes." ] } },