# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-pre-compaction-recall-obligation-and-the-summary-provenance-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-pre-compaction-recall-obligation-and-the-summary-provenance-gap.warrant.json
# Markdown SHA-256:   e55df2f6a744896e6b3521f5941cf02afad12c3c249cb489150859a4d7ba57a3
# Code AST SHA-256:   ad56f831dcfbc6b6fa2d3d4468f913f265f769d6dfc61b3e4639565f1cd62f09
# Verified Classes:   CompactionRefused, ObligationKind, Obligation, Span, ObligationsLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class CompactionRefused(RuntimeError):
    """Raised when eviction is attempted without a verified recall surrogate."""


class ObligationKind(Enum):
    LITERAL = "literal"            # IDs, SHAs, thresholds, ports
    CORRECTION = "correction"      # user supersession of a prior value
    NEGATIVE = "negative"          # "we ruled this out"
    COMMITMENT = "commitment"      # promise whose referent is a literal


@dataclass(frozen=True)
class Obligation:
    kind: ObligationKind
    literal: str
    source_span_id: str


@dataclass
class Span:
    span_id: str
    text: str
    is_derived_digest: bool = False


@dataclass
class ObligationsLedger:
    pinned: dict[str, Obligation] = field(default_factory=dict)

    def pin(self, ob: Obligation) -> None:
        self.pinned[ob.literal] = ob

    def surrogates_for(self, span_id: str) -> Iterable[Obligation]:
        return (o for o in self.pinned.values() if o.source_span_id == span_id)


def verify_surrogate(ob: Obligation, digest_text: str) -> bool:
    """Round-trip check: the literal must appear verbatim in the survivor."""
    return ob.literal in digest_text


def commit_compaction(
    span: Span,
    proposed_digest: str,
    ledger: ObligationsLedger,
    obligations_in_span: list[Obligation],
    source_remains: bool,
) -> None:
    # Invariant 4: never compact a digest when no source remains.
    if span.is_derived_digest and not source_remains:
        raise CompactionRefused(
            f"refusing digest-of-digest eviction of {span.span_id!r}: "
            "no recoverable source remains; escalate to external indexing"
        )

    # Invariant 1+2: every obligation must have a verified, pinned surrogate.
    for ob in obligations_in_span:
        if ob.literal not in ledger.pinned:
            raise CompactionRefused(
                f"unpinned {ob.kind.value} obligation {ob.literal!r} "
                f"from span {span.span_id!r}; eviction would void lossless recall"
            )
        if not verify_surrogate(ob, proposed_digest):
            raise CompactionRefused(
                f"surrogate for {ob.literal!r} failed round-trip against "
                f"proposed digest of {span.span_id!r}; summarizer distorted literal"
            )

    # Invariant 3: only now is eviction licensed.
    span.text = proposed_digest
    span.is_derived_digest = True


def recall(ledger: ObligationsLedger, literal: str) -> str:
    ob = ledger.pinned.get(literal)
    if ob is None:
        raise CompactionRefused(
            f"recall miss for {literal!r}: not pinned; cannot distinguish "
            "absent-from-episode from dropped-by-compactor"
        )
    return ob.literal
