# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-causal-trace-reconstruction-as-unsound-when-span-clocks-are-unsynchronized-across-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-causal-trace-reconstruction-as-unsound-when-span-clocks-are-unsynchronized-across-agent-hops.warrant.json
# Markdown SHA-256:   3846b05ebb465728ce0a5b8dd87a117ea2a35d2cdf507b524144290acb8ac829
# Code AST SHA-256:   68b7f3297a3f051efb3379569424451d4855ca30acdd6add2f20cdea43270e3f
# Verified Classes:   UnsoundCausalReconstruction
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnsoundCausalReconstruction(RuntimeError):
    """Raised when a decision graph's causal edges cannot be trusted as facts."""
    pass


def assert_graph_is_consumable(graph, *, min_hop_latency_s: float) -> None:
    """
    Guard a decision graph before it is used as a control input
    (SLO monitor, regression detector, auditor replay).

    A graph is consumable iff:
      - every edge is recorded, OR
      - every edge is inferred AND skew_max < min_hop_latency_s AND
        the graph contains no retries/fan-out that require explicit context.
    """
    edges = graph.edges
    if not edges:
        return

    edge_kinds = {e.kind for e in edges}  # {"recorded", "inferred"}
    if edge_kinds == {"recorded"}:
        return

    if "recorded" in edge_kinds and "inferred" in edge_kinds:
        raise UnsoundCausalReconstruction(
            f"Mixed causality in graph {graph.trace_id!r}: "
            f"{sum(e.kind == 'recorded' for e in edges)} recorded, "
            f"{sum(e.kind == 'inferred' for e in edges)} inferred. "
            "Cannot treat inferred edges as facts alongside recorded ones."
        )

    # All edges inferred: apply the skew-vs-latency invariant.
    if graph.skew_max_s is None:
        raise UnsoundCausalReconstruction(
            f"Graph {graph.trace_id!r} is fully inferred but skew_max is unknown; "
            "interval-overlap inference is unverifiable."
        )
    if graph.skew_max_s >= min_hop_latency_s:
        raise UnsoundCausalReconstruction(
            f"Graph {graph.trace_id!r}: skew_max={graph.skew_max_s:.3f}s "
            f">= min_hop_latency={min_hop_latency_s:.3f}s. "
            "Causal order is under-determined; edges may be inverted."
        )
    if graph.has_retries or graph.has_fanout:
        raise UnsoundCausalReconstruction(
            f"Graph {graph.trace_id!r}: retries/fan-out present under inferred "
            "causality; interval overlap cannot disambiguate sibling or "
            "retry edges. Require explicit span-context on every hop."
        )
    # Inferred but bounded: admissible as advisory input only.
    graph.causality_confidence = "advisory"
