# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-genai-span-graph-as-evidence-about-the-original-run-rather-than-as-a-new-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-genai-span-graph-as-evidence-about-the-original-run-rather-than-as-a-new-execution.warrant.json
# Markdown SHA-256:   90ef6b36caf2c3818e159aa2c54344abe36d44c8472c0501fbf5839d84aeb87a
# Code AST SHA-256:   d07094ee645574ee63dfa5c3257ee7e1e955a57bd66621e0b45702883f3e9ecf
# Verified Classes:   ReplayAdmissibilityError, InputProvenance, SpanReplay
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ReplayAdmissibilityError(RuntimeError):
    """Raised when a replay is cited as counterfactual evidence but violates input closure."""


class InputProvenance(Enum):
    PINNED = "pinned"      # copied verbatim from span record
    STUBBED = "stubbed"    # recorded tool output substituted
    LIVE = "live"          # re-derived from current environment
    UNKNOWN = "unknown"    # not recorded, not declared


@dataclass
class SpanReplay:
    span_id: str
    inputs: dict[str, InputProvenance]
    recorded_output_hash: str
    replayed_output_hash: str
    delta_field: str | None = None

    def is_hermetic(self) -> bool:
        return all(
            p in (InputProvenance.PINNED, InputProvenance.STUBBED)
            for p in self.inputs.values()
        )


def assert_counterfactual_evidence(replay: SpanReplay) -> None:
    """Guard: a replay may only be cited as evidence about the original run
    if every input is pinned or stubbed and exactly one delta is declared."""
    live = [k for k, v in replay.inputs.items() if v is InputProvenance.LIVE]
    unknown = [k for k, v in replay.inputs.items() if v is InputProvenance.UNKNOWN]

    if live or unknown:
        raise ReplayAdmissibilityError(
            f"span {replay.span_id} has uncontrolled channels: "
            f"live={live} unknown={unknown}; "
            f"replay is a sample, not counterfactual evidence"
        )
    if replay.delta_field is None:
        raise ReplayAdmissibilityError(
            f"span {replay.span_id} declares no single-variable delta; "
            f"attribution is confounded"
        )
    if replay.delta_field not in replay.inputs:
        raise ReplayAdmissibilityError(
            f"span {replay.span_id} delta {replay.delta_field!r} not in input set"
        )


def attribute_divergence(replay: SpanReplay) -> str:
    """Return an attribution only for admissible replays; otherwise classify
    the divergence as a channel-leak or sampling signal."""
    try:
        assert_counterfactual_evidence(replay)
    except ReplayAdmissibilityError as exc:
        # Divergence under pinned inputs is a channel-leak signal, not a model signal.
        if replay.is_hermetic() and replay.recorded_output_hash != replay.replayed_output_hash:
            return f"CHANNEL_LEAK: {exc}"
        return f"SAMPLING_ONLY: {exc}"

    if replay.recorded_output_hash == replay.replayed_output_hash:
        return "NO_DIVERGENCE"
    return f"COUNTERFACTUAL_DELTA: {replay.delta_field}"


def _h(s: str) -> str:
    return hashlib.sha256(s.encode()).hexdigest()[:16]


if __name__ == "__main__":
    # The observed failure: span C replayed with a live session store.
    bad = SpanReplay(
        span_id="C",
        inputs={
            "prompt": InputProvenance.PINNED,
            "session_state": InputProvenance.LIVE,   # rehydrated from current store
            "temperature": InputProvenance.PINNED,
        },
        recorded_output_hash=_h("issue_refund"),
        replayed_output_hash=_h("escalate_to_human"),
        delta_field="session_state",
    )
    print(attribute_divergence(bad))
    # -> SAMPLING_ONLY: ... live=['session_state'] ...

    # The sound experiment: stub span B's output, freeze downstream, one delta.
    good = SpanReplay(
        span_id="C",
        inputs={
            "prompt": InputProvenance.PINNED,
            "retrieval_from_B": InputProvenance.STUBBED,  # 2025 policy substituted
            "session_state": InputProvenance.PINNED,
        },
        recorded_output_hash=_h("issue_refund"),
        replayed_output_hash=_h("escalate_to_human"),
        delta_field="retrieval_from_B",
    )
    print(attribute_divergence(good))
    # -> COUNTERFACTUAL_DELTA: retrieval_from_B
