# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-lossy-compaction-against-irreversible-evidence-eviction-before-it-resumes-a-long-horizon-task.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-lossy-compaction-against-irreversible-evidence-eviction-before-it-resumes-a-long-horizon-task.warrant.json
# Markdown SHA-256:   a831fe5536d3b6ffb723cbb37c86eafd4d6bfa3100cb62315e055604fd0d3b3f
# Code AST SHA-256:   a6d43b5ca42232a781dc6e8865615fd6b81991e82b1367b506f0e8a9089f9e9c
# Verified Classes:   SpanClass, Span, Obligation, CompactionRefused
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpanClass(Enum):
    REDUNDANT = "redundant"            # safe to drop
    RE_DERIVABLE = "re_derivable"      # safe only if source confirmed live
    IRREVERSIBLE = "irreversible"      # never drop while obligation open


@dataclass
class Span:
    span_id: str
    cls: SpanClass
    source_live: bool = True           # re-validated at each compaction
    has_hedge: bool = True             # provenance/confidence marker present


@dataclass
class Obligation:
    step: str
    requires: set[str]                 # span_ids this future step consumes
    closed: bool = False


class CompactionRefused(RuntimeError):
    """Raised when compaction would evict evidence under an open obligation."""


def compact(
    spans: list[Span],
    obligations: list[Obligation],
    window_budget: int,
) -> list[str]:
    """Return span_ids safe to evict. Refuses rather than silently dropping
    evidence that an open obligation depends on."""
    pinned: set[str] = set()
    for ob in obligations:
        if not ob.closed:
            pinned |= ob.requires

    evictable: list[str] = []
    for s in spans:
        if s.span_id in pinned:
            continue
        if s.cls is SpanClass.REDUNDANT:
            evictable.append(s.span_id)
        elif s.cls is SpanClass.RE_DERIVABLE:
            if not s.source_live:
                # Was re-derivable once; the world moved. Treat as irreversible.
                raise CompactionRefused(
                    f"span {s.span_id} tagged re_derivable but source is no longer "
                    f"live; eviction would destroy the only copy"
                )
            evictable.append(s.span_id)
        elif s.cls is SpanClass.IRREVERSIBLE:
            # Only evictable if no open obligation references it (handled above),
            # and only if it carries a surviving provenance hedge.
            if not s.has_hedge:
                raise CompactionRefused(
                    f"span {s.span_id} is irreversible and lacks a provenance "
                    f"hedge; compaction would launder an inspection into a "
                    f"verification claim"
                )
            evictable.append(s.span_id)

    # Budget check: if pinning + retained spans exceed the window, fail loudly
    # instead of evicting pinned evidence to make room.
    retained = len(spans) - len(evictable)
    if retained > window_budget:
        raise CompactionRefused(
            f"pinned evidence ({retained} spans) exceeds window budget "
            f"({window_budget}); surface budget conflict, do not evict pinned spans"
        )
    return evictable
