# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-a-context-before-its-summary-has-been-verified-as-lossless-against-the-eviction-set.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-a-context-before-its-summary-has-been-verified-as-lossless-against-the-eviction-set.warrant.json
# Markdown SHA-256:   6802b876b350fe4b628a2f3e6af7d82e61f6a952d5b7a176987f102b1d90475d
# Code AST SHA-256:   4986f9832b4a0f35e5e386fea2c21665de57e929c1667db48ee1ce69b03bdd63
# Verified Classes:   CompactionFidelityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionFidelityError(RuntimeError):
    """Raised when a proposed context compaction fails to preserve referential commitments."""
    pass


def verify_compaction(eviction_set, summary_ledger, sample_k=8):
    """
    eviction_set: list of commitment dicts:
        {"id": str, "value": str, "polarity": "confirmed|refuted|suspected|pending"}
    summary_ledger: dict mapping id -> {"value": str, "polarity": str}
    Returns True only if every sampled commitment is recoverable by exact id with matching polarity.
    """
    if not eviction_set:
        return True

    sample = eviction_set[:sample_k]
    failures = []
    for c in sample:
        cid = c["id"]
        entry = summary_ledger.get(cid)
        if entry is None:
            failures.append((cid, "identifier_evicted"))
            continue
        if entry.get("value") != c["value"]:
            failures.append((cid, "value_drift"))
            continue
        if entry.get("polarity") != c["polarity"]:
            failures.append((cid, "polarity_laundered"))

    if failures:
        raise CompactionFidelityError(
            f"compaction rejected: {len(failures)} commitment(s) unrecoverable: {failures}"
        )
    return True


def maybe_compact(context, eviction_set, summary_ledger, tail_contains_working_set):
    """
    Three-way branch: commit / defer / halt.
    """
    if tail_contains_working_set:
        raise CompactionFidelityError(
            "tail continuity violated: working set is inside the eviction span; halt and checkpoint"
        )
    try:
        verify_compaction(eviction_set, summary_ledger)
    except CompactionFidelityError:
        # defer: spill to external store, splice a pointer, do not evict into prose
        return context.spill_and_pointer(eviction_set)
    return context.commit_compaction(summary_ledger)
