# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-asynchronous-safety-verdicts-with-already-closed-trace-spans-without-corrupting-the-slo-denominator.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-asynchronous-safety-verdicts-with-already-closed-trace-spans-without-corrupting-the-slo-denominator.warrant.json
# Markdown SHA-256:   27e8bfc9479cc9ba081ec6a8e684c7f27d582b21b06b95db0e4302b6c02a7bab
# Code AST SHA-256:   81ada9ee953d124dfe4f1bf00b6b7a0b283ee63b6fd42da483c0cda9bd109d60
# Verified Classes:   SLOSealViolation, VerdictState, Span, SLOWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional


class SLOSealViolation(RuntimeError):
    """Raised when an SLO window is sealed in a state that would corrupt the numerator/denominator."""
    pass


class VerdictState(Enum):
    INDETERMINATE = "indeterminate"
    SAFE = "safe"
    UNSAFE = "unsafe"


@dataclass
class Span:
    span_id: str
    content_hash: str
    replay_of: Optional[str] = None
    verdict: VerdictState = VerdictState.INDETERMINATE


@dataclass
class SLOWindow:
    window_id: str
    spans: Dict[str, Span] = field(default_factory=dict)
    undecided_grace_s: float = 900.0
    sealed: bool = False

    def _verdict_key(self, span: Span) -> str:
        # Idempotency must include content_hash so a divergent replay
        # does not collide with the original span's verdict.
        return f"{span.span_id}:{span.content_hash}"

    def apply_verdict(self, span_id: str, content_hash: str, verdict: VerdictState) -> None:
        if self.sealed:
            raise SLOSealViolation(
                f"late verdict for span {span_id} arrived after window {self.window_id} sealed; "
                "reconciliation must target a new window, not mutate a sealed one"
            )
        key = self._verdict_key(Span(span_id, content_hash))
        target = next(
            (s for s in self.spans.values() if self._verdict_key(s) == key), None
        )
        if target is None:
            raise SLOSealViolation(
                f"verdict for unknown span/content pair {key}; refusing to create phantom span"
            )
        target.verdict = verdict

    def seal(self, elapsed_s: float) -> Dict[str, float]:
        undecided = [s for s in self.spans.values() if s.verdict is VerdictState.INDETERMINATE]
        if undecided and elapsed_s < self.undecided_grace_s:
            raise SLOSealViolation(
                f"window {self.window_id} has {len(undecided)} undecided spans at "
                f"{elapsed_s:.0f}s < grace {self.undecided_grace_s:.0f}s; "
                "sealing now would count INDETERMINATE as SAFE"
            )
        decided = [s for s in self.spans.values() if s.verdict is not VerdictState.INDETERMINATE]
        safe = sum(1 for s in decided if s.verdict is VerdictState.SAFE)
        denom = len(decided)
        self.sealed = True
        return {
            "decided": denom,
            "safe": safe,
            "indeterminate": len(undecided),
            "safe_rate": (safe / denom) if denom else 0.0,
        }
