Skip to content

Speed up RuntimeServices on prepared feature panels - #200

Draft
0x0f0f0f wants to merge 4 commits into
ml4t:mainfrom
0x0f0f0f:perf/runtime-services-indexing
Draft

0x0f0f0f wants to merge 4 commits into
ml4t:mainfrom
0x0f0f0f:perf/runtime-services-indexing

Conversation

@0x0f0f0f

@0x0f0f0f 0x0f0f0f commented Nov 21, 2026 •

Copy link
Copy Markdown

Maintainer review and repair

Reviewed contributor revision c4d95dcf244817c6d3104962a9907573632d39c3. Its cached publication mask exposed a feature published 1 nanosecond after a millisecond/microsecond decision. Maintainer commit 04adb82b3073670e1a2f7d49becc32df22aa9c2a preserves physical-time precision with overflow-safe integer comparison. Four causal regressions fail on the original contribution; all 12 precision/future-append cases pass after repair.

The repaired wheel matches all 114 runtime modules and passes 155 installed RuntimeServices/history tests with the immutable Data/Engineer/Diagnostic cohort, zero skips. A public Engine portfolio using Engineer's real feature producer, 40 assets, 252 sessions, universe exclusions and missing observations matches main exactly: 406 fills, fees, observations, full equity series and final cash. No producer API change is required; publication/eligibility and decision-specific snapshot semantics remain authoritative.

The contributor's single-run timings below are retained as attributed observations, not adopted as retained benchmark claims. The existing 17 timed reference workflows do not instantiate RuntimeServices. Final integrated native evidence and all current-head hosted gates are still required before merge.

OpenAI Codex performed the maintainer review, wrote the precision repair/regressions, and ran the source and installed checks above. Original contributor commits and their AI disclosure are preserved. The author's unchecked accountability statement below has not been asserted on their behalf.

Owning issue

Closes #198

Outcome

RuntimeServices did per-bar Python work that cannot change its result. This change removes that work. Errors and results are unchanged.

 RuntimeServices._advance(event)
+  no signal row at this event and nothing to mask: return
-  for each asset: look up its signal row, check every market field
+  read the 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)
+  skip masking a field that no known-at, eligibility or lifetime can mask
+  check an instrument lifetime once per asset, not twelve fields of each bar
 MarketDataView.__init__
-  asset/timestamp index built one Python row at a time; known-at timezone checked per row
+  row numbers grouped by asset in Polars; one Python value per distinct instant; timezone checked per column

Bug regression evidence

Not a bug fix.

Compatibility

  • No public compatibility impact
  • Compatibility impact is documented in the owning issue and migration guidance

No numerical change: the same events reach the strategy with the same values. tests/test_prepared_features.py::test_feature_values_reach_a_strategy_only_at_decisions_when_prices_have_events_between_them (added here, with and without late publication) covers the new early return. It passes on the base and on this PR. The benchmark below reads the same 48,000 signal values on both.

Verification

Synthetic benchmark: 500 assets x 2,000 daily sessions, a prepared feature panel every 21 sessions (96 decisions) with eligibility declared, RuntimeServices(), and a strategy that reads every asset's signal at each event and does not trade. Apple M4 Pro, macOS 15.5, Python 3.14.0, one run each:

Revision DataFeed Engine.run Signal values read
base 99ee997 (src/ restored to main) 0.8 s 19.1 s 48,000
this PR, c4d95dc 0.8 s 2.2 s 48,000
bench_runtime.py (run from the repository root: uv run python bench_runtime.py)
"""Time Engine.run with RuntimeServices and a prepared feature panel on synthetic daily bars.

Decisions every 21 sessions, as a monthly book; the strategy reads every asset's signals at each
decision and trades nothing, so the time is the engine's and RuntimeServices'.
Run from a checkout of ml4t-backtest: uv run python bench_runtime.py
"""

import datetime as dt
import json
import time
from pathlib import Path

import numpy as np
import polars as pl
from ml4t.backtest import BacktestConfig, DataFeed, Engine, RuntimeServices, Strategy

ASSETS, SESSIONS, EVERY = 500, 2000, 21

rng = np.random.default_rng(0)
days = pl.Series(
    "timestamp",
    [dt.datetime(2017, 1, 2, 21, tzinfo=dt.UTC) + dt.timedelta(days=i) for i in range(SESSIONS)],
    dtype=pl.Datetime("ns", "UTC"),
)
assets = pl.Series("asset", [f"A{i:04d}" for i in range(ASSETS)])
close = 100 + rng.standard_normal(ASSETS * SESSIONS).cumsum() * 0.01
prices = (
    pl.DataFrame(assets)
    .join(pl.DataFrame(days), how="cross")
    .with_columns(close=pl.Series(close))
    .with_columns(open="close", high="close", low="close", volume=pl.lit(1e6))
    .sort("timestamp", "asset")
)
panel = (
    prices.filter(pl.col("timestamp").is_in(days.gather_every(EVERY).implode()))
    .select(
        pl.col("timestamp").dt.date().alias("timestamp"),
        "asset",
        pl.col("timestamp").alias("decision_time"),
        pl.col("close").alias("average"),
        pl.col("timestamp").alias("available_at"),
        member=pl.lit(True),
        eligible=pl.lit(True),
        price_basis=pl.lit("raw"),
        effective_session=pl.col("timestamp").dt.date(),
    )
)
spec = json.loads(Path("tests/fixtures/prepared_features/manifest.json").read_text())["feature_spec"]

start = time.perf_counter()
feed = DataFeed(
    prices_df=prices,
    signals_df=panel,
    feature_spec=spec,
    feed_spec={"time_contract_version": 2, "calendar": None, "timestamp_semantics": "event_time"},
)
built = time.perf_counter() - start
reads = []


class Read(Strategy):
    def on_data(self, timestamp, data, context, broker):
        reads.append(sum(1 for bar in data.values() if (bar.get("signals") or {}).get("average") is not None))


start = time.perf_counter()
Engine(feed, Read(), BacktestConfig(calendar=None), runtime=RuntimeServices()).run()
ran = time.perf_counter() - start
print(f"{ASSETS} assets x {SESSIONS} sessions, {panel['decision_time'].n_unique()} decisions")
print(f"DataFeed {built:.1f} s, Engine.run {ran:.1f} s, signal reads {sum(reads)}")

On our own workload, one monthly book over about 1,165 US stocks x 2,264 sessions (2.2M bars): the first commit took a run from 132 s to 30 s. The second took _bind from 4.7 s to 0.4 s, _advance from 7.2 s to 0.5 s and Engine.run from 14.9 s to 9.8 s, with identical fills and equity.

These numbers come from outside your retained performance harness (#62). If one of its workloads covers RuntimeServices, point me to it and I will add its numbers.

Checks from AGENTS.md, at this PR's revision:

  • uv run ruff check src tests: all checks passed

  • uv run ruff format --check src tests: 325 files already formatted

  • uv run ty check: all checks passed

  • uv run pytest: 3,187 passed, 125 skipped, 14 failed: the contract tests in tests/contracts/test_parity_claim_generation.py and tests/contracts/test_real_strategy_runner.py that pin the engine source digest of the retained correctness and performance evidence (backtrader/01 engine digest is stale, ...). On main all pass (3,199 passed, 125 skipped). Requalifying that evidence needs the retained real-strategy bundles, which I do not have, so as in Close fractional positions exactly at zero target weight #195 it is left to your requalification.

  • uv build: wheel and sdist built

  • Bug regression fails on the base and passes with the fix, or this is not a bug fix

  • Ruff lint and format checks pass

  • ty passes

  • Test suite passes (all but the 14 digest-pinned contract tests above)

  • Package build passes when applicable

  • Strict MkDocs build passes when documentation is affected (no documentation change)

  • Ecosystem qualification passes (not run)

AI assistance

An AI coding agent (Claude Code) wrote the change, its test, the benchmark and this description, and ran the commands above.

  • I reviewed and tested this submission and can explain its code and evidence

Documentation and release

No documentation change. Release notes, under Changed or Performance: faster RuntimeServices binding and event processing on prepared feature panels.

0x0f0f0f and others added 4 commits November 21, 2026 15:26
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.
…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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Faster RuntimeServices on large daily panels

2 participants