# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-litmus-safety-verdict-because-the-trajectory-s-tool-call-prefix-was-replayed-under-a-different-sampling-temperature.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-litmus-safety-verdict-because-the-trajectory-s-tool-call-prefix-was-replayed-under-a-different-sampling-temperature.warrant.json
# Markdown SHA-256:   27e2eeb4a32bd3dee214de27be57b387b6e6d7e1e8824ba599655f194f9bc877
# Code AST SHA-256:   89b3a0e71b6e40e52ed6058328df0a46d54aab6fdb007a0ca90fafefbe182765
# Verified Classes:   ReplayAttributionError, SamplingConfig, Checkpoint, Replay
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


class ReplayAttributionError(RuntimeError):
    """Raised when a replayed continuation cannot be validly attributed to a recorded trajectory."""


@dataclass
class SamplingConfig:
    temperature: float
    top_p: float
    seed: Optional[int] = None
    tool_choice: str = "auto"

    def identical_to(self, other: "SamplingConfig") -> bool:
        return (
            self.temperature == other.temperature
            and self.top_p == other.top_p
            and self.seed == other.seed
            and self.tool_choice == other.tool_choice
        )


@dataclass
class Checkpoint:
    message_history: List[Dict[str, Any]]
    tool_results: List[Dict[str, Any]]
    recorded_prefix: List[Dict[str, Any]]
    sampling_config: Optional[SamplingConfig]  # None == non-replayable


@dataclass
class Replay:
    replayed_prefix: List[Dict[str, Any]]
    continuation: Dict[str, Any]
    sampling_config: SamplingConfig


def prefix_equivalent(replayed: List[Dict[str, Any]], recorded: List[Dict[str, Any]]) -> bool:
    """Declared equivalence oracle. Tool-call argument divergence is non-equivalence."""
    if len(replayed) != len(recorded):
        return False
    for r, c in zip(replayed, recorded):
        if r.get("tool") != c.get("tool"):
            return False
        if r.get("args") != c.get("args"):
            return False
    return True


def attribute_continuation(checkpoint: Checkpoint, replay: Replay) -> str:
    """Return the metric namespace a continuation may be scored under.

    Raises ReplayAttributionError if the checkpoint is non-replayable or the
    replay violates the attribution invariant.
    """
    if checkpoint.sampling_config is None:
        raise ReplayAttributionError(
            "checkpoint carries no sampling configuration; trajectory is non-replayable "
            "and must be marked unscored at this boundary, not replayed under a default"
        )

    if not checkpoint.sampling_config.identical_to(replay.sampling_config):
        # Counterfactual: score under a separate namespace, never the transcript verdict.
        return "counterfactual_violation_rate"

    if not prefix_equivalent(replay.replayed_prefix, checkpoint.recorded_prefix):
        raise ReplayAttributionError(
            "replayed prefix diverges from recorded prefix under declared oracle; "
            "continuation cannot be attributed to the recorded trajectory"
        )

    return "transcript_verdict"


def score_trajectory(checkpoint: Checkpoint, replays: List[Replay]) -> Dict[str, List[Dict[str, Any]]]:
    buckets: Dict[str, List[Dict[str, Any]]] = {"transcript_verdict": [], "counterfactual_violation_rate": []}
    for replay in replays:
        namespace = attribute_continuation(checkpoint, replay)
        buckets[namespace].append(replay.continuation)
    return buckets
