"""QA edge cases for T-213 (M2.4b) Python `stockbot` batch runner and cross_section. Offline only: every test builds its own temporary curated root of Parquet fixtures and touches no QA database, live QuestDB, or execution module. """ from __future__ import annotations import json import os from datetime import datetime, timezone from pathlib import Path from typing import Mapping import duckdb import polars as pl import pytest import stockbot.features as features_mod from stockbot import ( RET_1D_V1, DuckDbConnectionBudget, FeatureDefinition, FeatureLibraryError, MarketDataStore, MarketDataStoreValidationError, VaultHoldoutFenceError, run_feature_batch, ) from stockbot.vault import parse_timestamp_micros UTC = timezone.utc VAULT_CUTOFF_DATE = "2025-07-01" VAULT_CUTOFF_MS = parse_timestamp_micros(VAULT_CUTOFF_DATE, "start", "cutoff") // 1000 def _budget(tmp_path: Path) -> DuckDbConnectionBudget: tmp_dir = tmp_path / "duckdb_tmp" tmp_dir.mkdir(parents=True, exist_ok=True) return DuckDbConnectionBudget(memory_limit="512MB", threads=2, temp_directory=str(tmp_dir)) def _write_parquet(df: pl.DataFrame, out_path: Path) -> None: out_path.parent.mkdir(parents=True, exist_ok=True) con = duckdb.connect(":memory:") try: con.execute("SET TimeZone = 'UTC';") con.register("src", df) con.execute(f"COPY src TO '{out_path}' (FORMAT PARQUET, COMPRESSION ZSTD)") finally: con.close() def _bars(rows: list[tuple[int, datetime, float]]) -> pl.DataFrame: """Builds bars_1d rows (listing_id, bar-close ts, close) with known_at == ts.""" return pl.DataFrame( { "listing_id": [r[0] for r in rows], "session_date": [r[1].date() for r in rows], "ts": [r[1] for r in rows], "open": [r[2] for r in rows], "high": [r[2] for r in rows], "low": [r[2] for r in rows], "close": [r[2] for r in rows], "volume": [1000.0 for _ in rows], "vwap": [r[2] for r in rows], "currency": ["USD" for _ in rows], "source": ["eod" for _ in rows], "known_at": [r[1] for r in rows], }, schema_overrides={ "listing_id": pl.Int32, "ts": pl.Datetime("us", "UTC"), "known_at": pl.Datetime("us", "UTC"), "session_date": pl.Date, }, ) def _seed_two_year_bars(curated: Path) -> None: _write_parquet( _bars( [ (1, datetime(2024, 12, 30, 21, tzinfo=UTC), 8.0), (1, datetime(2024, 12, 31, 21, tzinfo=UTC), 10.0), (2, datetime(2024, 12, 31, 21, tzinfo=UTC), 20.0), ] ), curated / "bars_1d" / "year=2024" / "part.parquet", ) _write_parquet( _bars( [ (1, datetime(2025, 1, 2, 21, tzinfo=UTC), 50.0), (2, datetime(2025, 1, 2, 21, tzinfo=UTC), 30.0), # Post-Vault bar (cutoff 2025-07-01): must never reach any partition. (1, datetime(2025, 7, 2, 21, tzinfo=UTC), 1000.0), ] ), curated / "bars_1d" / "year=2025" / "part.parquet", ) def _partition(curated: Path, name: str, year: int) -> Path: return curated / "features" / name / "v1" / f"year={year}" / "part.parquet" def _sql_feature(name: str, sql: str) -> FeatureDefinition: return FeatureDefinition( name=name, version=1, family="technical", kind="duckdb_sql", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", sql=sql, ) def test_sql_batch_earlier_year_partition_cannot_see_later_year_bars(tmp_path: Path) -> None: # Arrange: an unordered whole-history window (MAX over the listing) would leak the # 2025 close of 50.0 into 2024 rows if the 2024 scan were only fenced by the Vault cutoff. curated = tmp_path / "curated" _seed_two_year_bars(curated) defn = _sql_feature( "max_close_all", "SELECT listing_id, ts, ts AS known_at, " "MAX(close) OVER (PARTITION BY listing_id) AS value " "FROM {{input:bars_1d}}", ) # Act manifest = run_feature_batch( defn, curated_root=curated, from_year=2024, to_year=2025, vault_cutoff_date=VAULT_CUTOFF_DATE, budget=_budget(tmp_path), ) # Assert assert [w.year for w in manifest.writes] == [2024, 2025] out_2024 = pl.read_parquet(_partition(curated, "max_close_all", 2024), hive_partitioning=False) out_2025 = pl.read_parquet(_partition(curated, "max_close_all", 2025), hive_partitioning=False) assert out_2024.select("listing_id", "value").rows() == [(1, 10.0), (1, 10.0), (2, 20.0)] # 2025 sees 2024 history plus Jan 2 bars, never the post-Vault 1000.0 close. assert out_2025.select("listing_id", "value").rows() == [(1, 50.0), (2, 30.0)] def test_feature_batch_replay_is_deterministic_and_idempotent_on_same_definition( tmp_path: Path, ) -> None: # Arrange: two independent curated roots with identical retained inputs. root_a = tmp_path / "a" / "curated" root_b = tmp_path / "b" / "curated" _seed_two_year_bars(root_a) _seed_two_year_bars(root_b) # Act: run A twice (same definition re-publish) and B once. kwargs = dict(from_year=2024, to_year=2025, vault_cutoff_date=VAULT_CUTOFF_DATE) manifest_a1 = run_feature_batch(RET_1D_V1, curated_root=root_a, budget=_budget(tmp_path / "a"), **kwargs) sidecar_a = (root_a / "features" / "ret_1d" / "v1" / "_definition.json").read_bytes() manifest_a2 = run_feature_batch(RET_1D_V1, curated_root=root_a, budget=_budget(tmp_path / "a"), **kwargs) manifest_b = run_feature_batch(RET_1D_V1, curated_root=root_b, budget=_budget(tmp_path / "b"), **kwargs) # Assert: same hash, unchanged sidecar, identical ordered rows across replays/roots. assert manifest_a1.definition_hash == manifest_a2.definition_hash == manifest_b.definition_hash assert (root_a / "features" / "ret_1d" / "v1" / "_definition.json").read_bytes() == sidecar_a assert json.loads(sidecar_a)["definition_hash"] == manifest_a1.definition_hash for year in (2024, 2025): a = pl.read_parquet(_partition(root_a, "ret_1d", year), hive_partitioning=False) b = pl.read_parquet(_partition(root_b, "ret_1d", year), hive_partitioning=False) assert a.equals(b) # Hand-computed ret_1d: 2024 L1 10/8-1 = 0.25; 2025 L1 50/10-1 = 4.0, L2 30/20-1 = 0.5. out_2024 = pl.read_parquet(_partition(root_a, "ret_1d", 2024), hive_partitioning=False) out_2025 = pl.read_parquet(_partition(root_a, "ret_1d", 2025), hive_partitioning=False) assert out_2024.select("listing_id", "value").rows() == [(1, pytest.approx(0.25))] assert out_2025.select("listing_id", "value").rows() == [ (1, pytest.approx(4.0)), (2, pytest.approx(0.5)), ] def test_unreadable_definition_sidecar_fails_closed_before_any_write(tmp_path: Path) -> None: # Arrange curated = tmp_path / "curated" _seed_two_year_bars(curated) version_dir = curated / "features" / "ret_1d" / "v1" version_dir.mkdir(parents=True) (version_dir / "_definition.json").write_text("{not json", encoding="utf-8") # Act with pytest.raises(FeatureLibraryError) as err: run_feature_batch( RET_1D_V1, curated_root=curated, from_year=2024, to_year=2025, vault_cutoff_date=VAULT_CUTOFF_DATE, budget=_budget(tmp_path), ) # Assert assert err.value.code == "FEATURE_VERSION_IMMUTABLE" assert sorted(p.name for p in version_dir.rglob("*")) == ["_definition.json"] def test_claim_collision_between_check_and_link_aborts_before_publishing( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: # Arrange: deterministically inject a competing writer's claim in the window between the # missing-sidecar check and the create-if-absent link. curated = tmp_path / "curated" _seed_two_year_bars(curated) real_link = os.link link_calls: list[str] = [] def _competing_link(src: str, dst: str) -> None: link_calls.append(dst) with open(dst, "w", encoding="utf-8") as fh: json.dump({"definition_hash": "0" * 64, "ref": "ret_1d@v1"}, fh) real_link(src, dst) # raises FileExistsError, exactly as a lost race would monkeypatch.setattr(features_mod.os, "link", _competing_link) # Act with pytest.raises(FeatureLibraryError) as err: run_feature_batch( RET_1D_V1, curated_root=curated, from_year=2024, to_year=2025, vault_cutoff_date=VAULT_CUTOFF_DATE, budget=_budget(tmp_path), ) # Assert: the loser verified the winning hash and published nothing. assert len(link_calls) == 1 assert err.value.code == "FEATURE_VERSION_IMMUTABLE" version_dir = curated / "features" / "ret_1d" / "v1" assert list(version_dir.rglob("*.parquet")) == [] assert list(version_dir.rglob("*.tmp")) == [] assert json.loads((version_dir / "_definition.json").read_text())["definition_hash"] == "0" * 64 def test_polars_output_rows_at_or_after_vault_cutoff_are_dropped_at_microsecond_boundary( tmp_path: Path, ) -> None: # Arrange: callable fabricates rows straddling the cutoff by one microsecond. curated = tmp_path / "curated" _seed_two_year_bars(curated) just_before = datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=UTC) at_cutoff = datetime(2025, 7, 1, 0, 0, 0, tzinfo=UTC) def _fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: inputs["bars_1d"].collect() return pl.DataFrame( { "listing_id": [1, 2], "ts": [just_before, at_cutoff], "known_at": [just_before, at_cutoff], "value": [1.5, 2.5], }, schema_overrides={ "listing_id": pl.Int32, "ts": pl.Datetime("us", "UTC"), "known_at": pl.Datetime("us", "UTC"), }, ) defn = FeatureDefinition( name="cutoff_probe", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", polars_fn=_fn, expression="cutoff_probe", ) # Act run_feature_batch( defn, curated_root=curated, from_year=2025, to_year=2025, vault_cutoff_date=VAULT_CUTOFF_DATE, budget=_budget(tmp_path), ) # Assert out = pl.read_parquet(_partition(curated, "cutoff_probe", 2025), hive_partitioning=False) assert out.select("listing_id", "ts", "value").rows() == [(1, just_before, 1.5)] def test_polars_non_finite_value_fails_without_publishing_partition_or_claim( tmp_path: Path, ) -> None: # Arrange curated = tmp_path / "curated" _seed_two_year_bars(curated) def _fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.LazyFrame: return inputs["bars_1d"].select( pl.col("listing_id"), pl.col("ts"), pl.col("ts").alias("known_at"), (pl.col("close") / 0.0).alias("value"), ) defn = FeatureDefinition( name="inf_probe", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", polars_fn=_fn, expression="close / 0", ) # Act with pytest.raises(FeatureLibraryError) as err: run_feature_batch( defn, curated_root=curated, from_year=2024, to_year=2024, vault_cutoff_date=VAULT_CUTOFF_DATE, budget=_budget(tmp_path), ) # Assert assert err.value.code == "BATCH_WRITE_FAILED" assert err.value.failed_year == 2024 assert err.value.completed_years == () version_dir = curated / "features" / "inf_probe" / "v1" assert not (version_dir / "_definition.json").exists() assert list(version_dir.rglob("*.parquet")) == [] assert list(version_dir.rglob("*.tmp")) == [] def _seed_cross_section_fixture(curated: Path) -> None: session_close = datetime(2025, 6, 30, 21, tzinfo=UTC) _write_parquet( _bars([(1, session_close, 10.0), (2, session_close, 20.0), (3, session_close, 30.0)]), curated / "bars_1d" / "year=2025" / "part.parquet", ) feature = pl.DataFrame( { "listing_id": [1, 2], "ts": [session_close, session_close], # L1 becomes known exactly at the Vault cutoff (must be fenced out); # L2 one microsecond earlier (must be returned). "known_at": [ datetime(2025, 7, 1, 0, 0, 0, tzinfo=UTC), datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=UTC), ], "value": [9.0, 7.0], }, schema_overrides={ "listing_id": pl.Int32, "ts": pl.Datetime("us", "UTC"), "known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet(feature, _partition(curated, "probe", 2025)) def test_cross_section_clamps_late_as_of_to_vault_cutoff_microsecond(tmp_path: Path) -> None: # Arrange curated = tmp_path / "curated" _seed_cross_section_fixture(curated) with MarketDataStore(curated, vault_cutoff_ts=VAULT_CUTOFF_MS, budget=_budget(tmp_path)) as store: # Act cs = store.cross_section( features=["probe@v1", "probe@v1"], date="2025-06-30", universe="US_EQ", as_of="2025-08-01T00:00:00Z", ) # Assert: duplicate refs collapse; L1 (known_at == cutoff) null; L3 has no row -> null. assert cs.columns == ["listing_id", "probe@v1"] assert cs.rows() == [(1, None), (2, 7.0), (3, None)] assert cs.schema["listing_id"] == pl.Int32 assert cs.schema["probe@v1"] == pl.Float64 def test_cross_section_rejects_vault_dates_and_non_canonical_refs(tmp_path: Path) -> None: # Arrange curated = tmp_path / "curated" _seed_cross_section_fixture(curated) with MarketDataStore(curated, vault_cutoff_ts=VAULT_CUTOFF_MS, budget=_budget(tmp_path)) as store: # Act / Assert: a date on the cutoff is in the holdout. with pytest.raises(VaultHoldoutFenceError): store.cross_section(features=["probe@v1"], date="2025-07-01", universe="US_EQ") for bad_ref in ("probe", "probe@v01", "probe@v0", "Probe@v1", "probe@v1/../x"): with pytest.raises(MarketDataStoreValidationError): store.cross_section(features=[bad_ref], date="2025-06-30", universe="US_EQ") for bad_date in ("2025-6-30", "2025-06-30T00:00:00Z", "2025-02-30"): with pytest.raises(MarketDataStoreValidationError): store.cross_section(features=["probe@v1"], date=bad_date, universe="US_EQ") with pytest.raises(MarketDataStoreValidationError): store.cross_section(features=["probe@v1"], date="2025-06-30", universe="EU_EQ") # type: ignore[arg-type] def test_cross_section_universe_excludes_listing_whose_bar_is_not_yet_known(tmp_path: Path) -> None: # Arrange: L3's only bar is published after as_of, so it is not in the as-of universe. curated = tmp_path / "curated" curated.mkdir() close = datetime(2025, 6, 30, 21, tzinfo=UTC) bars = _bars([(1, close, 10.0), (3, close, 30.0)]).with_columns( pl.when(pl.col("listing_id") == 3) .then(pl.lit(datetime(2025, 6, 30, 22, 30, tzinfo=UTC))) .otherwise(pl.col("known_at")) .cast(pl.Datetime("us", "UTC")) .alias("known_at") ) _write_parquet(bars, curated / "bars_1d" / "year=2025" / "part.parquet") _write_parquet( pl.DataFrame( {"listing_id": [1], "ts": [close], "known_at": [close], "value": [0.5]}, schema_overrides={ "listing_id": pl.Int32, "ts": pl.Datetime("us", "UTC"), "known_at": pl.Datetime("us", "UTC"), }, ), _partition(curated, "probe", 2025), ) with MarketDataStore(curated, vault_cutoff_ts=VAULT_CUTOFF_MS, budget=_budget(tmp_path)) as store: # Act cs = store.cross_section( features=["probe@v1"], date="2025-06-30", universe="US_EQ", as_of="2025-06-30T22:00:00Z" ) # Assert assert cs.rows() == [(1, 0.5)]