# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-causal-replay-from-a-non-deterministic-agent-trace-when-span-level-attribution-has-already-been-corrupted-by-a-ha.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-causal-replay-from-a-non-deterministic-agent-trace-when-span-level-attribution-has-already-been-corrupted-by-a-ha.warrant.json
# Markdown SHA-256:   d7edb337c23a5b345c46d7f62c6f635689e96ac9169e0c286fc2ea97c0af16f3
# Code AST SHA-256:   feabeb4cdfc3ab033d8b7e8cf4cbac38f955087b8a8a93baae39ff4400a77ddb
# Verified Classes:   AttributionError, JustificationRole, Span, CausalPath
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class AttributionError(RuntimeError):
    """Raised when causal replay cannot soundly localize a root cause."""


class JustificationRole(str, Enum):
    PROVIDES_EVIDENCE = "provides_evidence"
    CHECKS_CONSISTENCY_WITH_INPUT = "checks_consistency_with_input"
    GROUNDS_AGAINST_EXTERNAL = "grounds_against_external"


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: Optional[str]
    transformation_id: Optional[str]          # None => transformation not captured
    provenance: Optional[dict]                # None => provenance not tagged
    justification_role: JustificationRole
    non_replayable: bool = False


@dataclass
class CausalPath:
    spans: list[Span] = field(default_factory=list)

    def evidence_edges(self) -> list[Span]:
        return [s for s in self.spans if s.justification_role is JustificationRole.PROVIDES_EVIDENCE]


def attribute_root_cause(path: CausalPath, symptom_span_id: str) -> str:
    """
    Reconstruct causal justification for a symptom span and return the
    earliest span whose provenance break can explain the symptom.

    Fails closed: any provenance gap on the path aborts attribution.
    """
    if not path.spans:
        raise AttributionError("empty causal path; nothing to replay")

    symptom = next((s for s in path.spans if s.span_id == symptom_span_id), None)
    if symptom is None:
        raise AttributionError(f"symptom span {symptom_span_id!r} not present in path")

    # Invariant 1: attribution is only as strong as the weakest provenance link.
    for span in path.spans:
        if span.transformation_id is None:
            raise AttributionError(
                f"provenance gap: span {span.span_id!r} has no transformation_id; "
                "cannot distinguish tool transform from model output"
            )
        if span.provenance is None:
            raise AttributionError(
                f"provenance gap: span {span.span_id!r} has no provenance tag; "
                "cache/tenant/source origin unknown"
            )

    # Invariant 2: a consistency check is not corroboration.
    corroborating = [
        s for s in path.spans
        if s.justification_role is JustificationRole.GROUNDS_AGAINST_EXTERNAL
    ]
    if not corroborating:
        raise AttributionError(
            "no external grounding on path; verify spans are internal-consistency only, "
            "so the symptom is 'consistent but ungrounded' and cannot be attributed to a model fault"
        )

    # Invariant 3: locate earliest provenance-scope mismatch, not first wrong-looking output.
    query_scope = path.spans[0].provenance.get("scope")
    for span in path.spans:
        if span.provenance.get("scope") != query_scope:
            return span.span_id

    # Invariant 4: stochastic spans cannot yield single-cause attribution from one sample.
    if any(s.non_replayable for s in path.spans):
        raise AttributionError(
            "path contains non_replayable spans; switch to counterfactual replay "
            "with pinned seed before asserting a single root cause"
        )

    raise AttributionError(
        f"symptom {symptom_span_id!r} has no provenance-scope mismatch on path; "
        "root cause is outside the recorded causal graph"
    )
