import json from pathlib import Path from typing import Any, Mapping MODEL_FEATURE_COUNT = 39 class FeatureContractError(ValueError): """Raised when a row or schema differs from the saved model contract.""" def load_feature_contract(schema_path: Path) -> tuple[dict[str, Any], tuple[str, ...]]: try: with schema_path.open("r", encoding="utf-8") as file: schema = json.load(file) except (OSError, ValueError) as exc: raise FeatureContractError(f"Unable to read feature schema: {exc}") from exc features = tuple(schema.get("model_features", ())) declared_count = schema.get("raw_feature_count") if len(features) != MODEL_FEATURE_COUNT or declared_count != MODEL_FEATURE_COUNT: raise FeatureContractError( "Saved schema must declare exactly 39 ordered model features" ) if len(set(features)) != len(features) or not all( isinstance(feature, str) and feature for feature in features ): raise FeatureContractError("Saved schema model_features are invalid") return schema, features def validate_feature_row( row: Mapping[str, Any], expected_features: tuple[str, ...] | list[str], ) -> None: actual = tuple(row.keys()) expected = tuple(expected_features) if len(actual) != MODEL_FEATURE_COUNT: raise FeatureContractError( f"Model inference requires exactly 39 features; received {len(actual)}" ) if actual != expected: raise FeatureContractError( "Model feature names or order differ from the saved schema" )