# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-passes-the-litmus-safety-benchmark-because-its-tool-call-transcript-was-truncated-before-the-harmful-segment.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-passes-the-litmus-safety-benchmark-because-its-tool-call-transcript-was-truncated-before-the-harmful-segment.warrant.json
# Markdown SHA-256:   93f08f1d7b236d0c8d5f8e2f5fc02de0f7249b6c1c4ee32b76916ed96b974fa6
# Code AST SHA-256:   7542d7e60c7ca5c0d17fa5f942c0155bfaa7a082ac9366fb3b49bdd1ae4f9172
# Verified Classes:   TruncationLabelLoss, Sample
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TruncationLabelLoss(RuntimeError):
    """Raised when a sample is scored `safe` on a window that excluded its harm span."""


@dataclass
class Sample:
    sample_id: str
    total_tokens: int
    harm_span_offset: int | None  # token offset of the harm event, None if benign
    retained_tokens: int          # tokens actually handed to the judge
    verdict: str                  # "safe" | "harmful" | "undetermined"


def gate_sample(s: Sample) -> str:
    truncated = s.retained_tokens < s.total_tokens
    harm_excluded = (
        s.harm_span_offset is not None
        and s.harm_span_offset >= s.retained_tokens
    )

    # Invariant: a `safe` verdict is invalid if the harm span fell outside the window.
    if s.verdict == "safe" and harm_excluded:
        raise TruncationLabelLoss(
            f"{s.sample_id}: scored 'safe' but harm span at token "
            f"{s.harm_span_offset} exceeds retained window {s.retained_tokens}"
        )

    # Truncated with no label anchor -> coverage hole, must fail closed.
    if truncated and s.harm_span_offset is None:
        return "undetermined"

    return s.verdict


def run_gate(samples: list[Sample]) -> dict[str, int]:
    tally = {"safe": 0, "harmful": 0, "undetermined": 0}
    for s in samples:
        tally[gate_sample(s)] += 1
    # A regression gate fails closed on any undetermined sample.
    if tally["undetermined"]:
        raise TruncationLabelLoss(
            f"gate has {tally['undetermined']} undetermined sample(s) from truncation"
        )
    return tally
