# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-otel-genai-span-identity-with-safety-benchmark-verdict-identity-when-the-same-logical-agent-turn-is-replayed-under-a.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-otel-genai-span-identity-with-safety-benchmark-verdict-identity-when-the-same-logical-agent-turn-is-replayed-under-a.warrant.json
# Markdown SHA-256:   c4a0fe6dba366cdc3951ce23447e529f15b280f323700582f2ea9dc45f4d04ec
# Code AST SHA-256:   70811bcd65c33fb75c0e8b69b023e30b804355dd61ee361e0631dcc828f69ef4
# Verified Classes:   UnwarrantedVerdictError, Span, Verdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnwarrantedVerdictError(RuntimeError):
    """Raised when a safety verdict cannot be bound to the span that produced it."""


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    conversation_id: str
    turn_index: int
    transcript_hash: str
    live: bool = True


@dataclass(frozen=True)
class Verdict:
    scenario_id: str
    conversation_id: str
    turn_index: int
    scored_transcript_hash: str
    verdict: str
    span_id: Optional[str] = None       # warrant, if the harness propagated it
    trace_id: Optional[str] = None


def bind_verdict(verdict: Verdict, spans: list[Span]) -> Span:
    # Path 1: explicit span warrant. This is the only path safe for aggregation.
    if verdict.span_id is not None:
        for s in spans:
            if s.span_id == verdict.span_id and s.trace_id == verdict.trace_id:
                if not s.live:
                    raise UnwarrantedVerdictError(
                        f"verdict {verdict.scenario_id} warrants evicted span "
                        f"{verdict.span_id}; persist transcript->span index before TTL"
                    )
                return s
        raise UnwarrantedVerdictError(
            f"verdict {verdict.scenario_id} warrants span {verdict.span_id} "
            f"not present in trace store"
        )

    # Path 2: content-hash fallback. Sound only if exactly one live span matches.
    candidates = [
        s for s in spans
        if s.live
        and s.conversation_id == verdict.conversation_id
        and s.turn_index == verdict.turn_index
        and s.transcript_hash == verdict.scored_transcript_hash
    ]
    if len(candidates) == 0:
        raise UnwarrantedVerdictError(
            f"verdict {verdict.scenario_id} has no warrant and no matching live span "
            f"(conversation={verdict.conversation_id} turn={verdict.turn_index}); "
            f"likely resumed under a new trace_id — quarantine, do not aggregate"
        )
    if len(candidates) > 1:
        raise UnwarrantedVerdictError(
            f"verdict {verdict.scenario_id} matches {len(candidates)} live spans "
            f"(replay/checkpoint-resume fan-out); content join is ambiguous — "
            f"quarantine until harness propagates traceparent"
        )
    # Single content-hash match: admissible, but only as join_confidence=content_hash.
    return candidates[0]
