# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-hierarchical-context-compaction-has-silently-converted-a-lossless-retrieval-handle-into-a-lossy-paraphrase.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-hierarchical-context-compaction-has-silently-converted-a-lossless-retrieval-handle-into-a-lossy-paraphrase.warrant.json
# Markdown SHA-256:   7bbd6ce678d1bc7a8cd0ffc04ea9d09dba1f1c199ce50632ffdb0d9ad5c1f4ec
# Code AST SHA-256:   c51f2799df77ee4f8048e7d0746917af1c60663a09888748d3838c4761e98401
# Verified Classes:   Fidelity, FidelityViolation, Handle, HandleStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class Fidelity(Enum):
    VERBATIM = "verbatim"   # resolves to exact original bytes
    SUMMARY = "summary"     # resolves to a paraphrase; lossy


class FidelityViolation(RuntimeError):
    """Raised when a caller requires VERBATIM but the handle resolves to a SUMMARY node."""
    pass


@dataclass(frozen=True)
class Handle:
    msg_id: str
    fidelity: Fidelity
    payload: str


class HandleStore:
    def __init__(self):
        self._handles: dict[str, Handle] = {}

    def register(self, handle: Handle) -> None:
        self._handles[handle.msg_id] = handle

    def alias_to_summary(self, source_id: str, summary_id: str, summary_text: str) -> None:
        # Compaction is permitted to be lossy, but it MUST relabel fidelity.
        # It may NOT keep the source handle's VERBATIM tag on a summary payload.
        self._handles[summary_id] = Handle(summary_id, Fidelity.SUMMARY, summary_text)

    def fetch(self, msg_id: str, required: Fidelity) -> str:
        handle = self._handles.get(msg_id)
        if handle is None:
            raise FidelityViolation(f"handle {msg_id!r} does not exist")
        if required is Fidelity.VERBATIM and handle.fidelity is not Fidelity.VERBATIM:
            raise FidelityViolation(
                f"handle {msg_id!r} resolves to {handle.fidelity.value}, "
                f"but caller required {required.value}; "
                f"re-fetch from original source or fail the subtask explicitly"
            )
        return handle.payload


def build_retry_loop(store: HandleStore, msg_id: str) -> dict:
    # Planner declared it needs exact numeric constraints -> VERBATIM.
    raw = store.fetch(msg_id, required=Fidelity.VERBATIM)
    if "max_retries" not in raw:
        raise FidelityViolation(
            f"verbatim payload for {msg_id!r} missing 'max_retries'; "
            f"compaction corrupted a lossless handle"
        )
    return {"raw": raw}


if __name__ == "__main__":
    store = HandleStore()
    store.register(Handle("B12_msg_2", Fidelity.VERBATIM,
                          "max_retries=3, backoff=exponential(base=2, cap=64s)"))
    # Compactor dedups the four source handles into one summary alias.
    store.alias_to_summary("B12_msg_2", "B12_msg_2", "retry policy configured")
    try:
        build_retry_loop(store, "B12_msg_2")
    except FidelityViolation as exc:
        print(f"BLOCKED (correct): {exc}")
