# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-when-hierarchical-summarization-would-evict-an-unreconstructable-leaf.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-when-hierarchical-summarization-would-evict-an-unreconstructable-leaf.warrant.json
# Markdown SHA-256:   216b236e146705b12207de39d256a7d7b4193e48860a837b2e0766b70b1a2ff2
# Code AST SHA-256:   4d27c64efd67ff719110d7a37fd7ee305b2afcfdb6ea59710b37d3875678e3bb
# Verified Classes:   UnreconstructableEvictionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnreconstructableEvictionError(RuntimeError):
    """Raised when auto-compaction would evict a live singular commitment
    that no surviving ancestor entails and no external store can refetch."""


def _is_singular_commitment(leaf: str) -> bool:
    # Heuristic hook: exact scalars, identifiers, verbatim imperatives, negations.
    markers = ("not ", "ceiling", "must", "exactly", "never", "=", ":=")
    return any(m in leaf.lower() for m in markers)


def _entailed_by_ancestor(leaf: str, ancestor_summary: str) -> bool:
    # Replace with a real entailment check; here we test for value survival.
    import re
    values = re.findall(r"\b\d+\b", leaf)
    return all(v in ancestor_summary for v in values) if values else leaf[:40] in ancestor_summary


def _refetchable(leaf_id: str, store) -> bool:
    return store.has(leaf_id)


def plan_compaction(candidates, ancestors, store):
    """Return the set safe to evict, or raise to halt and escalate."""
    safe = set()
    for leaf_id, leaf_text in candidates:
        if not _is_singular_commitment(leaf_text):
            safe.add(leaf_id)
            continue
        if _refetchable(leaf_id, store):
            safe.add(leaf_id)
            continue
        if any(_entailed_by_ancestor(leaf_text, a) for a in ancestors):
            safe.add(leaf_id)
            continue
        raise UnreconstructableEvictionError(
            f"leaf {leaf_id!r} is a live singular commitment not entailed by any "
            f"ancestor and not refetchable; refuse to compact, pin leaf and re-plan budget"
        )
    return safe


def auto_compact(candidates, ancestors, store, reclaim):
    try:
        evictable = plan_compaction(candidates, ancestors, store)
    except UnreconstructableEvictionError as e:
        # Escalate: pin the offending leaf, do not silently drop the constraint.
        return {"status": "halted", "reason": str(e)}
    reclaimed = reclaim(evictable)
    return {"status": "compacted", "reclaimed": reclaimed, "evicted": len(evictable)}
