# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-trace-linked-eval-and-the-causal-attribution-silently-re-roots-to-the-wrong-span.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-trace-linked-eval-and-the-causal-attribution-silently-re-roots-to-the-wrong-span.warrant.json
# Markdown SHA-256:   bb683e0ad0f18da2ee8d485286ae523ac0f3e6f80271e2dbb3ff39a3545a4c0b
# Code AST SHA-256:   54e38bdb52b18cf5243e596c17e5fa587e340c7182cb0561908c2bde202352ba
# Verified Classes:   AttributionReRootError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttributionReRootError(RuntimeError):
    """Raised when replay attempts to use a re-executed span as causal evidence."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    tool_name: str
    step_index: int
    output_hash: str
    output_frozen: bool  # True only if captured immutably at record time


def attribute_failure(
    recorded: dict[str, Span],
    replayed: dict[str, Span],
    suspect_span_id: str,
) -> str:
    """
    Attribute a failure to a causal span, refusing silent re-rooting.
    Returns the confirmed causal span_id, or raises if the evidence is
    a re-executed (non-frozen) span that diverged from the record.
    """
    if suspect_span_id not in recorded:
        raise AttributionReRootError(
            f"suspect span {suspect_span_id} absent from recorded trace"
        )

    rec = recorded[suspect_span_id]

    # Bind by immutable span_id, never by (tool_name, step_index).
    rep: Optional[Span] = replayed.get(rec.span_id)

    if rep is None:
        # Span not re-executed: attribution rests on frozen record. Safe.
        if not rec.output_frozen:
            raise AttributionReRootError(
                f"span {rec.span_id} output not frozen; causal claim unverifiable"
            )
        return rec.span_id

    # Span WAS re-executed. If it diverged, its clean output cannot
    # exculpate the original span -- that is the re-rooting trap.
    if rep.output_hash != rec.output_hash:
        raise AttributionReRootError(
            f"span {rec.span_id} re-rooted: recorded hash {rec.output_hash} "
            f"!= replayed hash {rep.output_hash}; attribution must downgrade "
            f"to 'unverified', not 'cleared'"
        )

    if not rec.output_frozen:
        raise AttributionReRootError(
            f"span {rec.span_id} matched on hash but was not frozen at record "
            f"time; causal verdict cannot be confirmed"
        )

    return rec.span_id


def run_attribution(recorded, replayed, suspect_span_id):
    try:
        return attribute_failure(recorded, replayed, suspect_span_id)
    except AttributionReRootError as e:
        # Downgrade to suspected; never close the incident as attributed.
        return {"verdict": "suspected", "reason": str(e)}
