# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-lose-tool-call-provenance-when-lossy-context-compaction-outruns-its-fidelity-score.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-lose-tool-call-provenance-when-lossy-context-compaction-outruns-its-fidelity-score.warrant.json
# Markdown SHA-256:   76ba0e6c1bbeb7221192719ed955632733201eee307efe29aebb80affaf2ea9a
# Code AST SHA-256:   88e15b04b59b858af90f2c22cc75fb5c1644d9b57f2e319d372ec4ebbdde16b6
# Verified Classes:   UnsoundCompactionBoundary, Binding, CompactionRegion
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnsoundCompactionBoundary(RuntimeError):
    """Raised when a lossy compaction would sever a live execution binding."""


@dataclass
class Binding:
    call_id: str
    handle: str
    idempotency_key: str
    producing_step: int
    last_deref_step: int


@dataclass
class CompactionRegion:
    start_step: int
    end_step: int
    fidelity_score: float
    bindings: list[Binding] = field(default_factory=list)


def authorize_compaction(
    region: CompactionRegion,
    external_ledger: dict[str, Binding],
    fidelity_gate: float = 0.85,
) -> bool:
    # Fidelity is necessary but never sufficient.
    if region.fidelity_score < fidelity_gate:
        return False

    for b in region.bindings:
        escapes = b.last_deref_step > region.end_step
        if not escapes:
            continue
        # Escaping binding: must be externalized with exact retrieval.
        ledgered = external_ledger.get(b.call_id)
        if ledgered is None:
            raise UnsoundCompactionBoundary(
                f"Region [{region.start_step}:{region.end_step}] would drop live "
                f"binding call_id={b.call_id} handle={b.handle} "
                f"(dereferenced at step {b.last_deref_step}); "
                f"fidelity={region.fidelity_score:.2f} is not a substitute for "
                f"exact referential state. Retain verbatim or externalize."
            )
        if ledgered.handle != b.handle or ledgered.idempotency_key != b.idempotency_key:
            raise UnsoundCompactionBoundary(
                f"Ledger entry for call_id={b.call_id} diverges from live binding; "
                f"compaction would propagate stale referential state."
            )
    return True


def compact(
    region: CompactionRegion,
    external_ledger: dict[str, Binding],
) -> Optional[str]:
    if not authorize_compaction(region, external_ledger):
        return None
    return f"summary[{region.start_step}:{region.end_step}]"
