# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-salience-preserving-compaction-from-silently-dropping-the-referent-of-an-active-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-salience-preserving-compaction-from-silently-dropping-the-referent-of-an-active-obligation.warrant.json
# Markdown SHA-256:   2746200149252e45e5eb78a339bde2fce6a567d2be504a28e171ac0227e9cd45
# Code AST SHA-256:   b6879685ba08aed5c9d65311bdc0fd26431ca4dad545d171301e358af502e830
# Verified Classes:   ReferentClosureViolation, Obligation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ReferentClosureViolation(RuntimeError):
    """Raised when a compaction pass would evict a span that a live obligation depends on."""
    pass


class Obligation:
    def __init__(self, oid, referent_span_ids):
        self.oid = oid
        self.referent_span_ids = set(referent_span_ids)
        self.resolved = False


def compact(spans, live_obligations, eviction_candidates, summarize):
    """
    spans: dict span_id -> text
    live_obligations: list[Obligation]
    eviction_candidates: set of span_ids the salience scorer wants to drop
    summarize: callable(list[str]) -> str
    """
    pinned = set()
    for ob in live_obligations:
        if ob.resolved:
            continue
        for sid in ob.referent_span_ids:
            if sid not in spans:
                # Referent already gone before this pass: refuse to proceed silently.
                raise ReferentClosureViolation(
                    f"obligation {ob.oid} references missing span {sid}"
                )
            pinned.add(sid)

    illegal = eviction_candidates & pinned
    if illegal:
        # Do not silently drop the pin; refuse the eviction of live referents.
        raise ReferentClosureViolation(
            f"compaction would evict live referents {sorted(illegal)} "
            f"for obligations {[o.oid for o in live_obligations if not o.resolved]}"
        )

    evictable = [spans[sid] for sid in eviction_candidates]
    summary = summarize(evictable)
    manifest = {
        "evicted": sorted(eviction_candidates),
        "pinned_retained": sorted(pinned),
        "summary": summary,
    }
    return manifest


def apply_compaction(spans, live_obligations, eviction_candidates, summarize):
    try:
        return compact(spans, live_obligations, eviction_candidates, summarize)
    except ReferentClosureViolation:
        # Loud refusal: do not compact; surface for caller to resolve obligations first.
        raise
