# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-safety-benchmark-outcomes-with-otel-genai-spans-that-were-sampled-away-before-the-verdict-was-written.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-safety-benchmark-outcomes-with-otel-genai-spans-that-were-sampled-away-before-the-verdict-was-written.warrant.json
# Markdown SHA-256:   106d7d03ce71599f25ca9faaba6610079eac941a571e2e92976abe3001825707
# Code AST SHA-256:   0bc30b6976a63e849a52eff3e0033bcd76fb12934eeff59ca2db2ba70828f39b
# Verified Classes:   OrphanedSafetyVerdict, Turn, Verdict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class OrphanedSafetyVerdict(RuntimeError):
    """Raised when a safety verdict references a span the sampler already dropped."""


@dataclass(frozen=True)
class Turn:
    trace_id: str
    span_id: str
    safety_candidate: bool          # cheap lexical screen at emit time
    sampler_kept: bool              # tail-sampler decision, committed at span close
    completion_hash: str
    ledger_present: bool            # durable side-channel row, never sampled


@dataclass(frozen=True)
class Verdict:
    trace_id: str
    violation: bool                 # ground truth from the stronger grader
    grader_model: str


def assert_correlatable(turn: Turn, verdict: Verdict, grader_is_stronger: bool) -> None:
    """
    Enforce the superset invariant: every confirmed violation must be replayable
    either from a surviving span or from a durable ledger row carrying the payload hash.
    """
    if turn.trace_id != verdict.trace_id:
        raise OrphanedSafetyVerdict(
            f"identity mismatch: turn {turn.trace_id} vs verdict {verdict.trace_id}"
        )

    if not verdict.violation:
        return  # non-violations may legitimately be sampled away

    replayable = turn.sampler_kept or turn.ledger_present
    if replayable:
        return

    # Confirmed violation, no surviving span, no ledger row: the retention predicate
    # was weaker than the grader and the drop is irreversible.
    if grader_is_stronger and not turn.safety_candidate:
        raise OrphanedSafetyVerdict(
            f"trace {turn.trace_id} span {turn.span_id}: grader '{verdict.grader_model}' "
            f"flagged violation but cheap screen said candidate=false and sampler dropped "
            f"the span; no ledger row to rehydrate. Predictor-dominant regime is invalid "
            f"for a stronger grader."
        )
    raise OrphanedSafetyVerdict(
        f"trace {turn.trace_id} span {turn.span_id}: violation verdict has no surviving "
        f"span and no ledger row; verdict is uncorrelatable."
    )


def orphan_rate(turns: list[Turn], verdicts: list[Verdict]) -> float:
    """Fraction of confirmed violations that cannot be replayed from span or ledger."""
    by_trace = {t.trace_id: t for t in turns}
    confirmed = [v for v in verdicts if v.violation]
    if not confirmed:
        return 0.0
    orphans = 0
    for v in confirmed:
        t = by_trace.get(v.trace_id)
        if t is None or not (t.sampler_kept or t.ledger_present):
            orphans += 1
    return orphans / len(confirmed)
