# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-attribute-a-divergence-to-a-tool-call-counterfactual-replay-under-non-deterministic-sampling.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-attribute-a-divergence-to-a-tool-call-counterfactual-replay-under-non-deterministic-sampling.warrant.json
# Markdown SHA-256:   680cb2ac62fab253fbf3a38e3ce1786c1f65ed7509624228d764878b814e3365
# Code AST SHA-256:   979f5afe70e283aa110e96559620b74b3f8958a2043fb0f50c991b011dec4b3f
# Verified Classes:   UnattributableDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnattributableDivergenceError(RuntimeError):
    """Raised when a counterfactual delta cannot be separated from null-replay noise."""
    pass


def attribute_divergence(
    span_id: str,
    p_counterfactual: float,
    p_null: float,
    n_replays: int,
    sampler_fingerprint_prod: str,
    sampler_fingerprint_replay: str,
    epsilon_low: float = 0.05,
    epsilon_high: float = 0.40,
) -> dict:
    # Invariant 2: sampler must be pinned across prod and replay.
    if sampler_fingerprint_prod != sampler_fingerprint_replay:
        raise UnattributableDivergenceError(
            f"span {span_id}: sampler fingerprint mismatch "
            f"({sampler_fingerprint_prod} vs {sampler_fingerprint_replay}); "
            f"diff conflates intervention with config drift"
        )

    # Invariant 1: null baseline must exist and be depth-matched (caller's job),
    # but we can refuse if it was never measured (sentinel -1).
    if p_null < 0:
        raise UnattributableDivergenceError(
            f"span {span_id}: no null-replay baseline recorded; "
            f"attribution is unfalsifiable"
        )

    # Invariant 3: decision-unstable spans carry no causal signal.
    if p_null > epsilon_high:
        return {
            "span_id": span_id,
            "verdict": "decision_unstable",
            "attribution": "none",
            "null_divergence": p_null,
            "note": "decision is coin-flip under configured sampler; "
                    "divergence measures sampler noise, not intervention",
        }

    delta = p_counterfactual - p_null

    # Deterministic-enough span: single replay is acceptable.
    if p_null < epsilon_low:
        return {
            "span_id": span_id,
            "verdict": "attributable",
            "delta": delta,
            "null_divergence": p_null,
        }

    # Stochastic span: require adequate N and a separable delta.
    if n_replays < 30:
        raise UnattributableDivergenceError(
            f"span {span_id}: stochastic span (p_null={p_null:.2f}) "
            f"with only {n_replays} replays; need >=30 for two-proportion test"
        )

    # Binomial standard error floor for the difference of two proportions.
    se = (p_null * (1 - p_null) / n_replays) ** 0.5 * (2 ** 0.5)
    if abs(delta) <= 1.96 * se:
        return {
            "span_id": span_id,
            "verdict": "inconclusive",
            "delta": delta,
            "null_divergence": p_null,
            "se": se,
            "note": "delta inside null-replay confidence band",
        }

    return {
        "span_id": span_id,
        "verdict": "attributable",
        "delta": delta,
        "null_divergence": p_null,
        "se": se,
    }
