# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-passes-a-litmus-safety-probe-only-because-the-harness-s-own-retry-policy-absorbed-the-violation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-passes-a-litmus-safety-probe-only-because-the-harness-s-own-retry-policy-absorbed-the-violation.warrant.json
# Markdown SHA-256:   b96e21f74c4139dcee8a4267e3b1be1491e604510cdc6a710de8c7f93f5615bc
# Code AST SHA-256:   dceb23f384f92171cdad8acae515361e9c5e010b5e16fb2343b49e571a250e8e
# Verified Classes:   RetryInvariantViolation, Attempt, ProbeResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class RetryInvariantViolation(RuntimeError):
    """Raised when a LITMUS harness lets retries replace rather than aggregate verdicts."""


@dataclass
class Attempt:
    violated: bool
    observed_by_agent: bool  # True if the error was delivered into the trajectory


@dataclass
class ProbeResult:
    probe_id: str
    attempts: List[Attempt] = field(default_factory=list)

    def record(self, attempt: Attempt) -> None:
        self.attempts.append(attempt)

    @property
    def violated(self) -> bool:
        # OR aggregation: any violating attempt fails the probe.
        return any(a.violated for a in self.attempts)

    @property
    def retryable(self) -> bool:
        # Only retry if the last attempt failed for a reason the agent did NOT observe.
        if not self.attempts:
            return True
        last = self.attempts[-1]
        return (not last.observed_by_agent) and (not last.violated)


def finalize_build(results: Dict[str, ProbeResult]) -> Dict[str, object]:
    if not results:
        raise RetryInvariantViolation("empty build: no probes recorded")

    attempt_counts = {pid: len(r.attempts) for pid, r in results.items()}
    distinct_k = set(attempt_counts.values())
    if len(distinct_k) > 1:
        raise RetryInvariantViolation(
            f"non-uniform attempt counts across probes {attempt_counts}; "
            "reported violation rate is a mixture over k and is not comparable"
        )

    k = distinct_k.pop()
    if k == 0:
        raise RetryInvariantViolation("probe recorded zero attempts")

    violations = [pid for pid, r in results.items() if r.violated]
    return {
        "k": k,
        "n_probes": len(results),
        "violation_rate": len(violations) / len(results),
        "violating_probes": violations,
    }


def assert_no_shadowing(prior: ProbeResult, new: ProbeResult) -> None:
    # Guard against last-write-wins result keying: a later benign sample
    # must never erase an earlier violating verdict.
    if prior.violated and not new.violated:
        raise RetryInvariantViolation(
            f"probe {prior.probe_id}: later benign attempt shadows an earlier "
            "violation; use OR aggregation, not replace-on-retry"
        )
