# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-semantic-trace-span-as-authoritative-when-its-parent-span-was-re-emitted-after-a-retry-and-how-does-cau.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-semantic-trace-span-as-authoritative-when-its-parent-span-was-re-emitted-after-a-retry-and-how-does-cau.warrant.json
# Markdown SHA-256:   d59bc28de6a487e2ea7fea6a01cdadbbfa3a7146ca43ebf9e78b95d89b5e5757
# Code AST SHA-256:   5ee5e54cd0fd62f746ede83ae7b9dae0a615bc727a3dab6941d2167ece1444c8
# Verified Classes:   CausalAttributionError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalAttributionError(RuntimeError):
    """Raised when a semantic trace cannot yield a single authoritative
    safety decision for a committed effect."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    logical_op_id: str
    attempt_index: int = 0
    superseded: bool = False
    effect_committed: bool = False
    input_hash: Optional[str] = None
    verdict: Optional[str] = None


def resolve_gating_decision(spans: list[Span], logical_op_id: str) -> Span:
    """Return the single span that authoritatively gated the committed effect
    for a logical operation. Fail closed on ambiguity."""
    candidates = [s for s in spans if s.logical_op_id == logical_op_id]
    if not candidates:
        raise CausalAttributionError(
            f"no spans for logical_op_id={logical_op_id!r}; trace is incomplete"
        )

    committed = [s for s in candidates if s.effect_committed and not s.superseded]
    if len(committed) == 0:
        raise CausalAttributionError(
            f"logical_op_id={logical_op_id!r} has no committed, non-superseded span; "
            f"causal chain is unattributable (retry collapse suspected)"
        )
    if len(committed) > 1:
        raise CausalAttributionError(
            f"logical_op_id={logical_op_id!r} has {len(committed)} committed spans; "
            f"supersession invariant violated"
        )

    winner = committed[0]

    # Verify no superseded sibling carries a divergent verdict without a
    # distinguishing input_hash — that is the retry-flip collapse signature.
    for s in candidates:
        if s is winner:
            continue
        if s.verdict is not None and s.verdict != winner.verdict:
            if s.input_hash is None or winner.input_hash is None:
                raise CausalAttributionError(
                    f"verdict divergence between span {s.span_id} ({s.verdict}) and "
                    f"committed span {winner.span_id} ({winner.verdict}) without "
                    f"input_hash linkage; cannot prove which payload was gated"
                )
            if s.input_hash == winner.input_hash:
                raise CausalAttributionError(
                    f"same input_hash but divergent verdicts across attempts for "
                    f"logical_op_id={logical_op_id!r}; non-deterministic safety gate"
                )
    return winner
