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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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
"""Frozen, calibration-only selection and paired analysis for Experiment 001B.



This module has no inference dependencies. It expects the per-generation JSON

records saved by the 001B runner and makes incomplete calibration coverage

visible instead of ranking the surviving candidates.

"""
from __future__ import annotations

from collections.abc import Iterable, Mapping, Sequence
from typing import Any

from paired_stats import paired_cluster_summary


_NATURAL_FINISHES = {"stop", "eos", "end_of_sequence", "natural_stop"}
_SCORABLE_STATUSES = {"correct", "incorrect"}
_KNOWN_SCORE_STATUSES = _SCORABLE_STATUSES | {"unresolved", "unparsed", "error"}
_DEFAULT_FORBIDDEN_CANDIDATES = {"base", "base_thinking", "base_no_thinking"}
DEFAULT_CONDITIONS = (
    "base",
    "edited",
    "published_constant",
    "independent_constant",
    "norm_matched_random",
    "rank1_activation_dependent",
)


def _record_key(record: Mapping[str, Any]) -> tuple[int, int]:
    return int(record["source_row"]), int(record["seed"])


def _score_status(record: Mapping[str, Any]) -> str | None:
    score = record.get("score")
    if not isinstance(score, Mapping):
        return None
    value = score.get("status")
    return str(value) if value is not None else None


def _score_issue(record: Mapping[str, Any]) -> str | None:
    """Return a data/scoring error instead of silently awarding model no-credit.



    The frozen grader emits one of: correct, incorrect, unresolved, unparsed,

    or error, with a matching tri-state ``correct`` value. Missing or

    inconsistent fields are malformed score records.

    """
    score = record.get("score")
    if not isinstance(score, Mapping):
        return "missing_score_object"
    status = score.get("status")
    if not isinstance(status, str) or status not in _KNOWN_SCORE_STATUSES:
        return "unknown_or_missing_score_status"
    correct = score.get("correct", _MISSING)
    if correct is _MISSING:
        return "missing_correct_flag"
    if status == "correct" and correct is not True:
        return "correct_status_mismatch"
    if status == "incorrect" and correct is not False:
        return "incorrect_status_mismatch"
    if status in {"unresolved", "unparsed", "error"} and correct is not None:
        return "unscorable_status_mismatch"
    return None


_MISSING = object()


def _record_problem(record: Mapping[str, Any]) -> str | None:
    if record.get("error"):
        return "technical_error"
    issue = _score_issue(record)
    if issue is not None:
        return f"scoring_error:{issue}"
    if _score_status(record) == "error":
        score = record.get("score")
        detail = score.get("error") if isinstance(score, Mapping) else None
        return f"scoring_error:{detail or 'grader_error_status'}"
    return None


def record_validation_issue(record: Mapping[str, Any]) -> str | None:
    """Public record-integrity check used by analysis summaries and CSV output."""
    return _record_problem(record)


def _is_natural_completion(record: Mapping[str, Any]) -> bool:
    if record.get("truncated") is True:
        return False
    reason = str(record.get("finish_reason", "")).lower()
    if reason in _NATURAL_FINISHES:
        return True
    return bool(record.get("stopped_on_eos", False))


def _capped_length(record: Mapping[str, Any] | None, max_new_tokens: int) -> int:
    if record is None:
        return max_new_tokens
    value = record.get("tokens", record.get("token_count"))
    if value is None:
        return max_new_tokens
    return min(max_new_tokens, max(0, int(value)))


def select_calibration_winners(

    records_by_candidate: Mapping[str, Iterable[Mapping[str, Any]]],

    families: Mapping[str, Sequence[str]],

    expected_question_seeds: Sequence[tuple[int, int]],

    *,

    max_new_tokens: int,

    forbidden_candidates: Iterable[str] = _DEFAULT_FORBIDDEN_CANDIDATES,

) -> dict[str, Any]:
    """Select one fully observed candidate per family using calibration only.



    Ranking, from best to worst: maximize verified solves; maximize natural

    completions; minimize unscorable outputs; minimize mean capped generated

    length; lexical candidate ID. Any missing record, technical error, or

    malformed grade blocks that whole family (no fallback winner); callers

    should resume the run or report the family incomplete. A base comparator

    cannot be a candidate.

    """
    if max_new_tokens <= 0:
        raise ValueError("max_new_tokens must be positive")
    if not expected_question_seeds:
        raise ValueError("expected_question_seeds cannot be empty")
    expected = [(int(row), int(seed)) for row, seed in expected_question_seeds]
    if len(expected) != len(set(expected)):
        raise ValueError("expected question/seed keys must be unique")

    forbidden = set(forbidden_candidates)
    indexed: dict[str, dict[tuple[int, int], Mapping[str, Any]]] = {}
    for candidate, records in records_by_candidate.items():
        if candidate in forbidden or candidate.lower() in forbidden:
            raise ValueError(f"Comparator {candidate!r} cannot be a calibration candidate")
        by_key: dict[tuple[int, int], Mapping[str, Any]] = {}
        for record in records:
            key = _record_key(record)
            if key in by_key:
                raise ValueError(f"Duplicate calibration record for {candidate}/{key}")
            if record.get("candidate_id", candidate) != candidate:
                raise ValueError(f"Record candidate_id disagrees with mapping key: {candidate}/{key}")
            by_key[key] = record
        extra = set(by_key) - set(expected)
        if extra:
            raise ValueError(f"Unexpected calibration keys for {candidate}: {sorted(extra)}")
        indexed[candidate] = by_key

    all_family_candidates = {candidate for values in families.values() for candidate in values}
    if not all_family_candidates:
        raise ValueError("families must contain at least one candidate")
    if sum(len(values) for values in families.values()) != len(all_family_candidates):
        raise ValueError("a candidate ID cannot appear in multiple calibration families")
    if all_family_candidates & forbidden:
        raise ValueError("Base/comparator cannot be selected in a family")
    missing_candidate_records = all_family_candidates - set(indexed)

    family_results: dict[str, Any] = {}
    for family, candidates_seq in families.items():
        candidates = list(candidates_seq)
        if not candidates or len(candidates) != len(set(candidates)):
            raise ValueError(f"Family {family!r} must list unique candidates")
        candidate_metrics: dict[str, Any] = {}
        family_blockers: list[str] = []
        for candidate in candidates:
            by_key = indexed.get(candidate, {})
            missing = sorted(set(expected) - set(by_key))
            error_keys = sorted(
                key for key, record in by_key.items()
                if _record_problem(record) == "technical_error"
            )
            score_error_keys = sorted(
                key for key, record in by_key.items()
                if _record_problem(record) is not None
                and _record_problem(record) != "technical_error"
            )
            if candidate in missing_candidate_records:
                family_blockers.append(f"missing_candidate:{candidate}")
            if missing:
                family_blockers.append(f"missing_records:{candidate}")
            if error_keys:
                family_blockers.append(f"technical_errors:{candidate}")
            if score_error_keys:
                family_blockers.append(f"scoring_errors:{candidate}")

            solves = sum(
                key in by_key
                and _record_problem(by_key[key]) is None
                and _score_status(by_key[key]) == "correct"
                for key in expected
            )
            natural = sum(_is_natural_completion(by_key[key]) for key in expected if key in by_key)
            unscorable = sum(
                _score_status(by_key.get(key, {})) not in _SCORABLE_STATUSES
                for key in expected
            )
            lengths = [_capped_length(by_key.get(key), max_new_tokens) for key in expected]
            candidate_metrics[candidate] = {
                "n_expected": len(expected),
                "n_recorded": len(by_key),
                "n_missing": len(missing),
                "missing_question_seeds": [list(key) for key in missing],
                "n_technical_errors": len(error_keys),
                "technical_error_question_seeds": [list(key) for key in error_keys],
                "n_scoring_errors": len(score_error_keys),
                "scoring_error_question_seeds": [list(key) for key in score_error_keys],
                "solves": solves,
                "natural_completions": natural,
                "unscorable": unscorable,
                "mean_capped_tokens": sum(lengths) / len(expected),
                "complete": not missing and not error_keys and not score_error_keys and candidate in indexed,
            }

        complete = not family_blockers
        winner = None
        if complete:
            winner = min(
                candidates,
                key=lambda candidate: (
                    -candidate_metrics[candidate]["solves"],
                    -candidate_metrics[candidate]["natural_completions"],
                    candidate_metrics[candidate]["unscorable"],
                    candidate_metrics[candidate]["mean_capped_tokens"],
                    candidate,
                ),
            )
        family_results[family] = {
            "status": "selected" if complete else "incomplete",
            "selected_candidate_id": winner,
            "blockers": sorted(set(family_blockers)),
            "candidates": candidate_metrics,
            "selection_rule": [
                "maximize solves",
                "maximize natural completions",
                "minimize unscorable outputs",
                "minimize mean capped generated tokens",
                "lexical candidate ID",
            ],
            "selection_source": "calibration only",
        }

    return {
        "phase": "calibration",
        "max_new_tokens": max_new_tokens,
        "expected_question_seeds": [list(key) for key in expected],
        "families": family_results,
        "base_is_comparator_only": True,
        "heldout_used_for_selection": False,
    }


def collect_paired_outcomes(

    records: Iterable[Mapping[str, Any]],

    condition: str,

    candidate_id: str | None = None,

) -> tuple[dict[int, dict[int, bool]], dict[tuple[int, int], str]]:
    """Index one condition's valid records; return technical/scoring exclusions too."""
    outcomes: dict[int, dict[int, bool]] = {}
    excluded: dict[tuple[int, int], str] = {}
    seen: set[tuple[int, int]] = set()
    for record in records:
        if record.get("condition") != condition:
            continue
        if candidate_id is not None and record.get("candidate_id") != candidate_id:
            continue
        key = _record_key(record)
        if key in seen:
            raise ValueError(f"Duplicate heldout record for {condition}/{key}")
        seen.add(key)
        question, seed = key
        outcomes.setdefault(question, {})
        problem = _record_problem(record)
        if problem is not None:
            excluded[key] = problem
            continue
        status = _score_status(record)
        # For author-aligned solve-by-cap accuracy, non-completion and
        # unscorable model outputs are no-credit outcomes, not technical errors.
        outcomes[question][seed] = status == "correct" or (
            isinstance(record.get("score"), Mapping)
            and record["score"].get("correct") is True
        )
    return outcomes, excluded


def paired_heldout_summary(

    records: Iterable[Mapping[str, Any]],

    first_condition: str,

    comparator_condition: str,

    expected_question_seeds: Sequence[tuple[int, int]],

    *,

    first_candidate_id: str | None = None,

    comparator_candidate_id: str | None = None,

    bootstrap_seed: int = 14353,

    bootstrap_samples: int = 10_000,

) -> dict[str, Any]:
    """Compare two heldout conditions and expose every missing/error pair."""
    if first_condition == comparator_condition:
        raise ValueError("first_condition and comparator_condition must differ")
    expected_list = [(int(question), int(seed)) for question, seed in expected_question_seeds]
    if len(expected_list) != len(set(expected_list)):
        raise ValueError("expected_question_seeds must be unique")
    rows = list(records)
    first, first_errors = collect_paired_outcomes(rows, first_condition, first_candidate_id)
    comparator, comparator_errors = collect_paired_outcomes(
        rows, comparator_condition, comparator_candidate_id
    )
    expected = set(expected_list)
    first_keys = {(question, seed) for question, seeds in first.items() for seed in seeds}
    comparator_keys = {(question, seed) for question, seeds in comparator.items() for seed in seeds}
    first_present = first_keys | set(first_errors)
    comparator_present = comparator_keys | set(comparator_errors)
    unexpected = (first_present | comparator_present) - expected
    if unexpected:
        raise ValueError(f"Unexpected heldout question/seed keys: {sorted(unexpected)}")

    matched_keys = sorted((first_keys & comparator_keys) & expected)
    first_map: dict[int, dict[int, bool]] = {}
    comparator_map: dict[int, dict[int, bool]] = {}
    for question, seed in matched_keys:
        first_map.setdefault(question, {})[seed] = first[question][seed]
        comparator_map.setdefault(question, {})[seed] = comparator[question][seed]

    summary = paired_cluster_summary(
        first_map,
        comparator_map,
        bootstrap_seed=bootstrap_seed,
        bootstrap_samples=bootstrap_samples,
    )
    incomplete = []
    for key in sorted(expected):
        missing = []
        if key not in first_present:
            missing.append(first_condition)
        if key not in comparator_present:
            missing.append(comparator_condition)
        reasons = {
            first_condition: first_errors.get(key),
            comparator_condition: comparator_errors.get(key),
        }
        if missing or any(reasons.values()):
            technical = {
                name: value for name, value in reasons.items() if value == "technical_error"
            }
            item = {
                "source_row": key[0],
                "seed": key[1],
                "missing_conditions": missing,
                "technical_errors": technical,
            }
            scoring = {
                name: value for name, value in reasons.items()
                if value and value != "technical_error"
            }
            if technical:
                item["technical_errors"] = technical
            if scoring:
                item["scoring_errors"] = scoring
            incomplete.append(item)
    summary.update(
        {
            "first_condition": first_condition,
            "comparator_condition": comparator_condition,
            "first_candidate_id": first_candidate_id,
            "comparator_candidate_id": comparator_candidate_id,
            "expected_generation_pairs": len(expected),
            "complete_matched_generation_pairs": len(matched_keys),
            "incomplete_pairs": incomplete,
            "analysis_uses_only_complete_pairs": True,
            "endpoint": "verified correct final answer; unresolved and unparsed are no-credit",
        }
    )
    if len(matched_keys) != len(expected):
        summary["question_bootstrap_percentile_95"] = None
        summary["exact_mcnemar_two_sided_p"] = None
        summary["inference_suppressed"] = (
            "Missing, technical-error, or scoring-error pairs make complete-case inferential summaries unsafe; report the matched counts descriptively."
        )
    return summary


def summarize_experiment_001b_contrasts(

    records: Iterable[Mapping[str, Any]],

    expected_question_seeds: Sequence[tuple[int, int]],

    condition_config_ids: Mapping[str, str] | None = None,

    *,

    bootstrap_seed: int = 14353,

    bootstrap_samples: int = 10_000,

) -> dict[str, Any]:
    """Build the frozen primary and explicitly exploratory 001B contrasts.



    The single prespecified contrast is edited checkpoint vs the

    calibration-selected published-constant direction. Remaining comparisons

    are diagnostics or intervention-vs-base summaries and their p-values are

    exploratory and unadjusted for multiplicity.

    """
    ids = dict(condition_config_ids or {})
    rows = list(records)

    def summarize(first: str, comparator: str) -> dict[str, Any]:
        return paired_heldout_summary(
            rows,
            first,
            comparator,
            expected_question_seeds,
            first_candidate_id=ids.get(first, first),
            comparator_candidate_id=ids.get(comparator, comparator),
            bootstrap_seed=bootstrap_seed,
            bootstrap_samples=bootstrap_samples,
        )

    base_conditions = [
        "edited",
        "published_constant",
        "independent_constant",
        "norm_matched_random",
        "rank1_activation_dependent",
    ]
    diagnostics = {
        "rank1_activation_dependent_minus_published_constant": (
            "rank1_activation_dependent",
            "published_constant",
        ),
        "rank1_activation_dependent_minus_norm_matched_random": (
            "rank1_activation_dependent",
            "norm_matched_random",
        ),
        "edited_minus_rank1_activation_dependent": (
            "edited",
            "rank1_activation_dependent",
        ),
    }
    return {
        "plan": {
            "primary": "edited_minus_published_constant",
            "primary_definition": (
                "edited checkpoint vs the published_constant candidate selected using calibration only"
            ),
            "other_comparisons": "exploratory; p-values are unadjusted and not confirmatory",
            "small_heldout_note": (
                "Ten heldout questions support a mechanism screen only; do not claim population accuracy effects or equivalence."
            ),
        },
        "primary_prespecified": {
            "comparison_id": "edited_minus_published_constant",
            "first_condition": "edited",
            "comparator_condition": "published_constant",
            "summary": summarize("edited", "published_constant"),
        },
        "exploratory_vs_base_unadjusted": {
            f"{condition}_minus_base": summarize(condition, "base")
            for condition in base_conditions
        },
        "exploratory_diagnostic_pairs_unadjusted": {
            comparison_id: {
                "first_condition": pair[0],
                "comparator_condition": pair[1],
                "summary": summarize(*pair),
            }
            for comparison_id, pair in diagnostics.items()
        },
    }


__all__ = [
    "DEFAULT_CONDITIONS",
    "collect_paired_outcomes",
    "paired_heldout_summary",
    "record_validation_issue",
    "select_calibration_winners",
    "summarize_experiment_001b_contrasts",
]