From 81ffdef24c2c1ee106c0de4e3635f4ea279e7095 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 5 Dec 2026 13:49:03 -0500 Subject: [PATCH] =?UTF-8?q?T-213:=20M2.4b=20=E2=80=94=20Add=20Python=20sto?= =?UTF-8?q?ckbot=20register=5Fsignal,=20batch=20feature=20runner,=20and=20?= =?UTF-8?q?M2=20MarketDataStore=20methods?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- python/stockbot/__init__.py | 43 +- python/stockbot/data.py | 858 ++++++++++- python/stockbot/features.py | 2124 ++++++++++++++++++++++++++++ python/stockbot/signals.py | 1 + python/stockbot/vault.py | 207 ++- python/tests/test_m2_sdk_parity.py | 1072 ++++++++++++++ 6 files changed, 4219 insertions(+), 86 deletions(-) create mode 100644 python/stockbot/features.py create mode 100644 python/tests/test_m2_sdk_parity.py diff --git a/python/stockbot/__init__.py b/python/stockbot/__init__.py index c61316f0..4d5d6e0c 100644 --- a/python/stockbot/__init__.py +++ b/python/stockbot/__init__.py @@ -1,6 +1,6 @@ """Stock Bot Python Research SDK (`stockbot`).""" -from . import data +from . import data, features from .calculations import ( DSR_VALIDATION_GATE, EULER_MASCHERONI, @@ -18,7 +18,26 @@ from .calculations import ( newey_west_mean_test, trial_moments, ) -from .data import MarketDataStore +from .data import MarketDataStore, PsycopgQuestDbExecutor, QuestDbExecutor +from .features import ( + RET_1D_V1, + FeatureBatchManifest, + FeatureBatchWriteReceipt, + FeatureDefinition, + FeatureLibraryError, + FeatureRefParts, + FeatureRegistry, + PlannedFeatureWrite, + RegisteredFeature, + create_feature_registry, + feature_definition_hash, + feature_ref, + parse_feature_ref, + plan_feature_batch, + register_signal, + run_feature_batch, + validate_feature_definition, +) from .ledger import ( ClusterDsrSummary, RecordedTrial, @@ -43,7 +62,27 @@ from .vault import ( __all__ = [ "data", + "features", "MarketDataStore", + "QuestDbExecutor", + "PsycopgQuestDbExecutor", + "register_signal", + "create_feature_registry", + "FeatureDefinition", + "RegisteredFeature", + "FeatureRefParts", + "PlannedFeatureWrite", + "FeatureBatchWriteReceipt", + "FeatureBatchManifest", + "FeatureRegistry", + "FeatureLibraryError", + "RET_1D_V1", + "feature_ref", + "parse_feature_ref", + "feature_definition_hash", + "validate_feature_definition", + "plan_feature_batch", + "run_feature_batch", "TrialLedgerClient", "RecordedTrial", "ClusterDsrSummary", diff --git a/python/stockbot/data.py b/python/stockbot/data.py index 5fca1827..0176cc34 100644 --- a/python/stockbot/data.py +++ b/python/stockbot/data.py @@ -1,36 +1,280 @@ -"""Vault-fenced DuckDB + Polars `MarketDataStore` for curated Hive Parquet.""" +"""Vault-fenced DuckDB + Polars + optional QuestDB `MarketDataStore` for curated datasets.""" from __future__ import annotations +import math import os -from datetime import date, datetime, timedelta, timezone +import re +from datetime import date, timedelta from pathlib import Path -from typing import Literal, Sequence +from typing import Any, Literal, Mapping, Protocol, Sequence, runtime_checkable +from urllib.parse import unquote, urlsplit import duckdb import polars as pl +import psycopg +from .features import FeatureLibraryError, parse_feature_ref from .vault import ( DataScope, DuckDbConnectionBudget, MarketDataStoreValidationError, + VaultHoldoutFenceError, apply_vault_fence, + epoch_micros_to_datetime, + format_utc_iso_micros, resolve_duckdb_budget, + validate_curated_root, ) EventKind = Literal["filing", "earnings", "ceo_post", "corporate_action"] AdjustmentMode = Literal["raw", "split", "total"] UniverseRef = Literal["US_EQ", "CA_EQ", "US_CA_EQ"] +_INT32_MIN = -2_147_483_648 +_INT32_MAX = 2_147_483_647 +_FX_1M_BAR_DURATION_MICROS = 60_000_000 + +_DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") +_CANONICAL_POSITIVE_INT_RE = re.compile(r"^[1-9]\d*$") +_CANONICAL_SIGNED_INT_RE = re.compile(r"^-?(?:0|[1-9]\d*)$") +_URL_USERINFO_RE = re.compile(r"://[^@\s/]+@") +_KV_PASSWORD_RE = re.compile(r"(password\s*=\s*)(?:'[^']*'|\"[^\"]*\"|\S+)", re.IGNORECASE) + +_EVENT_KINDS: tuple[EventKind, ...] = ("filing", "earnings", "ceo_post", "corporate_action") +_EVENT_KIND_SET: frozenset[str] = frozenset(_EVENT_KINDS) + _UNIVERSE_CURRENCIES: dict[str, tuple[str, ...]] = { "US_EQ": ("USD",), "CA_EQ": ("CAD",), "US_CA_EQ": ("USD", "CAD"), } +FUNDAMENTALS_PIT_VALUE_FIELDS: tuple[str, ...] = ( + "revenue", + "net_income", + "operating_cash_flow", + "total_assets", + "total_equity", + "shares_outstanding", + "ttm_revenue", + "ttm_net_income", + "ttm_operating_cash_flow", +) +_FUNDAMENTALS_PIT_VALUE_FIELD_SET: frozenset[str] = frozenset(FUNDAMENTALS_PIT_VALUE_FIELDS) +_FUNDAMENTALS_TTM_VALUE_FIELD_SET: frozenset[str] = frozenset( + ("ttm_revenue", "ttm_net_income", "ttm_operating_cash_flow") +) + +_BARS_1M_SCHEMA: dict[str, pl.DataType] = { + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "open": pl.Float64, + "high": pl.Float64, + "low": pl.Float64, + "close": pl.Float64, + "volume": pl.Float64, + "vwap": pl.Float64, + "known_at": pl.Datetime("us", "UTC"), +} + +_FX_1M_SCHEMA: dict[str, pl.DataType] = { + "pair": pl.String, + "ts": pl.Datetime("us", "UTC"), + "open": pl.Float64, + "high": pl.Float64, + "low": pl.Float64, + "close": pl.Float64, + "source": pl.String, + "known_at": pl.Datetime("us", "UTC"), +} + + +def _redact_dsn(message: str, dsn: str) -> str: + redacted = message + if dsn: + redacted = redacted.replace(dsn, "") + try: + parsed = urlsplit(dsn) + if parsed.password: + redacted = redacted.replace(parsed.password, "***") + decoded_pw = unquote(parsed.password) + if decoded_pw: + redacted = redacted.replace(decoded_pw, "***") + except Exception: + pass + redacted = _URL_USERINFO_RE.sub("://@", redacted) + redacted = _KV_PASSWORD_RE.sub(r"\1***", redacted) + return redacted + + +@runtime_checkable +class QuestDbExecutor(Protocol): + """Injected PGWire SQL executor protocol for QuestDB intraday queries.""" + + def query(self, sql: str, params: Sequence[Any]) -> Sequence[Mapping[str, Any]]: ... + + def close(self) -> None: ... + + +class PsycopgQuestDbExecutor: + """Autocommit psycopg PGWire executor for QuestDB with credential redaction on errors.""" + + def __init__(self, dsn: str) -> None: + if not isinstance(dsn, str) or not dsn.strip(): + raise MarketDataStoreValidationError("questdb_dsn must be a non-empty string.") + self._dsn = dsn + self._conn: psycopg.Connection[Any] | None = None + + def _ensure_conn(self) -> psycopg.Connection[Any]: + if self._conn is None or self._conn.closed: + try: + self._conn = psycopg.connect(self._dsn, autocommit=True) + except Exception as exc: + safe_msg = _redact_dsn(f"QuestDB connection failed: {exc}", self._dsn) + raise RuntimeError(safe_msg) from None + return self._conn + + def query(self, sql: str, params: Sequence[Any]) -> list[dict[str, Any]]: + conn = self._ensure_conn() + try: + with conn.cursor() as cur: + cur.execute(sql, tuple(params)) + if cur.description is None: + return [] + columns = [desc.name for desc in cur.description] + rows = cur.fetchall() + return [dict(zip(columns, row)) for row in rows] + except Exception as exc: + safe_msg = _redact_dsn(f"QuestDB query failed: {exc}", self._dsn) + raise RuntimeError(safe_msg) from None + + def close(self) -> None: + if self._conn is not None and not self._conn.closed: + try: + self._conn.close() + finally: + self._conn = None + + +def _validate_int32_listing_ids( + raw: Sequence[int], + *, + field: str = "listing_ids", + positive_only: bool = False, + sort_ascending: bool = False, +) -> list[int]: + if isinstance(raw, (str, bytes)) or not isinstance(raw, Sequence) or len(raw) == 0: + raise MarketDataStoreValidationError( + f'Expected a non-empty sequence of INT32 listing IDs for "{field}".' + ) + min_val = 1 if positive_only else _INT32_MIN + seen: set[int] = set() + normalized: list[int] = [] + for idx, item in enumerate(raw): + if isinstance(item, bool) or not isinstance(item, int) or item < min_val or item > _INT32_MAX: + raise MarketDataStoreValidationError( + f"Invalid INT32 listing ID at {field}[{idx}]: {item!r}." + ) + if item not in seen: + seen.add(item) + normalized.append(item) + if sort_ascending: + normalized.sort() + return normalized + + +def _validate_non_empty_strings(raw: Sequence[str], field: str) -> list[str]: + if isinstance(raw, (str, bytes)) or not isinstance(raw, Sequence) or len(raw) == 0: + raise MarketDataStoreValidationError( + f'Expected a non-empty sequence of strings for "{field}".' + ) + seen: set[str] = set() + out: list[str] = [] + for idx, item in enumerate(raw): + if not isinstance(item, str) or not item.strip(): + raise MarketDataStoreValidationError( + f'Expected a non-empty string at {field}[{idx}], got {item!r}.' + ) + if item not in seen: + seen.add(item) + out.append(item) + return out + + +def _validate_fundamentals_fields(raw: Sequence[str], field: str = "fields") -> list[str]: + if isinstance(raw, (str, bytes)) or not isinstance(raw, Sequence) or len(raw) == 0: + raise MarketDataStoreValidationError( + f'Expected a non-empty sequence of fundamentals value fields for "{field}".' + ) + seen: set[str] = set() + out: list[str] = [] + for item in raw: + if not isinstance(item, str) or item not in _FUNDAMENTALS_PIT_VALUE_FIELD_SET: + raise MarketDataStoreValidationError( + f'Unknown fundamentals field {item!r}. Expected one of: {", ".join(FUNDAMENTALS_PIT_VALUE_FIELDS)}.' + ) + if item not in seen: + seen.add(item) + out.append(item) + return out + + +def _parse_questdb_micros(raw: Any, column: str, row_idx: int) -> int: + if isinstance(raw, int) and not isinstance(raw, bool): + return raw + if isinstance(raw, str) and _CANONICAL_SIGNED_INT_RE.match(raw): + return int(raw) + raise MarketDataStoreValidationError( + f'Invalid QuestDB timestamp column "{column}" in result row {row_idx}: {raw!r}.' + ) + + +def _read_required_finite_float(row: Mapping[str, Any], key: str, row_idx: int) -> float: + val = row.get(key) + if isinstance(val, bool) or not isinstance(val, (int, float)) or not math.isfinite(float(val)): + raise MarketDataStoreValidationError( + f'Invalid numeric column "{key}" in result row {row_idx}: {val!r}.' + ) + fval = float(val) + return 0.0 if fval == 0.0 else fval + + +def _read_nullable_finite_float(row: Mapping[str, Any], key: str, row_idx: int) -> float | None: + val = row.get(key) + if val is None: + return None + if isinstance(val, bool) or not isinstance(val, (int, float)) or not math.isfinite(float(val)): + raise MarketDataStoreValidationError( + f'Invalid nullable numeric column "{key}" in result row {row_idx}: {val!r}.' + ) + fval = float(val) + return 0.0 if fval == 0.0 else fval + + +def _parse_questdb_listing_id( + row: Mapping[str, Any], row_idx: int, requested_ids: frozenset[int] +) -> int: + raw = row.get("listing_id") + if isinstance(raw, str) and _CANONICAL_POSITIVE_INT_RE.match(raw): + parsed = int(raw) + else: + raise MarketDataStoreValidationError( + f"Invalid bars_1m listing_id SYMBOL in result row {row_idx}: {raw!r}." + ) + if parsed < 1 or parsed > _INT32_MAX: + raise MarketDataStoreValidationError( + f"Out-of-range bars_1m listing_id SYMBOL in result row {row_idx}: {raw!r}." + ) + if parsed not in requested_ids: + raise MarketDataStoreValidationError( + f"Unexpected unrequested listing_id {parsed} in bars_1m result row {row_idx}." + ) + return parsed + class MarketDataStore: - """Vault-fenced DuckDB + Parquet reader enforcing `known_at <= as_of` and `ts < vault_cutoff_ts`.""" + """Vault-fenced DuckDB + Parquet + optional QuestDB reader enforcing `known_at <= as_of` and `ts < vault_cutoff_ts`.""" def __init__( self, @@ -40,8 +284,23 @@ class MarketDataStore: vault_operator_authorized: bool = False, budget: DuckDbConnectionBudget | None = None, adj_factors_path: str | Path | None = None, + questdb_dsn: str | None = None, + questdb_executor: QuestDbExecutor | None = None, ) -> None: - self.curated_root = str(Path(curated_root).resolve()) + if isinstance(vault_cutoff_ts, bool) or not isinstance(vault_cutoff_ts, int): + raise MarketDataStoreValidationError( + f"Invalid epoch millisecond timestamp for vault_cutoff_ts: {vault_cutoff_ts!r}." + ) + if questdb_dsn is not None and questdb_executor is not None: + raise MarketDataStoreValidationError( + "Options questdb_dsn and questdb_executor are mutually exclusive." + ) + if questdb_executor is not None and not isinstance(questdb_executor, QuestDbExecutor): + raise MarketDataStoreValidationError( + "Expected questdb_executor implementing query(sql, params) and close()." + ) + + self.curated_root = validate_curated_root(curated_root) self.vault_cutoff_ts = vault_cutoff_ts self.vault_operator_authorized = vault_operator_authorized self.budget = budget or resolve_duckdb_budget() @@ -50,13 +309,22 @@ class MarketDataStore: if adj_factors_path is not None else str(Path(self.curated_root) / "adj_factors" / "part.parquet") ) + self._questdb_executor: QuestDbExecutor | None = ( + PsycopgQuestDbExecutor(questdb_dsn) if questdb_dsn is not None else questdb_executor + ) + os.makedirs(self.budget.temp_directory, exist_ok=True) self._con = duckdb.connect(":memory:") + self._con.execute("SET TimeZone = 'UTC';") for stmt in self.budget.statements: self._con.execute(stmt) def close(self) -> None: - self._con.close() + try: + self._con.close() + finally: + if self._questdb_executor is not None: + self._questdb_executor.close() def __enter__(self) -> "MarketDataStore": return self @@ -68,7 +336,7 @@ class MarketDataStore: return f"{self.curated_root}/bars_1d/year=*/part.parquet" def _events_glob(self) -> str: - return f"{self.curated_root}/events/year=*/part.parquet" + return f"{self.curated_root}/events/year=*/*.parquet" def _shorts_path(self) -> str: return f"{self.curated_root}/shorts/part.parquet" @@ -76,6 +344,12 @@ class MarketDataStore: def _fx_path(self) -> str: return f"{self.curated_root}/fx_1d/part.parquet" + def _fundamentals_pit_glob(self) -> str: + return f"{self.curated_root}/fundamentals_pit/year=*/part.parquet" + + def _macro_path(self) -> str: + return f"{self.curated_root}/macro/part.parquet" + def _verify_fenced_adj_factors(self, as_of_micros: int, scope: DataScope) -> str: rows = self._con.execute( f"SELECT key::VARCHAR AS k, value::VARCHAR AS v FROM parquet_kv_metadata('{self.adj_factors_path}')" @@ -100,6 +374,113 @@ class MarketDataStore: ) return self.adj_factors_path + def _bars_1m( + self, + *, + listing_ids: Sequence[int] | None, + currencies: Sequence[str] | None, + from_date: str, + to_date: str, + adjustment: AdjustmentMode, + as_of: str | None, + scope: DataScope, + ) -> pl.DataFrame: + if self._questdb_executor is None: + raise MarketDataStoreValidationError( + "Intraday 1m bars require questdb_dsn or questdb_executor to be configured." + ) + if adjustment in ("split", "total"): + raise NotImplementedError( + f"Adjustment {adjustment!r} is not supported for intraday '1m' bars; bars_1m stores raw split-unadjusted values." + ) + if adjustment != "raw": + raise MarketDataStoreValidationError( + f"Invalid bars adjustment {adjustment!r}. Expected 'raw'." + ) + if currencies is not None: + raise MarketDataStoreValidationError( + "The currencies filter is not supported for intraday '1m' bars." + ) + if listing_ids is None: + raise MarketDataStoreValidationError( + "Intraday '1m' bars require a non-empty listing_ids sequence." + ) + sorted_ids = _validate_int32_listing_ids( + listing_ids, field="listing_ids", positive_only=True, sort_ascending=True + ) + fenced = apply_vault_fence( + from_date, + to_date, + self.vault_cutoff_ts, + as_of=as_of, + scope=scope, + vault_operator_authorized=self.vault_operator_authorized, + ) + assert fenced.from_micros is not None + assert fenced.to_micros is not None + assert fenced.as_of_micros is not None + + placeholders = ", ".join(["%s"] * len(sorted_ids)) + sql = ( + "SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, " + "CAST(known_at AS LONG) AS known_at_us " + "FROM bars_1m " + f"WHERE ts >= %s AND ts <= %s AND listing_id IN ({placeholders}) AND known_at <= %s " + "ORDER BY ts, listing_id" + ) + params: list[str] = [ + format_utc_iso_micros(fenced.from_micros), + format_utc_iso_micros(fenced.to_micros), + *(str(lid) for lid in sorted_ids), + format_utc_iso_micros(fenced.as_of_micros), + ] + raw_rows = self._questdb_executor.query(sql, params) + requested_set = frozenset(sorted_ids) + cutoff_micros = self.vault_cutoff_ts * 1000 + + records: list[dict[str, Any]] = [] + for idx, raw in enumerate(raw_rows): + if not isinstance(raw, Mapping): + raise MarketDataStoreValidationError( + f"QuestDB executor returned a non-mapping bars_1m row at index {idx}." + ) + lid = _parse_questdb_listing_id(raw, idx, requested_set) + ts_us = _parse_questdb_micros(raw.get("ts_us"), "ts_us", idx) + if ts_us < fenced.from_micros or ts_us > fenced.to_micros: + raise MarketDataStoreValidationError( + f"Row {idx} timestamp ts ({ts_us} us) is outside fenced range [{fenced.from_micros}, {fenced.to_micros}] us." + ) + if fenced.scope == "vault_fenced" and ts_us >= cutoff_micros: + raise MarketDataStoreValidationError( + f"Row {idx} timestamp ts ({ts_us} us) violates Vault cutoff ({cutoff_micros} us)." + ) + known_at_us = _parse_questdb_micros(raw.get("known_at_us"), "known_at_us", idx) + if known_at_us > fenced.as_of_micros: + raise MarketDataStoreValidationError( + f"Row {idx} availability known_at ({known_at_us} us) exceeds fenced as_of ({fenced.as_of_micros} us)." + ) + if fenced.scope == "vault_fenced" and known_at_us >= cutoff_micros: + raise MarketDataStoreValidationError( + f"Row {idx} availability known_at ({known_at_us} us) violates Vault cutoff ({cutoff_micros} us)." + ) + records.append( + { + "listing_id": lid, + "ts": epoch_micros_to_datetime(ts_us), + "open": _read_required_finite_float(raw, "open", idx), + "high": _read_required_finite_float(raw, "high", idx), + "low": _read_required_finite_float(raw, "low", idx), + "close": _read_required_finite_float(raw, "close", idx), + "volume": _read_required_finite_float(raw, "volume", idx), + "vwap": _read_nullable_finite_float(raw, "vwap", idx), + "known_at": epoch_micros_to_datetime(known_at_us), + } + ) + + if not records: + return pl.DataFrame(schema=_BARS_1M_SCHEMA) + return pl.DataFrame(records, schema=_BARS_1M_SCHEMA) + def bars( self, *, @@ -112,8 +493,23 @@ class MarketDataStore: as_of: str | None = None, scope: DataScope = "vault_fenced", ) -> pl.DataFrame: + if timeframe == "1m": + return self._bars_1m( + listing_ids=listing_ids, + currencies=currencies, + from_date=from_date, + to_date=to_date, + adjustment=adjustment, + as_of=as_of, + scope=scope, + ) + if timeframe in ("5m", "1h"): + raise NotImplementedError(f"Timeframe {timeframe!r} is not supported.") if timeframe != "1d": - raise NotImplementedError(f"Timeframe {timeframe!r} is reserved for QuestDB (M2).") + raise MarketDataStoreValidationError( + f"Invalid bars timeframe {timeframe!r}. Expected '1d' or '1m'." + ) + fenced = apply_vault_fence( from_date, to_date, @@ -122,9 +518,13 @@ class MarketDataStore: scope=scope, vault_operator_authorized=self.vault_operator_authorized, ) - from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc) - to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc) - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) + assert fenced.from_micros is not None + assert fenced.to_micros is not None + assert fenced.as_of_micros is not None + + from_ts = epoch_micros_to_datetime(fenced.from_micros) + to_ts = epoch_micros_to_datetime(fenced.to_micros) + as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros) where = ["b.ts >= ?", "b.ts <= ?", "b.known_at <= ?"] params: list[object] = [from_ts, to_ts, as_of_ts] @@ -190,6 +590,161 @@ class MarketDataStore: """ return self._con.execute(sql, [as_of_ts, *params]).pl() + def fundamentals_as_of( + self, + *, + listing_ids: Sequence[int], + fields: Sequence[str], + as_of: str, + allow_estimated_lag: bool = True, + ) -> pl.DataFrame: + """Vault-fenced 2D PIT fundamentals reader over `fundamentals_pit/year=*/part.parquet`. + + Selects at most one snapshot per requested `listing_id` — the latest with + `effective_known_at <= as_of` (clamped strictly below `vault_cutoff_ts * 1000` µs). + When `allow_estimated_lag=False`, listings whose latest snapshot has + `has_estimated_lag = true` are omitted without falling back to older snapshots, and + requested `ttm_*` value fields plus `ttm_period_end`/`ttm_currency` are masked to + NULL when `ttm_has_estimated_lag` is true while preserving `ttm_has_estimated_lag`. + """ + valid_ids = _validate_int32_listing_ids(listing_ids, field="listing_ids") + valid_fields = _validate_fundamentals_fields(fields, field="fields") + if not isinstance(allow_estimated_lag, bool): + raise MarketDataStoreValidationError( + f"Invalid allow_estimated_lag {allow_estimated_lag!r}. Expected a bool." + ) + + try: + fenced = apply_vault_fence( + as_of, + as_of, + self.vault_cutoff_ts, + as_of=as_of, + scope="vault_fenced", + ) + assert fenced.as_of_micros is not None + effective_as_of_micros = fenced.as_of_micros + except VaultHoldoutFenceError: + effective_as_of_micros = self.vault_cutoff_ts * 1000 - 1 + + as_of_iso = format_utc_iso_micros(effective_as_of_micros) + has_ttm_field = any(f in _FUNDAMENTALS_TTM_VALUE_FIELD_SET for f in valid_fields) + + inner_cols: list[str] = [ + "f.listing_id", + "f.effective_known_at", + "f.known_at_source", + "f.has_estimated_lag", + "f.period_end", + "f.fiscal_period", + "f.currency", + "f.period_known_at", + ] + outer_cols: list[str] = [ + "s.listing_id", + "s.effective_known_at", + "s.known_at_source", + "s.has_estimated_lag", + "s.period_end", + "s.fiscal_period", + "s.currency", + "s.period_known_at", + ] + + for field in valid_fields: + inner_cols.append(f"f.{field}") + if field in _FUNDAMENTALS_TTM_VALUE_FIELD_SET: + outer_cols.append( + f"CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.{field} ELSE NULL END AS {field}" + ) + else: + outer_cols.append(f"s.{field}") + + if has_ttm_field: + inner_cols.extend(["f.ttm_period_end", "f.ttm_currency", "f.ttm_has_estimated_lag"]) + outer_cols.extend( + [ + "CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_period_end ELSE NULL END AS ttm_period_end", + "CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency", + "s.ttm_has_estimated_lag", + ] + ) + + lid_ph = ", ".join(["?"] * len(valid_ids)) + sql = ( + f"WITH latest AS (SELECT {', '.join(inner_cols)} " + "FROM read_parquet(?, hive_partitioning = true) AS f " + f"WHERE f.listing_id IN ({lid_ph}) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) " + "QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) " + f"SELECT {', '.join(outer_cols)} " + "FROM latest AS s " + "CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts " + "WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) " + "ORDER BY s.listing_id ASC" + ) + params: list[object] = [ + self._fundamentals_pit_glob(), + *valid_ids, + as_of_iso, + allow_estimated_lag, + ] + return self._con.execute(sql, params).pl() + + def macro_as_of( + self, + *, + countries: Sequence[str], + indicators: Sequence[str], + from_date: str, + to_date: str, + as_of: str | None = None, + ) -> pl.DataFrame: + """Vault-fenced lagged macro reader over `macro/part.parquet` (coarse regime filters only). + + `teData` stores final-revised macro values without release vintages; `curate-macro` + applies statutory lag classes (+1d policy rates, +35d monthly, +65d/+90d GDP) into + `known_at` so this reader is suitable for coarse regime filters only, never + release-day surprise trading (`design/DATA-CONTRACTS.md` §1). + """ + valid_countries = _validate_non_empty_strings(countries, "countries") + valid_indicators = _validate_non_empty_strings(indicators, "indicators") + fenced = apply_vault_fence( + from_date, + to_date, + self.vault_cutoff_ts, + as_of=as_of, + scope="vault_fenced", + ) + assert fenced.from_micros is not None + assert fenced.to_micros is not None + assert fenced.as_of_micros is not None + + from_d = epoch_micros_to_datetime(fenced.from_micros).date() + to_d = epoch_micros_to_datetime(fenced.to_micros).date() + as_of_iso = format_utc_iso_micros(fenced.as_of_micros) + + country_ph = ", ".join(["?"] * len(valid_countries)) + indicator_ph = ", ".join(["?"] * len(valid_indicators)) + sql = ( + "SELECT m.country_iso, m.indicator, m.period_date, m.known_at, m.known_at_source, m.value " + "FROM read_parquet(?) AS m " + f"WHERE m.country_iso IN ({country_ph}) " + f"AND m.indicator IN ({indicator_ph}) " + "AND m.period_date >= ? " + "AND m.period_date <= ? " + "AND m.known_at <= CAST(? AS TIMESTAMPTZ) " + "ORDER BY m.country_iso ASC, m.indicator ASC, m.period_date ASC" + ) + params: list[object] = [ + self._macro_path(), + *valid_countries, + *valid_indicators, + from_d, + to_d, + as_of_iso, + ] + return self._con.execute(sql, params).pl() + def shorts_as_of( self, *, @@ -198,10 +753,16 @@ class MarketDataStore: to_date: str, as_of: str | None = None, ) -> pl.DataFrame: - fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced") - from_d = datetime.fromtimestamp(fenced.from_ms / 1000.0, tz=timezone.utc).date() - to_d = datetime.fromtimestamp(fenced.to_ms / 1000.0, tz=timezone.utc).date() - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) + fenced = apply_vault_fence( + from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced" + ) + assert fenced.from_micros is not None + assert fenced.to_micros is not None + assert fenced.as_of_micros is not None + + from_d = epoch_micros_to_datetime(fenced.from_micros).date() + to_d = epoch_micros_to_datetime(fenced.to_micros).date() + as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros) where = ["report_date >= ?", "report_date <= ?", "known_at <= ?"] params: list[object] = [from_d, to_d, as_of_ts] @@ -231,10 +792,21 @@ class MarketDataStore: ) -> pl.DataFrame: if not kinds: raise MarketDataStoreValidationError("events requires at least one kind.") - fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced") - from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc) - to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc) - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) + for k in kinds: + if k not in _EVENT_KIND_SET: + raise MarketDataStoreValidationError( + f"Unknown EventKind {k!r}. Expected one of: {', '.join(_EVENT_KINDS)}." + ) + fenced = apply_vault_fence( + from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced" + ) + assert fenced.from_micros is not None + assert fenced.to_micros is not None + assert fenced.as_of_micros is not None + + from_ts = epoch_micros_to_datetime(fenced.from_micros) + to_ts = epoch_micros_to_datetime(fenced.to_micros) + as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros) kind_ph = ", ".join(["?"] * len(kinds)) where = [f"kind IN ({kind_ph})", "ts >= ?", "ts <= ?", "known_at <= ?"] @@ -250,19 +822,122 @@ class MarketDataStore: SELECT listing_id, ts, known_at, known_at_source, kind, subtype, payload_json FROM read_parquet('{self._events_glob()}', hive_partitioning = true) WHERE {' AND '.join(where)} - ORDER BY listing_id ASC, ts ASC + ORDER BY listing_id ASC, ts ASC, kind ASC, subtype ASC, payload_json ASC, known_at ASC, known_at_source ASC """ return self._con.execute(sql, params).pl() - def fx(self, *, pair: str = "USD.CAD", timeframe: str = "1d", from_date: str, to_date: str) -> pl.DataFrame: - if timeframe != "1d": - raise NotImplementedError("FX intraday 1m is reserved for QuestDB (M2).") + def _fx_1m( + self, + *, + from_date: str, + to_date: str, + as_of: str | None, + ) -> pl.DataFrame: + if self._questdb_executor is None: + raise MarketDataStoreValidationError( + "Intraday 1m FX requires questdb_dsn or questdb_executor to be configured." + ) + fenced = apply_vault_fence( + from_date, + to_date, + self.vault_cutoff_ts, + as_of=as_of, + scope="vault_fenced", + ) + assert fenced.from_micros is not None + assert fenced.to_micros is not None + assert fenced.as_of_micros is not None + + cutoff_micros = self.vault_cutoff_ts * 1000 + # fx_1m stores bar-start `ts` with no `known_at` column; enforce bar-close availability + # (`bar_close = ts + 60s` strictly < vault_cutoff_ts and <= effective as_of). + max_bar_close_micros = min(fenced.as_of_micros, cutoff_micros - 1) + max_ts_micros = min(fenced.to_micros, max_bar_close_micros - _FX_1M_BAR_DURATION_MICROS) + if max_ts_micros < fenced.from_micros: + return pl.DataFrame(schema=_FX_1M_SCHEMA) + + sql = ( + "SELECT pair, CAST(ts AS LONG) AS ts_us, open, high, low, close, source " + "FROM fx_1m " + "WHERE pair = %s AND ts >= %s AND ts <= %s " + "ORDER BY ts ASC" + ) + params = [ + "USDCAD", + format_utc_iso_micros(fenced.from_micros), + format_utc_iso_micros(max_ts_micros), + ] + raw_rows = self._questdb_executor.query(sql, params) + records: list[dict[str, Any]] = [] + for idx, raw in enumerate(raw_rows): + if not isinstance(raw, Mapping): + raise MarketDataStoreValidationError( + f"QuestDB executor returned a non-mapping fx_1m row at index {idx}." + ) + row_pair = raw.get("pair") + if row_pair != "USDCAD": + raise MarketDataStoreValidationError( + f"Unexpected fx_1m pair {row_pair!r} in result row {idx}; expected 'USDCAD'." + ) + ts_us = _parse_questdb_micros(raw.get("ts_us"), "ts_us", idx) + bar_close_us = ts_us + _FX_1M_BAR_DURATION_MICROS + if ts_us < fenced.from_micros or ts_us > fenced.to_micros: + raise MarketDataStoreValidationError( + f"Row {idx} fx_1m timestamp ts ({ts_us} us) is outside fenced range [{fenced.from_micros}, {fenced.to_micros}] us." + ) + if bar_close_us >= cutoff_micros or bar_close_us > fenced.as_of_micros: + raise MarketDataStoreValidationError( + f"Row {idx} fx_1m bar_close ({bar_close_us} us) exceeds availability fence (as_of={fenced.as_of_micros} us, cutoff={cutoff_micros} us)." + ) + source = raw.get("source") + if not isinstance(source, str) or not source: + raise MarketDataStoreValidationError( + f"Invalid fx_1m source in result row {idx}: {source!r}." + ) + records.append( + { + "pair": row_pair, + "ts": epoch_micros_to_datetime(ts_us), + "open": _read_required_finite_float(raw, "open", idx), + "high": _read_required_finite_float(raw, "high", idx), + "low": _read_required_finite_float(raw, "low", idx), + "close": _read_required_finite_float(raw, "close", idx), + "source": source, + "known_at": epoch_micros_to_datetime(bar_close_us), + } + ) + + if not records: + return pl.DataFrame(schema=_FX_1M_SCHEMA) + return pl.DataFrame(records, schema=_FX_1M_SCHEMA) + + def fx( + self, + *, + pair: str = "USD.CAD", + timeframe: str = "1d", + from_date: str, + to_date: str, + as_of: str | None = None, + ) -> pl.DataFrame: if pair != "USD.CAD": raise MarketDataStoreValidationError(f"Unsupported FX pair: {pair!r}") - fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, scope="vault_fenced") - from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc) - to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc) - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) + if timeframe == "1m": + return self._fx_1m(from_date=from_date, to_date=to_date, as_of=as_of) + if timeframe != "1d": + raise MarketDataStoreValidationError( + f"Unsupported FX timeframe {timeframe!r}. Expected '1d' or '1m'." + ) + fenced = apply_vault_fence( + from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced" + ) + assert fenced.from_micros is not None + assert fenced.to_micros is not None + assert fenced.as_of_micros is not None + + from_ts = epoch_micros_to_datetime(fenced.from_micros) + to_ts = epoch_micros_to_datetime(fenced.to_micros) + as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros) sql = f""" SELECT pair, session_date, ts, open, high, low, close, source, known_at FROM read_parquet('{self._fx_path()}') @@ -274,11 +949,20 @@ class MarketDataStore: def universe(self, *, ref: UniverseRef, on_date: str, lookback_days: int = 7) -> list[int]: if ref not in _UNIVERSE_CURRENCIES: raise MarketDataStoreValidationError(f"Unsupported universe ref: {ref!r}") - fenced = apply_vault_fence(on_date, on_date, self.vault_cutoff_ts, as_of=on_date, scope="vault_fenced") + if not isinstance(on_date, str) or not _DATE_ONLY_RE.match(on_date): + raise MarketDataStoreValidationError( + f'Invalid universe date "{on_date}". Expected a UTC calendar date in YYYY-MM-DD format.' + ) + fenced = apply_vault_fence( + on_date, on_date, self.vault_cutoff_ts, as_of=on_date, scope="vault_fenced" + ) + assert fenced.to_micros is not None + assert fenced.as_of_micros is not None + end_d = date.fromisoformat(on_date) start_d = end_d - timedelta(days=lookback_days) - to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc) - as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc) + to_ts = epoch_micros_to_datetime(fenced.to_micros) + as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros) currencies = _UNIVERSE_CURRENCIES[ref] ph = ", ".join(["?"] * len(currencies)) sql = f""" @@ -293,3 +977,117 @@ class MarketDataStore: """ rows = self._con.execute(sql, [*currencies, start_d, end_d, to_ts, as_of_ts]).fetchall() return [int(r[0]) for r in rows] + + def cross_section( + self, + *, + features: Sequence[str], + date: str, + universe: UniverseRef, + as_of: str | None = None, + lookback_days: int = 7, + ) -> pl.DataFrame: + """Vault-fenced survivorship-free cross-section over materialized feature Parquet partitions. + + Reads `/features//v/year=*/part.parquet` for each canonical + `@v` ref and `LEFT JOIN`s against the active universe on `date`, preserving + NULLs for listings missing a feature observation and ordering by `listing_id ASC`. + """ + if isinstance(features, (str, bytes)) or not isinstance(features, Sequence) or len(features) == 0: + raise MarketDataStoreValidationError( + 'Expected a non-empty sequence of canonical "@v" feature refs.' + ) + if universe not in _UNIVERSE_CURRENCIES: + raise MarketDataStoreValidationError( + f"Unsupported universe ref: {universe!r}. Expected one of: US_EQ, CA_EQ, US_CA_EQ." + ) + if not isinstance(date, str) or not _DATE_ONLY_RE.match(date): + raise MarketDataStoreValidationError( + f'Invalid cross_section date "{date}". Expected a UTC calendar date in YYYY-MM-DD format.' + ) + if isinstance(lookback_days, bool) or not isinstance(lookback_days, int) or lookback_days < 1: + raise MarketDataStoreValidationError( + f"Invalid lookback_days {lookback_days!r}. Expected a positive integer." + ) + + parsed_refs: list[tuple[str, str, int]] = [] + seen_refs: set[str] = set() + for raw_ref in features: + try: + parts = parse_feature_ref(raw_ref) + except FeatureLibraryError as exc: + raise MarketDataStoreValidationError(str(exc)) from exc + canonical = f"{parts.name}@v{parts.version}" + if canonical not in seen_refs: + seen_refs.add(canonical) + parsed_refs.append((canonical, parts.name, parts.version)) + + fenced = apply_vault_fence( + date, + date, + self.vault_cutoff_ts, + as_of=as_of, + scope="vault_fenced", + ) + assert fenced.from_micros is not None + assert fenced.to_micros is not None + assert fenced.as_of_micros is not None + + end_d = epoch_micros_to_datetime(fenced.to_micros).date() + start_d = end_d - timedelta(days=lookback_days) + from_iso = format_utc_iso_micros(fenced.from_micros) + to_iso = format_utc_iso_micros(fenced.to_micros) + as_of_iso = format_utc_iso_micros(fenced.as_of_micros) + universe_known_at_iso = format_utc_iso_micros(min(fenced.to_micros, fenced.as_of_micros)) + + currencies = _UNIVERSE_CURRENCIES[universe] + curr_ph = ", ".join(["?"] * len(currencies)) + + ctes: list[str] = [ + ( + "u AS (" + "SELECT DISTINCT b.listing_id " + f"FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) AS b " + f"WHERE b.currency IN ({curr_ph}) " + "AND b.session_date >= ? " + "AND b.session_date <= ? " + "AND b.ts <= CAST(? AS TIMESTAMPTZ) " + "AND b.known_at <= CAST(? AS TIMESTAMPTZ)" + ")" + ) + ] + params: list[object] = [ + *currencies, + start_d, + end_d, + to_iso, + universe_known_at_iso, + ] + select_cols: list[str] = ["CAST(u.listing_id AS INTEGER) AS listing_id"] + joins: list[str] = [] + + for idx, (canonical_ref, name, version) in enumerate(parsed_refs): + alias = f"f_{idx}" + feat_glob = f"{self.curated_root}/features/{name}/v{version}/year=*/part.parquet" + ctes.append( + f"{alias} AS (" + "SELECT listing_id, CAST(value AS DOUBLE) AS value " + f"FROM read_parquet('{feat_glob}', hive_partitioning = true) " + "WHERE ts >= CAST(? AS TIMESTAMPTZ) " + "AND ts <= CAST(? AS TIMESTAMPTZ) " + "AND known_at <= CAST(? AS TIMESTAMPTZ) " + "QUALIFY ROW_NUMBER() OVER (PARTITION BY listing_id ORDER BY ts DESC, known_at DESC) = 1" + ")" + ) + params.extend([from_iso, to_iso, as_of_iso]) + escaped_col = canonical_ref.replace('"', '""') + select_cols.append(f'{alias}.value AS "{escaped_col}"') + joins.append(f"LEFT JOIN {alias} ON u.listing_id = {alias}.listing_id") + + sql = ( + f"WITH {', '.join(ctes)} " + f"SELECT {', '.join(select_cols)} " + f"FROM u {' '.join(joins)} " + "ORDER BY u.listing_id ASC" + ) + return self._con.execute(sql, params).pl() diff --git a/python/stockbot/features.py b/python/stockbot/features.py new file mode 100644 index 00000000..fd444657 --- /dev/null +++ b/python/stockbot/features.py @@ -0,0 +1,2124 @@ +"""Versioned Feature Library SDK: `register_signal`, SQL/Polars validation, and Vault-fenced batch materialization. + +Mirrors `libs/research/src/feature-library.ts` (D04 / D11) so features registered and +materialized from Python/marimo produce contract-compliant Zstd Parquet readable identically +by both Python `MarketDataStore.cross_section` and TypeScript `MarketDataStore.crossSection`. + +Output Parquet contract (`design/DATA-CONTRACTS.md` §3.A): +- `/features//v/year=YYYY/part.parquet` +- Columns: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, value DOUBLE)` +- Compression: `ZSTD`, ordered by `(listing_id, ts)`. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import uuid +from collections.abc import Iterator, Mapping +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Callable, Literal, Sequence + +import duckdb +import polars as pl + +from .vault import ( + DuckDbConnectionBudget, + MarketDataStoreValidationError, + VaultHoldoutFenceError, + apply_vault_fence, + epoch_micros_to_datetime, + format_utc_iso_micros, + parse_timestamp_micros, + resolve_duckdb_budget, + validate_curated_root, +) + +FeatureFamily = Literal[ + "technical", + "cross_sectional", + "fundamental", + "event", + "fx", + "regime", +] +FeatureKind = Literal["duckdb_sql", "polars"] +FeatureInputDataset = Literal[ + "bars_1d", + "adj_factors", + "events", + "shorts", + "fx_1d", + "fundamentals_pit", + "macro", + "corporate_actions", +] +FeatureKnownAtRule = Literal["bar_close", "source_known_at", "max_input_known_at"] +FeatureLibraryErrorCode = Literal[ + "INVALID_DEFINITION", + "INVALID_NAME", + "INVALID_VERSION", + "INVALID_FAMILY", + "INVALID_KIND", + "INVALID_WARMUP_BARS", + "INVALID_KNOWN_AT_RULE", + "INVALID_FEATURE_REF", + "INVALID_SQL_STATEMENT", + "PROHIBITED_SQL_OPERATION", + "EXTERNAL_DATA_ACCESS", + "INVALID_SQL_PROJECTION", + "UNSUPPORTED_INPUT_DATASET", + "UNDECLARED_INPUT", + "UNUSED_INPUT", + "FEATURE_VERSION_IMMUTABLE", + "INVALID_BATCH_OPTIONS", + "VAULT_RANGE_VIOLATION", + "BATCH_WRITE_FAILED", +] + +PolarsFeatureFn = Callable[[Mapping[str, pl.LazyFrame]], pl.LazyFrame | pl.DataFrame] + +FEATURE_FAMILIES: tuple[FeatureFamily, ...] = ( + "technical", + "cross_sectional", + "fundamental", + "event", + "fx", + "regime", +) +FEATURE_KINDS: tuple[FeatureKind, ...] = ("duckdb_sql", "polars") +FEATURE_INPUT_DATASETS: tuple[FeatureInputDataset, ...] = ( + "bars_1d", + "adj_factors", + "events", + "shorts", + "fx_1d", + "fundamentals_pit", + "macro", + "corporate_actions", +) +FEATURE_KNOWN_AT_RULES: tuple[FeatureKnownAtRule, ...] = ( + "bar_close", + "source_known_at", + "max_input_known_at", +) +FEATURE_OUTPUT_COLUMNS: tuple[str, ...] = ("listing_id", "ts", "known_at", "value") + +_FEATURE_FAMILY_SET: frozenset[str] = frozenset(FEATURE_FAMILIES) +_FEATURE_KIND_SET: frozenset[str] = frozenset(FEATURE_KINDS) +_FEATURE_INPUT_SET: frozenset[str] = frozenset(FEATURE_INPUT_DATASETS) +_FEATURE_KNOWN_AT_RULE_SET: frozenset[str] = frozenset(FEATURE_KNOWN_AT_RULES) + +_FEATURE_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,62}$") +_FEATURE_REF_RE = re.compile(r"^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$") +_PLACEHOLDER_INNER_RE = re.compile(r"^input:([a-z][a-z0-9_]*)$") +_DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") + +_MIN_FOUR_DIGIT_YEAR = 1000 +_MAX_FOUR_DIGIT_YEAR = 9999 + +_PROHIBITED_SQL_KEYWORDS: frozenset[str] = frozenset( + { + "ALTER", + "ANALYZE", + "ATTACH", + "BEGIN", + "CALL", + "CHECKPOINT", + "COMMIT", + "COPY", + "CREATE", + "DEALLOCATE", + "DELETE", + "DESCRIBE", + "DETACH", + "DROP", + "EXECUTE", + "EXPLAIN", + "EXPORT", + "GRANT", + "IMPORT", + "INSERT", + "INSTALL", + "LOAD", + "MERGE", + "PIVOT", + "PRAGMA", + "PREPARE", + "RESET", + "REVOKE", + "ROLLBACK", + "SET", + "SHOW", + "SUMMARIZE", + "TRUNCATE", + "UNPIVOT", + "UPDATE", + "UPSERT", + "USE", + "VACUUM", + } +) + +_EXTERNAL_READER_IDENTIFIERS: frozenset[str] = frozenset( + { + "CURRENT_SETTING", + "DELTA_SCAN", + "DUCKDB_COLUMNS", + "DUCKDB_CONSTRAINTS", + "DUCKDB_DATABASES", + "DUCKDB_DEPENDENCIES", + "DUCKDB_EXTENSIONS", + "DUCKDB_FUNCTIONS", + "DUCKDB_INDEXES", + "DUCKDB_KEYWORDS", + "DUCKDB_MEMORY", + "DUCKDB_OPTIMIZERS", + "DUCKDB_SCHEMAS", + "DUCKDB_SECRETS", + "DUCKDB_SEQUENCES", + "DUCKDB_SETTINGS", + "DUCKDB_TABLES", + "DUCKDB_TEMPORARY_FILES", + "DUCKDB_TYPES", + "DUCKDB_VIEWS", + "GETENV", + "GLOB", + "HTTP_GET", + "ICEBERG_SCAN", + "MYSQL_SCAN", + "PARQUET_FILE_METADATA", + "PARQUET_KV_METADATA", + "PARQUET_METADATA", + "PARQUET_SCAN", + "PARQUET_SCHEMA", + "POSTGRES_SCAN", + "PRAGMA_DATABASE_LIST", + "PRAGMA_STORAGE_INFO", + "PRAGMA_TABLE_INFO", + "READ_BLOB", + "READ_CSV", + "READ_CSV_AUTO", + "READ_EXCEL", + "READ_JSON", + "READ_JSON_AUTO", + "READ_NDJSON", + "READ_NDJSON_AUTO", + "READ_PARQUET", + "READ_STAT", + "READ_TEXT", + "SQLITE_SCAN", + "ST_READ", + } +) + +ALLOWED_SQL_FUNCTIONS: frozenset[str] = frozenset( + { + # Casting & type constructors + "BIT", + "CAST", + "CHAR", + "CHARACTER", + "DECIMAL", + "INTERVAL", + "NUMERIC", + "TIME", + "TIMESTAMP", + "TIMESTAMPTZ", + "TRY_CAST", + "TYPEOF", + "VARCHAR", + # Null / conditional + "COALESCE", + "GREATEST", + "IF", + "IFNULL", + "ISFINITE", + "ISINF", + "ISNAN", + "LEAST", + "NULLIF", + # Math + "ABS", + "ACOS", + "ASIN", + "ATAN", + "ATAN2", + "CBRT", + "CEIL", + "CEILING", + "COS", + "COT", + "DEGREES", + "EXP", + "FLOOR", + "LN", + "LOG", + "LOG10", + "LOG2", + "MOD", + "PI", + "POW", + "POWER", + "RADIANS", + "ROUND", + "SIGN", + "SIN", + "SQRT", + "TAN", + "TRUNC", + # Aggregate + "ANY_VALUE", + "ARG_MAX", + "ARG_MIN", + "AVG", + "CORR", + "COUNT", + "COVAR_POP", + "COVAR_SAMP", + "FIRST", + "GEOMEAN", + "KURTOSIS", + "LAST", + "MAD", + "MAX", + "MEDIAN", + "MIN", + "MODE", + "PERCENTILE_CONT", + "PERCENTILE_DISC", + "PRODUCT", + "QUANTILE", + "QUANTILE_CONT", + "QUANTILE_DISC", + "REGR_INTERCEPT", + "REGR_R2", + "REGR_SLOPE", + "SKEWNESS", + "STDDEV", + "STDDEV_POP", + "STDDEV_SAMP", + "SUM", + "VAR_POP", + "VAR_SAMP", + "VARIANCE", + # Window + "CUME_DIST", + "DENSE_RANK", + "FIRST_VALUE", + "LAG", + "LAST_VALUE", + "LEAD", + "NTH_VALUE", + "NTILE", + "PERCENT_RANK", + "RANK", + "ROW_NUMBER", + # Date / time + "DATE_ADD", + "DATE_DIFF", + "DATE_PART", + "DATE_SUB", + "DATE_TRUNC", + "DATEDIFF", + "DAY", + "DAYOFWEEK", + "DAYOFYEAR", + "EPOCH", + "EPOCH_MS", + "EPOCH_NS", + "EPOCH_US", + "EXTRACT", + "HOUR", + "LAST_DAY", + "MAKE_DATE", + "MAKE_TIMESTAMP", + "MINUTE", + "MONTH", + "QUARTER", + "SECOND", + "STRFTIME", + "STRPTIME", + "TIME_BUCKET", + "WEEK", + "YEAR", + # String & pure JSON + "CONCAT", + "CONCAT_WS", + "CONTAINS", + "ENDS_WITH", + "JSON_EXTRACT", + "JSON_EXTRACT_PATH", + "JSON_EXTRACT_PATH_TEXT", + "JSON_EXTRACT_STRING", + "LEFT", + "LENGTH", + "LOWER", + "LTRIM", + "POSITION", + "RIGHT", + "RTRIM", + "SPLIT_PART", + "STARTS_WITH", + "STRLEN", + "STRPOS", + "SUBSTR", + "SUBSTRING", + "TRIM", + "UPPER", + } +) + +_KEYWORD_BEFORE_LPAREN: frozenset[str] = frozenset( + { + "ALL", + "AND", + "ANY", + "AS", + "ASC", + "BETWEEN", + "BY", + "CASE", + "DESC", + "DISTINCT", + "ELSE", + "EXISTS", + "FILTER", + "FIRST", + "FROM", + "HAVING", + "IN", + "IS", + "JOIN", + "LAST", + "NOT", + "NULLS", + "ON", + "OR", + "ORDER", + "OVER", + "PARTITION", + "QUALIFY", + "SELECT", + "SOME", + "THEN", + "USING", + "VALUES", + "WHEN", + "WHERE", + "WITHIN", + } +) + +_CLAUSE_TERMINATOR_KEYWORDS: frozenset[str] = frozenset( + { + "EXCEPT", + "FETCH", + "FROM", + "GROUP", + "HAVING", + "INTERSECT", + "LIMIT", + "OFFSET", + "ORDER", + "QUALIFY", + "UNION", + "WHERE", + "WINDOW", + } +) + +_JOIN_MODIFIER_KEYWORDS: frozenset[str] = frozenset( + { + "ANTI", + "ASOF", + "CROSS", + "FULL", + "INNER", + "JOIN", + "LEFT", + "NATURAL", + "OUTER", + "POSITIONAL", + "RIGHT", + "SEMI", + } +) + +_NON_ALIAS_KEYWORDS: frozenset[str] = ( + _CLAUSE_TERMINATOR_KEYWORDS | _JOIN_MODIFIER_KEYWORDS | frozenset({"ON", "USING"}) +) + +_PATH_OR_URI_PREFIX_RE = re.compile( + r"^(?:/|\./|\.\./|~/|(?:s3|gs|http|https|file|hf|az|r2)://)", re.IGNORECASE +) +_PATH_EXTENSION_RE = re.compile( + r"\.(?:parquet|csv|tsv|json|jsonl|ndjson|duckdb|db|sqlite|txt|gz|zst)$", re.IGNORECASE +) +_PATH_GLOB_OR_TRAVERSAL_RE = re.compile(r"(?:^|/)\.\.(?:/|$)|/\*|\*\.") + + +@dataclass(frozen=True) +class _DatasetScanSpec: + relative_path: str + hive_partitioning: bool + predicate_kind: Literal["ts_and_known_at", "known_at", "effective_known_at"] + + +_DATASET_SCAN_SPECS: dict[FeatureInputDataset, _DatasetScanSpec] = { + "bars_1d": _DatasetScanSpec("bars_1d/year=*/part.parquet", True, "ts_and_known_at"), + "adj_factors": _DatasetScanSpec("adj_factors/part.parquet", False, "known_at"), + "events": _DatasetScanSpec("events/year=*/*.parquet", True, "ts_and_known_at"), + "shorts": _DatasetScanSpec("shorts/part.parquet", False, "known_at"), + "fx_1d": _DatasetScanSpec("fx_1d/part.parquet", False, "ts_and_known_at"), + "fundamentals_pit": _DatasetScanSpec( + "fundamentals_pit/year=*/part.parquet", True, "effective_known_at" + ), + "macro": _DatasetScanSpec("macro/part.parquet", False, "known_at"), + "corporate_actions": _DatasetScanSpec("corporate_actions/part.parquet", False, "known_at"), +} + + +@dataclass(frozen=True) +class FeatureBatchWriteReceipt: + year: int + output_path: str + + +class FeatureLibraryError(ValueError): + """Typed fail-closed error thrown by the Feature Library SDK.""" + + def __init__( + self, + code: FeatureLibraryErrorCode, + message: str, + *, + cause: BaseException | None = None, + failed_year: int | None = None, + completed_years: Sequence[int] | None = None, + completed_writes: Sequence[FeatureBatchWriteReceipt] | None = None, + ref: str | None = None, + ) -> None: + super().__init__(message) + self.code: FeatureLibraryErrorCode = code + self.failed_year = failed_year + self.completed_years = tuple(completed_years) if completed_years is not None else None + self.completed_writes = tuple(completed_writes) if completed_writes is not None else None + self.ref = ref + if cause is not None: + self.__cause__ = cause + + +@dataclass(frozen=True) +class FeatureDefinition: + name: str + version: int + family: FeatureFamily + kind: FeatureKind + inputs: tuple[FeatureInputDataset, ...] + warmup_bars: int + known_at_rule: FeatureKnownAtRule + sql: str | None = None + polars_fn: PolarsFeatureFn | None = None + expression: str | None = None + description: str | None = None + + def __post_init__(self) -> None: + if isinstance(self.inputs, (list, tuple)): + object.__setattr__(self, "inputs", tuple(self.inputs)) + + +@dataclass(frozen=True) +class FeatureRefParts: + name: str + version: int + + +@dataclass(frozen=True) +class RegisteredFeature: + ref: str + definition_hash: str + definition: FeatureDefinition + + +@dataclass(frozen=True) +class PlannedFeatureWrite: + year: int + output_path: str + sql: str + params: tuple[Any, ...] + + +@dataclass(frozen=True) +class FeatureBatchManifest: + ref: str + definition_hash: str + known_at_rule: FeatureKnownAtRule + warmup_bars: int + inputs: tuple[FeatureInputDataset, ...] + writes: tuple[FeatureBatchWriteReceipt, ...] + + +@dataclass(frozen=True) +class _SqlToken: + kind: Literal[ + "word", + "quoted_ident", + "string", + "number", + "placeholder", + "lparen", + "rparen", + "comma", + "dot", + "op", + ] + raw: str + value: str = "" + upper: str = "" + dataset: str = "" + + +def _is_ascii_whitespace(ch: str) -> bool: + return ch in (" ", "\t", "\n", "\r", "\f") + + +def _is_ident_start(ch: str) -> bool: + code = ord(ch) + return (0x41 <= code <= 0x5A) or (0x61 <= code <= 0x7A) or code == 0x5F + + +def _is_ident_continue(ch: str) -> bool: + code = ord(ch) + return _is_ident_start(ch) or (0x30 <= code <= 0x39) + + +def _is_digit(ch: str) -> bool: + code = ord(ch) + return 0x30 <= code <= 0x39 + + +def _looks_like_external_path(value: str) -> bool: + return bool( + _PATH_OR_URI_PREFIX_RE.search(value) + or _PATH_EXTENSION_RE.search(value) + or _PATH_GLOB_OR_TRAVERSAL_RE.search(value) + ) + + +def _fold_ascii_identifier(identifier: str) -> str: + """Folds ASCII A-Z only, matching DuckDB identifier folding.""" + out: list[str] = [] + for ch in identifier: + code = ord(ch) + if 0x41 <= code <= 0x5A: + out.append(chr(code + 32)) + else: + out.append(ch) + return "".join(out) + + +def _tokenize_feature_sql(sql: str) -> list[_SqlToken]: + tokens: list[_SqlToken] = [] + n = len(sql) + i = 0 + + while i < n: + ch = sql[i] + if _is_ascii_whitespace(ch): + i += 1 + continue + + # Reject SQL comments (-- or /* ... */) + if ch == "-" and i + 1 < n and sql[i + 1] == "-": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'SQL line comments ("--") are not permitted in feature definitions.', + ) + if ch == "/" and i + 1 < n and sql[i + 1] == "*": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'SQL block comments ("/* ... */") are not permitted in feature definitions.', + ) + if ch == "*" and i + 1 < n and sql[i + 1] == "/": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'Unexpected SQL block comment terminator ("*/") in feature definition.', + ) + + # Reject statement separators (;) + if ch == ";": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'Multiple SQL statements or semicolons (";") are not permitted in feature definitions.', + ) + + # Reject caller-supplied bind markers (?, $1, $name) + if ch == "?": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'Caller-supplied bind markers ("?") are not permitted in feature definitions.', + ) + if ch == "$": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'Dollar-prefixed parameters or dollar-quoted strings ("$") are not permitted in feature definitions.', + ) + + # Placeholder: {{input:}} + if ch == "{" and i + 1 < n and sql[i + 1] == "{": + close_idx = sql.find("}}", i + 2) + if close_idx == -1: + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'Unterminated placeholder "{{" in feature SQL.', + ) + inner = sql[i + 2 : close_idx] + m = _PLACEHOLDER_INNER_RE.match(inner) + if m is None: + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + f'Malformed input placeholder "{{{{{inner}}}}}". Expected "{{{{input:}}}}".', + ) + dataset = m.group(1) + raw = sql[i : close_idx + 2] + tokens.append(_SqlToken(kind="placeholder", raw=raw, dataset=dataset)) + i = close_idx + 2 + continue + + # Single-quoted string literal + if ch == "'": + start = i + i += 1 + chars: list[str] = [] + closed = False + while i < n: + c = sql[i] + if c == "'": + if i + 1 < n and sql[i + 1] == "'": + chars.append("'") + i += 2 + continue + i += 1 + closed = True + break + chars.append(c) + i += 1 + if not closed: + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "Unterminated single-quoted string literal in feature SQL.", + ) + tokens.append(_SqlToken(kind="string", raw=sql[start:i], value="".join(chars))) + continue + + # Double-quoted identifier + if ch == '"': + start = i + i += 1 + chars = [] + closed = False + while i < n: + c = sql[i] + if c == '"': + if i + 1 < n and sql[i + 1] == '"': + chars.append('"') + i += 2 + continue + i += 1 + closed = True + break + chars.append(c) + i += 1 + val = "".join(chars) + if not closed or not val: + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "Unterminated or empty double-quoted identifier in feature SQL.", + ) + tokens.append(_SqlToken(kind="quoted_ident", raw=sql[start:i], value=val)) + continue + + # Unquoted word + if _is_ident_start(ch): + start = i + i += 1 + while i < n and _is_ident_continue(sql[i]): + i += 1 + val = sql[start:i] + tokens.append(_SqlToken(kind="word", raw=val, value=val, upper=val.upper())) + continue + + # Numeric literal + if _is_digit(ch) or (ch == "." and i + 1 < n and _is_digit(sql[i + 1])): + start = i + has_dot = False + if ch == ".": + has_dot = True + i += 1 + while i < n and _is_digit(sql[i]): + i += 1 + if not has_dot and i < n and sql[i] == ".": + i += 1 + while i < n and _is_digit(sql[i]): + i += 1 + if i < n and sql[i] in ("e", "E"): + exp_pos = i + i += 1 + if i < n and sql[i] in ("+", "-"): + i += 1 + if i >= n or not _is_digit(sql[i]): + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + f"Malformed numeric exponent at offset {exp_pos} in feature SQL.", + ) + while i < n and _is_digit(sql[i]): + i += 1 + tokens.append(_SqlToken(kind="number", raw=sql[start:i])) + continue + + # Punctuation + if ch == "(": + tokens.append(_SqlToken(kind="lparen", raw="(")) + i += 1 + continue + if ch == ")": + tokens.append(_SqlToken(kind="rparen", raw=")")) + i += 1 + continue + if ch == ",": + tokens.append(_SqlToken(kind="comma", raw=",")) + i += 1 + continue + if ch == ".": + tokens.append(_SqlToken(kind="dot", raw=".")) + i += 1 + continue + + # Two-character operators + if i + 1 < n: + two = sql[i : i + 2] + if two in ("<>", "!=", "<=", ">=", "||", "::"): + tokens.append(_SqlToken(kind="op", raw=two)) + i += 2 + continue + + # Reject single ':' (named bind marker) + if ch == ":": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'Colon-prefixed bind markers (":name") are not permitted in feature definitions.', + ) + + # Single-character operators + if ch in ("+", "-", "*", "/", "%", "=", "<", ">"): + tokens.append(_SqlToken(kind="op", raw=ch)) + i += 1 + continue + + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + f'Unsupported token character "{ch}" at offset {i} in feature SQL.', + ) + + return tokens + + +def _find_matching_paren(tokens: Sequence[_SqlToken], open_idx: int, end: int) -> int: + depth = 0 + for i in range(open_idx, end): + tok = tokens[i] + if tok.kind == "lparen": + depth += 1 + elif tok.kind == "rparen": + depth -= 1 + if depth == 0: + return i + raise FeatureLibraryError("INVALID_SQL_STATEMENT", "Unbalanced parentheses in feature SQL.") + + +def _assert_balanced_parens(tokens: Sequence[_SqlToken]) -> None: + depth = 0 + for tok in tokens: + if tok.kind == "lparen": + depth += 1 + elif tok.kind == "rparen": + depth -= 1 + if depth < 0: + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'Unbalanced closing parenthesis ")" in feature SQL.', + ) + if depth != 0: + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + 'Unbalanced opening parenthesis "(" in feature SQL.', + ) + + +def _extract_identifier_text(tok: _SqlToken | None) -> str | None: + if tok is None: + return None + if tok.kind == "word": + return tok.value.lower() + if tok.kind == "quoted_ident": + return tok.value + return None + + +def _extract_projection_output_name(tokens: Sequence[_SqlToken], start: int, end: int) -> str: + if start >= end: + raise FeatureLibraryError( + "INVALID_SQL_PROJECTION", + "Empty projection expression in final SELECT list.", + ) + + depth = 0 + for i in range(start, end): + tok = tokens[i] + if tok.kind == "lparen": + depth += 1 + elif tok.kind == "rparen": + depth -= 1 + elif depth == 0 and tok.kind == "op" and tok.raw == "*": + prev = tokens[i - 1] if i > start else None + if prev is None or prev.kind == "dot": + raise FeatureLibraryError( + "INVALID_SQL_PROJECTION", + 'Wildcard projections ("*" / "alias.*") are not permitted; final SELECT must explicitly project listing_id, ts, known_at, value.', + ) + + if end - start >= 3: + as_tok = tokens[end - 2] + alias_tok = tokens[end - 1] + if as_tok.kind == "word" and as_tok.upper == "AS": + alias = _extract_identifier_text(alias_tok) + if alias is None: + raise FeatureLibraryError( + "INVALID_SQL_PROJECTION", + "Expected an output column identifier after AS in final SELECT projection.", + ) + return alias + + if end - start == 1: + name = _extract_identifier_text(tokens[start]) + if name is not None: + return name + if end - start == 3 and tokens[start + 1].kind == "dot": + qual = _extract_identifier_text(tokens[start]) + col = _extract_identifier_text(tokens[start + 2]) + if qual is not None and col is not None: + return col + + raise FeatureLibraryError( + "INVALID_SQL_PROJECTION", + "Every expression in the final SELECT list must be a direct column reference or use an explicit AS alias matching (listing_id, ts, known_at, value).", + ) + + +def _has_top_level_set_operator(tokens: Sequence[_SqlToken], start: int, end: int) -> bool: + depth = 0 + for i in range(start, end): + tok = tokens[i] + if tok.kind == "lparen": + depth += 1 + elif tok.kind == "rparen": + depth -= 1 + elif depth == 0 and tok.kind == "word" and tok.upper in ("UNION", "INTERSECT", "EXCEPT"): + return True + return False + + +def _validate_expression_slice( + tokens: Sequence[_SqlToken], start: int, end: int, in_scope_ctes: set[str] +) -> None: + i = start + while i < end: + tok = tokens[i] + + if tok.kind == "lparen": + close_idx = _find_matching_paren(tokens, i, end) + inner_first = tokens[i + 1] if i + 1 < close_idx else None + if ( + inner_first is not None + and inner_first.kind == "word" + and inner_first.upper in ("SELECT", "WITH") + ) or _has_top_level_set_operator(tokens, i + 1, close_idx): + _validate_query_slice(tokens, i + 1, close_idx, in_scope_ctes, False) + i = close_idx + 1 + continue + if ( + inner_first is not None + and inner_first.kind == "word" + and inner_first.upper in ("FROM", "TABLE") + ): + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + f'Unsupported subquery form "({inner_first.upper} ...)" in feature SQL; subqueries must begin with SELECT or WITH.', + ) + i += 1 + continue + + if tok.kind == "word" and tok.upper == "JOIN": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "Unexpected JOIN outside a parsed FROM/JOIN clause in feature SQL.", + ) + + if ( + tok.kind in ("word", "quoted_ident") + and i + 1 < end + and tokens[i + 1].kind == "lparen" + ): + upper = tok.upper if tok.kind == "word" else tok.value.upper() + if tok.kind == "word" and upper in _KEYWORD_BEFORE_LPAREN: + i += 1 + continue + if i > start and tokens[i - 1].kind == "dot": + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + f'Schema-qualified function call ".{tok.raw}(...)" is not permitted in feature SQL.', + ) + if upper not in ALLOWED_SQL_FUNCTIONS: + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + f'Unsupported or prohibited SQL function "{tok.raw}(...)" in feature SQL.', + ) + + i += 1 + + +def _parse_table_reference( + tokens: Sequence[_SqlToken], start: int, end: int, in_scope_ctes: set[str] +) -> int: + if start >= end: + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "Expected a relation source after FROM or JOIN in feature SQL.", + ) + + pos = start + tok = tokens[pos] + + if tok.kind == "placeholder": + pos += 1 + elif tok.kind == "lparen": + close_idx = _find_matching_paren(tokens, pos, end) + inner_first = tokens[pos + 1] if pos + 1 < close_idx else None + if ( + inner_first is None + or inner_first.kind != "word" + or inner_first.upper not in ("SELECT", "WITH") + ): + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + "Parenthesized relation source must be a SELECT or WITH subquery.", + ) + _validate_query_slice(tokens, pos + 1, close_idx, in_scope_ctes, False) + pos = close_idx + 1 + elif tok.kind in ("word", "quoted_ident"): + nxt = tokens[pos + 1] if pos + 1 < end else None + if nxt is not None and nxt.kind == "lparen": + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + f'Table function "{tok.raw}(...)" is not permitted as a relation source in feature SQL.', + ) + if nxt is not None and nxt.kind == "dot": + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + f'Catalog or schema-qualified relation "{tok.raw}...." is not permitted; use {{{{input:}}}} placeholders.', + ) + cte_name = _fold_ascii_identifier(tok.value) + if cte_name not in in_scope_ctes: + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + f'Direct table reference "{tok.raw}" is not an in-scope CTE; use {{{{input:}}}} placeholders.', + ) + pos += 1 + else: + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + f'Unsupported relation source "{tok.raw}" in feature SQL; use {{{{input:}}}}, an in-scope CTE, or a subquery.', + ) + + if pos < end: + maybe_as = tokens[pos] + if maybe_as.kind == "word" and maybe_as.upper == "AS": + pos += 1 + if pos >= end or tokens[pos].kind not in ("word", "quoted_ident"): + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "Expected table alias identifier after AS.", + ) + pos += 1 + elif ( + maybe_as.kind == "word" and maybe_as.upper not in _NON_ALIAS_KEYWORDS + ) or maybe_as.kind == "quoted_ident": + pos += 1 + + if pos < end and tokens[pos].kind == "lparen": + pos = _find_matching_paren(tokens, pos, end) + 1 + + return pos + + +def _is_join_clause_start(tokens: Sequence[_SqlToken], start: int, end: int) -> bool: + pos = start + while pos < end: + tok = tokens[pos] + if tok.kind != "word" or tok.upper not in _JOIN_MODIFIER_KEYWORDS: + return False + if tok.upper == "JOIN": + return True + pos += 1 + return False + + +def _validate_select_branch( + tokens: Sequence[_SqlToken], + start: int, + end: int, + in_scope_ctes: set[str], + require_contract_projection: bool, +) -> None: + if start >= end: + raise FeatureLibraryError("INVALID_SQL_STATEMENT", "Empty SELECT branch in feature SQL.") + + if tokens[start].kind == "lparen": + close_idx = _find_matching_paren(tokens, start, end) + if close_idx == end - 1: + _validate_query_slice( + tokens, start + 1, close_idx, in_scope_ctes, require_contract_projection + ) + return + + first = tokens[start] + if first.kind != "word" or first.upper != "SELECT": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + f'Expected SELECT statement, got "{first.raw}".', + ) + + pos = start + 1 + if pos < end and tokens[pos].kind == "word" and tokens[pos].upper in ("DISTINCT", "ALL"): + pos += 1 + + depth = 0 + proj_end = end + for i in range(pos, end): + tok = tokens[i] + if tok.kind == "lparen": + depth += 1 + elif tok.kind == "rparen": + depth -= 1 + elif depth == 0 and tok.kind == "word" and tok.upper in _CLAUSE_TERMINATOR_KEYWORDS: + proj_end = i + break + + if proj_end == pos: + raise FeatureLibraryError( + "INVALID_SQL_PROJECTION", + "SELECT clause has an empty projection list.", + ) + + _validate_expression_slice(tokens, pos, proj_end, in_scope_ctes) + + if require_contract_projection: + item_bounds: list[tuple[int, int]] = [] + item_start = pos + depth = 0 + for i in range(pos, proj_end): + tok = tokens[i] + if tok.kind == "lparen": + depth += 1 + elif tok.kind == "rparen": + depth -= 1 + elif depth == 0 and tok.kind == "comma": + item_bounds.append((item_start, i)) + item_start = i + 1 + item_bounds.append((item_start, proj_end)) + + if len(item_bounds) != len(FEATURE_OUTPUT_COLUMNS): + raise FeatureLibraryError( + "INVALID_SQL_PROJECTION", + f"Final SELECT must project exactly {len(FEATURE_OUTPUT_COLUMNS)} columns ({', '.join(FEATURE_OUTPUT_COLUMNS)}), got {len(item_bounds)}.", + ) + + for idx, (b_start, b_end) in enumerate(item_bounds): + actual_name = _extract_projection_output_name(tokens, b_start, b_end) + expected_name = FEATURE_OUTPUT_COLUMNS[idx] + if actual_name != expected_name: + raise FeatureLibraryError( + "INVALID_SQL_PROJECTION", + f'Final SELECT column #{idx + 1} must be named "{expected_name}", got "{actual_name}".', + ) + + pos = proj_end + while pos < end: + tok = tokens[pos] + if tok.kind == "word" and tok.upper == "FROM": + pos += 1 + pos = _parse_table_reference(tokens, pos, end, in_scope_ctes) + while pos < end: + next_tok = tokens[pos] + if next_tok.kind == "comma": + pos += 1 + pos = _parse_table_reference(tokens, pos, end, in_scope_ctes) + continue + if next_tok.kind == "word" and next_tok.upper in _JOIN_MODIFIER_KEYWORDS: + found_join = False + while pos < end: + j_tok = tokens[pos] + if j_tok.kind == "word" and j_tok.upper in _JOIN_MODIFIER_KEYWORDS: + pos += 1 + if j_tok.upper == "JOIN": + found_join = True + break + else: + break + if not found_join: + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "Malformed JOIN clause in feature SQL.", + ) + pos = _parse_table_reference(tokens, pos, end, in_scope_ctes) + + if pos < end and tokens[pos].kind == "word" and tokens[pos].upper in ("ON", "USING"): + cond_start = pos + 1 + cond_end = end + c_depth = 0 + for k in range(cond_start, end): + ct = tokens[k] + if ct.kind == "lparen": + c_depth += 1 + elif ct.kind == "rparen": + c_depth -= 1 + elif c_depth == 0 and ( + ct.kind == "comma" + or ( + ct.kind == "word" + and ( + ct.upper in _CLAUSE_TERMINATOR_KEYWORDS + or _is_join_clause_start(tokens, k, end) + ) + ) + ): + cond_end = k + break + _validate_expression_slice(tokens, cond_start, cond_end, in_scope_ctes) + pos = cond_end + continue + break + + if pos < end: + after_from = tokens[pos] + if ( + after_from.kind != "word" + or after_from.upper not in _CLAUSE_TERMINATOR_KEYWORDS + or after_from.upper == "FROM" + ): + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + f'Unexpected token "{after_from.raw}" after FROM/JOIN clause in feature SQL.', + ) + continue + + expr_start = pos + expr_end = end + e_depth = 0 + for k in range(expr_start + 1, end): + et = tokens[k] + if et.kind == "lparen": + e_depth += 1 + elif et.kind == "rparen": + e_depth -= 1 + elif e_depth == 0 and et.kind == "word" and et.upper == "FROM": + expr_end = k + break + _validate_expression_slice(tokens, expr_start, expr_end, in_scope_ctes) + pos = expr_end + + +def _validate_query_slice( + tokens: Sequence[_SqlToken], + start: int, + end: int, + outer_ctes: set[str], + require_contract_projection: bool, +) -> None: + if start >= end: + raise FeatureLibraryError("INVALID_SQL_STATEMENT", "Empty SQL query in feature definition.") + + in_scope_ctes = set(outer_ctes) + pos = start + + if tokens[pos].kind == "word" and tokens[pos].upper == "WITH": + pos += 1 + if pos < end and tokens[pos].kind == "word" and tokens[pos].upper == "RECURSIVE": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "WITH RECURSIVE CTEs are not permitted in feature SQL; use non-recursive CTEs.", + ) + + while pos < end: + name_tok = tokens[pos] + if name_tok.kind not in ("word", "quoted_ident"): + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "Expected CTE name identifier after WITH in feature SQL.", + ) + cte_name = _fold_ascii_identifier(name_tok.value) + pos += 1 + + if pos < end and tokens[pos].kind == "lparen": + pos = _find_matching_paren(tokens, pos, end) + 1 + + if pos >= end or tokens[pos].kind != "word" or tokens[pos].upper != "AS": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + f'Expected AS after CTE name "{name_tok.raw}" in feature SQL.', + ) + pos += 1 + + if pos < end and tokens[pos].kind == "word" and tokens[pos].upper == "NOT": + pos += 1 + if pos < end and tokens[pos].kind == "word" and tokens[pos].upper == "MATERIALIZED": + pos += 1 + + if pos >= end or tokens[pos].kind != "lparen": + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + f'Expected "(" opening CTE body for "{name_tok.raw}" in feature SQL.', + ) + body_close = _find_matching_paren(tokens, pos, end) + _validate_query_slice(tokens, pos + 1, body_close, in_scope_ctes, False) + in_scope_ctes.add(cte_name) + pos = body_close + 1 + + if pos < end and tokens[pos].kind == "comma": + pos += 1 + continue + break + + branches: list[tuple[int, int]] = [] + branch_start = pos + depth = 0 + i = pos + while i < end: + tok = tokens[i] + if tok.kind == "lparen": + depth += 1 + elif tok.kind == "rparen": + depth -= 1 + elif depth == 0 and tok.kind == "word" and tok.upper in ("UNION", "INTERSECT", "EXCEPT"): + branches.append((branch_start, i)) + next_pos = i + 1 + if ( + next_pos < end + and tokens[next_pos].kind == "word" + and tokens[next_pos].upper in ("ALL", "DISTINCT") + ): + next_pos += 1 + branch_start = next_pos + i = next_pos + continue + i += 1 + branches.append((branch_start, end)) + + for b_start, b_end in branches: + _validate_select_branch( + tokens, b_start, b_end, in_scope_ctes, require_contract_projection + ) + + +@dataclass(frozen=True) +class _ValidatedFeatureInternal: + defn: FeatureDefinition + tokens: tuple[_SqlToken, ...] + normalized_inputs: tuple[FeatureInputDataset, ...] + + +def _validate_name(name: Any) -> str: + if not isinstance(name, str) or not _FEATURE_NAME_RE.match(name): + raise FeatureLibraryError( + "INVALID_NAME", + f'Invalid feature name "{name}". Expected ^[a-z][a-z0-9_]{{0,62}}$.', + ) + return name + + +def _validate_version(version: Any) -> int: + if isinstance(version, bool) or not isinstance(version, int) or version < 1: + raise FeatureLibraryError( + "INVALID_VERSION", + f'Invalid feature version "{version}". Expected a positive integer.', + ) + return version + + +def _validate_feature_definition_internal(defn: FeatureDefinition) -> _ValidatedFeatureInternal: + if not isinstance(defn, FeatureDefinition): + raise FeatureLibraryError( + "INVALID_DEFINITION", + "Feature definition must be a FeatureDefinition instance.", + ) + + _validate_name(defn.name) + _validate_version(defn.version) + + if not isinstance(defn.family, str) or defn.family not in _FEATURE_FAMILY_SET: + raise FeatureLibraryError( + "INVALID_FAMILY", + f'Invalid feature family "{defn.family}". Expected one of: {", ".join(FEATURE_FAMILIES)}.', + ) + + if not isinstance(defn.kind, str) or defn.kind not in _FEATURE_KIND_SET: + raise FeatureLibraryError( + "INVALID_KIND", + f'Invalid feature kind "{defn.kind}". Expected one of: {", ".join(FEATURE_KINDS)}.', + ) + + if isinstance(defn.warmup_bars, bool) or not isinstance(defn.warmup_bars, int) or defn.warmup_bars < 0: + raise FeatureLibraryError( + "INVALID_WARMUP_BARS", + f'Invalid warmup_bars "{defn.warmup_bars}". Expected a non-negative integer.', + ) + + if not isinstance(defn.known_at_rule, str) or defn.known_at_rule not in _FEATURE_KNOWN_AT_RULE_SET: + raise FeatureLibraryError( + "INVALID_KNOWN_AT_RULE", + f'Invalid known_at_rule "{defn.known_at_rule}". Expected one of: {", ".join(FEATURE_KNOWN_AT_RULES)}.', + ) + + if defn.description is not None and not isinstance(defn.description, str): + raise FeatureLibraryError( + "INVALID_DEFINITION", + "Feature description must be a string when provided.", + ) + + if not isinstance(defn.inputs, (tuple, list)) or len(defn.inputs) == 0: + raise FeatureLibraryError( + "INVALID_DEFINITION", + "Feature definition must declare a non-empty inputs sequence.", + ) + + declared_set: set[FeatureInputDataset] = set() + normalized_inputs: list[FeatureInputDataset] = [] + for raw_input in defn.inputs: + if not isinstance(raw_input, str) or raw_input not in _FEATURE_INPUT_SET: + raise FeatureLibraryError( + "UNSUPPORTED_INPUT_DATASET", + f'Unsupported input dataset "{raw_input}". Allowed datasets: {", ".join(FEATURE_INPUT_DATASETS)}.', + ) + ds: FeatureInputDataset = raw_input # type: ignore[assignment] + if ds not in declared_set: + declared_set.add(ds) + normalized_inputs.append(ds) + + if defn.kind == "polars": + if defn.polars_fn is None or not callable(defn.polars_fn): + raise FeatureLibraryError( + "INVALID_DEFINITION", + "Polars feature definition requires a callable polars_fn.", + ) + if not isinstance(defn.expression, str) or not defn.expression.strip(): + raise FeatureLibraryError( + "INVALID_DEFINITION", + "Polars feature definition requires a non-empty canonical expression string for hashing.", + ) + return _ValidatedFeatureInternal( + defn=defn, + tokens=(), + normalized_inputs=tuple(normalized_inputs), + ) + + # kind == "duckdb_sql" + if not isinstance(defn.sql, str) or not defn.sql.strip(): + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "Feature SQL must be a non-empty string.", + ) + + tokens = _tokenize_feature_sql(defn.sql) + if not tokens: + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + "Feature SQL must contain a SELECT or WITH statement.", + ) + + # Pass 1: prohibited keywords + for tok in tokens: + if tok.kind == "word" and tok.upper in _PROHIBITED_SQL_KEYWORDS: + raise FeatureLibraryError( + "PROHIBITED_SQL_OPERATION", + f'Prohibited SQL operation "{tok.raw}" is not permitted in feature definitions.', + ) + + # Pass 2: external readers and quoted paths/URIs + for tok in tokens: + if tok.kind == "word" and tok.upper in _EXTERNAL_READER_IDENTIFIERS: + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + f'Direct external reader "{tok.raw}" is not permitted; reference datasets via {{{{input:}}}}.', + ) + if tok.kind == "quoted_ident" and tok.value.upper() in _EXTERNAL_READER_IDENTIFIERS: + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + f"Direct external reader {tok.raw} is not permitted; reference datasets via {{{{input:}}}}.", + ) + if tok.kind in ("string", "quoted_ident") and _looks_like_external_path(tok.value): + raise FeatureLibraryError( + "EXTERNAL_DATA_ACCESS", + f"Quoted file path or URI {tok.raw} is not permitted in feature SQL; reference datasets via {{{{input:}}}}.", + ) + + # Pass 3: leading keyword & balanced parens + first_tok = tokens[0] + if first_tok.kind != "word" or first_tok.upper not in ("SELECT", "WITH"): + raise FeatureLibraryError( + "INVALID_SQL_STATEMENT", + f'Feature SQL must begin with SELECT or WITH, got "{first_tok.raw}".', + ) + _assert_balanced_parens(tokens) + + # Pass 4: structural CTE / FROM / JOIN / function / projection validation + _validate_query_slice(tokens, 0, len(tokens), set(), True) + + # Pass 5: placeholder <-> inputs 1-to-1 check + used_inputs: set[FeatureInputDataset] = set() + for tok in tokens: + if tok.kind != "placeholder": + continue + if tok.dataset not in declared_set: + raise FeatureLibraryError( + "UNDECLARED_INPUT", + f'SQL placeholder "{{{{input:{tok.dataset}}}}}" is not declared in definition.inputs.', + ) + used_inputs.add(tok.dataset) # type: ignore[arg-type] + + for declared in normalized_inputs: + if declared not in used_inputs: + raise FeatureLibraryError( + "UNUSED_INPUT", + f'Declared input dataset "{declared}" is not referenced via "{{{{input:{declared}}}}}" in feature SQL.', + ) + + return _ValidatedFeatureInternal( + defn=defn, + tokens=tuple(tokens), + normalized_inputs=tuple(normalized_inputs), + ) + + +def validate_feature_definition(defn: FeatureDefinition) -> None: + """Validates a feature definition and raises `FeatureLibraryError` on any violation.""" + _validate_feature_definition_internal(defn) + + +def feature_ref(defn: FeatureDefinition | Mapping[str, Any]) -> str: + """Formats the canonical versioned feature reference `@v`.""" + if isinstance(defn, FeatureDefinition): + name = _validate_name(defn.name) + version = _validate_version(defn.version) + elif isinstance(defn, Mapping): + name = _validate_name(defn.get("name")) + version = _validate_version(defn.get("version")) + else: + raise FeatureLibraryError( + "INVALID_DEFINITION", + "Expected a FeatureDefinition or mapping with name and version for feature_ref.", + ) + return f"{name}@v{version}" + + +def parse_feature_ref(ref: str) -> FeatureRefParts: + """Parses a canonical `@v` feature ref, rejecting non-canonical forms.""" + if not isinstance(ref, str): + raise FeatureLibraryError( + "INVALID_FEATURE_REF", + f'Invalid feature ref "{ref}". Expected "@v".', + ) + m = _FEATURE_REF_RE.match(ref) + if m is None: + raise FeatureLibraryError( + "INVALID_FEATURE_REF", + f'Invalid feature ref "{ref}". Expected "@v" with lowercase name and canonical positive integer version.', + ) + name = m.group(1) + version = int(m.group(2)) + return FeatureRefParts(name=name, version=version) + + +def _canonicalize_sql_tokens(tokens: Sequence[_SqlToken]) -> str: + return " ".join(tok.raw for tok in tokens) + + +def feature_definition_hash(defn: FeatureDefinition) -> str: + """Computes deterministic 64-hex SHA-256 matching TypeScript `featureDefinitionHash`.""" + validated = _validate_feature_definition_internal(defn) + sorted_inputs = sorted(validated.normalized_inputs) + if defn.kind == "duckdb_sql": + payload: dict[str, Any] = { + "name": defn.name, + "version": defn.version, + "kind": defn.kind, + "sql": _canonicalize_sql_tokens(validated.tokens), + "inputs": sorted_inputs, + "warmupBars": defn.warmup_bars, + "knownAtRule": defn.known_at_rule, + } + else: + assert defn.expression is not None + payload = { + "name": defn.name, + "version": defn.version, + "kind": defn.kind, + "expression": " ".join(defn.expression.strip().split()), + "inputs": sorted_inputs, + "warmupBars": defn.warmup_bars, + "knownAtRule": defn.known_at_rule, + } + encoded = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +class FeatureRegistry: + """In-memory immutable versioned feature registry (`register_signal` SDK entrypoint, D11).""" + + def __init__(self) -> None: + self._entries: dict[str, RegisteredFeature] = {} + + def register_signal(self, defn: FeatureDefinition) -> RegisteredFeature: + _validate_feature_definition_internal(defn) + ref = feature_ref(defn) + def_hash = feature_definition_hash(defn) + existing = self._entries.get(ref) + if existing is not None: + if existing.definition_hash == def_hash: + return existing + raise FeatureLibraryError( + "FEATURE_VERSION_IMMUTABLE", + f'Feature "{ref}" is already registered with hash {existing.definition_hash}; cannot overwrite with {def_hash}. Bump version to register a changed definition.', + ref=ref, + ) + stored = RegisteredFeature(ref=ref, definition_hash=def_hash, definition=defn) + self._entries[ref] = stored + return stored + + def get(self, ref: str) -> FeatureDefinition | None: + if not isinstance(ref, str): + return None + entry = self._entries.get(ref) + return entry.definition if entry is not None else None + + def list(self) -> tuple[str, ...]: + return tuple(self._entries.keys()) + + +def create_feature_registry() -> FeatureRegistry: + """Creates an isolated in-memory `FeatureRegistry`.""" + return FeatureRegistry() + + +_DEFAULT_REGISTRY = create_feature_registry() + + +def register_signal( + defn: FeatureDefinition | None = None, + *, + name: str | None = None, + version: int | None = None, + family: FeatureFamily | None = None, + kind: FeatureKind | None = None, + inputs: Sequence[FeatureInputDataset] | None = None, + warmup_bars: int | None = None, + known_at_rule: FeatureKnownAtRule | None = None, + sql: str | None = None, + polars_fn: PolarsFeatureFn | None = None, + expression: str | None = None, + description: str | None = None, + registry: FeatureRegistry | None = None, +) -> RegisteredFeature: + """Registers a versioned signal definition in the default or injected `FeatureRegistry`. + + Accepts either a pre-built `FeatureDefinition` or keyword arguments. Re-registering an + identical semantic definition hash is idempotent; semantic drift on the same + `@v` raises `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. + """ + target_registry = registry if registry is not None else _DEFAULT_REGISTRY + if defn is not None: + if any( + v is not None + for v in ( + name, + version, + family, + kind, + inputs, + warmup_bars, + known_at_rule, + sql, + polars_fn, + expression, + description, + ) + ): + raise FeatureLibraryError( + "INVALID_DEFINITION", + "Pass either a FeatureDefinition or keyword arguments to register_signal, not both.", + ) + return target_registry.register_signal(defn) + + built = FeatureDefinition( + name=name, # type: ignore[arg-type] + version=version, # type: ignore[arg-type] + family=family, # type: ignore[arg-type] + kind=kind, # type: ignore[arg-type] + inputs=tuple(inputs) if inputs is not None else (), # type: ignore[arg-type] + warmup_bars=warmup_bars, # type: ignore[arg-type] + known_at_rule=known_at_rule, # type: ignore[arg-type] + sql=sql, + polars_fn=polars_fn, + expression=expression, + description=description, + ) + return target_registry.register_signal(built) + + +def _join_curated_path(normalized_root: str, relative_path: str) -> str: + return f"/{relative_path}" if normalized_root == "/" else f"{normalized_root}/{relative_path}" + + +def _validate_four_digit_year(value: Any, field: str) -> int: + if ( + isinstance(value, bool) + or not isinstance(value, int) + or value < _MIN_FOUR_DIGIT_YEAR + or value > _MAX_FOUR_DIGIT_YEAR + ): + raise FeatureLibraryError( + "INVALID_BATCH_OPTIONS", + f'Invalid "{field}": "{value}". Expected a four-digit integer year ({_MIN_FOUR_DIGIT_YEAR}..{_MAX_FOUR_DIGIT_YEAR}).', + ) + return value + + +def _parse_vault_cutoff_date_micros(raw: Any) -> int: + if not isinstance(raw, str) or not _DATE_ONLY_RE.match(raw): + raise FeatureLibraryError( + "INVALID_BATCH_OPTIONS", + f'Invalid "vault_cutoff_date": "{raw}". Expected strict UTC YYYY-MM-DD date string.', + ) + try: + return parse_timestamp_micros(raw, "start", "vault_cutoff_date") + except MarketDataStoreValidationError as exc: + raise FeatureLibraryError( + "INVALID_BATCH_OPTIONS", + f'Invalid "vault_cutoff_date": {exc}', + cause=exc, + ) from exc + + +def _expand_sql_for_year( + tokens: Sequence[_SqlToken], + curated_root: str, + ts_upper_iso: str, + known_at_upper_iso: str, +) -> tuple[str, list[Any]]: + scan_params: list[Any] = [] + parts: list[str] = [] + + for tok in tokens: + if tok.kind == "placeholder": + ds: FeatureInputDataset = tok.dataset # type: ignore[assignment] + spec = _DATASET_SCAN_SPECS[ds] + full_path = _join_curated_path(curated_root, spec.relative_path) + read_call = ( + f"read_parquet('{full_path}', hive_partitioning = true)" + if spec.hive_partitioning + else f"read_parquet('{full_path}')" + ) + if spec.predicate_kind == "ts_and_known_at": + parts.append( + f"(SELECT * FROM {read_call} WHERE ts <= CAST(? AS TIMESTAMPTZ) AND known_at <= CAST(? AS TIMESTAMPTZ))" + ) + scan_params.extend([ts_upper_iso, known_at_upper_iso]) + elif spec.predicate_kind == "effective_known_at": + parts.append( + f"(SELECT * FROM {read_call} WHERE effective_known_at <= CAST(? AS TIMESTAMPTZ))" + ) + scan_params.append(known_at_upper_iso) + else: + parts.append( + f"(SELECT * FROM {read_call} WHERE known_at <= CAST(? AS TIMESTAMPTZ))" + ) + scan_params.append(known_at_upper_iso) + continue + parts.append(tok.raw) + + return " ".join(parts), scan_params + + +def _resolve_batch_window( + *, + curated_root: str | Path, + from_year: int, + to_year: int, + vault_cutoff_date: str, +) -> tuple[str, int, int, int]: + try: + valid_root = validate_curated_root(curated_root) + except MarketDataStoreValidationError as exc: + raise FeatureLibraryError("INVALID_BATCH_OPTIONS", str(exc), cause=exc) from exc + + valid_from = _validate_four_digit_year(from_year, "from_year") + valid_to = _validate_four_digit_year(to_year, "to_year") + if valid_from > valid_to: + raise FeatureLibraryError( + "INVALID_BATCH_OPTIONS", + f"Invalid year range: from_year ({valid_from}) must not exceed to_year ({valid_to}).", + ) + + cutoff_micros = _parse_vault_cutoff_date_micros(vault_cutoff_date) + cutoff_ms = cutoff_micros // 1000 + range_from = f"{valid_from:04d}-01-01" + range_to = f"{valid_to:04d}-12-31" + + try: + fenced = apply_vault_fence(range_from, range_to, cutoff_ms, scope="vault_fenced") + except VaultHoldoutFenceError as exc: + raise FeatureLibraryError( + "VAULT_RANGE_VIOLATION", + f'Requested year range [{valid_from}, {valid_to}] falls on or after vault_cutoff_date "{vault_cutoff_date}".', + cause=exc, + ) from exc + except MarketDataStoreValidationError as exc: + raise FeatureLibraryError("INVALID_BATCH_OPTIONS", str(exc), cause=exc) from exc + + assert fenced.to_micros is not None + last_planned_year = min(valid_to, epoch_micros_to_datetime(fenced.to_micros).year) + if last_planned_year < valid_from: + raise FeatureLibraryError( + "VAULT_RANGE_VIOLATION", + f'No pre-cutoff years remain in [{valid_from}, {valid_to}] for vault_cutoff_date "{vault_cutoff_date}".', + ) + + return valid_root, valid_from, last_planned_year, cutoff_micros - 1 + + +def plan_feature_batch( + defn: FeatureDefinition, + *, + curated_root: str | Path, + from_year: int, + to_year: int, + vault_cutoff_date: str, +) -> tuple[PlannedFeatureWrite, ...]: + """Plans ordered yearly Vault-fenced Parquet writes for a validated feature definition.""" + validated = _validate_feature_definition_internal(defn) + valid_root, valid_from, last_planned_year, vault_ceiling_micros = _resolve_batch_window( + curated_root=curated_root, + from_year=from_year, + to_year=to_year, + vault_cutoff_date=vault_cutoff_date, + ) + + known_at_upper_iso = format_utc_iso_micros(vault_ceiling_micros) + writes: list[PlannedFeatureWrite] = [] + + for year in range(valid_from, last_planned_year + 1): + year_end_dt = datetime(year, 12, 31, 23, 59, 59, 999_999, tzinfo=timezone.utc) + year_end_micros = ( + (year_end_dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).days * 86_400 + 86_399 + ) * 1_000_000 + 999_999 + effective_ts_end_micros = min(year_end_micros, vault_ceiling_micros) + ts_upper_iso = format_utc_iso_micros(effective_ts_end_micros) + + output_path = _join_curated_path( + valid_root, f"features/{defn.name}/v{defn.version}/year={year}/part.parquet" + ) + + if defn.kind == "duckdb_sql": + expanded_sql, scan_params = _expand_sql_for_year( + validated.tokens, valid_root, ts_upper_iso, known_at_upper_iso + ) + sql = ( + "COPY (SELECT listing_id, ts, known_at, value " + "FROM (SELECT CAST(listing_id AS INTEGER) AS listing_id, " + "CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, " + "CAST(value AS DOUBLE) AS value " + f"FROM ({expanded_sql}) AS __feature_source) AS __feature_typed " + "WHERE year(ts) = ? AND ts <= CAST(? AS TIMESTAMPTZ) AND known_at <= CAST(? AS TIMESTAMPTZ) " + f"ORDER BY listing_id, ts) TO '{output_path}' (FORMAT PARQUET, COMPRESSION ZSTD)" + ) + params: tuple[Any, ...] = (*scan_params, year, ts_upper_iso, known_at_upper_iso) + else: + sql = "" + params = (year, ts_upper_iso, known_at_upper_iso) + + writes.append( + PlannedFeatureWrite(year=year, output_path=output_path, sql=sql, params=params) + ) + + return tuple(writes) + + +class _TrackingInputMapping(Mapping[str, pl.LazyFrame]): + """Read-only input mapping that enforces declared-only access and tracks used datasets.""" + + def __init__(self, frames: Mapping[str, pl.LazyFrame]) -> None: + self._frames = dict(frames) + self.accessed: set[str] = set() + + def __getitem__(self, key: str) -> pl.LazyFrame: + if key not in self._frames: + raise FeatureLibraryError( + "UNDECLARED_INPUT", + f'Polars feature attempted to access undeclared input dataset "{key}".', + ) + self.accessed.add(key) + return self._frames[key] + + def __iter__(self) -> Iterator[str]: + return iter(self._frames) + + def __len__(self) -> int: + return len(self._frames) + + +def _load_fenced_polars_inputs( + con: duckdb.DuckDBPyConnection, + curated_root: str, + datasets: Sequence[FeatureInputDataset], + ts_upper_iso: str, + known_at_upper_iso: str, +) -> dict[str, pl.LazyFrame]: + frames: dict[str, pl.LazyFrame] = {} + for ds in datasets: + spec = _DATASET_SCAN_SPECS[ds] + full_path = _join_curated_path(curated_root, spec.relative_path) + read_call = ( + f"read_parquet('{full_path}', hive_partitioning = true)" + if spec.hive_partitioning + else f"read_parquet('{full_path}')" + ) + if spec.predicate_kind == "ts_and_known_at": + df = con.execute( + f"SELECT * FROM {read_call} WHERE ts <= CAST(? AS TIMESTAMPTZ) AND known_at <= CAST(? AS TIMESTAMPTZ)", + [ts_upper_iso, known_at_upper_iso], + ).pl() + elif spec.predicate_kind == "effective_known_at": + df = con.execute( + f"SELECT * FROM {read_call} WHERE effective_known_at <= CAST(? AS TIMESTAMPTZ)", + [known_at_upper_iso], + ).pl() + else: + df = con.execute( + f"SELECT * FROM {read_call} WHERE known_at <= CAST(? AS TIMESTAMPTZ)", + [known_at_upper_iso], + ).pl() + frames[ds] = df.lazy() + return frames + + +def _validate_polars_feature_output(result: Any) -> pl.DataFrame: + if isinstance(result, pl.LazyFrame): + df = result.collect() + elif isinstance(result, pl.DataFrame): + df = result + else: + raise FeatureLibraryError( + "INVALID_SQL_PROJECTION", + f"Polars feature function must return a pl.LazyFrame or pl.DataFrame, got {type(result).__name__}.", + ) + + actual_cols = list(df.columns) + expected_cols = list(FEATURE_OUTPUT_COLUMNS) + if actual_cols != expected_cols: + raise FeatureLibraryError( + "INVALID_SQL_PROJECTION", + f"Polars feature output columns must be exactly {expected_cols}, got {actual_cols}.", + ) + + # Ensure value column is Float64 and contains only finite numbers (or NULL) + df = df.with_columns(pl.col("value").cast(pl.Float64)) + values = df.get_column("value") + for val in values.drop_nulls(): + if not math.isfinite(float(val)): + raise ValueError( + f"Polars feature produced non-finite Float64 value {val!r}; NaN/Inf are forbidden." + ) + + return df + + +def run_feature_batch( + defn: FeatureDefinition, + *, + curated_root: str | Path, + from_year: int, + to_year: int, + vault_cutoff_date: str, + budget: DuckDbConnectionBudget | None = None, +) -> FeatureBatchManifest: + """Materializes yearly Vault-fenced Zstd Parquet partitions for a SQL or Polars feature. + + Creates parent `year=YYYY` directories, writes each year to a staging file in the same + directory via a budgeted UTC DuckDB connection, and atomically publishes via `os.replace`. + Raises `FeatureLibraryError('BATCH_WRITE_FAILED')` with `failed_year`, `completed_years`, + and `completed_writes` on failure. + """ + validated = _validate_feature_definition_internal(defn) + planned_writes = plan_feature_batch( + defn, + curated_root=curated_root, + from_year=from_year, + to_year=to_year, + vault_cutoff_date=vault_cutoff_date, + ) + valid_root = validate_curated_root(curated_root) + ref = feature_ref(defn) + def_hash = feature_definition_hash(defn) + sorted_inputs = tuple(sorted(validated.normalized_inputs)) + resolved_budget = budget or resolve_duckdb_budget() + + os.makedirs(resolved_budget.temp_directory, exist_ok=True) + con = duckdb.connect(":memory:") + completed_writes: list[FeatureBatchWriteReceipt] = [] + + try: + con.execute("SET TimeZone = 'UTC';") + for stmt in resolved_budget.statements: + con.execute(stmt) + + for write in planned_writes: + parent_dir = os.path.dirname(write.output_path) + tmp_path = os.path.join( + parent_dir, f".part.parquet.{os.getpid()}.{uuid.uuid4().hex}.tmp" + ) + try: + os.makedirs(parent_dir, exist_ok=True) + if defn.kind == "duckdb_sql": + target_literal = f"TO '{write.output_path}' (FORMAT PARQUET, COMPRESSION ZSTD)" + tmp_literal = f"TO '{tmp_path}' (FORMAT PARQUET, COMPRESSION ZSTD)" + staged_sql = write.sql.replace(target_literal, tmp_literal, 1) + con.execute(staged_sql, list(write.params)) + else: + assert defn.polars_fn is not None + year, ts_upper_iso, known_at_upper_iso = write.params + raw_inputs = _load_fenced_polars_inputs( + con, valid_root, validated.normalized_inputs, ts_upper_iso, known_at_upper_iso + ) + tracking = _TrackingInputMapping(raw_inputs) + raw_out = defn.polars_fn(tracking) + for declared in validated.normalized_inputs: + if declared not in tracking.accessed: + raise FeatureLibraryError( + "UNUSED_INPUT", + f'Declared input dataset "{declared}" was not accessed by Polars feature "{ref}".', + ) + out_df = _validate_polars_feature_output(raw_out) + con.register("__polars_feature_out", out_df) + try: + con.execute( + "COPY (SELECT listing_id, ts, known_at, value " + "FROM (SELECT CAST(listing_id AS INTEGER) AS listing_id, " + "CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, " + "CAST(value AS DOUBLE) AS value " + "FROM __polars_feature_out) AS __feature_typed " + "WHERE year(ts) = ? AND ts <= CAST(? AS TIMESTAMPTZ) AND known_at <= CAST(? AS TIMESTAMPTZ) " + f"ORDER BY listing_id, ts) TO '{tmp_path}' (FORMAT PARQUET, COMPRESSION ZSTD)", + [year, ts_upper_iso, known_at_upper_iso], + ) + finally: + con.unregister("__polars_feature_out") + + os.replace(tmp_path, write.output_path) + except FeatureLibraryError as exc: + if os.path.exists(tmp_path): + try: + os.remove(tmp_path) + except OSError: + pass + if exc.code in ("UNDECLARED_INPUT", "UNUSED_INPUT", "INVALID_SQL_PROJECTION"): + raise + completed_years = [w.year for w in completed_writes] + raise FeatureLibraryError( + "BATCH_WRITE_FAILED", + f'Feature batch write failed for "{ref}" on year {write.year} (completed years: {", ".join(str(y) for y in completed_years) if completed_years else "none"}).', + cause=exc, + failed_year=write.year, + completed_years=completed_years, + completed_writes=completed_writes, + ref=ref, + ) from exc + except Exception as exc: + if os.path.exists(tmp_path): + try: + os.remove(tmp_path) + except OSError: + pass + completed_years = [w.year for w in completed_writes] + raise FeatureLibraryError( + "BATCH_WRITE_FAILED", + f'Feature batch write failed for "{ref}" on year {write.year} (completed years: {", ".join(str(y) for y in completed_years) if completed_years else "none"}).', + cause=exc, + failed_year=write.year, + completed_years=completed_years, + completed_writes=completed_writes, + ref=ref, + ) from exc + + completed_writes.append( + FeatureBatchWriteReceipt(year=write.year, output_path=write.output_path) + ) + finally: + con.close() + + return FeatureBatchManifest( + ref=ref, + definition_hash=def_hash, + known_at_rule=defn.known_at_rule, + warmup_bars=defn.warmup_bars, + inputs=sorted_inputs, + writes=tuple(completed_writes), + ) + + +RET_1D_V1 = FeatureDefinition( + name="ret_1d", + version=1, + family="technical", + kind="duckdb_sql", + inputs=("bars_1d",), + warmup_bars=1, + known_at_rule="bar_close", + description=( + "1-day simple raw-close return per listing with bar-close availability; " + "comparison baseline is 0 return with no execution or cost model." + ), + sql="\n".join( + [ + "WITH lagged AS (", + " SELECT", + " listing_id,", + " ts,", + " close,", + " LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close", + " FROM {{input:bars_1d}}", + ")", + "SELECT", + " listing_id,", + " ts,", + " ts AS known_at,", + " (close / prev_close) - 1.0 AS value", + "FROM lagged", + "WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0", + ] + ), +) diff --git a/python/stockbot/signals.py b/python/stockbot/signals.py index da18fbb4..1697cc35 100644 --- a/python/stockbot/signals.py +++ b/python/stockbot/signals.py @@ -7,6 +7,7 @@ from typing import Any, Mapping import polars as pl from .calculations import analyze_signal_panel, compute_event_study +from .features import register_signal from .ledger import ( ClusterDsrSummary, HorizonBucket, diff --git a/python/stockbot/vault.py b/python/stockbot/vault.py index b3e714dc..1335ac35 100644 --- a/python/stockbot/vault.py +++ b/python/stockbot/vault.py @@ -6,7 +6,8 @@ import calendar import os import re from dataclasses import dataclass -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone +from pathlib import Path from typing import Literal, Mapping DataScope = Literal["vault_fenced", "vault_evaluation_only"] @@ -15,7 +16,11 @@ DEFAULT_DUCKDB_MEMORY_LIMIT = "6GB" DEFAULT_DUCKDB_THREADS = 4 DEFAULT_DUCKDB_TEMP_DIRECTORY = "/mnt/data/stockbot/tmp/duckdb" +_EPOCH_UTC = datetime(1970, 1, 1, tzinfo=timezone.utc) _DATE_ONLY_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$") +_ISO_INSTANT_RE = re.compile( + r"^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$" +) _MEM_LIMIT_RE = re.compile(r"^(\d+(?:\.\d+)?)(MB|GB|MiB|GiB)$") @@ -47,19 +52,25 @@ class FencedTimeRange: scope: DataScope clamped_to: bool clamped_as_of: bool + from_micros: int | None = None + to_micros: int | None = None + as_of_micros: int | None = None - @property - def from_micros(self) -> int: - return self.from_ms * 1000 - - @property - def to_micros(self) -> int: - # Expand end-of-ms inclusive boundary to last microsecond (.999999) when ms ends in 999 - return self.to_ms * 1000 + (999 if self.to_ms % 1000 == 999 else 0) - - @property - def as_of_micros(self) -> int: - return self.as_of_ms * 1000 + (999 if self.as_of_ms % 1000 == 999 else 0) + def __post_init__(self) -> None: + if self.from_micros is None: + object.__setattr__(self, "from_micros", self.from_ms * 1000) + if self.to_micros is None: + object.__setattr__( + self, + "to_micros", + self.to_ms * 1000 + (999 if self.to_ms % 1000 == 999 else 0), + ) + if self.as_of_micros is None: + object.__setattr__( + self, + "as_of_micros", + self.as_of_ms * 1000 + (999 if self.as_of_ms % 1000 == 999 else 0), + ) @dataclass(frozen=True) @@ -78,30 +89,76 @@ class DuckDbConnectionBudget: ) -def parse_timestamp_ms(raw: str, bound_kind: Literal["start", "end"], field: str) -> int: +def _datetime_to_epoch_micros(dt: datetime) -> int: + delta = dt.astimezone(timezone.utc) - _EPOCH_UTC + return (delta.days * 86_400 + delta.seconds) * 1_000_000 + delta.microseconds + + +def epoch_micros_to_datetime(micros: int) -> datetime: + """Converts exact UTC epoch microseconds to a timezone-aware UTC datetime without float rounding.""" + return _EPOCH_UTC + timedelta(microseconds=micros) + + +def format_utc_iso_micros(micros: int) -> str: + """Formats exact UTC epoch microseconds as ISO-8601 UTC string.""" + dt = epoch_micros_to_datetime(micros) + if dt.microsecond % 1000 == 0: + ms = dt.microsecond // 1000 + return dt.strftime("%Y-%m-%dT%H:%M:%S") + f".{ms:03d}Z" + return dt.strftime("%Y-%m-%dT%H:%M:%S") + f".{dt.microsecond:06d}Z" + + +def parse_timestamp_micros(raw: str, bound_kind: Literal["start", "end"], field: str) -> int: + """Parses a UTC ISO-8601 date or timestamp into exact integer epoch microseconds.""" if not isinstance(raw, str) or not raw: raise MarketDataStoreValidationError(f'Expected non-empty ISO-8601 string for "{field}".') + m = _DATE_ONLY_RE.match(raw) if m: year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3)) - if bound_kind == "start": - dt = datetime(year, month, day, 0, 0, 0, 0, tzinfo=timezone.utc) - else: - dt = datetime(year, month, day, 23, 59, 59, 999000, tzinfo=timezone.utc) - return int(dt.timestamp() * 1000) + try: + if bound_kind == "start": + dt = datetime(year, month, day, 0, 0, 0, 0, tzinfo=timezone.utc) + else: + dt = datetime(year, month, day, 23, 59, 59, 999_999, tzinfo=timezone.utc) + except ValueError as exc: + raise MarketDataStoreValidationError( + f'Invalid calendar date for "{field}": "{raw}".' + ) from exc + return _datetime_to_epoch_micros(dt) - try: - dt = datetime.fromisoformat(raw.replace("Z", "+00:00")) - except ValueError as exc: - raise MarketDataStoreValidationError( - f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".' - ) from exc - if dt.tzinfo is None: - raise MarketDataStoreValidationError( - f'Naive timestamp without timezone offset is forbidden for "{field}": "{raw}".' - ) - dt_utc = dt.astimezone(timezone.utc) - return int(dt_utc.timestamp() * 1000) + im = _ISO_INSTANT_RE.match(raw) + if im: + year, month, day = int(im.group(1)), int(im.group(2)), int(im.group(3)) + hour, minute, second = int(im.group(4)), int(im.group(5)), int(im.group(6)) + frac = im.group(7) + micros = int(frac[:6].ljust(6, "0")) if frac is not None else 0 + tz_token = im.group(8) + offset_micros = 0 + if tz_token != "Z": + tz_sign = 1 if im.group(9) == "+" else -1 + tz_hours = int(im.group(10)) + tz_mins = int(im.group(11)) + if tz_hours > 23 or tz_mins > 59: + raise MarketDataStoreValidationError( + f'Invalid timezone offset for "{field}": "{raw}".' + ) + offset_micros = tz_sign * (tz_hours * 60 + tz_mins) * 60_000_000 + try: + dt = datetime(year, month, day, hour, minute, second, micros, tzinfo=timezone.utc) + except ValueError as exc: + raise MarketDataStoreValidationError( + f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".' + ) from exc + return _datetime_to_epoch_micros(dt) - offset_micros + + raise MarketDataStoreValidationError( + f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".' + ) + + +def parse_timestamp_ms(raw: str, bound_kind: Literal["start", "end"], field: str) -> int: + return parse_timestamp_micros(raw, bound_kind, field) // 1000 def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int: @@ -113,11 +170,11 @@ def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int: elif isinstance(max_ingested_ts, datetime): if max_ingested_ts.tzinfo is None: raise MarketDataStoreValidationError("max_ingested_ts datetime must be timezone-aware.") - epoch_ms = int(max_ingested_ts.astimezone(timezone.utc).timestamp() * 1000) + epoch_ms = _datetime_to_epoch_micros(max_ingested_ts) // 1000 else: raise MarketDataStoreValidationError("Invalid max_ingested_ts type.") - dt = datetime.fromtimestamp(epoch_ms / 1000.0, tz=timezone.utc) + dt = epoch_micros_to_datetime(epoch_ms * 1000) total_months = dt.year * 12 + (dt.month - 1) - 6 target_year, target_month_zero = divmod(total_months, 12) target_month = target_month_zero + 1 @@ -133,11 +190,11 @@ def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int: dt.microsecond, tzinfo=timezone.utc, ) - return int(cutoff_dt.timestamp() * 1000) + return _datetime_to_epoch_micros(cutoff_dt) // 1000 def vault_cutoff_date_str(vault_cutoff_ts: int) -> str: - return datetime.fromtimestamp(vault_cutoff_ts / 1000.0, tz=timezone.utc).strftime("%Y-%m-%d") + return epoch_micros_to_datetime(vault_cutoff_ts * 1000).strftime("%Y-%m-%d") def apply_vault_fence( @@ -148,11 +205,15 @@ def apply_vault_fence( scope: DataScope = "vault_fenced", vault_operator_authorized: bool = False, ) -> FencedTimeRange: - from_ms = parse_timestamp_ms(from_bound, "start", "from") - to_ms = parse_timestamp_ms(to_bound, "end", "to") - if to_ms < from_ms: + if not isinstance(vault_cutoff_ts, int) or isinstance(vault_cutoff_ts, bool): raise MarketDataStoreValidationError( - f'Query end "{to_bound}" ({to_ms}) precedes start "{from_bound}" ({from_ms}).' + f"Invalid epoch millisecond timestamp for vault_cutoff_ts: {vault_cutoff_ts!r}." + ) + from_micros = parse_timestamp_micros(from_bound, "start", "from") + to_micros = parse_timestamp_micros(to_bound, "end", "to") + if to_micros < from_micros: + raise MarketDataStoreValidationError( + f'Query end "{to_bound}" ({to_micros // 1000}) precedes start "{from_bound}" ({from_micros // 1000}).' ) if scope == "vault_evaluation_only": @@ -160,43 +221,54 @@ def apply_vault_fence( raise VaultScopeNotAuthorizedError( "Data scope 'vault_evaluation_only' requires explicit human operator authorization." ) - as_of_ms = parse_timestamp_ms(as_of, "end", "as_of") if as_of is not None else to_ms + as_of_micros = ( + parse_timestamp_micros(as_of, "end", "as_of") if as_of is not None else to_micros + ) return FencedTimeRange( - from_ms=from_ms, - to_ms=to_ms, - as_of_ms=as_of_ms, + from_ms=from_micros // 1000, + to_ms=to_micros // 1000, + as_of_ms=as_of_micros // 1000, scope=scope, clamped_to=False, clamped_as_of=False, + from_micros=from_micros, + to_micros=to_micros, + as_of_micros=as_of_micros, ) if scope != "vault_fenced": raise MarketDataStoreValidationError(f"Unsupported scope: {scope!r}") - if from_ms >= vault_cutoff_ts: - raise VaultHoldoutFenceError(from_bound, from_ms, vault_cutoff_ts) + cutoff_micros = vault_cutoff_ts * 1000 + max_allowed_micros = cutoff_micros - 1 + + if from_micros >= cutoff_micros: + raise VaultHoldoutFenceError(from_bound, from_micros // 1000, vault_cutoff_ts) clamped_to = False - if to_ms >= vault_cutoff_ts: - to_ms = vault_cutoff_ts - 1 + if to_micros >= cutoff_micros: + to_micros = max_allowed_micros clamped_to = True clamped_as_of = False if as_of is None: - as_of_ms = vault_cutoff_ts - 1 + as_of_micros = max_allowed_micros else: - as_of_ms = parse_timestamp_ms(as_of, "end", "as_of") - if as_of_ms >= vault_cutoff_ts: - as_of_ms = vault_cutoff_ts - 1 + as_of_micros = parse_timestamp_micros(as_of, "end", "as_of") + if as_of_micros >= cutoff_micros: + as_of_micros = max_allowed_micros clamped_as_of = True return FencedTimeRange( - from_ms=from_ms, - to_ms=to_ms, - as_of_ms=as_of_ms, + from_ms=from_micros // 1000, + to_ms=to_micros // 1000, + as_of_ms=as_of_micros // 1000, scope="vault_fenced", clamped_to=clamped_to, clamped_as_of=clamped_as_of, + from_micros=from_micros, + to_micros=to_micros, + as_of_micros=as_of_micros, ) @@ -224,3 +296,30 @@ def resolve_duckdb_budget( if not tmp_dir or not tmp_dir.startswith("/"): raise MarketDataStoreValidationError(f"Invalid DuckDB temp_directory: {tmp_dir!r}") return DuckDbConnectionBudget(memory_limit=mem, threads=raw_threads, temp_directory=tmp_dir) + + +def validate_curated_root(raw: str | Path) -> str: + """Validates `curated_root` as an absolute POSIX path without quotes, semicolons, control chars, or globs.""" + if isinstance(raw, Path): + value = str(raw) + elif isinstance(raw, str): + value = raw + else: + raise MarketDataStoreValidationError( + f"Invalid curated_root {raw!r}. Expected a non-empty absolute POSIX path." + ) + + if not value or not value.startswith("/"): + raise MarketDataStoreValidationError( + f'Invalid curated_root "{value}". Expected a non-empty absolute POSIX path.' + ) + + for ch in value: + code = ord(ch) + if code <= 0x1F or code == 0x7F or ch in ("'", ";", "*", "?", "[", "]"): + raise MarketDataStoreValidationError( + f'Invalid curated_root "{value}". Path must not contain control characters, quotes, semicolons, or glob characters (*, ?, [, ]).' + ) + + normalized = value.rstrip("/") + return normalized if normalized else "/" diff --git a/python/tests/test_m2_sdk_parity.py b/python/tests/test_m2_sdk_parity.py new file mode 100644 index 00000000..af04c6fc --- /dev/null +++ b/python/tests/test_m2_sdk_parity.py @@ -0,0 +1,1072 @@ +"""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 +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( + f"SELECT column_name, column_type FROM (DESCRIBE SELECT * FROM read_parquet('{out_2025}'))" + ).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, ts, 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][2] == pytest.approx(0.10) + assert rows_2025[1][2] == 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 + 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: {{ + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '512MB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))}, + }}, +}}); +try {{ + let mode = 'store'; + let result; + try {{ + 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', + }}); + }} catch (err) {{ + if (err && typeof err === 'object' && err.name === 'MarketDataStoreNotImplementedError') {{ + mode = 'executor'; + const rows = await opened.executor.query( + `WITH u AS ( + SELECT DISTINCT b.listing_id + FROM read_parquet('${{curatedRoot}}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b + WHERE b.currency = 'USD' AND b.session_date >= '2024-12-26' AND b.session_date <= '2025-01-02' + AND b.ts <= CAST('2025-01-02T23:59:59.999999Z' AS TIMESTAMPTZ) + AND b.known_at <= CAST('2025-01-02T22:00:00.000Z' AS TIMESTAMPTZ) + ), + f0 AS ( + SELECT listing_id, CAST(value AS DOUBLE) AS value + FROM read_parquet('${{curatedRoot}}/features/ret_1d/v1/year=*/part.parquet', hive_partitioning = true) + WHERE ts >= CAST('2025-01-02T00:00:00.000Z' AS TIMESTAMPTZ) + AND ts <= CAST('2025-01-02T23:59:59.999999Z' AS TIMESTAMPTZ) + AND known_at <= CAST('2025-01-02T22:00:00.000Z' AS TIMESTAMPTZ) + ), + f1 AS ( + SELECT listing_id, CAST(value AS DOUBLE) AS value + FROM read_parquet('${{curatedRoot}}/features/mom_diff/v1/year=*/part.parquet', hive_partitioning = true) + WHERE ts >= CAST('2025-01-02T00:00:00.000Z' AS TIMESTAMPTZ) + AND ts <= CAST('2025-01-02T23:59:59.999999Z' AS TIMESTAMPTZ) + AND known_at <= CAST('2025-01-02T22:00:00.000Z' AS TIMESTAMPTZ) + ) + SELECT CAST(u.listing_id AS INTEGER) AS listing_id, f0.value AS "ret_1d@v1", f1.value AS "mom_diff@v1" + FROM u LEFT JOIN f0 ON u.listing_id = f0.listing_id LEFT JOIN f1 ON u.listing_id = f1.listing_id + ORDER BY u.listing_id ASC`, + [] + ); + result = {{ columns: ['listing_id', 'ret_1d@v1', 'mom_diff@v1'], rows }}; + }} else {{ + throw err; + }} + }} + console.log(JSON.stringify({{ mode, ...result }})); +}} finally {{ + await opened.close(); +}} +""" + proc = subprocess.run( + [bun_bin, "-e", script], + cwd=str(REPO_ROOT), + capture_output=True, + text=True, + check=True, + ) + 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_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")