"""Service-level HIST backtest guards (authorization + UNKNOWN policy). DB CHECKs/triggers enforce structural invariants. Runners MUST also call these guards so authorization never trusts pin.authorized / caller claims / nonempty decision strings alone — a verified backtest_authorization_decisions row is required. """ from __future__ import annotations import sqlite3 from typing import Any, Optional class BacktestAuthError(PermissionError): pass class BacktestPolicyError(ValueError): pass def resolve_authorization( conn: sqlite3.Connection, *, rule_id: str, authorization_decision_id: Optional[str], pin_authorized_cache: int, expected_construct_id: Optional[str] = None, ) -> dict[str, Any]: """Authorize from frozen registry + verified delegated decision row. Never trusts pin.authorized alone. A nonempty authorization_decision_id string is insufficient — the id must resolve to backtest_authorization_decisions with decision='authorize_backtest' and matching rule_id (and construct when provided). """ row = conn.execute( """ SELECT rule_id, construct_id, status, authorized, concept_model_version, measurement_spec_version FROM measurement_rules WHERE rule_id = ? """, (rule_id,), ).fetchone() if row is None: raise BacktestAuthError(f"unknown measurement rule: {rule_id}") status = row["status"] if isinstance(row, sqlite3.Row) else row[2] authorized = int(row["authorized"] if isinstance(row, sqlite3.Row) else row[3]) registry_construct = row["construct_id"] if isinstance(row, sqlite3.Row) else row[1] if status != "FROZEN" or authorized != 1: raise BacktestAuthError( f"rule {rule_id} not production-authorized (status={status}, authorized={authorized})" ) if not authorization_decision_id: raise BacktestAuthError( "authorization_decision_id required; pin.authorized cache is not sufficient" ) dec = conn.execute( """ SELECT decision_id, rule_id, construct_id, decision, decided_by FROM backtest_authorization_decisions WHERE decision_id = ? """, (authorization_decision_id,), ).fetchone() if dec is None: raise BacktestAuthError( "authorization_decision_id not found in backtest_authorization_decisions; " "nonempty decision string is not a verified delegated decision" ) dec_rule = dec["rule_id"] if isinstance(dec, sqlite3.Row) else dec[1] dec_construct = dec["construct_id"] if isinstance(dec, sqlite3.Row) else dec[2] dec_decision = dec["decision"] if isinstance(dec, sqlite3.Row) else dec[3] if dec_rule != rule_id: raise BacktestAuthError( f"decision {authorization_decision_id} rule_id={dec_rule} != requested {rule_id}" ) if dec_decision != "authorize_backtest": raise BacktestAuthError( f"decision {authorization_decision_id} is '{dec_decision}', not authorize_backtest" ) if dec_construct != registry_construct: raise BacktestAuthError( f"decision construct {dec_construct} != registry construct {registry_construct}" ) if expected_construct_id is not None and expected_construct_id != registry_construct: raise BacktestAuthError( f"expected construct {expected_construct_id} != registry construct {registry_construct}" ) # pin cache may lag; mismatch is a hard fail (does not grant auth by itself) if int(pin_authorized_cache) not in (0, 1): raise BacktestAuthError("pin.authorized cache must be 0 or 1") if int(pin_authorized_cache) != 1: raise BacktestAuthError( "pin.authorized cache is 0 while registry is authorized — refresh pin via new pin_id" ) return { "rule_id": rule_id, "construct_id": registry_construct, "authorized": True, "source": "registry+delegated_decision", "authorization_decision_id": authorization_decision_id, "pin_authorized_cache": int(pin_authorized_cache), "decided_by": dec["decided_by"] if isinstance(dec, sqlite3.Row) else dec[4], } def validate_score_row( *, score: Optional[float], score_label: str, status_policy_version: Optional[str] = None, ) -> None: """Enforce UNKNOWN/null coupling unless an explicit versioned status policy exists.""" if score is not None and score_label == "UNKNOWN" and not status_policy_version: raise BacktestPolicyError( "non-null score with label UNKNOWN requires status_policy_version" ) if status_policy_version: return if score is None and score_label != "UNKNOWN": raise BacktestPolicyError("null score requires score_label=UNKNOWN under default policy") if score is not None and score_label == "UNKNOWN": raise BacktestPolicyError("non-null score cannot be labelled UNKNOWN under default policy")