# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-benchmark-on-replay-but-regress-in-production-adjudicator-cache-aliasing-across-harness-re-instantiation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-benchmark-on-replay-but-regress-in-production-adjudicator-cache-aliasing-across-harness-re-instantiation.warrant.json
# Markdown SHA-256:   42195de6cc2f00bb3a91d423b502cbfc13b2607149a90b591d124c937c5703a2
# Code AST SHA-256:   cf5a271f5e3c26acf0cdeab8c543a004cb91e2a314be64c50cafa2479c2539e3
# Verified Classes:   AdjudicatorCacheAliasingError, AdjudicationIdentity, VerdictCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AdjudicatorCacheAliasingError(RuntimeError):
    """Raised when a cached verdict is reused under an adjudication identity
    that differs from the one it was produced under."""
    pass


@dataclass(frozen=True)
class AdjudicationIdentity:
    trajectory_digest: str
    judge_model_snapshot: str
    judge_prompt_hash: str
    temperature: float
    seed_policy: str
    harness_version: str

    def cache_key(self) -> str:
        # Full identity, not a projection. Any omitted field is an aliasing bug.
        payload = json.dumps(self.__dict__, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(payload.encode()).hexdigest()


def trajectory_digest(trajectory: list[dict]) -> str:
    canonical = json.dumps(trajectory, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


class VerdictCache:
    def __init__(self) -> None:
        self._store: dict[str, dict] = {}

    def get(self, identity: AdjudicationIdentity) -> dict | None:
        entry = self._store.get(identity.cache_key())
        if entry is None:
            return None
        # Defensive: verify the stored identity matches the requested one.
        # A mismatch means the key was constructed lossily somewhere upstream.
        if entry["identity"] != identity.__dict__:
            raise AdjudicatorCacheAliasingError(
                f"cache key collision: stored identity {entry['identity']} "
                f"!= requested {identity.__dict__}"
            )
        return entry["verdict"]

    def put(self, identity: AdjudicationIdentity, verdict: dict) -> None:
        self._store[identity.cache_key()] = {
            "identity": identity.__dict__,
            "verdict": verdict,
        }


def adjudicate(identity: AdjudicationIdentity, cache: VerdictCache, judge_fn) -> dict:
    cached = cache.get(identity)
    if cached is not None:
        return cached
    verdict = judge_fn(identity)
    cache.put(identity, verdict)
    return verdict


def regression_gate(
    trajectories: list[list[dict]],
    old_identity: AdjudicationIdentity,
    new_identity: AdjudicationIdentity,
    cache: VerdictCache,
    judge_fn,
) -> dict:
    """Dual-run gate: hold trajectories fixed, vary only the adjudicator."""
    if old_identity.trajectory_digest != new_identity.trajectory_digest:
        raise AdjudicatorCacheAliasingError(
            "dual-run requires identical trajectory digest; "
            "varying the trajectory confounds the judge delta"
        )
    if old_identity.judge_model_snapshot == new_identity.judge_model_snapshot \
       and old_identity.judge_prompt_hash == new_identity.judge_prompt_hash:
        raise AdjudicatorCacheAliasingError(
            "dual-run invoked with no adjudicator change; "
            "delta would be undefined"
        )

    flips = []
    for traj in trajectories:
        digest = trajectory_digest(traj)
        old_id = AdjudicationIdentity(
            trajectory_digest=digest,
            judge_model_snapshot=old_identity.judge_model_snapshot,
            judge_prompt_hash=old_identity.judge_prompt_hash,
            temperature=old_identity.temperature,
            seed_policy=old_identity.seed_policy,
            harness_version=old_identity.harness_version,
        )
        new_id = AdjudicationIdentity(
            trajectory_digest=digest,
            judge_model_snapshot=new_identity.judge_model_snapshot,
            judge_prompt_hash=new_identity.judge_prompt_hash,
            temperature=new_identity.temperature,
            seed_policy=new_identity.seed_policy,
            harness_version=new_identity.harness_version,
        )
        old_v = adjudicate(old_id, cache, judge_fn)
        new_v = adjudicate(new_id, cache, judge_fn)
        if old_v["unsafe"] != new_v["unsafe"]:
            flips.append({"digest": digest, "old": old_v, "new": new_v})

    return {
        "total": len(trajectories),
        "flips": len(flips),
        "details": flips,
    }
