# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-safety-verdict-arrive-before-its-own-trace-span-and-how-does-that-orphan-the-evidence-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-safety-verdict-arrive-before-its-own-trace-span-and-how-does-that-orphan-the-evidence-chain.warrant.json
# Markdown SHA-256:   a3fbe10361c1b69f6d0c71ac95a14ae0249aec0a99d1c3812c9dc8f5beabfd50
# Code AST SHA-256:   f334444e1907bbe3bd2fc2deb0a32f0fb3e5acbcd285b99518eff0aa19f4948c
# Verified Classes:   EvidenceChainBroken, Verdict
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EvidenceChainBroken(RuntimeError):
    """Raised when a high-severity verdict's span is absent and past the staleness window."""
    pass


@dataclass
class Verdict:
    trace_id: str
    span_id: str
    severity: str
    emitted_at: float  # epoch seconds


FLUSH_STALENESS_WINDOW_S = 8.0  # schedule_delay_millis + retry_backoff, with margin


def assert_evidence_chain(
    verdicts: list[Verdict],
    spans_present: set[str],  # span_ids known to the trace store
    now: float | None = None,
) -> None:
    """Fail closed: never serve a trace-correlated safety view that hides a high-severity verdict."""
    now = now if now is not None else time.time()
    for v in verdicts:
        if v.severity != "high":
            continue
        if v.span_id in spans_present:
            continue
        age = now - v.emitted_at
        if age > FLUSH_STALENESS_WINDOW_S:
            raise EvidenceChainBroken(
                f"verdict trace_id={v.trace_id} span_id={v.span_id} severity=high "
                f"has no span after {age:.1f}s (window={FLUSH_STALENESS_WINDOW_S}s); "
                f"refusing to serve clean view — check sampling drop or ingest-time join"
            )
        # within window: tolerated as bounded staleness, but caller must mark view as partial
