"""Deterministic comparison-slot construction shared by all controlled arms.""" from __future__ import annotations import copy from collections.abc import Iterable, Mapping from dataclasses import dataclass from typing import Any from ..hashing import canonical_json_hash, join_manifest_sha256, sha256_text from .data import AdmittedGroup _TARGET_SOURCE_ROLES = frozenset({"TARGET_EVIDENCE", "TARGET_REFERENT", "SUBSTITUTE"}) @dataclass(frozen=True) class ComparisonSlot: slot_id: str group_id: str base_id: str source: str split: str question: str comparison_role: str source_role: str full_view: dict[str, Any] selected_view: dict[str, Any] full_answer: Any answer_type: str choices: tuple[dict[str, Any], ...] def to_row(self) -> dict[str, Any]: return { "schema_version": 2, "slot_id": self.slot_id, "group_id": self.group_id, "base_id": self.base_id, "source": self.source, "split": self.split, "question": self.question, "comparison_role": self.comparison_role, "source_role": self.source_role, "full_view_id": self.full_view["view_id"], "selected_view_id": self.selected_view["view_id"], "selected_state": self.selected_view["state"], "full_view": copy.deepcopy(self.full_view), "selected_view": copy.deepcopy(self.selected_view), "full_answer": self.full_answer, "selected_target": self.selected_view["target_canonical"], "answer_type": self.answer_type, "choices": [dict(choice) for choice in self.choices], } def _group_row(group: AdmittedGroup | Mapping[str, Any]) -> dict[str, Any]: return group.row if isinstance(group, AdmittedGroup) else copy.deepcopy(dict(group)) def _comparison_role(source_role: str) -> str: if source_role == "POSITIVE": return "POSITIVE" if source_role == "CONTROL": return "CONTROL" if source_role in _TARGET_SOURCE_ROLES: return "TARGET" raise ValueError(f"unsupported source role: {source_role!r}") def build_comparison_slots( groups: Iterable[AdmittedGroup | Mapping[str, Any]], *, seed: int, max_slots: int | None = None, ) -> tuple[ComparisonSlot, ...]: """Build one slot per available role and deterministically shuffle by seed.""" if seed < 0: raise ValueError("seed must be non-negative") if max_slots is not None and max_slots <= 0: raise ValueError("max_slots must be positive") slots: list[ComparisonSlot] = [] seen_groups: set[str] = set() for group_value in groups: group = _group_row(group_value) group_id = str(group["group_id"]) if group_id in seen_groups: raise ValueError(f"duplicate group_id: {group_id}") seen_groups.add(group_id) views = list(group["views"]) full_views = [view for view in views if view["state"] == "FULL"] if len(full_views) != 1: raise ValueError(f"group {group_id}: expected exactly one FULL view") full = copy.deepcopy(full_views[0]) for view in sorted(views, key=lambda item: str(item["view_id"])): source_role = str(view["role"]) role = _comparison_role(source_role) selected = copy.deepcopy(view) slot_id = canonical_json_hash( { "schema_version": 1, "group_id": group_id, "base_id": group["base_id"], "comparison_role": role, "source_role": source_role, "selected_view_id": selected["view_id"], } ) slots.append( ComparisonSlot( slot_id=slot_id, group_id=group_id, base_id=str(group["base_id"]), source=str(group.get("source", "")), split=str(group.get("split", "")), question=str(group["question"]), comparison_role=role, source_role=source_role, full_view=copy.deepcopy(full), selected_view=selected, full_answer=group["full_answer_canonical"], answer_type=str(group["answer_type"]), choices=tuple(copy.deepcopy(group.get("choices", []))), ) ) if not slots: raise ValueError("cannot build comparison slots from an empty group set") slots.sort(key=lambda slot: (sha256_text(f"{seed}:{slot.slot_id}"), slot.slot_id)) if max_slots is not None: slots = slots[:max_slots] return tuple(slots) def comparison_slot_from_row(row: Mapping[str, Any]) -> ComparisonSlot: """Restore a persisted v2 comparison slot without consulting group data.""" if row.get("schema_version") != 2: raise ValueError("comparison slot row must use schema_version=2") required_strings = ( "slot_id", "group_id", "base_id", "source", "split", "question", "comparison_role", "source_role", "answer_type", ) for field in required_strings: if not isinstance(row.get(field), str) or not str(row[field]): raise ValueError(f"comparison slot {field} must be a non-empty string") full_view = row.get("full_view") selected_view = row.get("selected_view") if not isinstance(full_view, Mapping) or not isinstance(selected_view, Mapping): raise ValueError("comparison slot must persist full_view and selected_view") if full_view.get("view_id") != row.get("full_view_id"): raise ValueError("comparison slot full_view_id drift") if selected_view.get("view_id") != row.get("selected_view_id"): raise ValueError("comparison slot selected_view_id drift") if selected_view.get("state") != row.get("selected_state"): raise ValueError("comparison slot selected_state drift") choices = row.get("choices") if not isinstance(choices, list) or any(not isinstance(choice, Mapping) for choice in choices): raise ValueError("comparison slot choices must be a list of objects") slot = ComparisonSlot( slot_id=str(row["slot_id"]), group_id=str(row["group_id"]), base_id=str(row["base_id"]), source=str(row["source"]), split=str(row["split"]), question=str(row["question"]), comparison_role=str(row["comparison_role"]), source_role=str(row["source_role"]), full_view=copy.deepcopy(dict(full_view)), selected_view=copy.deepcopy(dict(selected_view)), full_answer=copy.deepcopy(row.get("full_answer")), answer_type=str(row["answer_type"]), choices=tuple(copy.deepcopy(dict(choice)) for choice in choices), ) if slot.to_row() != copy.deepcopy(dict(row)): raise ValueError("comparison slot row is not canonical") return slot def comparison_slot_manifest_sha256(slots: Iterable[ComparisonSlot]) -> str: """Hash an ordered slot sequence; all arms must record the same value.""" return join_manifest_sha256(canonical_json_hash(slot.to_row()) for slot in slots)