# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-compaction-as-a-lossy-transform-rather-than-a-compression-the-mid-task-invariant-decay-of-summarizer-driven-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-compaction-as-a-lossy-transform-rather-than-a-compression-the-mid-task-invariant-decay-of-summarizer-driven-context-window.warrant.json
# Markdown SHA-256:   8e69bb90c737d2474cd5c0f40d28281f946e1ecdb638c66ceed4561630047a00
# Code AST SHA-256:   75907bb378ed88f1bae86369b592077eb2b7a3940ae182fe1b23e0d92c4c7d8b
# Verified Classes:   CompactionInvariantViolation, ContextElement, PinnedPartition
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class CompactionInvariantViolation(RuntimeError):
    """Raised when a compaction would drop irrecoverable, load-bearing state."""
    pass


@dataclass
class ContextElement:
    kind: str          # "recoverable" | "constraint" | "identifier" | "provenance" | "narrative"
    payload: str
    pinned: bool = False


@dataclass
class PinnedPartition:
    """State the summarizer is structurally forbidden to paraphrase or drop."""
    constraints: list[str] = field(default_factory=list)   # verbatim prohibitions/scope
    identifiers: dict[str, str] = field(default_factory=dict)  # byte-exact slots
    provenance: list[tuple[str, str, float]] = field(default_factory=list)  # (source, value, ts)

    def snapshot(self) -> tuple:
        return (tuple(self.constraints), dict(self.identifiers), tuple(self.provenance))


def compact_context(
    elements: list[ContextElement],
    summarize: Callable[[list[ContextElement]], str],
    pinned: PinnedPartition,
) -> tuple[str, PinnedPartition]:
    """Route elements: pin irrecoverable/identifier/provenance, summarize the rest.

    Refuses to run if any element that must be pinned would fall through to the
    summarizer, and re-verifies the partition is intact after summarization.
    """
    recoverable_or_narrative = []
    for el in elements:
        if el.kind in ("constraint", "identifier", "provenance"):
            if not el.pinned:
                raise CompactionInvariantViolation(
                    f"element of kind={el.kind!r} reached summarizer unpinned; "
                    f"payload={el.payload[:64]!r} would be lost irrecoverably"
                )
            # already captured in `pinned` by the caller; never passed to summarizer
        elif el.kind in ("recoverable", "narrative"):
            recoverable_or_narrative.append(el)
        else:
            raise CompactionInvariantViolation(f"unknown element kind {el.kind!r}")

    before = pinned.snapshot()
    digest = summarize(recoverable_or_narrative)
    after = pinned.snapshot()

    if before != after:
        raise CompactionInvariantViolation(
            "pinned partition mutated across compaction; refusing to emit digest"
        )
    if not digest and recoverable_or_narrative:
        raise CompactionInvariantViolation("summarizer returned empty digest for non-empty input")

    return digest, pinned
