diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts index fd6dd8ae..5e4aac3a 100644 --- a/libs/research/src/market-data-store-duckdb.ts +++ b/libs/research/src/market-data-store-duckdb.ts @@ -683,13 +683,13 @@ function validateFxPair(raw: unknown): (typeof FX_PAIR_MAP)[keyof typeof FX_PAIR ); } -function validateUniverseRef(raw: unknown): readonly string[] { +function validateUniverseRef(raw: unknown, field = 'ref'): readonly string[] { if (typeof raw === 'string' && Object.prototype.hasOwnProperty.call(UNIVERSE_CURRENCY_MAP, raw)) { return UNIVERSE_CURRENCY_MAP[raw as SupportedUniverseRef]; } throw new MarketDataStoreValidationError( `Unsupported universe ref "${String(raw)}". Expected one of: ${UNIVERSE_REFS.join(', ')}.`, - 'ref' + field ); } @@ -2280,8 +2280,8 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption return mapTableRows(FX_1D_COLUMNS, FX_1D_SCHEMA, rawRows); }, - crossSection(): Promise { - return Promise.reject(new MarketDataStoreNotImplementedError('crossSection')); + async crossSection(q: CrossSectionQuery): Promise
{ + return executeCrossSection(q, planCtx, ensureBudgetInitialized, typedExecutor); }, async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ @@ -2303,3 +2303,246 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption }, }; } + +export type CrossSectionQuery = Parameters[0]; + +const CROSS_SECTION_FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/; + +interface ParsedCrossSectionFeatureRef { + readonly canonical: string; + readonly name: string; + readonly version: number; +} + +function validateCrossSectionFeatures( + raw: readonly string[], + field = 'features' +): ParsedCrossSectionFeatureRef[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + 'Expected a non-empty array of canonical "@v" feature refs.', + field + ); + } + + const seen = new Set(); + const parsed: ParsedCrossSectionFeatureRef[] = []; + for (let i = 0; i < raw.length; i += 1) { + if (!(i in raw)) { + throw new MarketDataStoreValidationError( + `Invalid sparse feature ref at index ${i}. Expected canonical "@v".`, + field + ); + } + const item: unknown = raw[i]; + if (typeof item !== 'string') { + throw new MarketDataStoreValidationError( + `Invalid feature ref at index ${i}. Expected canonical "@v".`, + field + ); + } + const match = CROSS_SECTION_FEATURE_REF_RE.exec(item); + if (match === null) { + throw new MarketDataStoreValidationError( + `Invalid feature ref "${item}". Expected canonical "@v".`, + field + ); + } + const name = match[1]; + const versionStr = match[2]; + if (name === undefined || versionStr === undefined) { + throw new MarketDataStoreValidationError( + `Invalid feature ref "${item}". Expected canonical "@v".`, + field + ); + } + const version = Number(versionStr); + if (!Number.isSafeInteger(version) || version < 1) { + throw new MarketDataStoreValidationError( + `Invalid feature version in ref "${item}". Expected a positive safe integer.`, + field + ); + } + const canonical = `${name}@v${version}`; + if (!seen.has(canonical)) { + seen.add(canonical); + parsed.push({ canonical, name, version }); + } + } + return parsed; +} + +interface PlannedCrossSectionInternal { + readonly planned: PlannedDuckDbQuery; + readonly columns: readonly string[]; + readonly schema: readonly TableColumnSpec[]; +} + +function planCrossSectionInternal( + q: CrossSectionQuery, + ctx: DuckDbPlanContext +): PlannedCrossSectionInternal { + const curatedRoot = validateContext(ctx); + const lookbackDays = validateUniverseLookbackDays(ctx.universeLookbackDays); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a crossSection query object.', 'query'); + } + + const parsedRefs = validateCrossSectionFeatures(q.features, 'features'); + const currencies = validateUniverseRef(q.universe, 'universe'); + + if (typeof q.date !== 'string' || !DATE_ONLY_RE.test(q.date)) { + throw new MarketDataStoreValidationError( + `Invalid crossSection date "${String(q.date)}". Expected a UTC calendar date in YYYY-MM-DD format.`, + 'date' + ); + } + if (q.asOf !== undefined && typeof q.asOf !== 'string') { + throw new MarketDataStoreValidationError( + 'Invalid crossSection asOf timestamp. Expected a UTC date or ISO-8601 instant string.', + 'asOf' + ); + } + + let fenced: FencedTimeRange; + try { + fenced = applyVaultFence( + { + from: q.date, + to: q.date, + ...(q.asOf !== undefined ? { asOf: q.asOf } : {}), + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + } catch (err: unknown) { + if ( + err instanceof MarketDataStoreValidationError && + (err.field === 'from' || err.field === 'to') + ) { + throw new MarketDataStoreValidationError(err.message, 'date'); + } + throw err; + } + + const lookbackStartMs = fenced.fromMs - lookbackDays * MS_PER_DAY; + if (!Number.isSafeInteger(lookbackStartMs) || lookbackStartMs < MIN_ISO_DATE_EPOCH_MS) { + throw new MarketDataStoreValidationError( + `Invalid universeLookbackDays "${lookbackDays}". Lookback start precedes supported YYYY-MM-DD UTC date range.`, + 'universeLookbackDays' + ); + } + + const lookbackStartDate = formatUtcDate(lookbackStartMs); + const endDate = formatUtcDate(fenced.toMs); + const fromSubMs = resolveFromSubMsMicros(q.date); + const toSubMs = resolveToSubMsMicros(q.date, fenced); + const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.date, fenced); + const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); + const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); + const universeKnownAtIso = + fenced.toMs < fenced.asOfMs || (fenced.toMs === fenced.asOfMs && toSubMs <= asOfSubMs) + ? toIso + : asOfIso; + + const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); + const currencyPredicate = + currencies.length === 1 + ? 'b.currency = ?' + : `b.currency IN (${buildPlaceholders(currencies.length)})`; + + const ctes: string[] = [ + 'u AS (' + + 'SELECT DISTINCT b.listing_id ' + + `FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` + + `WHERE ${currencyPredicate} ` + + 'AND b.session_date >= ? ' + + 'AND b.session_date <= ? ' + + 'AND b.ts <= ? ' + + 'AND b.known_at <= ?)', + ]; + const params: DuckDbParam[] = [ + ...currencies, + lookbackStartDate, + endDate, + toIso, + universeKnownAtIso, + ]; + const selectCols: string[] = ['CAST(u.listing_id AS INTEGER) AS listing_id']; + const joins: string[] = []; + const columns: string[] = ['listing_id']; + const schema: TableColumnSpec[] = [{ name: 'listing_id', kind: 'int32', nullable: false }]; + + for (let i = 0; i < parsedRefs.length; i += 1) { + const parsed = parsedRefs[i]; + if (parsed === undefined) { + continue; + } + const alias = `f_${i}`; + const featPath = joinCuratedPath( + curatedRoot, + `features/${parsed.name}/v${parsed.version}/year=*/part.parquet` + ); + ctes.push( + `${alias} AS (` + + 'SELECT listing_id, CAST(value AS DOUBLE) AS value ' + + `FROM read_parquet('${featPath}', hive_partitioning = true) ` + + 'WHERE ts >= ? ' + + 'AND ts <= ? ' + + 'AND known_at <= ? ' + + 'QUALIFY ROW_NUMBER() OVER (PARTITION BY listing_id ORDER BY ts DESC, known_at DESC) = 1)' + ); + params.push(fromIso, toIso, asOfIso); + const escapedCol = parsed.canonical.replace(/"/g, '""'); + selectCols.push(`${alias}.value AS "${escapedCol}"`); + joins.push(`LEFT JOIN ${alias} ON u.listing_id = ${alias}.listing_id`); + columns.push(parsed.canonical); + schema.push({ name: parsed.canonical, kind: 'number', nullable: true }); + } + + const sql = + `WITH ${ctes.join(', ')} ` + + `SELECT ${selectCols.join(', ')} ` + + `FROM u ${joins.join(' ')} ` + + 'ORDER BY u.listing_id ASC'; + + return { + planned: { + sql, + params, + fenced: { + ...fenced, + fromMs: lookbackStartMs, + }, + }, + columns, + schema, + }; +} + +/** + * Plans a Vault-fenced, survivorship-free cross-section DuckDB SQL query over + * materialized feature Parquet partitions (`features//v/year=*\/part.parquet`) + * LEFT JOINed onto the active universe on `q.date`. + */ +export function planCrossSectionQuery( + q: CrossSectionQuery, + ctx: DuckDbPlanContext +): PlannedDuckDbQuery { + return planCrossSectionInternal(q, ctx).planned; +} + +async function executeCrossSection( + q: CrossSectionQuery, + planCtx: DuckDbPlanContext, + ensureBudgetInitialized: () => Promise, + typedExecutor: DuckDbExecutor +): Promise
{ + const { planned, columns, schema } = planCrossSectionInternal(q, planCtx); + await ensureBudgetInitialized(); + const rawRows = await typedExecutor.query(planned.sql, planned.params); + return mapTableRows(columns, schema, rawRows); +} diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index 599edece..5ad2bd8c 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -28,6 +28,7 @@ import { parseAdjFactorsSnapshotMetadata, planAdjFactorsMetadataQuery, planBars1dQuery, + planCrossSectionQuery, planEventsQuery, planFundamentalsAsOfQuery, planFx1dQuery, @@ -56,6 +57,7 @@ import { parseAdjFactorsSnapshotMetadata as subpathParseAdjFactorsSnapshotMetadata, planAdjFactorsMetadataQuery as subpathPlanAdjFactorsMetadataQuery, planBars1dQuery as subpathPlanBars1dQuery, + planCrossSectionQuery as subpathPlanCrossSectionQuery, planEventsQuery as subpathPlanEventsQuery, planFundamentalsAsOfQuery as subpathPlanFundamentalsAsOfQuery, planFx1dQuery as subpathPlanFx1dQuery, @@ -2418,15 +2420,6 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { to: '2025-02-01', }), }, - { - method: 'crossSection', - run: () => - store.crossSection({ - features: ['ret_20d'], - date: '2025-01-15', - universe: 'US_EQ', - }), - }, { method: 'macroAsOf', run: () => @@ -3277,3 +3270,86 @@ describe('fundamentalsAsOf hostile request inputs', () => { expect(afterCutoff.fenced.clampedAsOf).toBe(true); }); }); + +describe('planCrossSectionQuery & createDuckDbMarketDataStore().crossSection()', () => { + it('plans Vault-fenced survivorship-free crossSection SQL and maps nullable feature values', async () => { + expect(subpathPlanCrossSectionQuery).toBe(planCrossSectionQuery); + + const planned = planCrossSectionQuery( + { + features: ['ret_1d@v1', 'mom_diff@v1', 'ret_1d@v1'], + date: '2025-01-02', + universe: 'US_EQ', + asOf: '2025-01-02T22:00:00Z', + }, + DEFAULT_CTX + ); + + expect(planned.sql).toContain( + `FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b` + ); + expect(planned.sql).toContain( + `FROM read_parquet('${CURATED_ROOT}/features/ret_1d/v1/year=*/part.parquet', hive_partitioning = true)` + ); + expect(planned.sql).toContain( + `FROM read_parquet('${CURATED_ROOT}/features/mom_diff/v1/year=*/part.parquet', hive_partitioning = true)` + ); + expect(planned.sql).toContain('ORDER BY u.listing_id ASC'); + expect(planned.params).toEqual([ + 'USD', + '2024-12-26', + '2025-01-02', + '2025-01-02T23:59:59.999999Z', + '2025-01-02T22:00:00.000Z', + '2025-01-02T00:00:00.000Z', + '2025-01-02T23:59:59.999999Z', + '2025-01-02T22:00:00.000Z', + '2025-01-02T00:00:00.000Z', + '2025-01-02T23:59:59.999999Z', + '2025-01-02T22:00:00.000Z', + ]); + + const fake = createRecordingExecutor({ + onQuery: () => [ + { listing_id: 1, 'ret_1d@v1': 0.1, 'mom_diff@v1': 1.0 }, + { listing_id: 2, 'ret_1d@v1': null, 'mom_diff@v1': -5.0 }, + ], + }); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + }); + + const table = await store.crossSection({ + features: ['ret_1d@v1', 'mom_diff@v1'], + date: '2025-01-02', + universe: 'US_EQ', + asOf: '2025-01-02T22:00:00Z', + }); + expect(table.columns).toEqual(['listing_id', 'ret_1d@v1', 'mom_diff@v1']); + expect(table.rows).toEqual([ + { listing_id: 1, 'ret_1d@v1': 0.1, 'mom_diff@v1': 1.0 }, + { listing_id: 2, 'ret_1d@v1': null, 'mom_diff@v1': -5.0 }, + ]); + + // Rejects post-cutoff date and invalid feature refs with 0 additional executor calls + const beforeCalls = fake.calls.length; + await expect( + store.crossSection({ + features: ['ret_1d@v1'], + date: '2026-05-28', + universe: 'US_EQ', + }) + ).rejects.toBeInstanceOf(VaultHoldoutFenceError); + await expect( + store.crossSection({ + features: ['bad_ref'], + date: '2025-01-02', + universe: 'US_EQ', + }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + expect(fake.calls).toHaveLength(beforeCalls); + }); +}); 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..c3a5fcc7 --- /dev/null +++ b/python/stockbot/features.py @@ -0,0 +1,2254 @@ +"""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, + ) + + 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) + known_at_upper_iso = ts_upper_iso + + 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 _has_existing_feature_partitions(version_dir: str) -> bool: + if not os.path.isdir(version_dir): + return False + for _root, _dirs, files in os.walk(version_dir): + for name in files: + if name.endswith(".parquet") and not name.startswith("."): + return True + return False + + +def _verify_existing_version_metadata( + *, + meta_path: str, + ref: str, + definition_hash: str, +) -> None: + try: + with open(meta_path, "r", encoding="utf-8") as fh: + payload = json.load(fh) + except Exception as exc: + raise FeatureLibraryError( + "FEATURE_VERSION_IMMUTABLE", + f'Published feature "{ref}" has unreadable version metadata at "{meta_path}".', + cause=exc, + ref=ref, + ) from exc + existing_hash = payload.get("definition_hash") if isinstance(payload, dict) else None + if not isinstance(existing_hash, str) or existing_hash != definition_hash: + raise FeatureLibraryError( + "FEATURE_VERSION_IMMUTABLE", + f'Feature "{ref}" is already published on disk with a different definition hash; bump the feature version instead of overwriting.', + ref=ref, + ) + + +def _verify_or_persist_version_definition( + *, + version_dir: str, + ref: str, + definition_hash: str, + defn: FeatureDefinition, + persist: bool, +) -> bool: + """Checks on-disk version immutability metadata and atomically claims it if absent. + + Rejects existing published Parquet partitions that lack a verified `_definition.json` + (e.g. sidecar-free partitions from another writer), and uses POSIX create-if-absent + hard-link (`os.link`) so concurrent first-time writers race safely and always verify + the winning definition hash before publishing any partition. + """ + meta_path = os.path.join(version_dir, "_definition.json") + if os.path.exists(meta_path): + _verify_existing_version_metadata( + meta_path=meta_path, ref=ref, definition_hash=definition_hash + ) + return True + + if _has_existing_feature_partitions(version_dir): + if os.path.exists(meta_path): + _verify_existing_version_metadata( + meta_path=meta_path, ref=ref, definition_hash=definition_hash + ) + return True + raise FeatureLibraryError( + "FEATURE_VERSION_IMMUTABLE", + f'Feature "{ref}" already has published Parquet partitions at "{version_dir}" without verified version metadata ("_definition.json"); bump the feature version instead of overwriting or adopting unverified partitions.', + ref=ref, + ) + + if not persist: + return False + + os.makedirs(version_dir, exist_ok=True) + tmp_meta = os.path.join(version_dir, f"._definition.{os.getpid()}.{uuid.uuid4().hex}.tmp") + metadata = { + "ref": ref, + "name": defn.name, + "version": defn.version, + "kind": defn.kind, + "definition_hash": definition_hash, + } + try: + with open(tmp_meta, "w", encoding="utf-8") as fh: + json.dump(metadata, fh, sort_keys=True, separators=(",", ":")) + fh.write("\n") + fh.flush() + os.fsync(fh.fileno()) + try: + os.link(tmp_meta, meta_path) + return True + except FileExistsError: + pass + finally: + if os.path.exists(tmp_meta): + try: + os.remove(tmp_meta) + except OSError: + pass + + # Another writer won the atomic create-if-absent claim; verify the winning hash. + _verify_existing_version_metadata( + meta_path=meta_path, ref=ref, definition_hash=definition_hash + ) + return True + + +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`. + Persists and verifies `/features//v/_definition.json` so a + different definition cannot silently overwrite an already-published version across runs. + 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() + version_dir = _join_curated_path(valid_root, f"features/{defn.name}/v{defn.version}") + definition_persisted = _verify_or_persist_version_definition( + version_dir=version_dir, + ref=ref, + definition_hash=def_hash, + defn=defn, + persist=False, + ) + + 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") + + if not definition_persisted: + definition_persisted = _verify_or_persist_version_definition( + version_dir=version_dir, + ref=ref, + definition_hash=def_hash, + defn=defn, + persist=True, + ) + + 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 not completed_writes and exc.code in ( + "UNDECLARED_INPUT", + "UNUSED_INPUT", + "INVALID_SQL_PROJECTION", + "FEATURE_VERSION_IMMUTABLE", + ): + 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..6c2f8e1a --- /dev/null +++ b/python/tests/test_m2_sdk_parity.py @@ -0,0 +1,1506 @@ +"""Offline M2 parity tests for Python `stockbot` SDK (MarketDataStore, QuestDB 1m, Feature Library). + +All tests run over temporary DuckDB/Parquet fixtures or injected recording executors +with zero QA database, live QuestDB, or paper/live execution access. +""" + +from __future__ import annotations + +import json +import math +import shutil +import subprocess +import threading +from concurrent.futures import ThreadPoolExecutor +from datetime import date, datetime, timezone +from pathlib import Path +from typing import Any, Mapping, Sequence + +import duckdb +import polars as pl +import pytest + +import stockbot +from stockbot import ( + RET_1D_V1, + DuckDbConnectionBudget, + FeatureDefinition, + FeatureLibraryError, + MarketDataStore, + MarketDataStoreValidationError, + PsycopgQuestDbExecutor, + VaultHoldoutFenceError, + apply_vault_fence, + create_feature_registry, + feature_definition_hash, + feature_ref, + parse_feature_ref, + plan_feature_batch, + register_signal, + run_feature_batch, + validate_feature_definition, +) +from stockbot.vault import ( + epoch_micros_to_datetime, + parse_timestamp_micros, + validate_curated_root, +) + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _make_budget(tmp_path: Path) -> DuckDbConnectionBudget: + tmp_dir = tmp_path / "duckdb_tmp" + tmp_dir.mkdir(parents=True, exist_ok=True) + return DuckDbConnectionBudget(memory_limit="512MB", threads=2, temp_directory=str(tmp_dir)) + + +def _write_parquet_via_duckdb(df: pl.DataFrame, out_path: Path) -> None: + out_path.parent.mkdir(parents=True, exist_ok=True) + con = duckdb.connect(":memory:") + try: + con.execute("SET TimeZone = 'UTC';") + con.register("src", df) + con.execute(f"COPY src TO '{out_path}' (FORMAT PARQUET, COMPRESSION ZSTD)") + finally: + con.close() + + +class _RecordingQuestDbExecutor: + def __init__(self, rows: list[dict[str, Any]]) -> None: + self.rows = rows + self.calls: list[tuple[str, tuple[Any, ...]]] = [] + self.closed = False + + def query(self, sql: str, params: Sequence[Any]) -> Sequence[Mapping[str, Any]]: + self.calls.append((sql, tuple(params))) + return list(self.rows) + + def close(self) -> None: + self.closed = True + + +# --------------------------------------------------------------------------- +# 1. Vault microsecond bounds & curated_root hygiene +# --------------------------------------------------------------------------- + + +def test_vault_microsecond_bounds_and_curated_root_hygiene() -> None: + start_us = parse_timestamp_micros("2025-01-15", "start", "from") + end_us = parse_timestamp_micros("2025-01-15", "end", "to") + assert epoch_micros_to_datetime(start_us) == datetime(2025, 1, 15, 0, 0, 0, 0, tzinfo=timezone.utc) + assert epoch_micros_to_datetime(end_us) == datetime(2025, 1, 15, 23, 59, 59, 999_999, tzinfo=timezone.utc) + + exact_us = parse_timestamp_micros("2025-01-15T12:34:56.789123Z", "end", "as_of") + assert epoch_micros_to_datetime(exact_us) == datetime( + 2025, 1, 15, 12, 34, 56, 789_123, tzinfo=timezone.utc + ) + + with pytest.raises(MarketDataStoreValidationError): + parse_timestamp_micros("2025-02-29", "start", "from") + + with pytest.raises(MarketDataStoreValidationError): + parse_timestamp_micros("2025-01-15T12:00:00", "start", "from") + + # Sub-second cutoff alignment: vault_cutoff_ts ending in .500Z must clamp to cutoff*1000 - 1 us + sub_sec_cutoff_ms = parse_timestamp_micros("2025-07-01T00:00:00.500Z", "start", "cutoff") // 1000 + fenced = apply_vault_fence("2025-06-01", "2025-08-01", sub_sec_cutoff_ms) + assert fenced.clamped_to is True + assert fenced.to_micros == sub_sec_cutoff_ms * 1000 - 1 + assert fenced.as_of_micros == sub_sec_cutoff_ms * 1000 - 1 + + # curated_root hygiene + assert validate_curated_root("/tmp/curated///") == "/tmp/curated" + for bad in ("relative/path", "/tmp/bad'quote", "/tmp/bad;semi", "/tmp/bad*glob", "/tmp/bad\nctrl"): + with pytest.raises(MarketDataStoreValidationError): + validate_curated_root(bad) + + +# --------------------------------------------------------------------------- +# 2. fundamentals_as_of 2D PIT & Vault invariants +# --------------------------------------------------------------------------- + + +def test_fundamentals_as_of_restated_q1_non_overwrite_lag_mask_and_vault(tmp_path: Path) -> None: + curated = tmp_path / "curated" + vault_cutoff_dt = datetime(2025, 7, 1, 0, 0, 0, 0, tzinfo=timezone.utc) + vault_cutoff_ms = int(vault_cutoff_dt.timestamp() * 1000) + + # Multi-year Hive partitions (year=2023, 2024, 2025) + df_2023 = pl.DataFrame( + { + "listing_id": [101], + "effective_known_at": [datetime(2023, 11, 10, 12, 0, 0, tzinfo=timezone.utc)], + "known_at_source": ["edgar_filing"], + "has_estimated_lag": [False], + "period_end": [date(2023, 9, 30)], + "fiscal_period": ["Q3"], + "currency": ["USD"], + "period_known_at": [datetime(2023, 11, 10, 12, 0, 0, tzinfo=timezone.utc)], + "revenue": [90.0], + "net_income": [9.0], + "operating_cash_flow": [12.0], + "total_assets": [500.0], + "total_equity": [250.0], + "shares_outstanding": [100.0], + "ttm_period_end": [date(2023, 9, 30)], + "ttm_currency": ["USD"], + "ttm_revenue": [360.0], + "ttm_net_income": [36.0], + "ttm_operating_cash_flow": [48.0], + "ttm_has_estimated_lag": [False], + }, + schema_overrides={ + "listing_id": pl.Int32, + "effective_known_at": pl.Datetime("us", "UTC"), + "period_known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet_via_duckdb(df_2023, curated / "fundamentals_pit" / "year=2023" / "part.parquet") + + # Listing 101: Q2 filed 2024-08-05, then Q1 restated on 2024-09-15 (known_at > Q2) + # updates ttm_revenue from 400 -> 415 without overwriting Q2 period_end/fiscal_period/revenue. + # Listing 102: Q1 clean (has_estimated_lag=False), then Q2 estimated (has_estimated_lag=True); + # with allow_estimated_lag=False, 102 must be omitted (no fallback to Q1). + # Listing 103: Q2 clean (has_estimated_lag=False) but ttm_has_estimated_lag=True; + # with allow_estimated_lag=False, 103 is kept, standalone revenue kept, ttm_* masked to None. + df_2024 = pl.DataFrame( + { + "listing_id": [101, 101, 102, 102, 103], + "effective_known_at": [ + datetime(2024, 8, 5, 16, 0, 0, tzinfo=timezone.utc), + datetime(2024, 9, 15, 16, 0, 0, tzinfo=timezone.utc), + datetime(2024, 5, 10, 16, 0, 0, tzinfo=timezone.utc), + datetime(2024, 8, 15, 16, 0, 0, tzinfo=timezone.utc), + datetime(2024, 8, 20, 16, 0, 0, tzinfo=timezone.utc), + ], + "known_at_source": [ + "edgar_filing", + "edgar_filing", + "edgar_filing", + "statutory_lag_estimate", + "edgar_filing", + ], + "has_estimated_lag": [False, False, False, True, False], + "period_end": [ + date(2024, 6, 30), + date(2024, 6, 30), + date(2024, 3, 31), + date(2024, 6, 30), + date(2024, 6, 30), + ], + "fiscal_period": ["Q2", "Q2", "Q1", "Q2", "Q2"], + "currency": ["USD", "USD", "USD", "USD", "USD"], + "period_known_at": [ + datetime(2024, 8, 5, 16, 0, 0, tzinfo=timezone.utc), + datetime(2024, 8, 5, 16, 0, 0, tzinfo=timezone.utc), + datetime(2024, 5, 10, 16, 0, 0, tzinfo=timezone.utc), + datetime(2024, 8, 15, 16, 0, 0, tzinfo=timezone.utc), + datetime(2024, 8, 20, 16, 0, 0, tzinfo=timezone.utc), + ], + "revenue": [120.0, 120.0, 50.0, 55.0, 80.0], + "net_income": [15.0, 15.0, 5.0, 6.0, 8.0], + "operating_cash_flow": [20.0, 20.0, 7.0, 8.0, 10.0], + "total_assets": [600.0, 600.0, 200.0, 210.0, 300.0], + "total_equity": [300.0, 300.0, 100.0, 105.0, 150.0], + "shares_outstanding": [100.0, 100.0, 50.0, 50.0, 75.0], + "ttm_period_end": [ + date(2024, 6, 30), + date(2024, 6, 30), + date(2024, 3, 31), + date(2024, 6, 30), + date(2024, 6, 30), + ], + "ttm_currency": ["USD", "USD", "USD", "USD", "USD"], + "ttm_revenue": [400.0, 415.0, 200.0, 210.0, 320.0], + "ttm_net_income": [40.0, 44.0, 20.0, 22.0, 32.0], + "ttm_operating_cash_flow": [50.0, 52.0, 25.0, 26.0, 40.0], + "ttm_has_estimated_lag": [False, False, False, True, True], + }, + schema_overrides={ + "listing_id": pl.Int32, + "effective_known_at": pl.Datetime("us", "UTC"), + "period_known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet_via_duckdb(df_2024, curated / "fundamentals_pit" / "year=2024" / "part.parquet") + + # Listing 104: snapshot at vault_cutoff_ts - 1 us (INCLUDED) vs exact vault_cutoff_ts (EXCLUDED) + df_2025 = pl.DataFrame( + { + "listing_id": [104, 104], + "effective_known_at": [ + datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=timezone.utc), + datetime(2025, 7, 1, 0, 0, 0, 0, tzinfo=timezone.utc), + ], + "known_at_source": ["edgar_filing", "edgar_filing"], + "has_estimated_lag": [False, False], + "period_end": [date(2025, 3, 31), date(2025, 6, 30)], + "fiscal_period": ["Q1", "Q2"], + "currency": ["USD", "USD"], + "period_known_at": [ + datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=timezone.utc), + datetime(2025, 7, 1, 0, 0, 0, 0, tzinfo=timezone.utc), + ], + "revenue": [200.0, 999.0], + "net_income": [20.0, 99.0], + "operating_cash_flow": [25.0, 110.0], + "total_assets": [700.0, 800.0], + "total_equity": [350.0, 400.0], + "shares_outstanding": [100.0, 100.0], + "ttm_period_end": [date(2025, 3, 31), date(2025, 6, 30)], + "ttm_currency": ["USD", "USD"], + "ttm_revenue": [800.0, 1999.0], + "ttm_net_income": [80.0, 199.0], + "ttm_operating_cash_flow": [100.0, 250.0], + "ttm_has_estimated_lag": [False, False], + }, + schema_overrides={ + "listing_id": pl.Int32, + "effective_known_at": pl.Datetime("us", "UTC"), + "period_known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet_via_duckdb(df_2025, curated / "fundamentals_pit" / "year=2025" / "part.parquet") + + with MarketDataStore(curated, vault_cutoff_ts=vault_cutoff_ms, budget=_make_budget(tmp_path)) as store: + # 1. Restated Q1 (known_at > Q2) updates TTM without overwriting Q2 + res = store.fundamentals_as_of( + listing_ids=[101], + fields=["revenue", "ttm_revenue"], + as_of="2024-10-01", + allow_estimated_lag=True, + ) + assert res.height == 1 + row = res.to_dicts()[0] + assert row["listing_id"] == 101 + assert row["period_end"] == date(2024, 6, 30) + assert row["fiscal_period"] == "Q2" + assert row["period_known_at"] == datetime(2024, 8, 5, 16, 0, 0, tzinfo=timezone.utc) + assert row["effective_known_at"] == datetime(2024, 9, 15, 16, 0, 0, tzinfo=timezone.utc) + assert row["revenue"] == pytest.approx(120.0) + assert row["ttm_revenue"] == pytest.approx(415.0) + + # 2. allow_estimated_lag=False omits 102 (no fallback to Q1) and masks 103's ttm_* to None + strict = store.fundamentals_as_of( + listing_ids=[103, 102, 101], + fields=["revenue", "ttm_revenue"], + as_of="2024-10-01", + allow_estimated_lag=False, + ) + assert strict["listing_id"].to_list() == [101, 103] + rows_by_id = {r["listing_id"]: r for r in strict.to_dicts()} + assert rows_by_id[103]["revenue"] == pytest.approx(80.0) + assert rows_by_id[103]["ttm_revenue"] is None + assert rows_by_id[103]["ttm_period_end"] is None + assert rows_by_id[103]["ttm_currency"] is None + assert rows_by_id[103]["ttm_has_estimated_lag"] is True + + # 3. Vault cutoff microsecond fence: as_of after cutoff clamps to cutoff - 1 us + vault_res = store.fundamentals_as_of( + listing_ids=[104], + fields=["revenue", "ttm_revenue"], + as_of="2025-09-01", + allow_estimated_lag=True, + ) + assert vault_res.height == 1 + vrow = vault_res.to_dicts()[0] + assert vrow["fiscal_period"] == "Q1" + assert vrow["revenue"] == pytest.approx(200.0) + assert vrow["effective_known_at"] == datetime( + 2025, 6, 30, 23, 59, 59, 999_999, tzinfo=timezone.utc + ) + + +# --------------------------------------------------------------------------- +# 3. macro_as_of lagged regime & Vault fence +# --------------------------------------------------------------------------- + + +def test_macro_as_of_lag_filtering_sort_and_vault(tmp_path: Path) -> None: + curated = tmp_path / "curated" + vault_cutoff_ms = int(datetime(2025, 7, 1, 0, 0, 0, tzinfo=timezone.utc).timestamp() * 1000) + + macro_df = pl.DataFrame( + { + "country_iso": ["US", "CA", "US", "US"], + "indicator": ["CPI", "RATE", "CPI", "CPI"], + "period_date": [ + date(2025, 4, 30), + date(2025, 4, 15), + date(2025, 3, 31), + date(2025, 6, 30), + ], + "known_at": [ + datetime(2025, 6, 4, 0, 0, 0, tzinfo=timezone.utc), # +35d lag + datetime(2025, 4, 16, 0, 0, 0, tzinfo=timezone.utc), # +1d lag + datetime(2025, 5, 5, 0, 0, 0, tzinfo=timezone.utc), # +35d lag + datetime(2025, 8, 4, 0, 0, 0, tzinfo=timezone.utc), # post-cutoff + ], + "known_at_source": ["statutory_lag"] * 4, + "value": [3.2, 4.75, 3.1, 9.9], + }, + schema_overrides={"known_at": pl.Datetime("us", "UTC")}, + ) + _write_parquet_via_duckdb(macro_df, curated / "macro" / "part.parquet") + + with MarketDataStore(curated, vault_cutoff_ts=vault_cutoff_ms, budget=_make_budget(tmp_path)) as store: + # Filter known_at <= as_of (excludes 2025-04-30 CPI whose known_at is 2025-06-04) + res = store.macro_as_of( + countries=["US", "CA"], + indicators=["CPI", "RATE"], + from_date="2025-01-01", + to_date="2025-06-30", + as_of="2025-05-20", + ) + assert res.columns == [ + "country_iso", + "indicator", + "period_date", + "known_at", + "known_at_source", + "value", + ] + assert res["country_iso"].to_list() == ["CA", "US"] + assert res["indicator"].to_list() == ["RATE", "CPI"] + assert res["period_date"].to_list() == [date(2025, 4, 15), date(2025, 3, 31)] + + # Straddling to_date clamps strictly < vault_cutoff_ts (excludes 2025-08-04 known_at row) + clamped = store.macro_as_of( + countries=["US"], + indicators=["CPI"], + from_date="2025-01-01", + to_date="2025-12-31", + ) + assert clamped["period_date"].to_list() == [date(2025, 3, 31), date(2025, 4, 30)] + + # Post-cutoff from_date raises VaultHoldoutFenceError + with pytest.raises(VaultHoldoutFenceError): + store.macro_as_of( + countries=["US"], + indicators=["CPI"], + from_date="2025-07-01", + to_date="2025-08-01", + ) + + +# --------------------------------------------------------------------------- +# 4. QuestDB 1m bars & fx PGWire safety and fx_1m bar-close boundary +# --------------------------------------------------------------------------- + + +def test_questdb_bars_1m_and_fx_1m_bar_close_and_dsn_redaction( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + curated = tmp_path / "curated" + curated.mkdir(parents=True, exist_ok=True) + cutoff_dt = datetime(2025, 7, 1, 0, 0, 0, tzinfo=timezone.utc) + cutoff_us = parse_timestamp_micros("2025-07-01T00:00:00.000000Z", "start", "cutoff") + cutoff_ms = cutoff_us // 1000 + + # 4a. Without QuestDB executor/DSN, 1m bars and 1m fx fail closed + with MarketDataStore(curated, vault_cutoff_ts=cutoff_ms, budget=_make_budget(tmp_path)) as plain: + with pytest.raises(MarketDataStoreValidationError): + plain.bars(listing_ids=[10], timeframe="1m", from_date="2025-06-30", to_date="2025-06-30") + with pytest.raises(MarketDataStoreValidationError): + plain.fx(pair="USD.CAD", timeframe="1m", from_date="2025-06-30", to_date="2025-06-30") + + # 4b. Recording executor for bars('1m') + bar_ts_us = parse_timestamp_micros("2025-06-30T15:30:00.000000Z", "start", "ts") + bar_exec = _RecordingQuestDbExecutor( + rows=[ + { + "listing_id": "10", + "ts_us": bar_ts_us, + "open": 10.0, + "high": 10.5, + "low": 9.9, + "close": 10.2, + "volume": 1500.0, + "vwap": 10.15, + "known_at_us": bar_ts_us + 60_000_000, + } + ] + ) + with MarketDataStore( + curated, + vault_cutoff_ts=cutoff_ms, + budget=_make_budget(tmp_path), + questdb_executor=bar_exec, + ) as store: + # Reject split/total and currencies on 1m + with pytest.raises(NotImplementedError): + store.bars( + listing_ids=[10], + timeframe="1m", + from_date="2025-06-30", + to_date="2025-06-30", + adjustment="split", + ) + with pytest.raises(MarketDataStoreValidationError): + store.bars( + listing_ids=[10], + currencies=["USD"], + timeframe="1m", + from_date="2025-06-30", + to_date="2025-06-30", + ) + + df = store.bars( + listing_ids=[20, 10, 10], + timeframe="1m", + from_date="2025-06-30", + to_date="2025-07-05", + adjustment="raw", + ) + assert len(bar_exec.calls) == 1 + sql, params = bar_exec.calls[0] + assert "listing_id IN (%s, %s)" in sql + assert "10" not in sql and "20" not in sql + assert params[2:4] == ("10", "20") + assert df.height == 1 + assert df["listing_id"].to_list() == [10] + assert df["close"].to_list() == [10.2] + assert bar_exec.closed is True + + # 4c. Defense-in-depth rejection when executor returns an out-of-fence microsecond bar + leaky_bar_exec = _RecordingQuestDbExecutor( + rows=[ + { + "listing_id": "10", + "ts_us": cutoff_us, # exact cutoff -> must be rejected! + "open": 10.0, + "high": 10.5, + "low": 9.9, + "close": 10.2, + "volume": 100.0, + "vwap": None, + "known_at_us": cutoff_us, + } + ] + ) + with MarketDataStore( + curated, + vault_cutoff_ts=cutoff_ms, + budget=_make_budget(tmp_path), + questdb_executor=leaky_bar_exec, + ) as store: + with pytest.raises(MarketDataStoreValidationError): + store.bars(listing_ids=[10], timeframe="1m", from_date="2025-06-30", to_date="2025-06-30") + + # 4d. fx('1m') bar-close availability rule (bar_close = ts + 60s strictly < vault_cutoff_ts and <= as_of) + valid_fx_ts_us = cutoff_us - 120_000_000 # closes at cutoff - 60s (INCLUDED) + fx_exec = _RecordingQuestDbExecutor( + rows=[ + { + "pair": "USDCAD", + "ts_us": valid_fx_ts_us, + "open": 1.3600, + "high": 1.3610, + "low": 1.3595, + "close": 1.3605, + "source": "eod", + } + ] + ) + with MarketDataStore( + curated, + vault_cutoff_ts=cutoff_ms, + budget=_make_budget(tmp_path), + questdb_executor=fx_exec, + ) as store: + fx_df = store.fx( + pair="USD.CAD", + timeframe="1m", + from_date="2025-06-30T23:55:00Z", + to_date="2025-07-01T00:05:00Z", + ) + assert fx_df.height == 1 + assert fx_df["known_at"].to_list() == [epoch_micros_to_datetime(valid_fx_ts_us + 60_000_000)] + sql, params = fx_exec.calls[0] + assert "WHERE pair = %s AND ts >= %s AND ts <= %s" in sql + # Upper SQL ts bound must be cutoff - 60_000_001 us so ts=cutoff-60s and ts=cutoff-30s are excluded + assert params[2] == "2025-06-30T23:58:59.999999Z" + + # Defense-in-depth rejects bars ending at cutoff (cutoff - 60s), spanning cutoff (cutoff - 30s), or closing after as_of + for bad_ts_us, query_as_of in [ + (cutoff_us - 60_000_000, None), # ends at exact vault_cutoff_ts + (cutoff_us - 30_000_000, None), # spans vault_cutoff_ts + ( + parse_timestamp_micros("2025-06-30T23:57:30Z", "start", "ts"), + "2025-06-30T23:58:00Z", # closes at 23:58:30Z > as_of 23:58:00Z + ), + ]: + bad_fx_exec = _RecordingQuestDbExecutor( + rows=[ + { + "pair": "USDCAD", + "ts_us": bad_ts_us, + "open": 1.36, + "high": 1.36, + "low": 1.36, + "close": 1.36, + "source": "eod", + } + ] + ) + with MarketDataStore( + curated, + vault_cutoff_ts=cutoff_ms, + budget=_make_budget(tmp_path), + questdb_executor=bad_fx_exec, + ) as store: + with pytest.raises(MarketDataStoreValidationError): + store.fx( + pair="USD.CAD", + timeframe="1m", + from_date="2025-06-30T23:55:00Z", + to_date="2025-06-30T23:59:59Z", + as_of=query_as_of, + ) + + # 4e. PsycopgQuestDbExecutor DSN credential redaction on error + secret_dsn = "postgresql://qdb_user:SuperSecretPass99@127.0.0.1:8812/qdb" + + def _boom(*_args: Any, **_kwargs: Any) -> Any: + raise RuntimeError(f"connection to {secret_dsn} failed with password=SuperSecretPass99") + + monkeypatch.setattr("stockbot.data.psycopg.connect", _boom) + pg_exec = PsycopgQuestDbExecutor(secret_dsn) + with pytest.raises(RuntimeError) as exc_info: + pg_exec.query("SELECT 1", ()) + msg = str(exc_info.value) + assert "SuperSecretPass99" not in msg + assert "qdb_user" not in msg + + +# --------------------------------------------------------------------------- +# 5. register_signal immutability, SQL sandboxing, hash parity & batch runs +# --------------------------------------------------------------------------- + + +def test_register_signal_immutability_and_sql_sandboxing() -> None: + registry = create_feature_registry() + reg1 = register_signal(RET_1D_V1, registry=registry) + reg2 = register_signal(RET_1D_V1, registry=registry) + assert reg1.ref == "ret_1d@v1" + assert reg1.definition_hash == reg2.definition_hash + assert parse_feature_ref(reg1.ref).name == "ret_1d" + assert parse_feature_ref(reg1.ref).version == 1 + + # Semantic drift on same version raises FEATURE_VERSION_IMMUTABLE + drifted = FeatureDefinition( + name="ret_1d", + version=1, + family="technical", + kind="duckdb_sql", + inputs=("bars_1d",), + warmup_bars=2, + known_at_rule="bar_close", + sql=RET_1D_V1.sql, + ) + with pytest.raises(FeatureLibraryError) as exc_info: + register_signal(drifted, registry=registry) + assert exc_info.value.code == "FEATURE_VERSION_IMMUTABLE" + + # Reject prohibited SQL constructs + bad_sqls = [ + ("SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} -- comment", "INVALID_SQL_STATEMENT"), + ("SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} /* block */", "INVALID_SQL_STATEMENT"), + ("SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}; DROP TABLE x", "INVALID_SQL_STATEMENT"), + ("SELECT listing_id, ts, ts AS known_at, ? AS value FROM {{input:bars_1d}}", "INVALID_SQL_STATEMENT"), + ("WITH RECURSIVE r AS (SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}) SELECT listing_id, ts, known_at, value FROM r", "INVALID_SQL_STATEMENT"), + ("SELECT listing_id, ts, ts AS known_at, close AS value FROM read_parquet('/tmp/x.parquet')", "EXTERNAL_DATA_ACCESS"), + ("SELECT listing_id, ts, ts AS known_at, close AS value FROM bars_1d", "EXTERNAL_DATA_ACCESS"), + ("SELECT * FROM {{input:bars_1d}}", "INVALID_SQL_PROJECTION"), + ("SELECT listing_id, ts, ts AS known_at, close AS wrong_col FROM {{input:bars_1d}}", "INVALID_SQL_PROJECTION"), + ("SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:shorts}}", "UNDECLARED_INPUT"), + ] + for bad_sql, expected_code in bad_sqls: + bad_def = FeatureDefinition( + name="bad_feat", + version=1, + family="technical", + kind="duckdb_sql", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + sql=bad_sql, + ) + with pytest.raises(FeatureLibraryError) as err: + validate_feature_definition(bad_def) + assert err.value.code == expected_code, f"SQL={bad_sql!r} expected {expected_code}, got {err.value.code}" + + +def test_ret_1d_v1_hash_parity_with_typescript() -> None: + bun_bin = shutil.which("bun") + assert bun_bin is not None, "bun is required for cross-language featureDefinitionHash parity check" + proc = subprocess.run( + [ + bun_bin, + "-e", + "import { RET_1D_V1, featureDefinitionHash } from './libs/research/src/feature-library.ts'; " + "console.log(featureDefinitionHash(RET_1D_V1));", + ], + cwd=str(REPO_ROOT), + capture_output=True, + text=True, + check=True, + ) + ts_hash = proc.stdout.strip() + py_hash = feature_definition_hash(RET_1D_V1) + assert len(py_hash) == 64 + assert py_hash == ts_hash + + +def _build_bars_and_events_fixtures(curated: Path) -> None: + # Year 2024: Dec 30 & Dec 31 21:00Z (warmup across year boundary!) + bars_2024 = pl.DataFrame( + { + "listing_id": [1, 1, 2, 2], + "session_date": [ + date(2024, 12, 30), + date(2024, 12, 31), + date(2024, 12, 30), + date(2024, 12, 31), + ], + "ts": [ + datetime(2024, 12, 30, 21, 0, 0, tzinfo=timezone.utc), + datetime(2024, 12, 31, 21, 0, 0, tzinfo=timezone.utc), + datetime(2024, 12, 30, 21, 0, 0, tzinfo=timezone.utc), + datetime(2024, 12, 31, 21, 0, 0, tzinfo=timezone.utc), + ], + "open": [10.0, 10.0, 20.0, 20.0], + "high": [10.5, 10.5, 20.5, 20.5], + "low": [9.5, 9.5, 19.5, 19.5], + "close": [10.0, 10.0, 20.0, 25.0], + "volume": [1000.0, 1000.0, 2000.0, 2000.0], + "vwap": [10.0, 10.0, 20.0, 25.0], + "currency": ["USD", "USD", "USD", "USD"], + "source": ["eod", "eod", "eod", "eod"], + "known_at": [ + datetime(2024, 12, 30, 21, 0, 0, tzinfo=timezone.utc), + datetime(2024, 12, 31, 21, 0, 0, tzinfo=timezone.utc), + datetime(2024, 12, 30, 21, 0, 0, tzinfo=timezone.utc), + datetime(2024, 12, 31, 21, 0, 0, tzinfo=timezone.utc), + ], + }, + schema_overrides={ + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet_via_duckdb(bars_2024, curated / "bars_1d" / "year=2024" / "part.parquet") + + # Year 2025: + # - Listing 1: Jan 2 close=11.0 (ret_1d = +0.10 using Dec 31 warmup!) + # - Listing 2: Jan 2 close=20.0 (ret_1d = -0.20 using Dec 31 warmup!) + # - Listing 3: Jan 2 first bar ever (no prev_close -> NULL in ret_1d@v1 cross_section!) + # - Listing 1: Jul 2 post-cutoff row (vault_cutoff_date = 2025-07-01 -> must be fenced out!) + bars_2025 = pl.DataFrame( + { + "listing_id": [1, 2, 3, 1], + "session_date": [ + date(2025, 1, 2), + date(2025, 1, 2), + date(2025, 1, 2), + date(2025, 7, 2), + ], + "ts": [ + datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), + datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), + datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), + datetime(2025, 7, 2, 21, 0, 0, tzinfo=timezone.utc), + ], + "open": [10.5, 24.0, 5.0, 15.0], + "high": [11.2, 24.5, 5.2, 15.5], + "low": [10.4, 19.8, 4.9, 14.8], + "close": [11.0, 20.0, 5.0, 15.0], + "volume": [1200.0, 2200.0, 500.0, 900.0], + "vwap": [11.0, 20.0, 5.0, 15.0], + "currency": ["USD", "USD", "USD", "USD"], + "source": ["eod", "eod", "eod", "eod"], + "known_at": [ + datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), + datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), + datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc), + datetime(2025, 7, 2, 21, 0, 0, tzinfo=timezone.utc), + ], + }, + schema_overrides={ + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet_via_duckdb(bars_2025, curated / "bars_1d" / "year=2025" / "part.parquet") + + # Co-published events/year=2025/part.parquet (filing) + part-posts.parquet (ceo_post) + events_filings = pl.DataFrame( + { + "listing_id": [1], + "ts": [datetime(2025, 1, 2, 14, 0, 0, tzinfo=timezone.utc)], + "known_at": [datetime(2025, 1, 2, 14, 0, 5, tzinfo=timezone.utc)], + "known_at_source": ["edgar_filing"], + "kind": ["filing"], + "subtype": ["8-K"], + "payload_json": ['{"form":"8-K"}'], + }, + schema_overrides={ + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet_via_duckdb(events_filings, curated / "events" / "year=2025" / "part.parquet") + + events_posts = pl.DataFrame( + { + "listing_id": [1], + "ts": [datetime(2025, 1, 2, 14, 0, 0, tzinfo=timezone.utc)], + "known_at": [datetime(2025, 1, 2, 14, 0, 1, tzinfo=timezone.utc)], + "known_at_source": ["ceo_post_ts"], + "kind": ["ceo_post"], + "subtype": ["board_post"], + "payload_json": ['{"author":"alice"}'], + }, + schema_overrides={ + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet_via_duckdb(events_posts, curated / "events" / "year=2025" / "part-posts.parquet") + + +def test_sql_and_polars_batch_materialization_cross_section_and_events(tmp_path: Path) -> None: + curated = tmp_path / "curated" + _build_bars_and_events_fixtures(curated) + budget = _make_budget(tmp_path) + vault_cutoff_date = "2025-07-01" + vault_cutoff_ms = parse_timestamp_micros(vault_cutoff_date, "start", "cutoff") // 1000 + + # 5a. Post-cutoff year range raises VAULT_RANGE_VIOLATION + with pytest.raises(FeatureLibraryError) as err: + plan_feature_batch( + RET_1D_V1, + curated_root=curated, + from_year=2025, + to_year=2026, + vault_cutoff_date="2025-01-01", + ) + assert err.value.code == "VAULT_RANGE_VIOLATION" + + # 5b. Materialize duckdb_sql feature (RET_1D_V1) across 2024..2025 + sql_manifest_1 = run_feature_batch( + RET_1D_V1, + curated_root=curated, + from_year=2024, + to_year=2025, + vault_cutoff_date=vault_cutoff_date, + budget=budget, + ) + assert sql_manifest_1.ref == "ret_1d@v1" + assert [w.year for w in sql_manifest_1.writes] == [2024, 2025] + + # Verify ZSTD compression, schema, and Vault clamping on 2025 partition + out_2025 = curated / "features" / "ret_1d" / "v1" / "year=2025" / "part.parquet" + con = duckdb.connect(":memory:") + try: + con.execute("SET TimeZone = 'UTC';") + meta = con.execute(f"SELECT compression FROM parquet_metadata('{out_2025}')").fetchall() + assert meta and all(row[0] == "ZSTD" for row in meta) + schema_rows = con.execute( + # hive_partitioning = false: DuckDB auto-detects `year=2025` in the path and would + # append a virtual `year` column; the contract is about the physical file schema. + f"SELECT column_name, column_type FROM (DESCRIBE SELECT * FROM read_parquet('{out_2025}', hive_partitioning = false))" + ).fetchall() + assert schema_rows == [ + ("listing_id", "INTEGER"), + ("ts", "TIMESTAMP WITH TIME ZONE"), + ("known_at", "TIMESTAMP WITH TIME ZONE"), + ("value", "DOUBLE"), + ] + rows_2025 = con.execute(f"SELECT listing_id, value FROM read_parquet('{out_2025}')").fetchall() + assert [r[0] for r in rows_2025] == [1, 2] # listing 3 had no prev_close; Jul 2 post-cutoff excluded + assert rows_2025[0][1] == pytest.approx(0.10) + assert rows_2025[1][1] == pytest.approx(-0.20) + finally: + con.close() + + # Deterministic replay check: second run produces identical rows + run_feature_batch( + RET_1D_V1, + curated_root=curated, + from_year=2024, + to_year=2025, + vault_cutoff_date=vault_cutoff_date, + budget=budget, + ) + replayed = pl.read_parquet(out_2025) + assert replayed["listing_id"].to_list() == [1, 2] + assert replayed["value"].to_list() == pytest.approx([0.10, -0.20]) + + # 5c. Materialize Polars feature (mom_diff@v1: close - prev_close) via register_signal + run_feature_batch + def _mom_diff_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.LazyFrame: + bars = inputs["bars_1d"].sort(["listing_id", "ts"]) + return ( + bars.with_columns( + pl.col("close").shift(1).over("listing_id").alias("prev_close") + ) + .filter(pl.col("prev_close").is_not_null()) + .select( + pl.col("listing_id"), + pl.col("ts"), + pl.col("ts").alias("known_at"), + (pl.col("close") - pl.col("prev_close")).cast(pl.Float64).alias("value"), + ) + ) + + reg_polars = register_signal( + name="mom_diff", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=1, + known_at_rule="bar_close", + polars_fn=_mom_diff_fn, + expression="close - lag(close, 1)", + registry=create_feature_registry(), + ) + polars_manifest = run_feature_batch( + reg_polars.definition, + curated_root=curated, + from_year=2025, + to_year=2025, + vault_cutoff_date=vault_cutoff_date, + budget=budget, + ) + assert polars_manifest.ref == "mom_diff@v1" + + # Polars input-tracking checks (UNDECLARED_INPUT & UNUSED_INPUT) + undeclared_def = FeatureDefinition( + name="bad_polars_u", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + polars_fn=lambda inp: inp["shorts"], + expression="shorts", + ) + with pytest.raises(FeatureLibraryError) as err: + run_feature_batch( + undeclared_def, + curated_root=curated, + from_year=2025, + to_year=2025, + vault_cutoff_date=vault_cutoff_date, + budget=budget, + ) + assert err.value.code == "UNDECLARED_INPUT" + + unused_def = FeatureDefinition( + name="bad_polars_unused", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + polars_fn=lambda _inp: pl.DataFrame( + {"listing_id": [1], "ts": [datetime(2025, 1, 2, tzinfo=timezone.utc)], "known_at": [datetime(2025, 1, 2, tzinfo=timezone.utc)], "value": [1.0]} + ), + expression="const(1.0)", + ) + with pytest.raises(FeatureLibraryError) as err: + run_feature_batch( + unused_def, + curated_root=curated, + from_year=2025, + to_year=2025, + vault_cutoff_date=vault_cutoff_date, + budget=budget, + ) + assert err.value.code == "UNUSED_INPUT" + + # 5d. Python cross_section + co-published events() verification + with MarketDataStore(curated, vault_cutoff_ts=vault_cutoff_ms, budget=budget) as store: + cs = store.cross_section( + features=["ret_1d@v1", "mom_diff@v1"], + date="2025-01-02", + universe="US_EQ", + as_of="2025-01-02T22:00:00Z", + ) + assert cs.columns == ["listing_id", "ret_1d@v1", "mom_diff@v1"] + assert cs["listing_id"].to_list() == [1, 2, 3] + assert cs["ret_1d@v1"].to_list()[0] == pytest.approx(0.10) + assert cs["ret_1d@v1"].to_list()[1] == pytest.approx(-0.20) + assert cs["ret_1d@v1"].to_list()[2] is None # active universe listing with missing feature -> null + assert cs["mom_diff@v1"].to_list()[0] == pytest.approx(1.0) + assert cs["mom_diff@v1"].to_list()[1] == pytest.approx(-5.0) + assert cs["mom_diff@v1"].to_list()[2] is None + + # Post-as_of feature row exclusion: as_of before 21:00Z excludes all 21:00Z feature rows + cs_early = store.cross_section( + features=["ret_1d@v1"], + date="2025-01-02", + universe="US_EQ", + as_of="2025-01-02T20:00:00Z", + ) + assert cs_early["listing_id"].to_list() == [1, 2] # active from Dec 31 bars within 7d lookback + assert cs_early["ret_1d@v1"].to_list() == [None, None] + + # Co-published events/year=2025/part.parquet + part-posts.parquet (kind='ceo_post') + ev = store.events( + kinds=["filing", "ceo_post"], + listing_ids=[1], + from_date="2025-01-01", + to_date="2025-01-05", + ) + assert ev.height == 2 + assert ev["kind"].to_list() == ["ceo_post", "filing"] # tie-breaker: kind ASC + + # 5e. Cross-language Bun @stock-bot/duckdb read-back parity check (public MarketDataStore.crossSection) + bun_bin = shutil.which("bun") + assert bun_bin is not None, "bun is required for cross-language Parquet read-back check" + script = f""" +import {{ openDuckDbMarketDataStore }} from './libs/data/duckdb/src/index.ts'; +const curatedRoot = {json.dumps(str(curated))}; +const vaultCutoffTs = {vault_cutoff_ms}; +const opened = await openDuckDbMarketDataStore({{ + curatedRoot, + vaultCutoffTs, + env: {{ + STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', + STOCKBOT_DUCKDB_THREADS: '2', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))}, + STOCK_BOT_DUCKDB_TEMP_DIR: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))}, + }}, +}}); +try {{ + const result = await opened.store.crossSection({{ + features: ['ret_1d@v1', 'mom_diff@v1'], + date: '2025-01-02', + universe: 'US_EQ', + asOf: '2025-01-02T22:00:00Z', + }}); + console.log(JSON.stringify(result)); +}} finally {{ + await opened.close(); +}} +""" + proc = subprocess.run( + [bun_bin, "-e", script], + cwd=str(REPO_ROOT), + capture_output=True, + text=True, + ) + assert ( + proc.returncode == 0 + ), f"bun crossSection exited {proc.returncode}:\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr}" + ts_payload = json.loads(proc.stdout.strip()) + assert ts_payload["columns"] == cs.columns + ts_rows = ts_payload["rows"] + py_rows = cs.to_dicts() + assert len(ts_rows) == len(py_rows) + for ts_row, py_row in zip(ts_rows, py_rows): + assert ts_row["listing_id"] == py_row["listing_id"] + for col in ("ret_1d@v1", "mom_diff@v1"): + if py_row[col] is None: + assert ts_row[col] is None + else: + assert math.isclose(ts_row[col], py_row[col], rel_tol=1e-12, abs_tol=1e-12) + + +def test_polars_batch_per_year_availability_ceiling_blocks_later_year_macro_leak( + tmp_path: Path, +) -> None: + curated = tmp_path / "curated" + _build_bars_and_events_fixtures(curated) + budget = _make_budget(tmp_path) + + # Extend 2025 bars with an April 1 bar (after the 2025-03-15 macro release) alongside + # the Jan 2 bars (before the 2025-03-15 release) and Jul 2 post-Vault bar. + bars_2025_existing = pl.read_parquet(curated / "bars_1d" / "year=2025" / "part.parquet") + bars_2025_apr = pl.DataFrame( + { + "listing_id": [1], + "session_date": [date(2025, 4, 1)], + "ts": [datetime(2025, 4, 1, 21, 0, 0, tzinfo=timezone.utc)], + "open": [11.5], + "high": [12.2], + "low": [11.4], + "close": [12.0], + "volume": [1300.0], + "vwap": [12.0], + "currency": ["USD"], + "source": ["eod"], + "known_at": [datetime(2025, 4, 1, 21, 0, 0, tzinfo=timezone.utc)], + }, + schema_overrides={ + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet_via_duckdb( + pl.concat([bars_2025_existing, bars_2025_apr]), + curated / "bars_1d" / "year=2025" / "part.parquet", + ) + + # Macro releases across 2023 (prior history), 2024, 2025 pre-Vault, and 2025 post-Vault + macro_df = pl.DataFrame( + { + "country_iso": ["US", "US", "US", "US"], + "indicator": ["CPI", "CPI", "CPI", "CPI"], + "period_date": [ + date(2023, 12, 1), + date(2024, 6, 1), + date(2025, 2, 1), + date(2025, 7, 1), + ], + "value": [1.0, 2.0, 99.0, 999.0], + "unit": ["pct", "pct", "pct", "pct"], + "known_at": [ + datetime(2023, 12, 15, 13, 30, 0, tzinfo=timezone.utc), + datetime(2024, 7, 15, 13, 30, 0, tzinfo=timezone.utc), + datetime(2025, 3, 15, 13, 30, 0, tzinfo=timezone.utc), + datetime(2025, 8, 15, 13, 30, 0, tzinfo=timezone.utc), + ], + "known_at_source": ["statutory_lag"] * 4, + "has_estimated_lag": [True] * 4, + }, + schema_overrides={ + "known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet_via_duckdb(macro_df, curated / "macro" / "part.parquet") + + seen_macro_counts: list[int] = [] + + def _asof_macro_regime_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: + macro_rows = ( + inputs["macro"] + .select( + pl.col("known_at").alias("macro_known_at"), + pl.col("value").cast(pl.Float64).alias("macro_value"), + ) + .sort("macro_known_at") + .collect() + ) + seen_macro_counts.append(macro_rows.height) + bars = inputs["bars_1d"].select("listing_id", "ts").sort("ts").collect() + joined = bars.join_asof( + macro_rows, + left_on="ts", + right_on="macro_known_at", + strategy="backward", + coalesce=False, + ) + return joined.select( + pl.col("listing_id"), + pl.col("ts"), + pl.max_horizontal("ts", "macro_known_at").alias("known_at"), + pl.col("macro_value").alias("value"), + ) + + defn = register_signal( + name="macro_regime_latest", + version=1, + family="regime", + kind="polars", + inputs=("bars_1d", "macro"), + warmup_bars=0, + known_at_rule="max_input_known_at", + polars_fn=_asof_macro_regime_fn, + expression="asof(macro.value)", + registry=create_feature_registry(), + ).definition + + manifest = run_feature_batch( + defn, + curated_root=curated, + from_year=2024, + to_year=2025, + vault_cutoff_date="2025-07-01", + budget=budget, + ) + assert [w.year for w in manifest.writes] == [2024, 2025] + # 2024 sees 2023 + 2024 (2 rows, retaining prior-year history, excluding 2025 release); + # 2025 sees 2023 + 2024 + 2025-03 (3 rows, excluding 2025-08 post-Vault release). + assert seen_macro_counts == [2, 3] + + out_2024 = pl.read_parquet( + curated / "features" / "macro_regime_latest" / "v1" / "year=2024" / "part.parquet" + ) + out_2025 = pl.read_parquet( + curated / "features" / "macro_regime_latest" / "v1" / "year=2025" / "part.parquet" + ) + assert out_2024.height > 0 + assert all(v == pytest.approx(2.0) for v in out_2024["value"].to_list()) + + # In 2025, Jan 2 bars precede the 2025-03-15 release so they must still see 2.0 (not 99.0); + # only the Apr 1 bar (after 2025-03-15) sees 99.0, and the post-Vault Jul 2 bar is excluded. + jan_2025 = out_2025.filter(pl.col("ts") == datetime(2025, 1, 2, 21, 0, 0, tzinfo=timezone.utc)) + apr_2025 = out_2025.filter(pl.col("ts") == datetime(2025, 4, 1, 21, 0, 0, tzinfo=timezone.utc)) + assert jan_2025.height == 3 + assert all(v == pytest.approx(2.0) for v in jan_2025["value"].to_list()) + assert apr_2025.height == 1 + assert apr_2025["value"].to_list() == pytest.approx([99.0]) + assert out_2025.height == 4 + + +def test_run_feature_batch_persists_definition_hash_and_blocks_cross_registry_overwrite( + tmp_path: Path, +) -> None: + curated = tmp_path / "curated" + _build_bars_and_events_fixtures(curated) + budget = _make_budget(tmp_path) + + def _fn_v1(inputs: Mapping[str, pl.LazyFrame]) -> pl.LazyFrame: + return inputs["bars_1d"].select( + pl.col("listing_id"), + pl.col("ts"), + pl.col("ts").alias("known_at"), + pl.col("close").cast(pl.Float64).alias("value"), + ) + + reg_a = register_signal( + name="close_level", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + polars_fn=_fn_v1, + expression="close", + registry=create_feature_registry(), + ) + run_feature_batch( + reg_a.definition, + curated_root=curated, + from_year=2025, + to_year=2025, + vault_cutoff_date="2025-07-01", + budget=budget, + ) + + out_2025 = curated / "features" / "close_level" / "v1" / "year=2025" / "part.parquet" + meta_file = curated / "features" / "close_level" / "v1" / "_definition.json" + assert meta_file.exists() + original_bytes = out_2025.read_bytes() + + # Fresh registry (simulating restarted notebook) with modified formula under same name + version + def _fn_mutated(inputs: Mapping[str, pl.LazyFrame]) -> pl.LazyFrame: + return inputs["bars_1d"].select( + pl.col("listing_id"), + pl.col("ts"), + pl.col("ts").alias("known_at"), + (pl.col("close") * 2.0).cast(pl.Float64).alias("value"), + ) + + reg_b = register_signal( + name="close_level", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + polars_fn=_fn_mutated, + expression="close * 2.0", + registry=create_feature_registry(), + ) + with pytest.raises(FeatureLibraryError) as err: + run_feature_batch( + reg_b.definition, + curated_root=curated, + from_year=2025, + to_year=2025, + vault_cutoff_date="2025-07-01", + budget=budget, + ) + assert err.value.code == "FEATURE_VERSION_IMMUTABLE" + assert out_2025.read_bytes() == original_bytes + + +def test_polars_batch_post_publication_failure_wraps_in_batch_write_failed_with_receipts( + tmp_path: Path, +) -> None: + curated = tmp_path / "curated" + _build_bars_and_events_fixtures(curated) + budget = _make_budget(tmp_path) + + call_count = 0 + + def _fail_second_year_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: + nonlocal call_count + call_count += 1 + bars = inputs["bars_1d"].collect() + if call_count == 2: + # Return empty DataFrame missing required output columns on year 2025 + return pl.DataFrame() + return bars.select( + pl.col("listing_id"), + pl.col("ts"), + pl.col("ts").alias("known_at"), + pl.col("close").cast(pl.Float64).alias("value"), + ) + + defn = FeatureDefinition( + name="fail_year2", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + polars_fn=_fail_second_year_fn, + expression="close_fail_year2", + ) + + with pytest.raises(FeatureLibraryError) as err: + run_feature_batch( + defn, + curated_root=curated, + from_year=2024, + to_year=2025, + vault_cutoff_date="2025-07-01", + budget=budget, + ) + + assert err.value.code == "BATCH_WRITE_FAILED" + assert err.value.failed_year == 2025 + assert err.value.completed_years == (2024,) + assert len(err.value.completed_writes) == 1 + assert err.value.completed_writes[0].year == 2024 + assert err.value.completed_writes[0].output_path.endswith( + "features/fail_year2/v1/year=2024/part.parquet" + ) + assert isinstance(err.value.__cause__, FeatureLibraryError) + assert err.value.__cause__.code == "INVALID_SQL_PROJECTION" + + +def test_run_feature_batch_rejects_sidecar_free_ts_partitions(tmp_path: Path) -> None: + curated = tmp_path / "curated" + _build_bars_and_events_fixtures(curated) + budget = _make_budget(tmp_path) + vault_cutoff_date = "2025-07-01" + vault_cutoff_ms = parse_timestamp_micros(vault_cutoff_date, "start", "cutoff") // 1000 + + # Materialize ret_1d@v1 year=2024 using the TypeScript batch runner (no _definition.json sidecar) + bun_bin = shutil.which("bun") + assert bun_bin is not None, "bun is required for TypeScript sidecar-free fixture" + year_2024_dir = curated / "features" / "ret_1d" / "v1" / "year=2024" + year_2024_dir.mkdir(parents=True, exist_ok=True) + script = f""" +import {{ openDuckDbMarketDataStore }} from './libs/data/duckdb/src/index.ts'; +import {{ RET_1D_V1, runFeatureBatch }} from './libs/research/src/feature-library.ts'; +const curatedRoot = {json.dumps(str(curated))}; +const vaultCutoffTs = {vault_cutoff_ms}; +const opened = await openDuckDbMarketDataStore({{ + curatedRoot, + vaultCutoffTs, + env: {{ + STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', + STOCKBOT_DUCKDB_THREADS: '2', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))}, + STOCK_BOT_DUCKDB_TEMP_DIR: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))}, + }}, +}}); +try {{ + await opened.executor.run("SET TimeZone = 'UTC';"); + await runFeatureBatch( + RET_1D_V1, + {{ curatedRoot, fromYear: 2024, toYear: 2024, vaultCutoffDate: {json.dumps(vault_cutoff_date)} }}, + opened.executor, + ); +}} finally {{ + await opened.close(); +}} +""" + subprocess.run( + [bun_bin, "-e", script], + cwd=str(REPO_ROOT), + capture_output=True, + text=True, + check=True, + ) + + ts_part_2024 = year_2024_dir / "part.parquet" + meta_file = curated / "features" / "ret_1d" / "v1" / "_definition.json" + part_2025 = curated / "features" / "ret_1d" / "v1" / "year=2025" / "part.parquet" + assert ts_part_2024.exists() + assert not meta_file.exists() + original_2024_bytes = ts_part_2024.read_bytes() + + # Promoting a revised Python formula under ret_1d@v1 for 2025 must fail closed + revised_ret = register_signal( + name="ret_1d", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=1, + known_at_rule="bar_close", + polars_fn=lambda inp: inp["bars_1d"].select( + pl.col("listing_id"), + pl.col("ts"), + pl.col("ts").alias("known_at"), + (pl.col("close") * 0.0).cast(pl.Float64).alias("value"), + ), + expression="0.0", + registry=create_feature_registry(), + ).definition + + with pytest.raises(FeatureLibraryError) as err: + run_feature_batch( + revised_ret, + curated_root=curated, + from_year=2025, + to_year=2025, + vault_cutoff_date=vault_cutoff_date, + budget=budget, + ) + assert err.value.code == "FEATURE_VERSION_IMMUTABLE" + assert not meta_file.exists() + assert not part_2025.exists() + assert ts_part_2024.read_bytes() == original_2024_bytes + + +def test_run_feature_batch_atomic_version_claim_blocks_competing_first_writes( + tmp_path: Path, +) -> None: + curated = tmp_path / "curated" + _build_bars_and_events_fixtures(curated) + vault_cutoff_date = "2025-07-01" + barrier = threading.Barrier(2, timeout=10.0) + + def _fn_a(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: + barrier.wait() + return ( + inputs["bars_1d"] + .select( + pl.col("listing_id"), + pl.col("ts"), + pl.col("ts").alias("known_at"), + pl.col("close").cast(pl.Float64).alias("value"), + ) + .collect() + ) + + def _fn_b(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: + barrier.wait() + return ( + inputs["bars_1d"] + .select( + pl.col("listing_id"), + pl.col("ts"), + pl.col("ts").alias("known_at"), + (pl.col("close") * 2.0).cast(pl.Float64).alias("value"), + ) + .collect() + ) + + reg_a = register_signal( + name="close_race", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + polars_fn=_fn_a, + expression="close", + registry=create_feature_registry(), + ) + reg_b = register_signal( + name="close_race", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + polars_fn=_fn_b, + expression="close * 2.0", + registry=create_feature_registry(), + ) + + def _run_writer( + defn: FeatureDefinition, year: int, tag: str + ) -> tuple[str, Any]: + try: + manifest = run_feature_batch( + defn, + curated_root=curated, + from_year=year, + to_year=year, + vault_cutoff_date=vault_cutoff_date, + budget=_make_budget(tmp_path / tag), + ) + return ("ok", manifest) + except FeatureLibraryError as exc: + return ("err", exc) + + with ThreadPoolExecutor(max_workers=2) as pool: + fut_a = pool.submit(_run_writer, reg_a.definition, 2024, "a") + fut_b = pool.submit(_run_writer, reg_b.definition, 2025, "b") + res_a = fut_a.result() + res_b = fut_b.result() + + outcomes = [res_a, res_b] + winners = [payload for status, payload in outcomes if status == "ok"] + losers = [payload for status, payload in outcomes if status == "err"] + assert len(winners) == 1 + assert len(losers) == 1 + assert isinstance(losers[0], FeatureLibraryError) + assert losers[0].code == "FEATURE_VERSION_IMMUTABLE" + + winner_manifest = winners[0] + version_dir = curated / "features" / "close_race" / "v1" + meta_payload = json.loads((version_dir / "_definition.json").read_text(encoding="utf-8")) + assert meta_payload["definition_hash"] == winner_manifest.definition_hash + + part_2024 = version_dir / "year=2024" / "part.parquet" + part_2025 = version_dir / "year=2025" / "part.parquet" + if winner_manifest.definition_hash == reg_a.definition_hash: + assert part_2024.exists() + assert not part_2025.exists() + else: + assert winner_manifest.definition_hash == reg_b.definition_hash + assert part_2025.exists() + assert not part_2024.exists() + + leftover_tmp = [p for p in version_dir.rglob("*.tmp")] + assert leftover_tmp == [] + + +def test_sdk_exports() -> None: + expected_exports = ( + "features", + "register_signal", + "create_feature_registry", + "FeatureDefinition", + "RegisteredFeature", + "FeatureRegistry", + "FeatureLibraryError", + "RET_1D_V1", + "feature_ref", + "parse_feature_ref", + "feature_definition_hash", + "validate_feature_definition", + "plan_feature_batch", + "run_feature_batch", + "QuestDbExecutor", + "PsycopgQuestDbExecutor", + ) + for name in expected_exports: + assert hasattr(stockbot, name), f"Missing stockbot export: {name}" + assert name in stockbot.__all__, f"Missing {name} in stockbot.__all__" + assert hasattr(stockbot.signals, "register_signal") diff --git a/python/tests/test_m2_sdk_qa_edges.py b/python/tests/test_m2_sdk_qa_edges.py new file mode 100644 index 00000000..a0541cfd --- /dev/null +++ b/python/tests/test_m2_sdk_qa_edges.py @@ -0,0 +1,447 @@ +"""QA edge cases for T-213 (M2.4b) Python `stockbot` batch runner and cross_section. + +Offline only: every test builds its own temporary curated root of Parquet fixtures and +touches no QA database, live QuestDB, or execution module. +""" + +from __future__ import annotations + +import json +import os +from datetime import datetime, timezone +from pathlib import Path +from typing import Mapping + +import duckdb +import polars as pl +import pytest + +import stockbot.features as features_mod +from stockbot import ( + RET_1D_V1, + DuckDbConnectionBudget, + FeatureDefinition, + FeatureLibraryError, + MarketDataStore, + MarketDataStoreValidationError, + VaultHoldoutFenceError, + run_feature_batch, +) +from stockbot.vault import parse_timestamp_micros + +UTC = timezone.utc +VAULT_CUTOFF_DATE = "2025-07-01" +VAULT_CUTOFF_MS = parse_timestamp_micros(VAULT_CUTOFF_DATE, "start", "cutoff") // 1000 + + +def _budget(tmp_path: Path) -> DuckDbConnectionBudget: + tmp_dir = tmp_path / "duckdb_tmp" + tmp_dir.mkdir(parents=True, exist_ok=True) + return DuckDbConnectionBudget(memory_limit="512MB", threads=2, temp_directory=str(tmp_dir)) + + +def _write_parquet(df: pl.DataFrame, out_path: Path) -> None: + out_path.parent.mkdir(parents=True, exist_ok=True) + con = duckdb.connect(":memory:") + try: + con.execute("SET TimeZone = 'UTC';") + con.register("src", df) + con.execute(f"COPY src TO '{out_path}' (FORMAT PARQUET, COMPRESSION ZSTD)") + finally: + con.close() + + +def _bars(rows: list[tuple[int, datetime, float]]) -> pl.DataFrame: + """Builds bars_1d rows (listing_id, bar-close ts, close) with known_at == ts.""" + return pl.DataFrame( + { + "listing_id": [r[0] for r in rows], + "session_date": [r[1].date() for r in rows], + "ts": [r[1] for r in rows], + "open": [r[2] for r in rows], + "high": [r[2] for r in rows], + "low": [r[2] for r in rows], + "close": [r[2] for r in rows], + "volume": [1000.0 for _ in rows], + "vwap": [r[2] for r in rows], + "currency": ["USD" for _ in rows], + "source": ["eod" for _ in rows], + "known_at": [r[1] for r in rows], + }, + schema_overrides={ + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "known_at": pl.Datetime("us", "UTC"), + "session_date": pl.Date, + }, + ) + + +def _seed_two_year_bars(curated: Path) -> None: + _write_parquet( + _bars( + [ + (1, datetime(2024, 12, 30, 21, tzinfo=UTC), 8.0), + (1, datetime(2024, 12, 31, 21, tzinfo=UTC), 10.0), + (2, datetime(2024, 12, 31, 21, tzinfo=UTC), 20.0), + ] + ), + curated / "bars_1d" / "year=2024" / "part.parquet", + ) + _write_parquet( + _bars( + [ + (1, datetime(2025, 1, 2, 21, tzinfo=UTC), 50.0), + (2, datetime(2025, 1, 2, 21, tzinfo=UTC), 30.0), + # Post-Vault bar (cutoff 2025-07-01): must never reach any partition. + (1, datetime(2025, 7, 2, 21, tzinfo=UTC), 1000.0), + ] + ), + curated / "bars_1d" / "year=2025" / "part.parquet", + ) + + +def _partition(curated: Path, name: str, year: int) -> Path: + return curated / "features" / name / "v1" / f"year={year}" / "part.parquet" + + +def _sql_feature(name: str, sql: str) -> FeatureDefinition: + return FeatureDefinition( + name=name, + version=1, + family="technical", + kind="duckdb_sql", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + sql=sql, + ) + + +def test_sql_batch_earlier_year_partition_cannot_see_later_year_bars(tmp_path: Path) -> None: + # Arrange: an unordered whole-history window (MAX over the listing) would leak the + # 2025 close of 50.0 into 2024 rows if the 2024 scan were only fenced by the Vault cutoff. + curated = tmp_path / "curated" + _seed_two_year_bars(curated) + defn = _sql_feature( + "max_close_all", + "SELECT listing_id, ts, ts AS known_at, " + "MAX(close) OVER (PARTITION BY listing_id) AS value " + "FROM {{input:bars_1d}}", + ) + + # Act + manifest = run_feature_batch( + defn, + curated_root=curated, + from_year=2024, + to_year=2025, + vault_cutoff_date=VAULT_CUTOFF_DATE, + budget=_budget(tmp_path), + ) + + # Assert + assert [w.year for w in manifest.writes] == [2024, 2025] + out_2024 = pl.read_parquet(_partition(curated, "max_close_all", 2024), hive_partitioning=False) + out_2025 = pl.read_parquet(_partition(curated, "max_close_all", 2025), hive_partitioning=False) + assert out_2024.select("listing_id", "value").rows() == [(1, 10.0), (1, 10.0), (2, 20.0)] + # 2025 sees 2024 history plus Jan 2 bars, never the post-Vault 1000.0 close. + assert out_2025.select("listing_id", "value").rows() == [(1, 50.0), (2, 30.0)] + + +def test_feature_batch_replay_is_deterministic_and_idempotent_on_same_definition( + tmp_path: Path, +) -> None: + # Arrange: two independent curated roots with identical retained inputs. + root_a = tmp_path / "a" / "curated" + root_b = tmp_path / "b" / "curated" + _seed_two_year_bars(root_a) + _seed_two_year_bars(root_b) + + # Act: run A twice (same definition re-publish) and B once. + kwargs = dict(from_year=2024, to_year=2025, vault_cutoff_date=VAULT_CUTOFF_DATE) + manifest_a1 = run_feature_batch(RET_1D_V1, curated_root=root_a, budget=_budget(tmp_path / "a"), **kwargs) + sidecar_a = (root_a / "features" / "ret_1d" / "v1" / "_definition.json").read_bytes() + manifest_a2 = run_feature_batch(RET_1D_V1, curated_root=root_a, budget=_budget(tmp_path / "a"), **kwargs) + manifest_b = run_feature_batch(RET_1D_V1, curated_root=root_b, budget=_budget(tmp_path / "b"), **kwargs) + + # Assert: same hash, unchanged sidecar, identical ordered rows across replays/roots. + assert manifest_a1.definition_hash == manifest_a2.definition_hash == manifest_b.definition_hash + assert (root_a / "features" / "ret_1d" / "v1" / "_definition.json").read_bytes() == sidecar_a + assert json.loads(sidecar_a)["definition_hash"] == manifest_a1.definition_hash + for year in (2024, 2025): + a = pl.read_parquet(_partition(root_a, "ret_1d", year), hive_partitioning=False) + b = pl.read_parquet(_partition(root_b, "ret_1d", year), hive_partitioning=False) + assert a.equals(b) + # Hand-computed ret_1d: 2024 L1 10/8-1 = 0.25; 2025 L1 50/10-1 = 4.0, L2 30/20-1 = 0.5. + out_2024 = pl.read_parquet(_partition(root_a, "ret_1d", 2024), hive_partitioning=False) + out_2025 = pl.read_parquet(_partition(root_a, "ret_1d", 2025), hive_partitioning=False) + assert out_2024.select("listing_id", "value").rows() == [(1, pytest.approx(0.25))] + assert out_2025.select("listing_id", "value").rows() == [ + (1, pytest.approx(4.0)), + (2, pytest.approx(0.5)), + ] + + +def test_unreadable_definition_sidecar_fails_closed_before_any_write(tmp_path: Path) -> None: + # Arrange + curated = tmp_path / "curated" + _seed_two_year_bars(curated) + version_dir = curated / "features" / "ret_1d" / "v1" + version_dir.mkdir(parents=True) + (version_dir / "_definition.json").write_text("{not json", encoding="utf-8") + + # Act + with pytest.raises(FeatureLibraryError) as err: + run_feature_batch( + RET_1D_V1, + curated_root=curated, + from_year=2024, + to_year=2025, + vault_cutoff_date=VAULT_CUTOFF_DATE, + budget=_budget(tmp_path), + ) + + # Assert + assert err.value.code == "FEATURE_VERSION_IMMUTABLE" + assert sorted(p.name for p in version_dir.rglob("*")) == ["_definition.json"] + + +def test_claim_collision_between_check_and_link_aborts_before_publishing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # Arrange: deterministically inject a competing writer's claim in the window between the + # missing-sidecar check and the create-if-absent link. + curated = tmp_path / "curated" + _seed_two_year_bars(curated) + real_link = os.link + link_calls: list[str] = [] + + def _competing_link(src: str, dst: str) -> None: + link_calls.append(dst) + with open(dst, "w", encoding="utf-8") as fh: + json.dump({"definition_hash": "0" * 64, "ref": "ret_1d@v1"}, fh) + real_link(src, dst) # raises FileExistsError, exactly as a lost race would + + monkeypatch.setattr(features_mod.os, "link", _competing_link) + + # Act + with pytest.raises(FeatureLibraryError) as err: + run_feature_batch( + RET_1D_V1, + curated_root=curated, + from_year=2024, + to_year=2025, + vault_cutoff_date=VAULT_CUTOFF_DATE, + budget=_budget(tmp_path), + ) + + # Assert: the loser verified the winning hash and published nothing. + assert len(link_calls) == 1 + assert err.value.code == "FEATURE_VERSION_IMMUTABLE" + version_dir = curated / "features" / "ret_1d" / "v1" + assert list(version_dir.rglob("*.parquet")) == [] + assert list(version_dir.rglob("*.tmp")) == [] + assert json.loads((version_dir / "_definition.json").read_text())["definition_hash"] == "0" * 64 + + +def test_polars_output_rows_at_or_after_vault_cutoff_are_dropped_at_microsecond_boundary( + tmp_path: Path, +) -> None: + # Arrange: callable fabricates rows straddling the cutoff by one microsecond. + curated = tmp_path / "curated" + _seed_two_year_bars(curated) + just_before = datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=UTC) + at_cutoff = datetime(2025, 7, 1, 0, 0, 0, tzinfo=UTC) + + def _fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame: + inputs["bars_1d"].collect() + return pl.DataFrame( + { + "listing_id": [1, 2], + "ts": [just_before, at_cutoff], + "known_at": [just_before, at_cutoff], + "value": [1.5, 2.5], + }, + schema_overrides={ + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "known_at": pl.Datetime("us", "UTC"), + }, + ) + + defn = FeatureDefinition( + name="cutoff_probe", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + polars_fn=_fn, + expression="cutoff_probe", + ) + + # Act + run_feature_batch( + defn, + curated_root=curated, + from_year=2025, + to_year=2025, + vault_cutoff_date=VAULT_CUTOFF_DATE, + budget=_budget(tmp_path), + ) + + # Assert + out = pl.read_parquet(_partition(curated, "cutoff_probe", 2025), hive_partitioning=False) + assert out.select("listing_id", "ts", "value").rows() == [(1, just_before, 1.5)] + + +def test_polars_non_finite_value_fails_without_publishing_partition_or_claim( + tmp_path: Path, +) -> None: + # Arrange + curated = tmp_path / "curated" + _seed_two_year_bars(curated) + + def _fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.LazyFrame: + return inputs["bars_1d"].select( + pl.col("listing_id"), + pl.col("ts"), + pl.col("ts").alias("known_at"), + (pl.col("close") / 0.0).alias("value"), + ) + + defn = FeatureDefinition( + name="inf_probe", + version=1, + family="technical", + kind="polars", + inputs=("bars_1d",), + warmup_bars=0, + known_at_rule="bar_close", + polars_fn=_fn, + expression="close / 0", + ) + + # Act + with pytest.raises(FeatureLibraryError) as err: + run_feature_batch( + defn, + curated_root=curated, + from_year=2024, + to_year=2024, + vault_cutoff_date=VAULT_CUTOFF_DATE, + budget=_budget(tmp_path), + ) + + # Assert + assert err.value.code == "BATCH_WRITE_FAILED" + assert err.value.failed_year == 2024 + assert err.value.completed_years == () + version_dir = curated / "features" / "inf_probe" / "v1" + assert not (version_dir / "_definition.json").exists() + assert list(version_dir.rglob("*.parquet")) == [] + assert list(version_dir.rglob("*.tmp")) == [] + + +def _seed_cross_section_fixture(curated: Path) -> None: + session_close = datetime(2025, 6, 30, 21, tzinfo=UTC) + _write_parquet( + _bars([(1, session_close, 10.0), (2, session_close, 20.0), (3, session_close, 30.0)]), + curated / "bars_1d" / "year=2025" / "part.parquet", + ) + feature = pl.DataFrame( + { + "listing_id": [1, 2], + "ts": [session_close, session_close], + # L1 becomes known exactly at the Vault cutoff (must be fenced out); + # L2 one microsecond earlier (must be returned). + "known_at": [ + datetime(2025, 7, 1, 0, 0, 0, tzinfo=UTC), + datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=UTC), + ], + "value": [9.0, 7.0], + }, + schema_overrides={ + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "known_at": pl.Datetime("us", "UTC"), + }, + ) + _write_parquet(feature, _partition(curated, "probe", 2025)) + + +def test_cross_section_clamps_late_as_of_to_vault_cutoff_microsecond(tmp_path: Path) -> None: + # Arrange + curated = tmp_path / "curated" + _seed_cross_section_fixture(curated) + + with MarketDataStore(curated, vault_cutoff_ts=VAULT_CUTOFF_MS, budget=_budget(tmp_path)) as store: + # Act + cs = store.cross_section( + features=["probe@v1", "probe@v1"], + date="2025-06-30", + universe="US_EQ", + as_of="2025-08-01T00:00:00Z", + ) + + # Assert: duplicate refs collapse; L1 (known_at == cutoff) null; L3 has no row -> null. + assert cs.columns == ["listing_id", "probe@v1"] + assert cs.rows() == [(1, None), (2, 7.0), (3, None)] + assert cs.schema["listing_id"] == pl.Int32 + assert cs.schema["probe@v1"] == pl.Float64 + + +def test_cross_section_rejects_vault_dates_and_non_canonical_refs(tmp_path: Path) -> None: + # Arrange + curated = tmp_path / "curated" + _seed_cross_section_fixture(curated) + + with MarketDataStore(curated, vault_cutoff_ts=VAULT_CUTOFF_MS, budget=_budget(tmp_path)) as store: + # Act / Assert: a date on the cutoff is in the holdout. + with pytest.raises(VaultHoldoutFenceError): + store.cross_section(features=["probe@v1"], date="2025-07-01", universe="US_EQ") + for bad_ref in ("probe", "probe@v01", "probe@v0", "Probe@v1", "probe@v1/../x"): + with pytest.raises(MarketDataStoreValidationError): + store.cross_section(features=[bad_ref], date="2025-06-30", universe="US_EQ") + for bad_date in ("2025-6-30", "2025-06-30T00:00:00Z", "2025-02-30"): + with pytest.raises(MarketDataStoreValidationError): + store.cross_section(features=["probe@v1"], date=bad_date, universe="US_EQ") + with pytest.raises(MarketDataStoreValidationError): + store.cross_section(features=["probe@v1"], date="2025-06-30", universe="EU_EQ") # type: ignore[arg-type] + + +def test_cross_section_universe_excludes_listing_whose_bar_is_not_yet_known(tmp_path: Path) -> None: + # Arrange: L3's only bar is published after as_of, so it is not in the as-of universe. + curated = tmp_path / "curated" + curated.mkdir() + close = datetime(2025, 6, 30, 21, tzinfo=UTC) + bars = _bars([(1, close, 10.0), (3, close, 30.0)]).with_columns( + pl.when(pl.col("listing_id") == 3) + .then(pl.lit(datetime(2025, 6, 30, 22, 30, tzinfo=UTC))) + .otherwise(pl.col("known_at")) + .cast(pl.Datetime("us", "UTC")) + .alias("known_at") + ) + _write_parquet(bars, curated / "bars_1d" / "year=2025" / "part.parquet") + _write_parquet( + pl.DataFrame( + {"listing_id": [1], "ts": [close], "known_at": [close], "value": [0.5]}, + schema_overrides={ + "listing_id": pl.Int32, + "ts": pl.Datetime("us", "UTC"), + "known_at": pl.Datetime("us", "UTC"), + }, + ), + _partition(curated, "probe", 2025), + ) + + with MarketDataStore(curated, vault_cutoff_ts=VAULT_CUTOFF_MS, budget=_budget(tmp_path)) as store: + # Act + cs = store.cross_section( + features=["probe@v1"], date="2025-06-30", universe="US_EQ", as_of="2025-06-30T22:00:00Z" + ) + + # Assert + assert cs.rows() == [(1, 0.5)] diff --git a/scripts/test/m2-master-audit.test.ts b/scripts/test/m2-master-audit.test.ts index 9b8f6cca..2191ff51 100644 --- a/scripts/test/m2-master-audit.test.ts +++ b/scripts/test/m2-master-audit.test.ts @@ -147,9 +147,6 @@ describe('design/m2-master-audit.md citations', () => { ['libs/research/src/feature-library.ts', 61, 'export const FEATURE_INPUT_DATASETS'], ['libs/research/src/notebook-snapshot-node.ts', 67, 'export function createNodeNotebookCommandRunner'], ['scripts/research-copilot-mcp.ts', 77, 'export async function runResearchCopilotMcp'], - ['python/stockbot/data.py', 21, '"ceo_post"'], - ['python/stockbot/data.py', 71, 'events/year=*/part.parquet'], - ['python/stockbot/data.py', 259, 'NotImplementedError'], ['package.json', 56, '"mcp:research-copilot"'], ['design/MILESTONES.md', 96, 'eodIntraday1M'], ['docker-compose.quant.yml', 35, '1048576'], diff --git a/scripts/test/python-stockbot-sdk.test.ts b/scripts/test/python-stockbot-sdk.test.ts new file mode 100644 index 00000000..af950df3 --- /dev/null +++ b/scripts/test/python-stockbot-sdk.test.ts @@ -0,0 +1,44 @@ +import { existsSync } from 'node:fs'; +import { delimiter, dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { expect, test } from 'bun:test'; + +const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); +const pythonDir = join(repoRoot, 'python'); +const venvPython = join(pythonDir, '.venv/bin/python'); + +function buildEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(baseEnv)) { + if (value !== undefined) { + env[key] = value; + } + } + const bunDir = dirname(process.execPath); + env.PATH = env.PATH ? `${bunDir}${delimiter}${env.PATH}` : bunDir; + env.PYTHONPATH = pythonDir; + env.PYTHONDONTWRITEBYTECODE = '1'; + return env; +} + +test( + 'python stockbot SDK offline pytest suite passes', + () => { + const cmd = existsSync(venvPython) + ? [venvPython, '-m', 'pytest', '-q', '-rf', join(pythonDir, 'tests')] + : ['uv', 'run', '--directory', pythonDir, '--offline', '--extra', 'dev', 'pytest', '-q', '-rf']; + + const spawned = Bun.spawnSync(cmd, { + cwd: pythonDir, + env: buildEnv(), + stdout: 'pipe', + stderr: 'pipe', + }); + + const stdout = new TextDecoder().decode(spawned.stdout); + const stderr = new TextDecoder().decode(spawned.stderr); + + expect(spawned.exitCode, `${stdout}\n${stderr}`).toBe(0); + }, + 60_000 +);