# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-sampled-trace-and-mistakes-reconstruction-for-causation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-sampled-trace-and-mistakes-reconstruction-for-causation.warrant.json
# Markdown SHA-256:   6ee6ab106d5847ee278d3dba5b6a71cddc1ac4c84de65da907781a104071257c
# Code AST SHA-256:   9ec5b776082e6009ec09cf972462149163873236870450b4812c810e9ff5764a
# Verified Classes:   Provenance, CausalAttributionError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class Provenance(Enum):
    OBSERVED = "observed"
    SYNTHESIZED = "synthesized"
    MISSING = "missing"


class CausalAttributionError(RuntimeError):
    """Raised when attribution would traverse a non-observed causal edge."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    provenance: Provenance
    payload: dict = field(default_factory=dict)


def attribute_root_cause(
    spans: dict[str, Span],
    failing_span_id: str,
) -> str:
    """
    Walk the ancestor path from the failing span to the root and return the
    root-cause span_id. Refuses if any ancestor is SYNTHESIZED or MISSING,
    because the causal chain is not fully observed and attribution would be
    a reconstruction, not a record.
    """
    path: list[Span] = []
    cursor = spans.get(failing_span_id)
    if cursor is None:
        raise CausalAttributionError(
            f"failing span {failing_span_id} not in storage; cannot attribute"
        )

    while cursor is not None:
        if cursor.provenance is Provenance.MISSING:
            raise CausalAttributionError(
                f"causal chain broken at span {cursor.span_id}: ancestor was "
                f"sampled out and is MISSING. Attribution is indeterminate; "
                f"do not synthesize a parent. Re-collect with per-trace sampling."
            )
        if cursor.provenance is Provenance.SYNTHESIZED:
            raise CausalAttributionError(
                f"causal chain crosses SYNTHESIZED span {cursor.span_id}: this "
                f"span was reconstructed during replay and did not exist in the "
                f"original execution. Attribution would assign blame to an "
                f"inferred edge. Return ATTRIBUTION_INDETERMINATE."
            )
        path.append(cursor)
        if cursor.parent_span_id is None:
            break
        parent = spans.get(cursor.parent_span_id)
        if parent is None:
            # Parent referenced but not stored: evidence of a sampled-out ancestor.
            raise CausalAttributionError(
                f"span {cursor.span_id} references parent "
                f"{cursor.parent_span_id} which is not in storage; the "
                f"ancestor was dropped by sampling. Attribution refused."
            )
        cursor = parent

    # All edges on the path are OBSERVED; the root of the path is the
    # earliest observed span, which is the best-supported causal candidate.
    return path[-1].span_id
