# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-samples-its-own-reasoning-trace-with-head-biased-observability-and-silently-discards-the-tail-of-a-failed-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-samples-its-own-reasoning-trace-with-head-biased-observability-and-silently-discards-the-tail-of-a-failed-plan.warrant.json
# Markdown SHA-256:   3c4ca8866438ff5b556677369be92ec1d73c08b8014b9d0c5da765bbf4b80ff1
# Code AST SHA-256:   be73aa269709b25754c4edb4471c83b5a8b1bf07be75e35b0ac9dc76c88f79bf
# Verified Classes:   SamplingInvariantError, SpanStatus, Span, Trace, HeadSampler, TailSampler
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class SamplingInvariantError(RuntimeError):
    """Raised when a sampling decision is made on a feature that cannot
    separate the outcome class it is meant to diagnose."""


class SpanStatus(Enum):
    OK = "ok"
    PARTIAL = "partial"
    ERROR = "error"


@dataclass
class Span:
    name: str
    status: SpanStatus = SpanStatus.OK


@dataclass
class Trace:
    trace_id: str
    spans: list = field(default_factory=list)

    def outcome_observable(self) -> bool:
        return any(s.status in (SpanStatus.PARTIAL, SpanStatus.ERROR) for s in self.spans)


class HeadSampler:
    """Head-biased sampler that decides on an early feature.

    BUG: if decision_feature is invariant across the success/failure boundary,
    the retained corpus is conditioned on a feature uncorrelated with Y.
    """

    def __init__(self, sample_rate: float, decision_feature: str):
        self.sample_rate = sample_rate
        self.decision_feature = decision_feature

    def decide(self, trace: Trace, feature_value: str) -> bool:
        # The decision is made here, before the outcome is observable.
        # If the feature does not encode the outcome, this is a coin flip
        # that the failure class will lose.
        if not self._feature_separates_outcome(feature_value):
            raise SamplingInvariantError(
                f"decision feature {self.decision_feature!r}={feature_value!r} "
                f"is invariant across the outcome boundary; retained corpus "
                f"will be conditioned on success"
            )
        h = hashlib.sha256(f"{trace.trace_id}:{feature_value}".encode()).hexdigest()
        return int(h[:8], 16) / 0xFFFFFFFF < self.sample_rate

    def _feature_separates_outcome(self, feature_value: str) -> bool:
        # In practice this is a periodic audit: compute I(F; Y) over retained
        # traces and fail closed if it is ~0 while log-derived failure rate > 0.
        # Here we hard-code the known-bad feature for planner-v7.
        return feature_value != "plan_hash"


class TailSampler:
    """Buffered tail sampler with error-priority retention."""

    def __init__(self, base_rate: float, buffer_size: int = 64):
        self.base_rate = base_rate
        self.buffer_size = buffer_size
        self._buffer: list[Trace] = []

    def on_span(self, trace: Trace, span: Span) -> None:
        trace.spans.append(span)
        if trace not in self._buffer:
            if len(self._buffer) >= self.buffer_size:
                self._buffer.pop(0)
            self._buffer.append(trace)

    def on_complete(self, trace: Trace) -> bool:
        if not trace.outcome_observable() and not self._uniform(trace.trace_id):
            return False
        if trace.outcome_observable():
            return True  # error-override: always retain
        return self._uniform(trace.trace_id)

    def _uniform(self, trace_id: str) -> bool:
        h = hashlib.sha256(trace_id.encode()).hexdigest()
        return int(h[:8], 16) / 0xFFFFFFFF < self.base_rate


def audit_sampler(sampler: HeadSampler, trace: Trace, feature_value: str) -> bool:
    """Run the sampler under an audit that fails closed on invariant violation."""
    try:
        return sampler.decide(trace, feature_value)
    except SamplingInvariantError:
        # Fail closed: retain the trace rather than drop it on a blind decision.
        return True
