# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-eviction-when-the-summarizer-s-own-input-is-the-region-being-pruned.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-eviction-when-the-summarizer-s-own-input-is-the-region-being-pruned.warrant.json
# Markdown SHA-256:   a72206f1c367e7b358b0b9dac64cb6ca8a91ffb558ccbe41a1cbad7a6c763c35
# Code AST SHA-256:   a2cabcfc41be1f736493920d96ec652b77aca1faef3ca68bb651a9bfb6318218
# Verified Classes:   UnsafeEvictionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsafeEvictionError(RuntimeError):
    """Raised when a compaction pass would evict policy-typed spans without a pinned copy."""


POLICY_TAGS = frozenset({"provenance:rule", "tool:allowlist", "auth:confirm", "format:contract"})


def plan_compaction(spans, summarizer, pinned_floor=0):
    """
    spans: list of dicts with keys 'id', 'tag', 'text', 'tokens'.
    Returns (surrogate_text, evicted_ids). Raises UnsafeEvictionError if a
    policy span is inside the region and has no verbatim copy in the surrogate.
    """
    region = [s for s in spans if s["id"] >= pinned_floor]
    policy_in_region = [s for s in region if s["tag"] in POLICY_TAGS]

    # Condition 1: policy independence. Policy spans must be pinned, not summarized.
    if policy_in_region:
        raise UnsafeEvictionError(
            f"refusing model-driven eviction: {len(policy_in_region)} policy span(s) "
            f"inside compaction region: {[s['id'] for s in policy_in_region]}"
        )

    surrogate = summarizer(region)

    # Condition 2: verifiability. Any rule-tagged text must survive verbatim.
    for s in region:
        if s["tag"] in POLICY_TAGS and s["text"] not in surrogate:
            raise UnsafeEvictionError(
                f"surrogate dropped policy span {s['id']} without a pinned copy"
            )

    # Condition 3: reversibility is the caller's job; we return evicted ids so the
    # caller can checkpoint them before committing the surrogate.
    return surrogate, [s["id"] for s in region]


def commit_compaction(buffer, surrogate, evicted_ids, checkpoint):
    """Checkpoint the pre-compaction region before the surrogate becomes live."""
    if not checkpoint.write(evicted_ids, [b for b in buffer if b["id"] in evicted_ids]):
        raise UnsafeEvictionError(
            "checkpoint failed; refusing to commit irreversible compaction"
        )
    return [{"id": -1, "tag": "summary", "text": surrogate}] + [
        b for b in buffer if b["id"] not in evicted_ids
    ]
