# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-head-based-trace-sampling-to-preserve-multi-turn-causal-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-head-based-trace-sampling-to-preserve-multi-turn-causal-chains.warrant.json
# Markdown SHA-256:   7bc371afe7302b5f6b394ec53f3580775fc714e50cf9fa49c43ffc2ad3eadf75
# Code AST SHA-256:   a97b4841aeb0ed6e50ac087087f738ce1a56690759ccaaee595b2c549c320f67
# Verified Classes:   CausalSamplingViolation, Span, TraceBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CausalSamplingViolation(RuntimeError):
    """Raised when a sampling decision would break causal closure of a trace."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    trace_id: str
    turn_index: int
    error: bool = False


@dataclass
class TraceBuffer:
    trace_id: str
    spans: dict = field(default_factory=dict)
    sealed: bool = False

    def add(self, span: Span) -> None:
        if span.trace_id != self.trace_id:
            raise CausalSamplingViolation(
                f"span {span.span_id} trace_id {span.trace_id} != buffer {self.trace_id}"
            )
        self.spans[span.span_id] = span

    def seal(self) -> None:
        # Causal closure check: every non-root span's parent must be present.
        for span in self.spans.values():
            if span.parent_id is not None and span.parent_id not in self.spans:
                raise CausalSamplingViolation(
                    f"trace {self.trace_id} not causally closed: "
                    f"span {span.span_id} references missing parent {span.parent_id}"
                )
        self.sealed = True


def decide_retention(buf: TraceBuffer, rate: float) -> bool:
    """Whole-trace retention decision. Must only run on a sealed trace."""
    if not buf.sealed:
        raise CausalSamplingViolation(
            f"sampling decision attempted on unsealed trace {buf.trace_id}; "
            "seal-then-sample invariant violated"
        )
    # Deterministic, key-stable across services.
    digest = hashlib.sha256(buf.trace_id.encode()).digest()
    bucket = int.from_bytes(digest[:4], "big") / 0xFFFFFFFF
    # Whole-trace promotion: any error span forces full retention.
    if any(s.error for s in buf.spans.values()):
        return True
    return bucket < rate


def retain_subset(buf: TraceBuffer, keep_ids: set) -> dict:
    """Forbidden operation: retaining a subset breaks causal closure."""
    kept = {sid: s for sid, s in buf.spans.items() if sid in keep_ids}
    for span in kept.values():
        if span.parent_id is not None and span.parent_id not in kept:
            raise CausalSamplingViolation(
                f"partial retention of trace {buf.trace_id} orphans span "
                f"{span.span_id} from parent {span.parent_id}; "
                "use whole-trace retention or mark partial=true"
            )
    return kept
