# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-so-that-a-summarizer-s-lossy-rewrite-cannot-silently-delete-the-one-fact-a-downstream-tool-call-de.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-so-that-a-summarizer-s-lossy-rewrite-cannot-silently-delete-the-one-fact-a-downstream-tool-call-de.warrant.json
# Markdown SHA-256:   6abc59478e4984d6e5b7fea4414b03f0532c1507e722686de71bb3a9c06519f1
# Code AST SHA-256:   e5315e50e04929725d187a5ff85b13e20979acbf7a305d251403355b533d06d7
# Verified Classes:   CompactionReferenceError, PinnedRef, CompactionWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionReferenceError(RuntimeError):
    """Raised when a compaction pass evicts or corrupts a live reference target."""


@dataclass
class PinnedRef:
    handle: str
    exact_value: str


@dataclass
class CompactionWindow:
    # Spans the summarizer is allowed to rewrite (Regime A region).
    lossy_spans: list[str] = field(default_factory=list)
    # Spans that must survive byte-exact (Regime B region).
    pinned: dict[str, PinnedRef] = field(default_factory=dict)


def compact(window: CompactionWindow, live_reference_set: set[str], budget_ok: bool) -> CompactionWindow:
    """Compact only if no live reference target falls in the lossy region.

    live_reference_set is supplied by the orchestration layer that owns the
    pending call graph. The summarizer never computes it.
    """
    if not budget_ok:
        return window  # nothing to do

    lossy_targets = live_reference_set.intersection(window.lossy_spans)
    if lossy_targets:
        # Over-summarizing would orphan a capability; refuse and force pinning.
        raise CompactionReferenceError(
            f"refusing to summarize spans that are live reference targets: {sorted(lossy_targets)}; "
            f"route these through pin-and-externalize instead"
        )
    # Safe: lossy region is disjoint from the reference set.
    window.lossy_spans = [s[:64] for s in window.lossy_spans]
    return window


def dereference(window: CompactionWindow, handle: str) -> str:
    """Resolve a pinned handle at tool-call time; fail loudly, never confabulate."""
    ref = window.pinned.get(handle)
    if ref is None:
        raise CompactionReferenceError(
            f"handle {handle!r} not pinned: compaction dropped a capability the next call depends on"
        )
    return ref.exact_value
