# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-litmus-safety-verdict-to-the-wrong-otel-span-after-a-retried-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-litmus-safety-verdict-to-the-wrong-otel-span-after-a-retried-tool-call.warrant.json
# Markdown SHA-256:   d786c0b12e94e6eb97926b22ad211a3464b04694a22c39b2c719a6f5c88574b6
# Code AST SHA-256:   f94dcd5432c246b2e9def024a738bf9773bd241ec73feda2e113793ff08f9ab3
# Verified Classes:   VerdictAttributionError, Span, Verdict, Correlator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class VerdictAttributionError(RuntimeError):
    """Raised when a LITMUS verdict cannot be provably attributed to an OTel span."""


@dataclass
class Span:
    trace_id: str
    span_id: str
    request_id: str
    attempt: int
    request_payload_hash: str
    closed: bool = False


@dataclass
class Verdict:
    trace_id: str
    request_id: str
    span_id: Optional[str]          # present only if evaluator saw span identity
    payload_hash: str
    decision: str                   # "ALLOW" | "BLOCK"
    emitted_at: float


@dataclass
class Correlator:
    spans: dict = field(default_factory=dict)          # (trace_id, span_id) -> Span
    by_request: dict = field(default_factory=dict)     # (trace_id, request_id) -> list[Span]
    quarantined: list = field(default_factory=list)

    def register(self, span: Span) -> None:
        self.spans[(span.trace_id, span.span_id)] = span
        self.by_request.setdefault((span.trace_id, span.request_id), []).append(span)

    def attach(self, verdict: Verdict) -> Span:
        # Path 1: span-scoped key, provable by payload hash.
        if verdict.span_id is not None:
            span = self.spans.get((verdict.trace_id, verdict.span_id))
            if span is None:
                raise VerdictAttributionError(
                    f"verdict for span {verdict.span_id} has no matching span "
                    f"(trace {verdict.trace_id}); cannot attach"
                )
            if span.request_payload_hash != verdict.payload_hash:
                raise VerdictAttributionError(
                    f"payload hash mismatch on span {verdict.span_id}: "
                    f"evaluator judged {verdict.payload_hash}, span recorded "
                    f"{span.request_payload_hash} (retry mutated span in place?)"
                )
            return span

        # Path 2: request-scoped key. Only safe if exactly one attempt exists.
        attempts = self.by_request.get((verdict.trace_id, verdict.request_id), [])
        if len(attempts) == 0:
            raise VerdictAttributionError(
                f"verdict references unknown request {verdict.request_id}"
            )
        if len(attempts) > 1:
            # Ambiguous: multiple attempts under one request id. Quarantine,
            # do NOT guess. This is the retry-attribution trap.
            self.quarantined.append(verdict)
            raise VerdictAttributionError(
                f"request {verdict.request_id} has {len(attempts)} attempts; "
                f"verdict {verdict.decision} quarantined rather than misattributed"
            )
        only = attempts[0]
        if only.request_payload_hash != verdict.payload_hash:
            raise VerdictAttributionError(
                f"single-attempt request {verdict.request_id} payload hash mismatch; "
                f"evaluator and runtime disagree on what was judged"
            )
        return only
