2208 lines
73 KiB
Python
2208 lines
73 KiB
Python
"""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):
|
|
- `<curated_root>/features/<name>/v<version>/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:<dataset>}}
|
|
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>}}}}".',
|
|
)
|
|
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 <name> 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:<dataset>}}}} 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:<dataset>}}}} placeholders.',
|
|
)
|
|
pos += 1
|
|
else:
|
|
raise FeatureLibraryError(
|
|
"EXTERNAL_DATA_ACCESS",
|
|
f'Unsupported relation source "{tok.raw}" in feature SQL; use {{{{input:<dataset>}}}}, 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:<dataset>}}}}.',
|
|
)
|
|
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:<dataset>}}}}.",
|
|
)
|
|
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:<dataset>}}}}.",
|
|
)
|
|
|
|
# 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 `<name>@v<version>`."""
|
|
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 `<name>@v<version>` feature ref, rejecting non-canonical forms."""
|
|
if not isinstance(ref, str):
|
|
raise FeatureLibraryError(
|
|
"INVALID_FEATURE_REF",
|
|
f'Invalid feature ref "{ref}". Expected "<name>@v<version>".',
|
|
)
|
|
m = _FEATURE_REF_RE.match(ref)
|
|
if m is None:
|
|
raise FeatureLibraryError(
|
|
"INVALID_FEATURE_REF",
|
|
f'Invalid feature ref "{ref}". Expected "<name>@v<version>" 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
|
|
`<name>@v<version>` 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 _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 optionally persists it atomically.
|
|
|
|
Returns True when `_definition.json` is verified on disk with matching `definition_hash`.
|
|
"""
|
|
meta_path = os.path.join(version_dir, "_definition.json")
|
|
if os.path.exists(meta_path):
|
|
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,
|
|
)
|
|
return True
|
|
|
|
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")
|
|
os.replace(tmp_meta, meta_path)
|
|
except Exception:
|
|
if os.path.exists(tmp_meta):
|
|
try:
|
|
os.remove(tmp_meta)
|
|
except OSError:
|
|
pass
|
|
raise
|
|
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 `<curated_root>/features/<name>/v<version>/_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",
|
|
]
|
|
),
|
|
)
|