# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-benchmark-harness-determinism-as-a-scoring-invariant-rather-than-a-test-fixture.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-benchmark-harness-determinism-as-a-scoring-invariant-rather-than-a-test-fixture.warrant.json
# Markdown SHA-256:   ce5dffdf29d40972da69fb33e3ee9762741e33bcb25e4fa1d788cef6383d6941
# Code AST SHA-256:   0ec38f3a3502b17521fcda2c66f84fd8ad6a94bd0b8700edf8768af9ba32bd0a
# Verified Classes:   UnboundScoreError, JudgeConfig
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class UnboundScoreError(RuntimeError):
    """Raised when a score cannot be tied to an exact trajectory + judge config."""


@dataclass(frozen=True)
class JudgeConfig:
    model_id: str
    temperature: float
    rubric: str
    serialization: str

    def content_hash(self) -> str:
        blob = json.dumps(self.__dict__, sort_keys=True).encode()
        return hashlib.sha256(blob).hexdigest()


def trajectory_hash(turns: list[dict]) -> str:
    # Canonical serialization: turn order, tool args, tool results all included.
    blob = json.dumps(turns, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def record_score(turns: list[dict], judge: JudgeConfig, verdict: float,
                 store: dict) -> str:
    if judge.temperature != 0.0:
        raise UnboundScoreError(
            f"judge temperature {judge.temperature} != 0.0; score is not "
            "reproducible even given a fixed trajectory"
        )
    if not turns:
        raise UnboundScoreError("empty trajectory cannot be scored")

    t_hash = trajectory_hash(turns)
    j_hash = judge.content_hash()
    key = (t_hash, j_hash)

    # Re-scoring the same trajectory under the same judge must be idempotent.
    if key in store and store[key] != verdict:
        raise UnboundScoreError(
            f"verdict drift for trajectory {t_hash[:12]} under judge "
            f"{j_hash[:12]}: stored {store[key]} vs new {verdict}"
        )

    store[key] = verdict
    return t_hash


def assert_replayable(turns: list[dict], judge: JudgeConfig,
                      original_verdict: float, rescore_fn) -> None:
    """Invariant guard: re-scoring a stored trajectory must reproduce the verdict."""
    replay = rescore_fn(turns, judge)
    if replay != original_verdict:
        raise UnboundScoreError(
            f"non-replayable score: original={original_verdict} "
            f"replay={replay} on trajectory {trajectory_hash(turns)[:12]}"
        )
