# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-counterfactual-span-analysis-from-corrupting-causal-replay-in-non-deterministic-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-counterfactual-span-analysis-from-corrupting-causal-replay-in-non-deterministic-agent-traces.warrant.json
# Markdown SHA-256:   895d0bfed92dee15c49cf775b8d3722a00dcbe2f9a94edc84a55a1aa5824d52e
# Code AST SHA-256:   9502ca8c9b58ee42d1e1146665ff45146853a13478a91ca28e5d8fbbfcbfd18b
# Verified Classes:   CounterfactualClosureError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, List


class CounterfactualClosureError(RuntimeError):
    """Raised when a counterfactual substitution cannot be soundly replayed."""
    pass


@dataclass
class Span:
    span_id: str
    # content-addressed ids of upstream span outputs this span actually consumed
    consumed: Set[str] = field(default_factory=set)
    # True if re-execution is stochastic and not pinned to recorded values
    stochastic_unpinned: bool = False
    # provenance of prompt composition is required if this span composes prompts
    provenance_recorded: bool = True


def compute_reexecution_set(spans: Dict[str, Span], substituted: str) -> Set[str]:
    # forward reachability over actual dataflow (consumed edges), not parentage
    consumers: Dict[str, List[str]] = {}
    for sid, s in spans.items():
        for upstream in s.consumed:
            consumers.setdefault(upstream, []).append(sid)
    closure: Set[str] = set()
    frontier = [substituted]
    while frontier:
        cur = frontier.pop()
        for c in consumers.get(cur, []):
            if c not in closure:
                closure.add(c)
                frontier.append(c)
    return closure


def plan_counterfactual(
    spans: Dict[str, Span],
    substituted: str,
    single_sample: bool,
) -> Set[str]:
    if substituted not in spans:
        raise CounterfactualClosureError(
            f"substituted span {substituted!r} not found in trace"
        )
    closure = compute_reexecution_set(spans, substituted)
    for sid in closure:
        s = spans[sid]
        if not s.provenance_recorded:
            raise CounterfactualClosureError(
                f"span {sid!r} consumes substituted output but records no "
                f"prompt provenance; dataflow closure unverifiable"
            )
        if single_sample and s.stochastic_unpinned:
            raise CounterfactualClosureError(
                f"span {sid!r} is unpinned-stochastic in the re-execution "
                f"set; a single-sample counterfactual would be a category "
                f"error (request a distribution, N>=20)"
            )
    return closure
