# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tail-biased-sampler-collapse-from-erasing-the-only-spans-that-explain-a-failed-agent-run.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tail-biased-sampler-collapse-from-erasing-the-only-spans-that-explain-a-failed-agent-run.warrant.json
# Markdown SHA-256:   16295b12f1c8b1c79f090795f380d09bbad26ed2e51f4af303b01e1c13230693
# Code AST SHA-256:   7b718761c3e0ec0e36f8a1b0fe7ae2ddcd64ace288a01d342c7976ecebae7028
# Verified Classes:   RetentionDecision, CausalClosureViolation, Span, Trace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class RetentionDecision(Enum):
    RETAIN = "retain"
    DROP_WITH_TOMBSTONE = "drop_with_tombstone"
    DROP_SILENT = "drop_silent"


class CausalClosureViolation(RuntimeError):
    """Raised when a retained error span's causal ancestors are neither
    retained nor tombstoned, making the trace inadmissible as evidence."""


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    status: str
    estimated_tokens: int
    decision: RetentionDecision = RetentionDecision.RETAIN
    tombstoned: bool = False


@dataclass
class Trace:
    spans: Dict[str, Span] = field(default_factory=dict)
    token_cap: int = 200_000

    def add(self, span: Span) -> None:
        self.spans[span.span_id] = span

    def ancestors(self, span_id: str) -> List[Span]:
        chain: List[Span] = []
        current = self.spans.get(span_id)
        seen: Set[str] = set()
        while current is not None and current.parent_id is not None:
            if current.parent_id in seen:
                break
            seen.add(current.parent_id)
            parent = self.spans.get(current.parent_id)
            if parent is None:
                break
            chain.append(parent)
            current = parent
        return chain


def enforce_causal_closure(trace: Trace) -> None:
    """Verify that every retained error span has all ancestors either
    retained or tombstoned. Raises if the invariant is violated."""
    for span in trace.spans.values():
        if span.status not in ("ERROR", "FAILED"):
            continue
        if span.decision is not RetentionDecision.RETAIN:
            continue
        for anc in trace.ancestors(span.span_id):
            if anc.decision is RetentionDecision.DROP_SILENT:
                raise CausalClosureViolation(
                    f"retained error span {span.span_id} has silently dropped "
                    f"ancestor {anc.span_id}; trace is not admissible as evidence"
                )
            if anc.decision is RetentionDecision.DROP_WITH_TOMBSTONE and not anc.tombstoned:
                raise CausalClosureViolation(
                    f"ancestor {anc.span_id} of error span {span.span_id} was "
                    f"dropped without a tombstone; causal edge is lost"
                )


def apply_greedy_budget(trace: Trace) -> None:
    """Arrival-order budget enforcement: the failure mode under study."""
    spent = 0
    for span in trace.spans.values():
        if spent + span.estimated_tokens > trace.token_cap:
            span.decision = RetentionDecision.DROP_SILENT
        else:
            spent += span.estimated_tokens
            span.decision = RetentionDecision.RETAIN


def apply_closure_preserving_budget(trace: Trace) -> None:
    """Closure-preserving retention: pin ancestors of error spans before
    spending budget, and tombstone any span dropped for cost."""
    pinned: Set[str] = set()
    for span in trace.spans.values():
        if span.status in ("ERROR", "FAILED"):
            for anc in trace.ancestors(span.span_id):
                pinned.add(anc.span_id)
    spent = 0
    for span in trace.spans.values():
        if span.span_id in pinned:
            span.decision = RetentionDecision.RETAIN
            spent += span.estimated_tokens
            continue
        if spent + span.estimated_tokens > trace.token_cap:
            span.decision = RetentionDecision.DROP_WITH_TOMBSTONE
            span.tombstoned = True
        else:
            spent += span.estimated_tokens
            span.decision = RetentionDecision.RETAIN


if __name__ == "__main__":
    t = Trace(token_cap=50_000)
    t.add(Span("root", None, "OK", 100))
    t.add(Span("step1", "root", "OK", 100))
    t.add(Span("gen1", "step1", "OK", 38_000))
    t.add(Span("tool1", "step1", "ERROR", 50))
    t.add(Span("step2", "root", "OK", 100))
    t.add(Span("gen2", "step2", "OK", 47_000))
    t.add(Span("verify", "root", "ERROR", 50))

    apply_greedy_budget(t)
    try:
        enforce_causal_closure(t)
    except CausalClosureViolation as exc:
        print(f"greedy sampler rejected: {exc}")

    t2 = Trace(token_cap=50_000)
    for s in t.spans.values():
        t2.add(Span(s.span_id, s.parent_id, s.status, s.estimated_tokens))
    apply_closure_preserving_budget(t2)
    enforce_causal_closure(t2)
    print("closure-preserving sampler: trace admissible")
