"""Fail-closed evaluation of normalized question predicates.""" from __future__ import annotations from numbers import Real from typing import Any, Mapping from pvr_eval.question_eval.schema import AnswerRecord, EvidencePacket, EvalProcedure STATUS_SCORES = {"pass": 1.0, "partial": 0.5, "fail": 0.0} def value_in_band(value: float, band: Mapping[str, float | None]) -> bool: """Return whether *value* is inside an inclusive numeric band.""" lower = band.get("min") upper = band.get("max") return (lower is None or value >= float(lower)) and (upper is None or value <= float(upper)) def classify_numeric(value: Any, bands: Mapping[str, Mapping[str, float | None]]) -> str | None: if isinstance(value, bool) or not isinstance(value, Real): return None matched = [status for status in ("pass", "partial", "fail") if status in bands and value_in_band(float(value), bands[status])] return matched[0] if len(matched) == 1 else None def _uncertain(procedure: EvalProcedure, packet: EvidencePacket, *reasons: str) -> AnswerRecord: return AnswerRecord( case_id=procedure.rubric.case_id, check_id=procedure.rubric.check_id, status="uncertain", score=0.0, confidence=0.0, answer_source="deterministic", evidence_packet_hash=packet.packet_hash, cited_call_ids=packet.successful_call_ids, rationale="Deterministic scoring was withheld because required evidence is insufficient.", formal_eligible=False, reasons=tuple(reasons) or ("insufficient_evidence",), ) def answer_deterministically(procedure: EvalProcedure, packet: EvidencePacket) -> AnswerRecord: """Answer one normalized predicate without guessing missing semantics. Scores always mean positive rubric satisfaction, including penalty-role questions. Aggregation/deduction is a separate scoring concern. """ if not procedure.predicate.deterministic: return _uncertain(procedure, packet, "predicate_not_objectively_executable") if packet.status != "success": return _uncertain(procedure, packet, f"evidence_packet:{packet.status}", *packet.reasons) metric = procedure.predicate.metric value = packet.derived_facts.get(metric) status = classify_numeric(value, procedure.predicate.bands) if status is None: return _uncertain(procedure, packet, f"metric_missing_or_outside_unique_band:{metric}") if not packet.successful_call_ids: return _uncertain(procedure, packet, "no_citable_tool_calls") score_overrides = procedure.predicate.parameters.get("status_scores", {}) score = float(score_overrides.get(status, STATUS_SCORES[status])) if isinstance(score_overrides, Mapping) else STATUS_SCORES[status] return AnswerRecord( case_id=procedure.rubric.case_id, check_id=procedure.rubric.check_id, status=status, score=max(0.0, min(1.0, score)), confidence=1.0, answer_source="deterministic", evidence_packet_hash=packet.packet_hash, cited_call_ids=packet.successful_call_ids, rationale=f"{metric}={float(value):.6g} falls in the normalized {status} band.", formal_eligible=True, )