# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-hierarchical-summarization-triggers-and-the-irreversible-eviction-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-hierarchical-summarization-triggers-and-the-irreversible-eviction-invariant.warrant.json
# Markdown SHA-256:   59b27c77f6bf4b30c867b8f64ba0398b213a9a67a2735fc0d729cf320fbafe51
# Code AST SHA-256:   c25ba9dd138ff1699e74b34a5959bde9fd2f4d3940061ee6f0d2c881960155a6
# Verified Classes:   IrreversibleCompactionError, Obligation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class IrreversibleCompactionError(RuntimeError):
    """Raised when a compaction would evict obligations that are not preserved
    in the summary and not retained in any reachable store."""
    pass


class Obligation:
    def __init__(self, kind: str, value: str):
        self.kind = kind      # "literal" | "negation" | "identifier" | "conditional"
        self.value = value

    def __repr__(self) -> str:
        return f"Obligation({self.kind}={self.value!r})"


def extract_obligations(span_text: str) -> list[Obligation]:
    # Simplified stand-in for a real extraction pass.
    import re
    found = []
    for m in re.finditer(r"\b\d{2,}\b", span_text):
        found.append(Obligation("literal", m.group()))
    for m in re.finditer(r"\b(do not|must not|never|exclude)\b", span_text, re.I):
        found.append(Obligation("negation", m.group().lower()))
    return found


def compact_with_gate(
    span_text: str,
    summarizer,
    retained_store,
    obligation_store,
) -> str:
    obligations = extract_obligations(span_text)
    summary = summarizer(span_text)

    # Retention path: if raw span is addressable, compaction is reversible.
    if retained_store is not None and retained_store.has(span_text):
        for ob in obligations:
            obligation_store.put(ob)
        return summary

    # Irrecoverable path: every obligation must survive in the summary.
    missing = [ob for ob in obligations if ob.value not in summary]
    if missing:
        # Refuse: do not silently evict. Halt rather than proceed lossy.
        raise IrreversibleCompactionError(
            f"Compaction would irreversibly evict {len(missing)} obligation(s): "
            f"{missing!r}. Summary={summary!r}. "
            "Refusing to compact; spill to obligation_store or retain raw span."
        )

    for ob in obligations:
        obligation_store.put(ob)
    return summary


def run_turn_compaction(span_text: str, summarizer, retained_store, obligation_store):
    try:
        return compact_with_gate(span_text, summarizer, retained_store, obligation_store)
    except IrreversibleCompactionError as e:
        # Surface, do not swallow. A stalled-but-correct state is preferred.
        raise IrreversibleCompactionError(
            f"Turn compaction halted at boundary: {e}"
        ) from e
