# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-tool-use-replay-divergence-as-a-certification-failure-rather-than-a-tolerable-nondeterminism.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-tool-use-replay-divergence-as-a-certification-failure-rather-than-a-tolerable-nondeterminism.warrant.json
# Markdown SHA-256:   9efd5457e48e3b9f56b9ce3ba89b21173c233e42ea6651cd52f085a24b6e2d9d
# Code AST SHA-256:   0efcceb96c9aeb5f9a950c745e3ae2f24e6b9e79c85187a41a697907b0a39edd
# Verified Classes:   ReplayCertificationError, Action
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any


class ReplayCertificationError(RuntimeError):
    """Raised when a replay exhibits policy divergence under transport perturbation."""


@dataclass(frozen=True)
class Action:
    tool: str
    kwargs: dict[str, Any]
    seq: int

    def canonical(self) -> tuple:
        return (self.tool, tuple(sorted(self.kwargs.items())), self.seq)


TRANSPORT_PERTURBATIONS = {"latency_injection", "schema_order_shuffle", "rng_reseed"}


def certify_replay(
    recorded: list[Action],
    replayed: list[Action],
    perturbation_class: str,
    tool_impl_changed: bool = False,
) -> str:
    if perturbation_class not in TRANSPORT_PERTURBATIONS:
        raise ReplayCertificationError(
            f"unknown perturbation class {perturbation_class!r}; cannot attribute divergence"
        )

    if tool_impl_changed:
        return "quarantine_for_rerecord"

    recorded_set = {a.canonical() for a in recorded}
    replayed_set = {a.canonical() for a in replayed}
    closure_gap = replayed_set - recorded_set

    if not closure_gap:
        return "pass"

    # Policy divergence under a transport perturbation: the agent folded
    # transport noise into a privileged action. Certificate is invalid.
    offending = sorted(closure_gap)
    raise ReplayCertificationError(
        f"policy divergence under {perturbation_class}: "
        f"{len(offending)} uncertified action(s) emitted, e.g. {offending[0]}"
    )


def run_fuzz_suite(recordings: list[dict]) -> dict[str, str]:
    results: dict[str, str] = {}
    for rec in recordings:
        try:
            results[rec["id"]] = certify_replay(
                recorded=rec["recorded"],
                replayed=rec["replayed"],
                perturbation_class=rec["class"],
                tool_impl_changed=rec.get("tool_impl_changed", False),
            )
        except ReplayCertificationError as exc:
            results[rec["id"]] = f"REVOKED: {exc}"
    return results
