# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-trace-whose-summarization-loss-exceeds-the-recoverable-retrieval-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-trace-whose-summarization-loss-exceeds-the-recoverable-retrieval-budget.warrant.json
# Markdown SHA-256:   2b2be7760d01a8c92f820c3c5724a5b3a85a295076ab60bfc711dbf2de48a9ea
# Code AST SHA-256:   bee7201ffae90c31a7c1152d9cdad7d72401cbc613922f60258490fa2285a36a
# Verified Classes:   CompactionShadowError, DroppedToken, CompactionPlan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionShadowError(RuntimeError):
    """Raised when an auto-compaction event would create an unrecoverable
    compaction shadow: a dropped fact that is neither in the summary nor
    reachable by any query the post-compaction agent can form."""


@dataclass(frozen=True)
class DroppedToken:
    token: str
    kind: str          # "self_describing" | "context_dependent"
    anchor_in_summary: bool
    dense_retrievable: bool
    exact_retrievable: bool


@dataclass
class CompactionPlan:
    evicted_span_ids: list[int]
    summary: str
    loss_manifest: list[DroppedToken] = field(default_factory=list)
    recovery_budget_tokens: int = 0


def validate_compaction(plan: CompactionPlan, min_recovery_tokens: int = 1) -> None:
    """Enforce the compaction-safety invariant before eviction.

    Refuses (raises) when any dropped token is unreachable from the
    post-compaction agent's reachable query distribution, or when the
    recovery budget cannot support re-expansion.
    """
    if not plan.loss_manifest:
        # No manifest means coverage is unknowable -> refuse (C3).
        raise CompactionShadowError(
            "compactor emitted no loss manifest; coverage unverifiable"
        )

    if plan.recovery_budget_tokens < min_recovery_tokens:
        raise CompactionShadowError(
            f"recovery budget {plan.recovery_budget_tokens} < "
            f"required {min_recovery_tokens}; evicted spans functionally deleted (C4)"
        )

    unrecoverable: list[str] = []
    for tok in plan.loss_manifest:
        if tok.kind == "context_dependent":
            # Safe only if the anchor survives in the summary.
            if not tok.anchor_in_summary:
                unrecoverable.append(tok.token)
        elif tok.kind == "self_describing":
            # Safe only if some reachable path can surface it. Dense-only
            # retrieval over spans dominated by unrelated tokens is not a
            # reachable path for a token the agent no longer knows it lost.
            if not (tok.exact_retrievable or tok.dense_retrievable):
                unrecoverable.append(tok.token)
        else:
            raise CompactionShadowError(f"unknown token kind: {tok.kind!r}")

    if unrecoverable:
        raise CompactionShadowError(
            "refusing to compact: unrecoverable dropped tokens "
            f"{unrecoverable!r} across spans {plan.evicted_span_ids!r}; "
            "preserve anchor spans verbatim or raise compaction threshold"
        )


def maybe_compact(tokens_used: int, ceiling: int, plan: CompactionPlan) -> bool:
    """Return True iff compaction is safe to execute at this utilization."""
    if tokens_used < int(0.75 * ceiling):
        return False
    validate_compaction(plan)  # raises CompactionShadowError on violation
    return True
