# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-level-safety-scoring-from-silently-diverging-when-anomaly-attribution-runs-on-partial-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-level-safety-scoring-from-silently-diverging-when-anomaly-attribution-runs-on-partial-spans.warrant.json
# Markdown SHA-256:   12415e0615846211d8ac06c02e69138e6670376d58d9d996c4f2978b23f2b821
# Code AST SHA-256:   f92ebc891d08d85ec37b4dcf4b919709b809acbd3ac5f7d715f3a7e22e12107a
# Verified Classes:   ClosureState, TraceIntegrityError, UnsoundAggregationError, AttributionLabel, SafetySLO
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ClosureState(Enum):
    OPEN = "open"
    FLUSHED = "flushed"
    SEALED = "sealed"


class TraceIntegrityError(RuntimeError):
    """Raised when a span arrives for a trace already marked sealed."""
    pass


class UnsoundAggregationError(RuntimeError):
    """Raised when a safety SLO is fed from non-sealed labels."""
    pass


@dataclass
class AttributionLabel:
    trace_id: str
    unsafe: bool
    closure: ClosureState
    retracted: bool = False


@dataclass
class SafetySLO:
    sealed_labels: dict[str, AttributionLabel] = field(default_factory=dict)
    provisional_labels: dict[str, AttributionLabel] = field(default_factory=dict)
    unresolved: set[str] = field(default_factory=set)

    def ingest(self, label: AttributionLabel) -> None:
        if label.closure is ClosureState.SEALED:
            # Sealed label is final; a later sealed label for the same trace
            # means the trace was split or re-scored — re-score wins.
            self.sealed_labels[label.trace_id] = label
            self.provisional_labels.pop(label.trace_id, None)
            self.unresolved.discard(label.trace_id)
        else:
            # Provisional only; never allowed into the safety numerator.
            self.provisional_labels[label.trace_id] = label

    def seal(self, trace_id: str, unsafe: bool) -> None:
        self.ingest(
            AttributionLabel(trace_id, unsafe, ClosureState.SEALED)
        )

    def mark_unresolved(self, trace_id: str) -> None:
        if trace_id in self.sealed_labels:
            raise TraceIntegrityError(
                f"trace {trace_id} already sealed; cannot mark unresolved"
            )
        self.unresolved.add(trace_id)
        self.provisional_labels.pop(trace_id, None)

    def safety_fraction(self) -> float:
        if not self.sealed_labels:
            raise UnsoundAggregationError(
                "no sealed labels; safety SLO cannot be computed "
                "from provisional data"
            )
        safe = sum(
            1 for l in self.sealed_labels.values() if not l.unsafe
        )
        return safe / len(self.sealed_labels)

    def unresolved_fraction(self) -> float:
        total = (
            len(self.sealed_labels)
            + len(self.unresolved)
        )
        if total == 0:
            return 0.0
        return len(self.unresolved) / total
