# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-lossy-handoff-invariant-in-nested-subagent-context-budgets.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-lossy-handoff-invariant-in-nested-subagent-context-budgets.warrant.json
# Markdown SHA-256:   e9f169d27b6d917ff56dcaf820e4fded7d22d98cd46c88ee887ab449ab1eb34e
# Code AST SHA-256:   e974341d80ff74fcec713f2a9b2c83ee49e082efda9a1947b95dfd3cbab2b479
# Verified Classes:   LossyHandoffError, Span, Level
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class LossyHandoffError(RuntimeError):
    """Raised when a level attempts to compact a span whose consumer cannot recover it."""
    pass


@dataclass
class Span:
    tokens: list[str]
    external_handle: Optional[str] = None      # C1: resolvable by consumer?
    consumer_queries_depend: bool = True       # C2: live consumer needs it?
    duplicated_live: bool = False              # C3: canonical copy elsewhere?
    compaction_trigger_is_pressure: bool = True  # C4: budget-driven, not relevance-driven


@dataclass
class Level:
    name: str
    ceiling: int
    used: int = 0
    provenance: list[str] = field(default_factory=list)

    def remaining(self) -> int:
        return self.ceiling - self.used

    def must_refuse_compaction(self, span: Span) -> bool:
        # C1: irrecoverable if no handle OR consumer cannot resolve it
        irrecoverable = span.external_handle is None
        # C2: a live consumer depends on the span
        consumer_dependent = span.consumer_queries_depend
        # C3: not reproducible from another live span
        non_redundant = not span.duplicated_live
        # C4: compaction is driven by token pressure, not relevance judgment
        pressure_driven = span.compaction_trigger_is_pressure
        return irrecoverable and consumer_dependent and non_redundant and pressure_driven

    def compact_or_escalate(self, span: Span) -> str:
        if self.must_refuse_compaction(span):
            # Loud refusal: do not silently summarize a consumer-critical span.
            raise LossyHandoffError(
                f"level={self.name!r} refused to compact span of "
                f"{len(span.tokens)} tokens: consumer cannot recover it "
                f"(handle={span.external_handle!r}, "
                f"consumer_dependent={span.consumer_queries_depend}, "
                f"non_redundant={not span.duplicated_live}, "
                f"pressure_driven={span.compaction_trigger_is_pressure}). "
                f"Escalate: externalize behind a handle or request budget."
            )
        # Safe path: externalize (if handle exists) or evict (if redundant/irrelevant).
        if span.external_handle is not None:
            self.provenance.append(f"externalized:{span.external_handle}")
            return f"handle:{span.external_handle}"
        self.provenance.append("evicted:redundant_or_irrelevant")
        return "evicted"


def handoff(parent: Level, child_span: Span) -> str:
    """Parent prepares a handoff span for a child; refuses lossy compaction."""
    try:
        return parent.compact_or_escalate(child_span)
    except LossyHandoffError as e:
        # Propagate as a hard precondition failure, not a degraded success.
        raise LossyHandoffError(
            f"handoff from {parent.name!r} blocked; provenance={parent.provenance}"
        ) from e
