# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-auto-compaction-as-a-non-idempotent-order-sensitive-transform-rather-than-a-lossless-cache-evict.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-auto-compaction-as-a-non-idempotent-order-sensitive-transform-rather-than-a-lossless-cache-evict.warrant.json
# Markdown SHA-256:   20f53307ecf9578eec2440c05ce147d42149f2260d7d49940d4c7aa56f52be8f
# Code AST SHA-256:   fe958267c8580b484cef38275cbe8ac0da7b368e1b092b73f1e2692629d59f42
# Verified Classes:   CompactionInvariantViolation, Span, SummaryTree
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionInvariantViolation(RuntimeError):
    """Raised when a compaction step would drop a decision-critical literal
    or when the pin ledger exceeds the budget it needs to stay out of summarization."""


@dataclass
class Span:
    text: str
    pins: frozenset[str]          # exact literals that must survive verbatim
    salience: float = 0.0


@dataclass
class SummaryTree:
    budget_tokens: int
    pin_ledger: set[str] = field(default_factory=set)
    summarized_tokens: int = 0

    def compact(self, leaves: Iterable[Span]) -> str:
        leaves = list(leaves)

        # Invariant 1: every pin in every leaf must be carried forward verbatim.
        incoming_pins = set().union(*(leaf.pins for leaf in leaves)) if leaves else set()
        lost = incoming_pins - self.pin_ledger - set(
            p for leaf in leaves for p in leaf.pins if p in leaf.text
        )
        if lost:
            raise CompactionInvariantViolation(
                f"compaction would drop decision-critical literals: {sorted(lost)}"
            )

        # Invariant 2: never summarize a summary without re-injecting lower pins.
        # If the incoming set is itself derived, its pins must already be in ledger.
        for leaf in leaves:
            if leaf.salience < 0 and leaf.pins - self.pin_ledger:
                raise CompactionInvariantViolation(
                    "derived span carries pins not present in ledger; "
                    "re-inject pins from level below before summarizing"
                )

        # Invariant 3: the pin ledger must stay out of the summarization budget.
        new_ledger = self.pin_ledger | incoming_pins
        ledger_cost = sum(len(p) for p in new_ledger)
        if ledger_cost >= self.budget_tokens:
            raise CompactionInvariantViolation(
                f"pin ledger cost {ledger_cost} >= budget {self.budget_tokens}; "
                "escalate: checkpoint to durable store and restart from pins"
            )

        # Only now is summarization permitted; prose is lossy, pins are not.
        self.pin_ledger = new_ledger
        self.summarized_tokens += sum(len(leaf.text) for leaf in leaves)
        return self._summarize(leaves)

    def _summarize(self, leaves: list[Span]) -> str:
        # Model call omitted; the point is that the return value is lossy prose
        # and MUST NOT be trusted to carry any literal in self.pin_ledger.
        return " ".join(leaf.text[:64] for leaf in leaves)
