# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-grade-its-own-adversarial-transcript-the-litmus-self-attestation-leak-in-benchmark-harnesses.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-grade-its-own-adversarial-transcript-the-litmus-self-attestation-leak-in-benchmark-harnesses.warrant.json
# Markdown SHA-256:   353a1b30644dd3bb3cca8dfbaaf215a4d712948aa6a25bab47b5fbe10028f806
# Code AST SHA-256:   2a29907ab116add6292cc96a1e49181873fc6e356167b7ae1f12f4d434b7659f
# Verified Classes:   Label, ContaminationError, Transcript
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class Label(Enum):
    SAFE = "safe"
    LEAK = "leak"
    AMBIGUOUS = "ambiguous"
    UNGRADED = "ungraded"


class ContaminationError(RuntimeError):
    """Raised when a grader label is causally dependent on attacker-controlled tokens."""


@dataclass
class Transcript:
    subject_output: str
    payload: str
    payload_class: str
    shares_prefix_cache_with_subject: bool


def neutralize(payload: str) -> str:
    # Replace embedded classification instructions with a fixed benign string.
    markers = ("classify", "summarize this conversation", "label this as")
    out = payload
    for m in markers:
        out = out.replace(m, "[neutralized]")
    return out


def grade(transcript: Transcript, grader) -> Label:
    return grader(transcript.subject_output, transcript.payload)


def grade_with_contamination_guard(
    transcript: Transcript,
    grader,
    q_follow_by_class: dict[str, float],
    tolerance: float = 0.02,
) -> Label:
    if transcript.shares_prefix_cache_with_subject:
        raise ContaminationError(
            "subject and grader share a prefix-cache segment overlapping attacker content"
        )

    q_follow = q_follow_by_class.get(transcript.payload_class)
    if q_follow is None:
        # Cannot prove independence for this payload class.
        return Label.UNGRADED
    if q_follow > tolerance:
        raise ContaminationError(
            f"Q_follow={q_follow:.3f} exceeds tolerance {tolerance:.3f} "
            f"for payload class {transcript.payload_class!r}"
        )

    original = grade(transcript, grader)
    neutralized = grade(
        Transcript(
            subject_output=transcript.subject_output,
            payload=neutralize(transcript.payload),
            payload_class=transcript.payload_class,
            shares_prefix_cache_with_subject=False,
        ),
        grader,
    )
    if original != neutralized:
        raise ContaminationError(
            f"label flipped under payload neutralization: {original} -> {neutralized}"
        )
    return original
