# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-sibling-s-span-causal-parent-reattachment-and-the-phantom-tool-call-divergence-in-opentelemetry-genai-trace-g.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-sibling-s-span-causal-parent-reattachment-and-the-phantom-tool-call-divergence-in-opentelemetry-genai-trace-g.warrant.json
# Markdown SHA-256:   92ba83f0344f9d3605b4d77fb73a9d6d31ed16fcc4a96ac8c8fcbb68783c6b03
# Code AST SHA-256:   65fdc80c1b4f83ee7b531bba6d72ebe3068f45aa774262f04ff21207d02da350
# Verified Classes:   CounterfactualReplayError, Span, ReplayPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class CounterfactualReplayError(RuntimeError):
    """Raised when a replay graph contains phantom spans."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    recorded_output_hash: str
    input_dependency_hash: str | None = None  # None => no attestation


@dataclass
class ReplayPlan:
    target_ids: set[str]
    replayed_output_hash: dict[str, str] = field(default_factory=dict)
    invalidated: set[str] = field(default_factory=set)


def causal_descendants(spans: dict[str, Span], roots: Iterable[str]) -> set[str]:
    children: dict[str, list[str]] = {}
    for s in spans.values():
        if s.parent_id is not None:
            children.setdefault(s.parent_id, []).append(s.span_id)
    out: set[str] = set()
    stack = list(roots)
    while stack:
        cur = stack.pop()
        for child in children.get(cur, []):
            if child not in out:
                out.add(child)
                stack.append(child)
    return out


def validate_replay_graph(spans: dict[str, Span], plan: ReplayPlan) -> None:
    """Enforce: no recorded span may survive if a replayed ancestor diverged
    and the span lacks an independence attestation matching the replayed state."""
    affected = causal_descendants(spans, plan.target_ids)
    for sid in affected:
        if sid in plan.target_ids:
            continue  # re-executed; not a recorded leaf
        span = spans[sid]
        replayed_ancestor_diverged = any(
            plan.replayed_output_hash.get(a) != spans[a].recorded_output_hash
            for a in _ancestors(spans, sid)
            if a in plan.target_ids
        )
        if not replayed_ancestor_diverged:
            continue
        if sid in plan.invalidated:
            continue
        if span.input_dependency_hash is None:
            raise CounterfactualReplayError(
                f"phantom span {sid}: causal ancestor diverged, no independence "
                f"attestation, and span was not re-executed or invalidated"
            )
        # Attestation present: must match the replayed upstream state.
        expected = _upstream_hash(spans, sid, plan)
        if span.input_dependency_hash != expected:
            raise CounterfactualReplayError(
                f"phantom span {sid}: attestation {span.input_dependency_hash} "
                f"does not match replayed upstream hash {expected}"
            )


def _ancestors(spans: dict[str, Span], sid: str) -> Iterable[str]:
    cur = spans[sid].parent_id
    while cur is not None:
        yield cur
        cur = spans[cur].parent_id


def _upstream_hash(spans: dict[str, Span], sid: str, plan: ReplayPlan) -> str:
    parts = []
    for a in _ancestors(spans, sid):
        parts.append(plan.replayed_output_hash.get(a, spans[a].recorded_output_hash))
    return "|".join(parts)
