# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-exemplar-trace-link-has-silently-desynchronized-from-its-eval-verdict.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-exemplar-trace-link-has-silently-desynchronized-from-its-eval-verdict.warrant.json
# Markdown SHA-256:   137dfa57cabdbbdac9c99d5f1eff32a7420427f21c54288bd7edc2e7d813c740
# Code AST SHA-256:   c7849d2758595840a66cae0d7d736fd123391157e0233694d16fa3ec23a41f93
# Verified Classes:   ExemplarLinkError, Exemplar, Verdict, LinkRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ExemplarLinkError(RuntimeError):
    """Raised when an eval/safety verdict cannot be validly bound to a trace exemplar."""
    pass


@dataclass(frozen=True)
class Exemplar:
    trace_id: str
    span_id: str
    attempt_ordinal: int
    content_hash: str          # sha256 of the exact judged bytes, frozen at emit
    model: str


@dataclass(frozen=True)
class Verdict:
    trace_id: str
    span_id: str
    attempt_ordinal: int
    judged_content_hash: str   # hash of the bytes the scorer actually saw
    scorer_version: Optional[str]  # rubric/judge/model version pin
    label: str


@dataclass
class LinkRecord:
    exemplar: Exemplar
    verdict: Verdict
    status: str                # "attached" | "pending_link"
    supersedes: Optional[str] = field(default=None)


def _judged_key(v: Verdict) -> tuple:
    return (v.trace_id, v.span_id, v.attempt_ordinal)


def attach_verdict(exemplar: Exemplar, verdict: Verdict,
                   existing: dict) -> LinkRecord:
    # 1. Join-key uniqueness: retries must not alias onto one key.
    key = _judged_key(verdict)
    if key in existing and existing[key].status == "attached":
        raise ExemplarLinkError(
            f"non-unique join key {key}: verdict would overwrite an "
            f"already-attached safety record (retry aliasing)"
        )

    # 2. Content-hash equality: the verdict must judge the frozen bytes.
    if verdict.judged_content_hash != exemplar.content_hash:
        raise ExemplarLinkError(
            f"content drift on {key}: exemplar hash {exemplar.content_hash} "
            f"!= judged hash {verdict.judged_content_hash}; verdict is about "
            f"different content and must not attach"
        )

    # 3. Scorer-version pinning: unversioned verdicts are uninterpretable.
    if not verdict.scorer_version:
        return LinkRecord(exemplar, verdict, status="pending_link")

    # 4. Monotonic attachment handled by caller via `existing`; here we attach.
    return LinkRecord(exemplar, verdict, status="attached")


def replay_pending(link: LinkRecord, rejudged: Verdict) -> LinkRecord:
    if link.status != "pending_link":
        raise ExemplarLinkError(
            f"replay only valid for pending_link, got {link.status}"
        )
    if rejudged.judged_content_hash != link.exemplar.content_hash:
        raise ExemplarLinkError(
            "replay judged different content than the frozen exemplar"
        )
    if not rejudged.scorer_version:
        raise ExemplarLinkError(
            "replay verdict still missing scorer_version; cannot attach"
        )
    return LinkRecord(link.exemplar, rejudged, status="attached")
