# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-benchmark-verdict-inheritance-as-invalid-across-a-re-sampled-eval-batch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-benchmark-verdict-inheritance-as-invalid-across-a-re-sampled-eval-batch.warrant.json
# Markdown SHA-256:   8d81ed922b49cabba4d8e6342dc59b85690663b9fa5597c19b00a6d1ad2705ca
# Code AST SHA-256:   16d41c42931e26f7990d0e73d1898883b71dd365295eeefffdcde67b3c413417
# Verified Classes:   VerdictInheritanceError, Trajectory, CachedVerdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class VerdictInheritanceError(RuntimeError):
    """Raised when a cached LITMUS verdict is about to be inherited onto a
    trajectory sample that is not provably equivalent to the sample the
    verdict was computed on."""


@dataclass(frozen=True)
class Trajectory:
    scenario_id: str
    action_trace: tuple          # normalized (tool_name, args, order)
    checkpoint_start: str
    checkpoint_end: str
    scorer_deterministic: bool


@dataclass(frozen=True)
class CachedVerdict:
    scenario_id: str
    action_trace_hash: str
    checkpoint_hash: str
    label: str                   # "pass" | "fail" | "uncertain"


def action_trace_hash(trace: tuple) -> str:
    h = hashlib.sha256()
    for tool_name, args in trace:
        h.update(tool_name.encode())
        h.update(repr(sorted(args.items())).encode())
    return h.hexdigest()


def attach_verdict(traj: Trajectory, cached: CachedVerdict) -> str:
    # Guard 1: checkpoint must be stable across the trajectory.
    if traj.checkpoint_start != traj.checkpoint_end:
        raise VerdictInheritanceError(
            f"scenario {traj.scenario_id}: checkpoint changed mid-trajectory "
            f"({traj.checkpoint_start} -> {traj.checkpoint_end}); "
            f"trajectory is unscoreable and cannot inherit."
        )
    # Guard 2: model-graded scorers are never inheritable.
    if not traj.scorer_deterministic:
        raise VerdictInheritanceError(
            f"scenario {traj.scenario_id}: non-deterministic scorer; "
            f"verdict inheritance is invalid by construction."
        )
    # Guard 3: action trace must match the sample the verdict was computed on.
    live_hash = action_trace_hash(traj.action_trace)
    if live_hash != cached.action_trace_hash:
        raise VerdictInheritanceError(
            f"scenario {traj.scenario_id}: action trace diverged "
            f"(cached={cached.action_trace_hash[:12]}, "
            f"live={live_hash[:12]}); this is a new sample and must be re-scored."
        )
    # Guard 4: checkpoint under which the verdict was cached must match.
    if cached.checkpoint_hash != traj.checkpoint_start:
        raise VerdictInheritanceError(
            f"scenario {traj.scenario_id}: cached verdict belongs to checkpoint "
            f"{cached.checkpoint_hash}, trajectory ran under {traj.checkpoint_start}."
        )
    return cached.label


def run_batch(trajectories, cache):
    results = {}
    for traj in trajectories:
        key = (traj.scenario_id, action_trace_hash(traj.action_trace))
        cached = cache.get(key)
        if cached is None:
            results[traj.scenario_id] = "needs_scoring"
            continue
        results[traj.scenario_id] = attach_verdict(traj, cached)
    return results
