# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-span-identity-before-eval-score-attribution-in-multi-hop-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-span-identity-before-eval-score-attribution-in-multi-hop-agent-traces.warrant.json
# Markdown SHA-256:   b7e3d34507a4f121e962c8233958d23f9878a07cfc919fe6d907f83a6ffd56b5
# Code AST SHA-256:   95c1827494e0800e7f9ef6ed34b09d8a2fac481bd35753e7bcbacc0719a4544b
# Verified Classes:   AttributionError, Span, EvalScore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttributionError(RuntimeError):
    """Raised when an eval score cannot be unambiguously attributed to a generation span."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    trace_id: str
    operation: str  # e.g. "chat", "tool", "invoke_agent"


@dataclass(frozen=True)
class EvalScore:
    trace_id: str
    span_id: Optional[str]
    payload_key: Optional[str]
    value: float


def attribute_score(score: EvalScore, spans: list[Span], payload_index: dict[str, str]) -> Span:
    """
    Resolve an eval score to exactly one generation span, or raise AttributionError.
    Never guess. Never average across hops. Never attach to a trace when ambiguous.
    """
    generation_spans = [s for s in spans if s.trace_id == score.trace_id and s.operation == "chat"]

    # Path 1: explicit span_id from the scorer.
    if score.span_id is not None:
        for s in generation_spans:
            if s.span_id == score.span_id:
                return s
        raise AttributionError(
            f"score span_id={score.span_id!r} does not resolve to a generation span "
            f"under trace {score.trace_id!r}; quarantine"
        )

    # Path 2: payload key must map to a span via the explicit link index.
    if score.payload_key is not None:
        linked_span_id = payload_index.get(score.payload_key)
        if linked_span_id is None:
            raise AttributionError(
                f"payload_key={score.payload_key!r} has no span link; "
                f"likely retry or payload/span id divergence; quarantine"
            )
        for s in generation_spans:
            if s.span_id == linked_span_id:
                return s
        raise AttributionError(
            f"payload_key={score.payload_key!r} links to span {linked_span_id!r} "
            f"which is not a generation span in trace {score.trace_id!r}; quarantine"
        )

    # Path 3: trace-only score. Valid only under the single-generation invariant.
    if len(generation_spans) == 1:
        return generation_spans[0]

    raise AttributionError(
        f"trace {score.trace_id!r} has {len(generation_spans)} generation spans; "
        f"trace-level attribution is invalid for multi-hop traces; quarantine"
    )


def ingest(score: EvalScore, spans: list[Span], payload_index: dict[str, str]) -> tuple[str, Span]:
    try:
        span = attribute_score(score, spans, payload_index)
        return ("attributed", span)
    except AttributionError as e:
        # Quarantine, do not drop: quarantine is recoverable, misattribution is not.
        return (f"quarantined: {e}", None)  # type: ignore[return-value]
