# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-non-replayable-divergence-in-agent-span-graphs-recorded-for-time-travel-debugging.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-non-replayable-divergence-in-agent-span-graphs-recorded-for-time-travel-debugging.warrant.json
# Markdown SHA-256:   fc68b8cdee93affa6b838ca57da5f36398e6b03a2aab851d84eac8df87d6b684
# Code AST SHA-256:   5f55b02984e1b79f424c8eef4239f009ed20667ac10f5e172f0cd9afb2dcc198
# Verified Classes:   NonReplayableDivergenceError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class NonReplayableDivergenceError(RuntimeError):
    """Raised when a span graph cannot support the requested replay mode."""
    pass


def audit_span_graph(graph, mode: str) -> None:
    """
    mode: 'reproduce' or 'counterfactual'.
    Enforces that counterfactual replay only proceeds over spans with
    derivation edges and model_generated provenance.
    """
    if mode not in ("reproduce", "counterfactual"):
        raise NonReplayableDivergenceError(f"unknown replay mode: {mode}")

    for span in graph.spans:
        # Invariant: every consumed argument must trace to a journaled root.
        for arg_name, arg in span.args.items():
            if not graph.has_provenance_chain(arg):
                raise NonReplayableDivergenceError(
                    f"span {span.id} arg {arg_name!r} has no journaled derivation; "
                    f"graph is causally unfaithful"
                )

        if mode == "counterfactual":
            # Counterfactual replay requires the span to be a decision,
            # not a frozen injection from the journal.
            if span.provenance != "model_generated":
                raise NonReplayableDivergenceError(
                    f"span {span.id} has provenance {span.provenance!r}; "
                    f"counterfactual perturbation would be a silent no-op"
                )
            if span.is_branch and not span.has_predicate_span:
                raise NonReplayableDivergenceError(
                    f"span {span.id} branches without a recorded predicate; "
                    f"replay would reconstruct control flow from outputs, "
                    f"not from the original decision"
                )
