# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-trajectory-whose-tool-outputs-were-non-deterministic-trace-divergence-at-the-observation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-trajectory-whose-tool-outputs-were-non-deterministic-trace-divergence-at-the-observation-boundary.warrant.json
# Markdown SHA-256:   a0d6d784cd20066e9edf04c6df8ef5a8bf1ee6e59cba0ae9d686cc575e52017b
# Code AST SHA-256:   77695aeb18ef6ce0102fa42bd357cd90ae842fb69de5944a9fd11bacd7fe309b
# Verified Classes:   ProvenanceViolation, DivergenceClass, Step, TraceDiff
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ProvenanceViolation(RuntimeError):
    """Raised when a trace diff attributes divergence to the model without a byte-identical input tuple."""


class DivergenceClass(Enum):
    OBS = "observation"   # environment moved; provenance intact
    SAMP = "sampling"     # decoding variance; provenance intact, non-reproducible
    POL = "policy"        # genuine provenance break; regression ticket
    NOT_COMPARABLE = "not_comparable"


@dataclass
class Step:
    index: int
    input_tuple: tuple            # (prompt_hash, obs_hash, tool_version, seed)
    output_hash: str
    obs_source: str               # "recorded" | "re-derived"


@dataclass
class TraceDiff:
    step_index: int
    classification: DivergenceClass
    detail: str


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


def diff_trajectories(
    recorded: list[Step],
    replayed: list[Step],
    *,
    require_injection: bool = True,
) -> list[TraceDiff]:
    if len(recorded) != len(replayed):
        raise ProvenanceViolation(
            f"length mismatch: recorded={len(recorded)} replayed={len(replayed)}; "
            "cannot align steps for causal attribution"
        )

    diffs: list[TraceDiff] = []
    tainted = False  # once an upstream input diverges, downstream is NOT_COMPARABLE

    for rec, rep in zip(recorded, replayed):
        if tainted:
            diffs.append(TraceDiff(rep.index, DivergenceClass.NOT_COMPARABLE,
                                   "upstream input diverged; downstream not causally attributable"))
            continue

        if rec.input_tuple != rep.input_tuple:
            if require_injection and rep.obs_source != "recorded":
                raise ProvenanceViolation(
                    f"step {rep.index}: replay re-derived observation instead of injecting recorded one; "
                    f"recorded_input={rec.input_tuple} replayed_input={rep.input_tuple}. "
                    "Diff would misattribute environment drift to the model."
                )
            diffs.append(TraceDiff(rep.index, DivergenceClass.OBS,
                                   f"input tuple differs: {rec.input_tuple} -> {rep.input_tuple}"))
            tainted = True
            continue

        if rec.output_hash != rep.output_hash:
            # Inputs byte-identical; divergence is decoding variance unless seed pinned.
            seed_pinned = rec.input_tuple[-1] is not None
            cls = DivergenceClass.SAMP if not seed_pinned else DivergenceClass.POL
            diffs.append(TraceDiff(rep.index, cls,
                                   f"identical input, output differs ({cls.value}); "
                                   f"seed_pinned={seed_pinned}"))

    return diffs


def assert_no_false_policy_divergence(diffs: list[TraceDiff]) -> None:
    """Any POL divergence must be preceded by zero OBS divergences on the same path."""
    for d in diffs:
        if d.classification is DivergenceClass.POL and any(
            p.classification is DivergenceClass.OBS for p in diffs if p.step_index < d.step_index
        ):
            raise ProvenanceViolation(
                f"step {d.step_index}: classified POL but an upstream OBS divergence exists; "
                "this is environment drift misattributed as a model regression"
            )
