"""Offline M2 parity tests for Python `stockbot` SDK (MarketDataStore, QuestDB 1m, Feature Library). All tests run over temporary DuckDB/Parquet fixtures or injected recording executors with zero QA database, live QuestDB, or paper/live execution access. """ from __future__ import annotations import json import math import shutil import subprocess import threading from concurrent.futures import ThreadPoolExecutor from datetime import date, datetime, timezone from pathlib import Path from typing import Any, Mapping, Sequence import duckdb import polars as pl import pytest import stockbot from stockbot import ( RET_1D_V1, DuckDbConnectionBudget, FeatureDefinition, FeatureLibraryError, MarketDataStore, MarketDataStoreValidationError, PsycopgQuestDbExecutor, VaultHoldoutFenceError, apply_vault_fence, create_feature_registry, feature_definition_hash, feature_ref, parse_feature_ref, plan_feature_batch, register_signal, run_feature_batch, validate_feature_definition, ) from stockbot.vault import ( epoch_micros_to_datetime, parse_timestamp_micros, validate_curated_root, ) REPO_ROOT = Path(__file__).resolve().parents[2] def _make_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_via_duckdb(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() class _RecordingQuestDbExecutor: def __init__(self, rows: list[dict[str, Any]]) -> None: self.rows = rows self.calls: list[tuple[str, tuple[Any, ...]]] = [] self.closed = False def query(self, sql: str, params: Sequence[Any]) -> Sequence[Mapping[str, Any]]: self.calls.append((sql, tuple(params))) return list(self.rows) def close(self) -> None: self.closed = True # --------------------------------------------------------------------------- # 1. Vault microsecond bounds & curated_root hygiene # --------------------------------------------------------------------------- def test_vault_microsecond_bounds_and_curated_root_hygiene() -> None: start_us = parse_timestamp_micros("2025-01-15", "start", "from") end_us = parse_timestamp_micros("2025-01-15", "end", "to") assert epoch_micros_to_datetime(start_us) == datetime(2025, 1, 15, 0, 0, 0, 0, tzinfo=timezone.utc) assert epoch_micros_to_datetime(end_us) == datetime(2025, 1, 15, 23, 59, 59, 999_999, tzinfo=timezone.utc) exact_us = parse_timestamp_micros("2025-01-15T12:34:56.789123Z", "end", "as_of") assert epoch_micros_to_datetime(exact_us) == datetime( 2025, 1, 15, 12, 34, 56, 789_123, tzinfo=timezone.utc ) with pytest.raises(MarketDataStoreValidationError): parse_timestamp_micros("2025-02-29", "start", "from") with pytest.raises(MarketDataStoreValidationError): parse_timestamp_micros("2025-01-15T12:00:00", "start", "from") # Sub-second cutoff alignment: vault_cutoff_ts ending in .500Z must clamp to cutoff*1000 - 1 us sub_sec_cutoff_ms = parse_timestamp_micros("2025-07-01T00:00:00.500Z", "start", "cutoff") // 1000 fenced = apply_vault_fence("2025-06-01", "2025-08-01", sub_sec_cutoff_ms) assert fenced.clamped_to is True assert fenced.to_micros == sub_sec_cutoff_ms * 1000 - 1 assert fenced.as_of_micros == sub_sec_cutoff_ms * 1000 - 1 # curated_root hygiene assert validate_curated_root("/tmp/curated///") == "/tmp/curated" for bad in ("relative/path", "/tmp/bad'quote", "/tmp/bad;semi", "/tmp/bad*glob", "/tmp/bad\nctrl"): with pytest.raises(MarketDataStoreValidationError): validate_curated_root(bad) # --------------------------------------------------------------------------- # 2. fundamentals_as_of 2D PIT & Vault invariants # --------------------------------------------------------------------------- def test_fundamentals_as_of_restated_q1_non_overwrite_lag_mask_and_vault(tmp_path: Path) -> None: curated = tmp_path / "curated" vault_cutoff_dt = datetime(2025, 7, 1, 0, 0, 0, 0, tzinfo=timezone.utc) vault_cutoff_ms = int(vault_cutoff_dt.timestamp() * 1000) # Multi-year Hive partitions (year=2023, 2024, 2025) df_2023 = pl.DataFrame( { "listing_id": [101], "effective_known_at": [datetime(2023, 11, 10, 12, 0, 0, tzinfo=timezone.utc)], "known_at_source": ["edgar_filing"], "has_estimated_lag": [False], "period_end": [date(2023, 9, 30)], "fiscal_period": ["Q3"], "currency": ["USD"], "period_known_at": [datetime(2023, 11, 10, 12, 0, 0, tzinfo=timezone.utc)], "revenue": [90.0], "net_income": [9.0], "operating_cash_flow": [12.0], "total_assets": [500.0], "total_equity": [250.0], "shares_outstanding": [100.0], "ttm_period_end": [date(2023, 9, 30)], "ttm_currency": ["USD"], "ttm_revenue": [360.0], "ttm_net_income": [36.0], "ttm_operating_cash_flow": [48.0], "ttm_has_estimated_lag": [False], }, schema_overrides={ "listing_id": pl.Int32, "effective_known_at": pl.Datetime("us", "UTC"), "period_known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet_via_duckdb(df_2023, curated / "fundamentals_pit" / "year=2023" / "part.parquet") # Listing 101: Q2 filed 2024-08-05, then Q1 restated on 2024-09-15 (known_at > Q2) # updates ttm_revenue from 400 -> 415 without overwriting Q2 period_end/fiscal_period/revenue. # Listing 102: Q1 clean (has_estimated_lag=False), then Q2 estimated (has_estimated_lag=True); # with allow_estimated_lag=False, 102 must be omitted (no fallback to Q1). # Listing 103: Q2 clean (has_estimated_lag=False) but ttm_has_estimated_lag=True; # with allow_estimated_lag=False, 103 is kept, standalone revenue kept, ttm_* masked to None. df_2024 = pl.DataFrame( { "listing_id": [101, 101, 102, 102, 103], "effective_known_at": [ datetime(2024, 8, 5, 16, 0, 0, tzinfo=timezone.utc), datetime(2024, 9, 15, 16, 0, 0, tzinfo=timezone.utc), datetime(2024, 5, 10, 16, 0, 0, tzinfo=timezone.utc), datetime(2024, 8, 15, 16, 0, 0, tzinfo=timezone.utc), datetime(2024, 8, 20, 16, 0, 0, tzinfo=timezone.utc), ], "known_at_source": [ "edgar_filing", "edgar_filing", "edgar_filing", "statutory_lag_estimate", "edgar_filing", ], "has_estimated_lag": [False, False, False, True, False], "period_end": [ date(2024, 6, 30), date(2024, 6, 30), date(2024, 3, 31), date(2024, 6, 30), date(2024, 6, 30), ], "fiscal_period": ["Q2", "Q2", "Q1", "Q2", "Q2"], "currency": ["USD", "USD", "USD", "USD", "USD"], "period_known_at": [ datetime(2024, 8, 5, 16, 0, 0, tzinfo=timezone.utc), datetime(2024, 8, 5, 16, 0, 0, tzinfo=timezone.utc), datetime(2024, 5, 10, 16, 0, 0, tzinfo=timezone.utc), datetime(2024, 8, 15, 16, 0, 0, tzinfo=timezone.utc), datetime(2024, 8, 20, 16, 0, 0, tzinfo=timezone.utc), ], "revenue": [120.0, 120.0, 50.0, 55.0, 80.0], "net_income": [15.0, 15.0, 5.0, 6.0, 8.0], "operating_cash_flow": [20.0, 20.0, 7.0, 8.0, 10.0], "total_assets": [600.0, 600.0, 200.0, 210.0, 300.0], "total_equity": [300.0, 300.0, 100.0, 105.0, 150.0], "shares_outstanding": [100.0, 100.0, 50.0, 50.0, 75.0], "ttm_period_end": [ date(2024, 6, 30), date(2024, 6, 30), date(2024, 3, 31), date(2024, 6, 30), date(2024, 6, 30), ], "ttm_currency": ["USD", "USD", "USD", "USD", "USD"], "ttm_revenue": [400.0, 415.0, 200.0, 210.0, 320.0], "ttm_net_income": [40.0, 44.0, 20.0, 22.0, 32.0], "ttm_operating_cash_flow": [50.0, 52.0, 25.0, 26.0, 40.0], "ttm_has_estimated_lag": [False, False, False, True, True], }, schema_overrides={ "listing_id": pl.Int32, "effective_known_at": pl.Datetime("us", "UTC"), "period_known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet_via_duckdb(df_2024, curated / "fundamentals_pit" / "year=2024" / "part.parquet") # Listing 104: snapshot at vault_cutoff_ts - 1 us (INCLUDED) vs exact vault_cutoff_ts (EXCLUDED) df_2025 = pl.DataFrame( { "listing_id": [104, 104], "effective_known_at": [ datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=timezone.utc), datetime(2025, 7, 1, 0, 0, 0, 0, tzinfo=timezone.utc), ], "known_at_source": ["edgar_filing", "edgar_filing"], "has_estimated_lag": [False, False], "period_end": [date(2025, 3, 31), date(2025, 6, 30)], "fiscal_period": ["Q1", "Q2"], "currency": ["USD", "USD"], "period_known_at": [ datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=timezone.utc), datetime(2025, 7, 1, 0, 0, 0, 0, tzinfo=timezone.utc), ], "revenue": [200.0, 999.0], "net_income": [20.0, 99.0], "operating_cash_flow": [25.0, 110.0], "total_assets": [700.0, 800.0], "total_equity": [350.0, 400.0], "shares_outstanding": [100.0, 100.0], "ttm_period_end": [date(2025, 3, 31), date(2025, 6, 30)], "ttm_currency": ["USD", "USD"], "ttm_revenue": [800.0, 1999.0], "ttm_net_income": [80.0, 199.0], "ttm_operating_cash_flow": [100.0, 250.0], "ttm_has_estimated_lag": [False, False], }, schema_overrides={ "listing_id": pl.Int32, "effective_known_at": pl.Datetime("us", "UTC"), "period_known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet_via_duckdb(df_2025, curated / "fundamentals_pit" / "year=2025" / "part.parquet") with MarketDataStore(curated, vault_cutoff_ts=vault_cutoff_ms, budget=_make_budget(tmp_path)) as store: # 1. Restated Q1 (known_at > Q2) updates TTM without overwriting Q2 res = store.fundamentals_as_of( listing_ids=[101], fields=["revenue", "ttm_revenue"], as_of="2024-10-01", allow_estimated_lag=True, ) assert res.height == 1 row = res.to_dicts()[0] assert row["listing_id"] == 101 assert row["period_end"] == date(2024, 6, 30) assert row["fiscal_period"] == "Q2" assert row["period_known_at"] == datetime(2024, 8, 5, 16, 0, 0, tzinfo=timezone.utc) assert row["effective_known_at"] == datetime(2024, 9, 15, 16, 0, 0, tzinfo=timezone.utc) assert row["revenue"] == pytest.approx(120.0) assert row["ttm_revenue"] == pytest.approx(415.0) # 2. allow_estimated_lag=False omits 102 (no fallback to Q1) and masks 103's ttm_* to None strict = store.fundamentals_as_of( listing_ids=[103, 102, 101], fields=["revenue", "ttm_revenue"], as_of="2024-10-01", allow_estimated_lag=False, ) assert strict["listing_id"].to_list() == [101, 103] rows_by_id = {r["listing_id"]: r for r in strict.to_dicts()} assert rows_by_id[103]["revenue"] == pytest.approx(80.0) assert rows_by_id[103]["ttm_revenue"] is None assert rows_by_id[103]["ttm_period_end"] is None assert rows_by_id[103]["ttm_currency"] is None assert rows_by_id[103]["ttm_has_estimated_lag"] is True # 3. Vault cutoff microsecond fence: as_of after cutoff clamps to cutoff - 1 us vault_res = store.fundamentals_as_of( listing_ids=[104], fields=["revenue", "ttm_revenue"], as_of="2025-09-01", allow_estimated_lag=True, ) assert vault_res.height == 1 vrow = vault_res.to_dicts()[0] assert vrow["fiscal_period"] == "Q1" assert vrow["revenue"] == pytest.approx(200.0) assert vrow["effective_known_at"] == datetime( 2025, 6, 30, 23, 59, 59, 999_999, tzinfo=timezone.utc ) # --------------------------------------------------------------------------- # 3. macro_as_of lagged regime & Vault fence # --------------------------------------------------------------------------- def test_macro_as_of_lag_filtering_sort_and_vault(tmp_path: Path) -> None: curated = tmp_path / "curated" vault_cutoff_ms = int(datetime(2025, 7, 1, 0, 0, 0, tzinfo=timezone.utc).timestamp() * 1000) macro_df = pl.DataFrame( { "country_iso": ["US", "CA", "US", "US"], "indicator": ["CPI", "RATE", "CPI", "CPI"], "period_date": [ date(2025, 4, 30), date(2025, 4, 15), date(2025, 3, 31), date(2025, 6, 30), ], "known_at": [ datetime(2025, 6, 4, 0, 0, 0, tzinfo=timezone.utc), # +35d lag datetime(2025, 4, 16, 0, 0, 0, tzinfo=timezone.utc), # +1d lag datetime(2025, 5, 5, 0, 0, 0, tzinfo=timezone.utc), # +35d lag datetime(2025, 8, 4, 0, 0, 0, tzinfo=timezone.utc), # post-cutoff ], "known_at_source": ["statutory_lag"] * 4, "value": [3.2, 4.75, 3.1, 9.9], }, schema_overrides={"known_at": pl.Datetime("us", "UTC")}, ) _write_parquet_via_duckdb(macro_df, curated / "macro" / "part.parquet") with MarketDataStore(curated, vault_cutoff_ts=vault_cutoff_ms, budget=_make_budget(tmp_path)) as store: # Filter known_at <= as_of (excludes 2025-04-30 CPI whose known_at is 2025-06-04) res = store.macro_as_of( countries=["US", "CA"], indicators=["CPI", "RATE"], from_date="2025-01-01", to_date="2025-06-30", as_of="2025-05-20", ) assert res.columns == [ "country_iso", "indicator", "period_date", "known_at", "known_at_source", "value", ] assert res["country_iso"].to_list() == ["CA", "US"] assert res["indicator"].to_list() == ["RATE", "CPI"] assert res["period_date"].to_list() == [date(2025, 4, 15), date(2025, 3, 31)] # Straddling to_date clamps strictly < vault_cutoff_ts (excludes 2025-08-04 known_at row) clamped = store.macro_as_of( countries=["US"], indicators=["CPI"], from_date="2025-01-01", to_date="2025-12-31", ) assert clamped["period_date"].to_list() == [date(2025, 3, 31), date(2025, 4, 30)] # Post-cutoff from_date raises VaultHoldoutFenceError with pytest.raises(VaultHoldoutFenceError): store.macro_as_of( countries=["US"], indicators=["CPI"], from_date="2025-07-01", to_date="2025-08-01", ) # --------------------------------------------------------------------------- # 4. QuestDB 1m bars & fx PGWire safety and fx_1m bar-close boundary # --------------------------------------------------------------------------- def test_questdb_bars_1m_and_fx_1m_bar_close_and_dsn_redaction( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: curated = tmp_path / "curated" curated.mkdir(parents=True, exist_ok=True) cutoff_dt = datetime(2025, 7, 1, 0, 0, 0, tzinfo=timezone.utc) cutoff_us = parse_timestamp_micros("2025-07-01T00:00:00.000000Z", "start", "cutoff") cutoff_ms = cutoff_us // 1000 # 4a. Without QuestDB executor/DSN, 1m bars and 1m fx fail closed with MarketDataStore(curated, vault_cutoff_ts=cutoff_ms, budget=_make_budget(tmp_path)) as plain: with pytest.raises(MarketDataStoreValidationError): plain.bars(listing_ids=[10], timeframe="1m", from_date="2025-06-30", to_date="2025-06-30") with pytest.raises(MarketDataStoreValidationError): plain.fx(pair="USD.CAD", timeframe="1m", from_date="2025-06-30", to_date="2025-06-30") # 4b. Recording executor for bars('1m') bar_ts_us = parse_timestamp_micros("2025-06-30T15:30:00.000000Z", "start", "ts") bar_exec = _RecordingQuestDbExecutor( rows=[ { "listing_id": "10", "ts_us": bar_ts_us, "open": 10.0, "high": 10.5, "low": 9.9, "close": 10.2, "volume": 1500.0, "vwap": 10.15, "known_at_us": bar_ts_us + 60_000_000, } ] ) with MarketDataStore( curated, vault_cutoff_ts=cutoff_ms, budget=_make_budget(tmp_path), questdb_executor=bar_exec, ) as store: # Reject split/total and currencies on 1m with pytest.raises(NotImplementedError): store.bars( listing_ids=[10], timeframe="1m", from_date="2025-06-30", to_date="2025-06-30", adjustment="split", ) with pytest.raises(MarketDataStoreValidationError): store.bars( listing_ids=[10], currencies=["USD"], timeframe="1m", from_date="2025-06-30", to_date="2025-06-30", ) df = store.bars( listing_ids=[20, 10, 10], timeframe="1m", from_date="2025-06-30", to_date="2025-07-05", adjustment="raw", ) assert len(bar_exec.calls) == 1 sql, params = bar_exec.calls[0] assert "listing_id IN (%s, %s)" in sql assert "10" not in sql and "20" not in sql assert params[2:4] == ("10", "20") assert df.height == 1 assert df["listing_id"].to_list() == [10] assert df["close"].to_list() == [10.2] assert bar_exec.closed is True # 4c. Defense-in-depth rejection when executor returns an out-of-fence microsecond bar leaky_bar_exec = _RecordingQuestDbExecutor( rows=[ { "listing_id": "10", "ts_us": cutoff_us, # exact cutoff -> must be rejected! "open": 10.0, "high": 10.5, "low": 9.9, "close": 10.2, "volume": 100.0, "vwap": None, "known_at_us": cutoff_us, } ] ) with MarketDataStore( curated, vault_cutoff_ts=cutoff_ms, budget=_make_budget(tmp_path), questdb_executor=leaky_bar_exec, ) as store: with pytest.raises(MarketDataStoreValidationError): store.bars(listing_ids=[10], timeframe="1m", from_date="2025-06-30", to_date="2025-06-30") # 4d. fx('1m') bar-close availability rule (bar_close = ts + 60s strictly < vault_cutoff_ts and <= as_of) valid_fx_ts_us = cutoff_us - 120_000_000 # closes at cutoff - 60s (INCLUDED) fx_exec = _RecordingQuestDbExecutor( rows=[ { "pair": "USDCAD", "ts_us": valid_fx_ts_us, "open": 1.3600, "high": 1.3610, "low": 1.3595, "close": 1.3605, "source": "eod", } ] ) with MarketDataStore( curated, vault_cutoff_ts=cutoff_ms, budget=_make_budget(tmp_path), questdb_executor=fx_exec, ) as store: fx_df = store.fx( pair="USD.CAD", timeframe="1m", from_date="2025-06-30T23:55:00Z", to_date="2025-07-01T00:05:00Z", ) assert fx_df.height == 1 assert fx_df["known_at"].to_list() == [epoch_micros_to_datetime(valid_fx_ts_us + 60_000_000)] sql, params = fx_exec.calls[0] assert "WHERE pair = %s AND ts >= %s AND ts <= %s" in sql # Upper SQL ts bound must be cutoff - 60_000_001 us so ts=cutoff-60s and ts=cutoff-30s are excluded assert params[2] == "2025-06-30T23:58:59.999999Z" # Defense-in-depth rejects bars ending at cutoff (cutoff - 60s), spanning cutoff (cutoff - 30s), or closing after as_of for bad_ts_us, query_as_of in [ (cutoff_us - 60_000_000, None), # ends at exact vault_cutoff_ts (cutoff_us - 30_000_000, None), # spans vault_cutoff_ts ( parse_timestamp_micros("2025-06-30T23:57:30Z", "start", "ts"), "2025-06-30T23:58:00Z", # closes at 23:58:30Z > as_of 23:58:00Z ), ]: bad_fx_exec = _RecordingQuestDbExecutor( rows=[ { "pair": "USDCAD", "ts_us": bad_ts_us, "open": 1.36, "high": 1.36, "low": 1.36, "close": 1.36, "source": "eod", } ] ) with MarketDataStore( curated, vault_cutoff_ts=cutoff_ms, budget=_make_budget(tmp_path), questdb_executor=bad_fx_exec, ) as store: with pytest.raises(MarketDataStoreValidationError): store.fx( pair="USD.CAD", timeframe="1m", from_date="2025-06-30T23:55:00Z", to_date="2025-06-30T23:59:59Z", as_of=query_as_of, ) # 4e. PsycopgQuestDbExecutor DSN credential redaction on error secret_dsn = "postgresql://qdb_user:SuperSecretPass99@127.0.0.1:8812/qdb" def _boom(*_args: Any, **_kwargs: Any) -> Any: raise RuntimeError(f"connection to {secret_dsn} failed with password=SuperSecretPass99") monkeypatch.setattr("stockbot.data.psycopg.connect", _boom) pg_exec = PsycopgQuestDbExecutor(secret_dsn) with pytest.raises(RuntimeError) as exc_info: pg_exec.query("SELECT 1", ()) msg = str(exc_info.value) assert "SuperSecretPass99" not in msg assert "qdb_user" not in msg # --------------------------------------------------------------------------- # 5. register_signal immutability, SQL sandboxing, hash parity & batch runs # --------------------------------------------------------------------------- def test_register_signal_immutability_and_sql_sandboxing() -> None: registry = create_feature_registry() reg1 = register_signal(RET_1D_V1, registry=registry) reg2 = register_signal(RET_1D_V1, registry=registry) assert reg1.ref == "ret_1d@v1" assert reg1.definition_hash == reg2.definition_hash assert parse_feature_ref(reg1.ref).name == "ret_1d" assert parse_feature_ref(reg1.ref).version == 1 # Semantic drift on same version raises FEATURE_VERSION_IMMUTABLE drifted = FeatureDefinition( name="ret_1d", version=1, family="technical", kind="duckdb_sql", inputs=("bars_1d",), warmup_bars=2, known_at_rule="bar_close", sql=RET_1D_V1.sql, ) with pytest.raises(FeatureLibraryError) as exc_info: register_signal(drifted, registry=registry) assert exc_info.value.code == "FEATURE_VERSION_IMMUTABLE" # Reject prohibited SQL constructs bad_sqls = [ ("SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} -- comment", "INVALID_SQL_STATEMENT"), ("SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} /* block */", "INVALID_SQL_STATEMENT"), ("SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}; DROP TABLE x", "INVALID_SQL_STATEMENT"), ("SELECT listing_id, ts, ts AS known_at, ? AS value FROM {{input:bars_1d}}", "INVALID_SQL_STATEMENT"), ("WITH RECURSIVE r AS (SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}) SELECT listing_id, ts, known_at, value FROM r", "INVALID_SQL_STATEMENT"), ("SELECT listing_id, ts, ts AS known_at, close AS value FROM read_parquet('/tmp/x.parquet')", "EXTERNAL_DATA_ACCESS"), ("SELECT listing_id, ts, ts AS known_at, close AS value FROM bars_1d", "EXTERNAL_DATA_ACCESS"), ("SELECT * FROM {{input:bars_1d}}", "INVALID_SQL_PROJECTION"), ("SELECT listing_id, ts, ts AS known_at, close AS wrong_col FROM {{input:bars_1d}}", "INVALID_SQL_PROJECTION"), ("SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:shorts}}", "UNDECLARED_INPUT"), ] for bad_sql, expected_code in bad_sqls: bad_def = FeatureDefinition( name="bad_feat", version=1, family="technical", kind="duckdb_sql", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", sql=bad_sql, ) with pytest.raises(FeatureLibraryError) as err: validate_feature_definition(bad_def) assert err.value.code == expected_code, f"SQL={bad_sql!r} expected {expected_code}, got {err.value.code}" def test_ret_1d_v1_hash_parity_with_typescript() -> None: bun_bin = shutil.which("bun") assert bun_bin is not None, "bun is required for cross-language featureDefinitionHash parity check" proc = subprocess.run( [ bun_bin, "-e", "import { RET_1D_V1, featureDefinitionHash } from './libs/research/src/feature-library.ts'; " "console.log(featureDefinitionHash(RET_1D_V1));", ], cwd=str(REPO_ROOT), capture_output=True, text=True, check=True, ) ts_hash = proc.stdout.strip() py_hash = feature_definition_hash(RET_1D_V1) assert len(py_hash) == 64 assert py_hash == ts_hash def _build_bars_and_events_fixtures(curated: Path) -> None: # Year 2024: Dec 30 & Dec 31 21:00Z (warmup across year boundary!) bars_2024 = pl.DataFrame( { "listing_id": [1, 1, 2, 2], "session_date": [ date(2024, 12, 30), date(2024, 12, 31), date(2024, 12, 30), date(2024, 12, 31), ], "ts": [ datetime(2024, 12, 30, 21, 0, 0, tzinfo=timezone.utc), datetime(2024, 12, 31, 21, 0, 0, tzinfo=timezone.utc), datetime(2024, 12, 30, 21, 0, 0, tzinfo=timezone.utc), datetime(2024, 12, 31, 21, 0, 0, tzinfo=timezone.utc), ], "open": [10.0, 10.0, 20.0, 20.0], "high": [10.5, 10.5, 20.5, 20.5], "low": [9.5, 9.5, 19.5, 19.5], "close": [10.0, 10.0, 20.0, 25.0], "volume": [1000.0, 1000.0, 2000.0, 2000.0], "vwap": [10.0, 10.0, 20.0, 25.0], "currency": ["USD", "USD", "USD", "USD"], "source": ["eod", "eod", "eod", "eod"], "known_at": [ datetime(2024, 12, 30, 21, 0, 0, tzinfo=timezone.utc), datetime(2024, 12, 31, 21, 0, 0, tzinfo=timezone.utc), datetime(2024, 12, 30, 21, 0, 0, tzinfo=timezone.utc), datetime(2024, 12, 31, 21, 0, 0, tzinfo=timezone.utc), ], }, schema_overrides={ "listing_id": pl.Int32, "ts": pl.Datetime("us", "UTC"), "known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet_via_duckdb(bars_2024, curated / "bars_1d" / "year=2024" / "part.parquet") # Year 2025: # - Listing 1: Jan 2 close=11.0 (ret_1d = +0.10 using Dec 31 warmup!) # - Listing 2: Jan 2 close=20.0 (ret_1d = -0.20 using Dec 31 warmup!) # - Listing 3: Jan 2 first bar ever (no prev_close -> NULL in ret_1d@v1 cross_section!) # - Listing 1: Jul 2 post-cutoff row (vault_cutoff_date = 2025-07-01 -> must be fenced out!) bars_2025 = pl.DataFrame( { "listing_id": [1, 2, 3, 1], "session_date": [ date(2025, 1, 2), date(2025, 1, 2), date(2025, 1, 2), date(2025, 7, 2), ], "ts": [ datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), datetime(2025, 7, 2, 21, 0, 0, tzinfo=timezone.utc), ], "open": [10.5, 24.0, 5.0, 15.0], "high": [11.2, 24.5, 5.2, 15.5], "low": [10.4, 19.8, 4.9, 14.8], "close": [11.0, 20.0, 5.0, 15.0], "volume": [1200.0, 2200.0, 500.0, 900.0], "vwap": [11.0, 20.0, 5.0, 15.0], "currency": ["USD", "USD", "USD", "USD"], "source": ["eod", "eod", "eod", "eod"], "known_at": [ datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), datetime(2025, 7, 2, 21, 0, 0, tzinfo=timezone.utc), ], }, schema_overrides={ "listing_id": pl.Int32, "ts": pl.Datetime("us", "UTC"), "known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet_via_duckdb(bars_2025, curated / "bars_1d" / "year=2025" / "part.parquet") # Co-published events/year=2025/part.parquet (filing) + part-posts.parquet (ceo_post) events_filings = pl.DataFrame( { "listing_id": [1], "ts": [datetime(2025, 1, 2, 14, 0, 0, tzinfo=timezone.utc)], "known_at": [datetime(2025, 1, 2, 14, 0, 5, tzinfo=timezone.utc)], "known_at_source": ["edgar_filing"], "kind": ["filing"], "subtype": ["8-K"], "payload_json": ['{"form":"8-K"}'], }, schema_overrides={ "listing_id": pl.Int32, "ts": pl.Datetime("us", "UTC"), "known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet_via_duckdb(events_filings, curated / "events" / "year=2025" / "part.parquet") events_posts = pl.DataFrame( { "listing_id": [1], "ts": [datetime(2025, 1, 2, 14, 0, 0, tzinfo=timezone.utc)], "known_at": [datetime(2025, 1, 2, 14, 0, 1, tzinfo=timezone.utc)], "known_at_source": ["ceo_post_ts"], "kind": ["ceo_post"], "subtype": ["board_post"], "payload_json": ['{"author":"alice"}'], }, schema_overrides={ "listing_id": pl.Int32, "ts": pl.Datetime("us", "UTC"), "known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet_via_duckdb(events_posts, curated / "events" / "year=2025" / "part-posts.parquet") def test_sql_and_polars_batch_materialization_cross_section_and_events(tmp_path: Path) -> None: curated = tmp_path / "curated" _build_bars_and_events_fixtures(curated) budget = _make_budget(tmp_path) vault_cutoff_date = "2025-07-01" vault_cutoff_ms = parse_timestamp_micros(vault_cutoff_date, "start", "cutoff") // 1000 # 5a. Post-cutoff year range raises VAULT_RANGE_VIOLATION with pytest.raises(FeatureLibraryError) as err: plan_feature_batch( RET_1D_V1, curated_root=curated, from_year=2025, to_year=2026, vault_cutoff_date="2025-01-01", ) assert err.value.code == "VAULT_RANGE_VIOLATION" # 5b. Materialize duckdb_sql feature (RET_1D_V1) across 2024..2025 sql_manifest_1 = run_feature_batch( RET_1D_V1, curated_root=curated, from_year=2024, to_year=2025, vault_cutoff_date=vault_cutoff_date, budget=budget, ) assert sql_manifest_1.ref == "ret_1d@v1" assert [w.year for w in sql_manifest_1.writes] == [2024, 2025] # Verify ZSTD compression, schema, and Vault clamping on 2025 partition out_2025 = curated / "features" / "ret_1d" / "v1" / "year=2025" / "part.parquet" con = duckdb.connect(":memory:") try: con.execute("SET TimeZone = 'UTC';") meta = con.execute(f"SELECT compression FROM parquet_metadata('{out_2025}')").fetchall() assert meta and all(row[0] == "ZSTD" for row in meta) schema_rows = con.execute( # hive_partitioning = false: DuckDB auto-detects `year=2025` in the path and would # append a virtual `year` column; the contract is about the physical file schema. f"SELECT column_name, column_type FROM (DESCRIBE SELECT * FROM read_parquet('{out_2025}', hive_partitioning = false))" ).fetchall() assert schema_rows == [ ("listing_id", "INTEGER"), ("ts", "TIMESTAMP WITH TIME ZONE"), ("known_at", "TIMESTAMP WITH TIME ZONE"), ("value", "DOUBLE"), ] rows_2025 = con.execute(f"SELECT listing_id, value FROM read_parquet('{out_2025}')").fetchall() assert [r[0] for r in rows_2025] == [1, 2] # listing 3 had no prev_close; Jul 2 post-cutoff excluded assert rows_2025[0][1] == pytest.approx(0.10) assert rows_2025[1][1] == pytest.approx(-0.20) finally: con.close() # Deterministic replay check: second run produces identical rows run_feature_batch( RET_1D_V1, curated_root=curated, from_year=2024, to_year=2025, vault_cutoff_date=vault_cutoff_date, budget=budget, ) replayed = pl.read_parquet(out_2025) assert replayed["listing_id"].to_list() == [1, 2] assert replayed["value"].to_list() == pytest.approx([0.10, -0.20]) # 5c. Materialize Polars feature (mom_diff@v1: close - prev_close) via register_signal + run_feature_batch def _mom_diff_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.LazyFrame: bars = inputs["bars_1d"].sort(["listing_id", "ts"]) return ( bars.with_columns( pl.col("close").shift(1).over("listing_id").alias("prev_close") ) .filter(pl.col("prev_close").is_not_null()) .select( pl.col("listing_id"), pl.col("ts"), pl.col("ts").alias("known_at"), (pl.col("close") - pl.col("prev_close")).cast(pl.Float64).alias("value"), ) ) reg_polars = register_signal( name="mom_diff", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=1, known_at_rule="bar_close", polars_fn=_mom_diff_fn, expression="close - lag(close, 1)", registry=create_feature_registry(), ) polars_manifest = run_feature_batch( reg_polars.definition, curated_root=curated, from_year=2025, to_year=2025, vault_cutoff_date=vault_cutoff_date, budget=budget, ) assert polars_manifest.ref == "mom_diff@v1" # Polars input-tracking checks (UNDECLARED_INPUT & UNUSED_INPUT) undeclared_def = FeatureDefinition( name="bad_polars_u", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", polars_fn=lambda inp: inp["shorts"], expression="shorts", ) with pytest.raises(FeatureLibraryError) as err: run_feature_batch( undeclared_def, curated_root=curated, from_year=2025, to_year=2025, vault_cutoff_date=vault_cutoff_date, budget=budget, ) assert err.value.code == "UNDECLARED_INPUT" unused_def = FeatureDefinition( name="bad_polars_unused", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", polars_fn=lambda _inp: pl.DataFrame( {"listing_id": [1], "ts": [datetime(2025, 1, 2, tzinfo=timezone.utc)], "known_at": [datetime(2025, 1, 2, tzinfo=timezone.utc)], "value": [1.0]} ), expression="const(1.0)", ) with pytest.raises(FeatureLibraryError) as err: run_feature_batch( unused_def, curated_root=curated, from_year=2025, to_year=2025, vault_cutoff_date=vault_cutoff_date, budget=budget, ) assert err.value.code == "UNUSED_INPUT" # 5d. Python cross_section + co-published events() verification with MarketDataStore(curated, vault_cutoff_ts=vault_cutoff_ms, budget=budget) as store: cs = store.cross_section( features=["ret_1d@v1", "mom_diff@v1"], date="2025-01-02", universe="US_EQ", as_of="2025-01-02T22:00:00Z", ) assert cs.columns == ["listing_id", "ret_1d@v1", "mom_diff@v1"] assert cs["listing_id"].to_list() == [1, 2, 3] assert cs["ret_1d@v1"].to_list()[0] == pytest.approx(0.10) assert cs["ret_1d@v1"].to_list()[1] == pytest.approx(-0.20) assert cs["ret_1d@v1"].to_list()[2] is None # active universe listing with missing feature -> null assert cs["mom_diff@v1"].to_list()[0] == pytest.approx(1.0) assert cs["mom_diff@v1"].to_list()[1] == pytest.approx(-5.0) assert cs["mom_diff@v1"].to_list()[2] is None # Post-as_of feature row exclusion: as_of before 21:00Z excludes all 21:00Z feature rows cs_early = store.cross_section( features=["ret_1d@v1"], date="2025-01-02", universe="US_EQ", as_of="2025-01-02T20:00:00Z", ) assert cs_early["listing_id"].to_list() == [1, 2] # active from Dec 31 bars within 7d lookback assert cs_early["ret_1d@v1"].to_list() == [None, None] # Co-published events/year=2025/part.parquet + part-posts.parquet (kind='ceo_post') ev = store.events( kinds=["filing", "ceo_post"], listing_ids=[1], from_date="2025-01-01", to_date="2025-01-05", ) assert ev.height == 2 assert ev["kind"].to_list() == ["ceo_post", "filing"] # tie-breaker: kind ASC # 5e. Cross-language Bun @stock-bot/duckdb read-back parity check (public MarketDataStore.crossSection) bun_bin = shutil.which("bun") assert bun_bin is not None, "bun is required for cross-language Parquet read-back check" script = f""" import {{ openDuckDbMarketDataStore }} from './libs/data/duckdb/src/index.ts'; const curatedRoot = {json.dumps(str(curated))}; const vaultCutoffTs = {vault_cutoff_ms}; const opened = await openDuckDbMarketDataStore({{ curatedRoot, vaultCutoffTs, env: {{ STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', STOCKBOT_DUCKDB_THREADS: '2', STOCKBOT_DUCKDB_TEMP_DIRECTORY: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))}, STOCK_BOT_DUCKDB_TEMP_DIR: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))}, }}, }}); try {{ const result = await opened.store.crossSection({{ features: ['ret_1d@v1', 'mom_diff@v1'], date: '2025-01-02', universe: 'US_EQ', asOf: '2025-01-02T22:00:00Z', }}); console.log(JSON.stringify(result)); }} finally {{ await opened.close(); }} """ proc = subprocess.run( [bun_bin, "-e", script], cwd=str(REPO_ROOT), capture_output=True, text=True, ) assert ( proc.returncode == 0 ), f"bun crossSection exited {proc.returncode}:\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr}" ts_payload = json.loads(proc.stdout.strip()) assert ts_payload["columns"] == cs.columns ts_rows = ts_payload["rows"] py_rows = cs.to_dicts() assert len(ts_rows) == len(py_rows) for ts_row, py_row in zip(ts_rows, py_rows): assert ts_row["listing_id"] == py_row["listing_id"] for col in ("ret_1d@v1", "mom_diff@v1"): if py_row[col] is None: assert ts_row[col] is None else: assert math.isclose(ts_row[col], py_row[col], rel_tol=1e-12, abs_tol=1e-12) def test_polars_batch_per_year_availability_ceiling_blocks_later_year_macro_leak( tmp_path: Path, ) -> None: curated = tmp_path / "curated" _build_bars_and_events_fixtures(curated) budget = _make_budget(tmp_path) # Extend 2025 bars with an April 1 bar (after the 2025-03-15 macro release) alongside # the Jan 2 bars (before the 2025-03-15 release) and Jul 2 post-Vault bar. bars_2025_existing = pl.read_parquet(curated / "bars_1d" / "year=2025" / "part.parquet") bars_2025_apr = pl.DataFrame( { "listing_id": [1], "session_date": [date(2025, 4, 1)], "ts": [datetime(2025, 4, 1, 21, 0, 0, tzinfo=timezone.utc)], "open": [11.5], "high": [12.2], "low": [11.4], "close": [12.0], "volume": [1300.0], "vwap": [12.0], "currency": ["USD"], "source": ["eod"], "known_at": [datetime(2025, 4, 1, 21, 0, 0, tzinfo=timezone.utc)], }, schema_overrides={ "listing_id": pl.Int32, "ts": pl.Datetime("us", "UTC"), "known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet_via_duckdb( pl.concat([bars_2025_existing, bars_2025_apr]), curated / "bars_1d" / "year=2025" / "part.parquet", ) # Macro releases across 2023 (prior history), 2024, 2025 pre-Vault, and 2025 post-Vault macro_df = pl.DataFrame( { "country_iso": ["US", "US", "US", "US"], "indicator": ["CPI", "CPI", "CPI", "CPI"], "period_date": [ date(2023, 12, 1), date(2024, 6, 1), date(2025, 2, 1), date(2025, 7, 1), ], "value": [1.0, 2.0, 99.0, 999.0], "unit": ["pct", "pct", "pct", "pct"], "known_at": [ datetime(2023, 12, 15, 13, 30, 0, tzinfo=timezone.utc), datetime(2024, 7, 15, 13, 30, 0, tzinfo=timezone.utc), datetime(2025, 3, 15, 13, 30, 0, tzinfo=timezone.utc), datetime(2025, 8, 15, 13, 30, 0, tzinfo=timezone.utc), ], "known_at_source": ["statutory_lag"] * 4, "has_estimated_lag": [True] * 4, }, schema_overrides={ "known_at": pl.Datetime("us", "UTC"), }, ) _write_parquet_via_duckdb(macro_df, curated / "macro" / "part.parquet") seen_macro_counts: list[int] = [] def _asof_macro_regime_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: macro_rows = ( inputs["macro"] .select( pl.col("known_at").alias("macro_known_at"), pl.col("value").cast(pl.Float64).alias("macro_value"), ) .sort("macro_known_at") .collect() ) seen_macro_counts.append(macro_rows.height) bars = inputs["bars_1d"].select("listing_id", "ts").sort("ts").collect() joined = bars.join_asof( macro_rows, left_on="ts", right_on="macro_known_at", strategy="backward", coalesce=False, ) return joined.select( pl.col("listing_id"), pl.col("ts"), pl.max_horizontal("ts", "macro_known_at").alias("known_at"), pl.col("macro_value").alias("value"), ) defn = register_signal( name="macro_regime_latest", version=1, family="regime", kind="polars", inputs=("bars_1d", "macro"), warmup_bars=0, known_at_rule="max_input_known_at", polars_fn=_asof_macro_regime_fn, expression="asof(macro.value)", registry=create_feature_registry(), ).definition manifest = run_feature_batch( defn, curated_root=curated, from_year=2024, to_year=2025, vault_cutoff_date="2025-07-01", budget=budget, ) assert [w.year for w in manifest.writes] == [2024, 2025] # 2024 sees 2023 + 2024 (2 rows, retaining prior-year history, excluding 2025 release); # 2025 sees 2023 + 2024 + 2025-03 (3 rows, excluding 2025-08 post-Vault release). assert seen_macro_counts == [2, 3] out_2024 = pl.read_parquet( curated / "features" / "macro_regime_latest" / "v1" / "year=2024" / "part.parquet" ) out_2025 = pl.read_parquet( curated / "features" / "macro_regime_latest" / "v1" / "year=2025" / "part.parquet" ) assert out_2024.height > 0 assert all(v == pytest.approx(2.0) for v in out_2024["value"].to_list()) # In 2025, Jan 2 bars precede the 2025-03-15 release so they must still see 2.0 (not 99.0); # only the Apr 1 bar (after 2025-03-15) sees 99.0, and the post-Vault Jul 2 bar is excluded. jan_2025 = out_2025.filter(pl.col("ts") == datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc)) apr_2025 = out_2025.filter(pl.col("ts") == datetime(2025, 4, 1, 21, 0, 0, tzinfo=timezone.utc)) assert jan_2025.height == 3 assert all(v == pytest.approx(2.0) for v in jan_2025["value"].to_list()) assert apr_2025.height == 1 assert apr_2025["value"].to_list() == pytest.approx([99.0]) assert out_2025.height == 4 def test_run_feature_batch_persists_definition_hash_and_blocks_cross_registry_overwrite( tmp_path: Path, ) -> None: curated = tmp_path / "curated" _build_bars_and_events_fixtures(curated) budget = _make_budget(tmp_path) def _fn_v1(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").cast(pl.Float64).alias("value"), ) reg_a = register_signal( name="close_level", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", polars_fn=_fn_v1, expression="close", registry=create_feature_registry(), ) run_feature_batch( reg_a.definition, curated_root=curated, from_year=2025, to_year=2025, vault_cutoff_date="2025-07-01", budget=budget, ) out_2025 = curated / "features" / "close_level" / "v1" / "year=2025" / "part.parquet" meta_file = curated / "features" / "close_level" / "v1" / "_definition.json" assert meta_file.exists() original_bytes = out_2025.read_bytes() # Fresh registry (simulating restarted notebook) with modified formula under same name + version def _fn_mutated(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") * 2.0).cast(pl.Float64).alias("value"), ) reg_b = register_signal( name="close_level", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", polars_fn=_fn_mutated, expression="close * 2.0", registry=create_feature_registry(), ) with pytest.raises(FeatureLibraryError) as err: run_feature_batch( reg_b.definition, curated_root=curated, from_year=2025, to_year=2025, vault_cutoff_date="2025-07-01", budget=budget, ) assert err.value.code == "FEATURE_VERSION_IMMUTABLE" assert out_2025.read_bytes() == original_bytes def test_polars_batch_post_publication_failure_wraps_in_batch_write_failed_with_receipts( tmp_path: Path, ) -> None: curated = tmp_path / "curated" _build_bars_and_events_fixtures(curated) budget = _make_budget(tmp_path) call_count = 0 def _fail_second_year_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: nonlocal call_count call_count += 1 bars = inputs["bars_1d"].collect() if call_count == 2: # Return empty DataFrame missing required output columns on year 2025 return pl.DataFrame() return bars.select( pl.col("listing_id"), pl.col("ts"), pl.col("ts").alias("known_at"), pl.col("close").cast(pl.Float64).alias("value"), ) defn = FeatureDefinition( name="fail_year2", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", polars_fn=_fail_second_year_fn, expression="close_fail_year2", ) with pytest.raises(FeatureLibraryError) as err: run_feature_batch( defn, curated_root=curated, from_year=2024, to_year=2025, vault_cutoff_date="2025-07-01", budget=budget, ) assert err.value.code == "BATCH_WRITE_FAILED" assert err.value.failed_year == 2025 assert err.value.completed_years == (2024,) assert len(err.value.completed_writes) == 1 assert err.value.completed_writes[0].year == 2024 assert err.value.completed_writes[0].output_path.endswith( "features/fail_year2/v1/year=2024/part.parquet" ) assert isinstance(err.value.__cause__, FeatureLibraryError) assert err.value.__cause__.code == "INVALID_SQL_PROJECTION" def test_run_feature_batch_rejects_sidecar_free_ts_partitions(tmp_path: Path) -> None: curated = tmp_path / "curated" _build_bars_and_events_fixtures(curated) budget = _make_budget(tmp_path) vault_cutoff_date = "2025-07-01" vault_cutoff_ms = parse_timestamp_micros(vault_cutoff_date, "start", "cutoff") // 1000 # Materialize ret_1d@v1 year=2024 using the TypeScript batch runner (no _definition.json sidecar) bun_bin = shutil.which("bun") assert bun_bin is not None, "bun is required for TypeScript sidecar-free fixture" year_2024_dir = curated / "features" / "ret_1d" / "v1" / "year=2024" year_2024_dir.mkdir(parents=True, exist_ok=True) script = f""" import {{ openDuckDbMarketDataStore }} from './libs/data/duckdb/src/index.ts'; import {{ RET_1D_V1, runFeatureBatch }} from './libs/research/src/feature-library.ts'; const curatedRoot = {json.dumps(str(curated))}; const vaultCutoffTs = {vault_cutoff_ms}; const opened = await openDuckDbMarketDataStore({{ curatedRoot, vaultCutoffTs, env: {{ STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', STOCKBOT_DUCKDB_THREADS: '2', STOCKBOT_DUCKDB_TEMP_DIRECTORY: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))}, STOCK_BOT_DUCKDB_TEMP_DIR: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))}, }}, }}); try {{ await opened.executor.run("SET TimeZone = 'UTC';"); await runFeatureBatch( RET_1D_V1, {{ curatedRoot, fromYear: 2024, toYear: 2024, vaultCutoffDate: {json.dumps(vault_cutoff_date)} }}, opened.executor, ); }} finally {{ await opened.close(); }} """ subprocess.run( [bun_bin, "-e", script], cwd=str(REPO_ROOT), capture_output=True, text=True, check=True, ) ts_part_2024 = year_2024_dir / "part.parquet" meta_file = curated / "features" / "ret_1d" / "v1" / "_definition.json" part_2025 = curated / "features" / "ret_1d" / "v1" / "year=2025" / "part.parquet" assert ts_part_2024.exists() assert not meta_file.exists() original_2024_bytes = ts_part_2024.read_bytes() # Promoting a revised Python formula under ret_1d@v1 for 2025 must fail closed revised_ret = register_signal( name="ret_1d", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=1, known_at_rule="bar_close", polars_fn=lambda inp: inp["bars_1d"].select( pl.col("listing_id"), pl.col("ts"), pl.col("ts").alias("known_at"), (pl.col("close") * 0.0).cast(pl.Float64).alias("value"), ), expression="0.0", registry=create_feature_registry(), ).definition with pytest.raises(FeatureLibraryError) as err: run_feature_batch( revised_ret, curated_root=curated, from_year=2025, to_year=2025, vault_cutoff_date=vault_cutoff_date, budget=budget, ) assert err.value.code == "FEATURE_VERSION_IMMUTABLE" assert not meta_file.exists() assert not part_2025.exists() assert ts_part_2024.read_bytes() == original_2024_bytes def test_run_feature_batch_atomic_version_claim_blocks_competing_first_writes( tmp_path: Path, ) -> None: curated = tmp_path / "curated" _build_bars_and_events_fixtures(curated) vault_cutoff_date = "2025-07-01" barrier = threading.Barrier(2, timeout=10.0) def _fn_a(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: barrier.wait() return ( inputs["bars_1d"] .select( pl.col("listing_id"), pl.col("ts"), pl.col("ts").alias("known_at"), pl.col("close").cast(pl.Float64).alias("value"), ) .collect() ) def _fn_b(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: barrier.wait() return ( inputs["bars_1d"] .select( pl.col("listing_id"), pl.col("ts"), pl.col("ts").alias("known_at"), (pl.col("close") * 2.0).cast(pl.Float64).alias("value"), ) .collect() ) reg_a = register_signal( name="close_race", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", polars_fn=_fn_a, expression="close", registry=create_feature_registry(), ) reg_b = register_signal( name="close_race", version=1, family="technical", kind="polars", inputs=("bars_1d",), warmup_bars=0, known_at_rule="bar_close", polars_fn=_fn_b, expression="close * 2.0", registry=create_feature_registry(), ) def _run_writer( defn: FeatureDefinition, year: int, tag: str ) -> tuple[str, Any]: try: manifest = run_feature_batch( defn, curated_root=curated, from_year=year, to_year=year, vault_cutoff_date=vault_cutoff_date, budget=_make_budget(tmp_path / tag), ) return ("ok", manifest) except FeatureLibraryError as exc: return ("err", exc) with ThreadPoolExecutor(max_workers=2) as pool: fut_a = pool.submit(_run_writer, reg_a.definition, 2024, "a") fut_b = pool.submit(_run_writer, reg_b.definition, 2025, "b") res_a = fut_a.result() res_b = fut_b.result() outcomes = [res_a, res_b] winners = [payload for status, payload in outcomes if status == "ok"] losers = [payload for status, payload in outcomes if status == "err"] assert len(winners) == 1 assert len(losers) == 1 assert isinstance(losers[0], FeatureLibraryError) assert losers[0].code == "FEATURE_VERSION_IMMUTABLE" winner_manifest = winners[0] version_dir = curated / "features" / "close_race" / "v1" meta_payload = json.loads((version_dir / "_definition.json").read_text(encoding="utf-8")) assert meta_payload["definition_hash"] == winner_manifest.definition_hash part_2024 = version_dir / "year=2024" / "part.parquet" part_2025 = version_dir / "year=2025" / "part.parquet" if winner_manifest.definition_hash == reg_a.definition_hash: assert part_2024.exists() assert not part_2025.exists() else: assert winner_manifest.definition_hash == reg_b.definition_hash assert part_2025.exists() assert not part_2024.exists() leftover_tmp = [p for p in version_dir.rglob("*.tmp")] assert leftover_tmp == [] def test_sdk_exports() -> None: expected_exports = ( "features", "register_signal", "create_feature_registry", "FeatureDefinition", "RegisteredFeature", "FeatureRegistry", "FeatureLibraryError", "RET_1D_V1", "feature_ref", "parse_feature_ref", "feature_definition_hash", "validate_feature_definition", "plan_feature_batch", "run_feature_batch", "QuestDbExecutor", "PsycopgQuestDbExecutor", ) for name in expected_exports: assert hasattr(stockbot, name), f"Missing stockbot export: {name}" assert name in stockbot.__all__, f"Missing {name} in stockbot.__all__" assert hasattr(stockbot.signals, "register_signal")