# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-otel-span-to-token-to-safety-correlation-from-silently-misattributing-a-safety-event-to-the-wrong-generation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-otel-span-to-token-to-safety-correlation-from-silently-misattributing-a-safety-event-to-the-wrong-generation.warrant.json
# Markdown SHA-256:   a04cd37ee3afd78a45c7710ea7a70d24744bd1ff6ffd833a9c49bef3808bce30
# Code AST SHA-256:   7c97967912fe7a8c6351b719c34500b634aa9aeeaa7f4f114be55bccb25f6535
# Verified Classes:   CorrelationInvariantError, Span, UsageRecord, SafetyAnnotation, CorrelationResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class CorrelationInvariantError(RuntimeError):
    """Raised when a safety annotation cannot be bound to exactly one generation."""


@dataclass(frozen=True)
class Span:
    generation_id: str
    request_hash: str          # grouping only, NEVER a correlation key
    status: str                # "OK" | "ERROR"
    output_tokens: int


@dataclass(frozen=True)
class UsageRecord:
    generation_id: str
    output_tokens: int


@dataclass(frozen=True)
class SafetyAnnotation:
    generation_id: Optional[str]
    request_hash: str
    policy: str
    severity: str


@dataclass
class CorrelationResult:
    attached: dict[str, list[SafetyAnnotation]] = field(default_factory=dict)
    quarantined: list[SafetyAnnotation] = field(default_factory=list)


def correlate_safety_events(
    spans: list[Span],
    usage: list[UsageRecord],
    annotations: list[SafetyAnnotation],
) -> CorrelationResult:
    # Invariant 3: token accounting must reconcile per generation_id.
    usage_by_gen = {u.generation_id: u.output_tokens for u in usage}
    for s in spans:
        if s.generation_id not in usage_by_gen:
            raise CorrelationInvariantError(
                f"span {s.generation_id}: no usage record; correlation unverified"
            )
        if usage_by_gen[s.generation_id] != s.output_tokens:
            raise CorrelationInvariantError(
                f"span {s.generation_id}: token mismatch "
                f"span={s.output_tokens} usage={usage_by_gen[s.generation_id]}"
            )

    span_ids = {s.generation_id for s in spans}
    result = CorrelationResult()

    for ann in annotations:
        # Invariant 1: identity must be generation-scoped, not request-hash-scoped.
        if ann.generation_id is None:
            raise CorrelationInvariantError(
                f"annotation policy={ann.policy} has no generation_id; "
                f"request_hash={ann.request_hash} is not a valid correlation key"
            )
        if ann.generation_id not in span_ids:
            # Invariant 2: fail closed. Never attach by nearest-timestamp heuristic.
            result.quarantined.append(ann)
            continue
        result.attached.setdefault(ann.generation_id, []).append(ann)

    return result
