# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-irreducible-witness-boundary-in-auto-compaction-with-fidelity-guarantees.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-irreducible-witness-boundary-in-auto-compaction-with-fidelity-guarantees.warrant.json
# Markdown SHA-256:   c82146bfce9d3b2e4e49047ed80c0d3e36a43fbe8b877fabc48b3e3649e6b04a
# Code AST SHA-256:   d4fccf60c3c35f76a46c4e44133c1edbee66bc54e52b092f37ad0135684f1cf7
# Verified Classes:   CompactionFidelityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionFidelityError(RuntimeError):
    """Raised when a compactor would violate its stated fidelity guarantee."""
    pass


WITNESS_KINDS = frozenset({"negative_result", "error_signature", "nonce",
                           "verbatim_constraint", "numeric_threshold"})


def compact(context, plan_predicates, witness_budget, external_store, epsilon=0.01):
    """
    context: list of spans, each {id, text, kind, key}
    plan_predicates: set of future predicates, or None if plan is open (C1 fails)
    witness_budget: max tokens of pinned witnesses allowed in-window
    external_store: object with .put(key, span) for C3 reversibility
    """
    witnesses = [s for s in context if s["kind"] in WITNESS_KINDS]
    witness_tokens = sum(len(s["text"]) for s in witnesses)

    # C2/C4: witnesses must be pinned; if budget cannot hold them, we must
    # externalize (C3) and close the plan -- never drop to make room.
    if witness_tokens > witness_budget:
        if plan_predicates is None:
            # Cannot close an open plan; cannot pin; must refuse.
            raise CompactionFidelityError(
                f"witness_budget exhausted ({witness_tokens}>{witness_budget}) "
                f"with open plan: cannot guarantee fidelity"
            )
        for s in witnesses:
            external_store.put(s["key"], s)  # C3
        # Plan is closed, so predicate set bounds what remains droppable.
        witnesses = []

    if plan_predicates is None:
        # C1 fails: recurrence risk undefined for any non-witness span.
        raise CompactionFidelityError(
            "plan predicates unknown; recurrence risk undefined; must refuse"
        )

    droppable, pinned = [], list(witnesses)
    for s in context:
        if s in witnesses:
            continue
        referenced = any(s["key"] in p for p in plan_predicates)
        if referenced:
            pinned.append(s)  # r(s) high: future predicate references it
        else:
            droppable.append(s)

    # C3: every dropped span must be recoverable.
    for s in droppable:
        external_store.put(s["key"], s)

    return {"pinned": pinned, "dropped_keys": [s["key"] for s in droppable],
            "refused": False}
