# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-causal-span-links-before-replay-when-a-parent-span-s-tool-result-is-non-deterministic-and-the-child-span-s-inputs-wer.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-causal-span-links-before-replay-when-a-parent-span-s-tool-result-is-non-deterministic-and-the-child-span-s-inputs-wer.warrant.json
# Markdown SHA-256:   956e39ebe52aae678eda163f9a24e91029ef4fba6d0f74259708bf20f988f18a
# Code AST SHA-256:   f9bbb50b584a9378ec4277a5519647faf67a579ed111b8bcaf9ca53c5d32eb06
# Verified Classes:   CausalBindingError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class CausalBindingError(RuntimeError):
    """Raised when a child span's recorded input hash does not match the
    payload it would receive from its (anchored) parent during replay.
    This indicates the replay is counterfactual, not fidelity, or that the
    trace is missing a binding and cannot be faithfully replayed."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_span_id: str | None
    determinism: str  # "deterministic" | "sampled"
    output: Any
    # For child spans: hash over the exact slice of parent output consumed.
    parent_output_hash: str | None
    # For parent spans: the exact slice children are allowed to bind to.
    consumed_slice: Any = None


def canonical_hash(payload: Any) -> str:
    """Deterministic hash over a serialized payload. Rejects non-canonical types
    (sets, unordered dicts) that would make the binding unstable across runs."""
    if isinstance(payload, (set, frozenset)):
        raise CausalBindingError(
            "Cannot hash a set: iteration order is not stable across processes. "
            "Serialize to a sorted list before binding."
        )
    serialized = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
    return hashlib.sha256(serialized.encode("utf-8")).hexdigest()


def replay_child(parent: Span, child: Span, *, allow_counterfactual: bool = False) -> Any:
    """Replay a child span against an anchored parent. Verifies the causal
    binding before executing; refuses to proceed on mismatch unless the
    caller explicitly opts into counterfactual exploration."""
    if child.parent_output_hash is None:
        raise CausalBindingError(
            f"Child span {child.span_id} has no parent_output_hash. "
            "Trace is temporally ordered, not causally linked; ineligible for fidelity replay."
        )

    if parent.determinism == "sampled" and parent.consumed_slice is None:
        raise CausalBindingError(
            f"Parent span {parent.span_id} is sampled but exposes no consumed_slice; "
            "cannot anchor child replay. Re-execution would be counterfactual."
        )

    anchored_payload = parent.consumed_slice if parent.consumed_slice is not None else parent.output
    actual_hash = canonical_hash(anchored_payload)

    if actual_hash != child.parent_output_hash:
        if not allow_counterfactual:
            raise CausalBindingError(
                f"Causal binding broken: child {child.span_id} recorded "
                f"hash {child.parent_output_hash[:12]}… but anchored parent "
                f"{parent.span_id} yields {actual_hash[:12]}…. "
                "This replay would be counterfactual, not fidelity. "
                "Pass allow_counterfactual=True to explore, and tag the result accordingly."
            )
        # Counterfactual path: proceed, but the caller must not report this as fidelity.
        return {"counterfactual": True, "child": child.span_id, "payload": anchored_payload}

    return {"counterfactual": False, "child": child.span_id, "payload": anchored_payload}
