# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-when-lossy-summarization-silently-invalidates-an-in-flight-cache-prefix.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-when-lossy-summarization-silently-invalidates-an-in-flight-cache-prefix.warrant.json
# Markdown SHA-256:   d853335dcb4d924e867e614785775265c5dd7009fe8808c851b01e28636466f0
# Code AST SHA-256:   1608a2e3d79b9f2706310ec8ddb07adb82d21a1220ea8f9c6670e6312f5b0b81
# Verified Classes:   CompactionBoundaryError, CompactionProposal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CompactionBoundaryError(RuntimeError):
    """Raised when a proposed compaction would mutate the cached prefix
    or drop a referentially-live token required by an in-flight tool call."""


@dataclass
class CompactionProposal:
    head_tokens: tuple          # tokens at the cache-covered head, in order
    cached_head: tuple          # the exact prefix the cache is keyed on
    summary: str
    placement: str              # "append" | "splice_head"
    live_handles: FrozenSet[str] = field(default_factory=frozenset)
    preserved_handles: FrozenSet[str] = field(default_factory=frozenset)


def validate_compaction(p: CompactionProposal) -> None:
    # Invariant 1: the cached head must be byte-stable (prefix-stable).
    if p.placement == "splice_head":
        raise CompactionBoundaryError(
            "compaction splices into the cached head; prefix key changes and "
            "the entire downstream cache is silently invalidated"
        )
    if p.head_tokens != p.cached_head:
        raise CompactionBoundaryError(
            "head tokens diverged from the cached prefix; treating as cache-cold "
            "requires an explicit re-warm, not an implicit continuation"
        )

    # Invariant 2: every live tool binding must survive losslessly.
    dropped = p.live_handles - p.preserved_handles
    if dropped:
        raise CompactionBoundaryError(
            f"lossy summary dropped live resource handles {sorted(dropped)}; "
            "downstream tool calls would target hallucinated identifiers"
        )


def compact_or_defer(p: CompactionProposal) -> str:
    validate_compaction(p)
    # Safe path: prefix-stable and referentially lossless.
    return p.summary
