File size: 7,370 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""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)