# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-safety-event-trace-that-arrives-after-its-parent-prompt-span-has-already-been-evicted-from-the-observability-correl.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-safety-event-trace-that-arrives-after-its-parent-prompt-span-has-already-been-evicted-from-the-observability-correl.warrant.json
# Markdown SHA-256:   7719fd111768d108c48b93c0d89da210d8eb61b11e2074377acb2ef1e3e93d1e
# Code AST SHA-256:   02110aeb17958a2ed23a749166b6142705ad1781bbaf57b98424031949cb32bb
# Verified Classes:   OrphanedSafetyEventError, CorrelationAnchor, SafetyEvent, Correlator
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedSafetyEventError(RuntimeError):
    """Raised when a safety event cannot be correlated to a live or
    reconstructable parent span. This is a pipeline defect, not a data
    condition, and must never be swallowed into a silent drop."""


@dataclass
class CorrelationAnchor:
    trace_id: str
    span_id: str
    prompt_hash: str
    model_id: str
    tool_output_hashes: tuple[str, ...]
    closed_at: float


@dataclass
class SafetyEvent:
    trace_id: str
    span_id: str
    severity: str
    category: str
    arrived_at: float


@dataclass
class Correlator:
    retention_ttl: float
    hot_index: dict[str, CorrelationAnchor] = field(default_factory=dict)
    anchors: dict[str, CorrelationAnchor] = field(default_factory=dict)
    orphans: list[SafetyEvent] = field(default_factory=list)
    quarantined: list[SafetyEvent] = field(default_factory=list)

    def close_span(self, anchor: CorrelationAnchor) -> None:
        # Durable anchor written BEFORE eviction can occur.
        self.anchors[anchor.span_id] = anchor
        self.hot_index[anchor.span_id] = anchor

    def evict(self, now: float) -> None:
        expired = [
            sid for sid, a in self.hot_index.items()
            if now - a.closed_at > self.retention_ttl
        ]
        for sid in expired:
            del self.hot_index[sid]

    def correlate(self, event: SafetyEvent) -> str:
        if event.span_id in self.hot_index:
            return "correlated"
        anchor = self.anchors.get(event.span_id)
        if anchor is None:
            self.orphans.append(event)
            raise OrphanedSafetyEventError(
                f"safety event for trace={event.trace_id} span={event.span_id} "
                f"has no correlation anchor; pipeline defect"
            )
        # Anchor exists but hot index does not: late arrival.
        if not anchor.tool_output_hashes:
            # Incomplete subtree: quarantine, do NOT merge as complete.
            self.quarantined.append(event)
            return "quarantined_partial_context"
        return "reconstructed"

    def orphan_rate(self) -> float:
        total = len(self.orphans) + len(self.quarantined) + 1
        return len(self.orphans) / total
