# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-the-fidelity-scoring-blind-spot-at-the-summarization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-the-fidelity-scoring-blind-spot-at-the-summarization-boundary.warrant.json
# Markdown SHA-256:   29b9d4296d2274239b7ccac12bed463912fb29f9657d1fcb6f987e3aa6d1d97a
# Code AST SHA-256:   c3ffe61c66f1b414d6e2b11f4ceeb89cf42b4466a92a26bf7d10ea3a9992a4bc
# Verified Classes:   PreconditionCompactionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PreconditionCompactionError(RuntimeError):
    """Raised when lossy compaction would drop a pending precondition."""
    pass


POLARITY_SENSITIVE = {"not", "pending", "revoked", "approved", "issued", "unset"}


def extract_preconditions(spans):
    """Yield (span_id, text, is_polarity_sensitive) for candidate spans."""
    for sid, text in spans:
        tokens = set(text.lower().split())
        sensitive = bool(tokens & POLARITY_SENSITIVE) or any(
            ch.isdigit() for ch in text
        )
        yield sid, text, sensitive


def compact(candidate_spans, pending_refs, fidelity_score, threshold, budget):
    pinned, eligible = [], []
    for sid, text, sensitive in extract_preconditions(candidate_spans):
        if sid in pending_refs and sensitive:
            pinned.append(text)
        else:
            eligible.append(text)

    pinned_tokens = sum(len(t.split()) for t in pinned)
    if pinned_tokens > budget:
        raise PreconditionCompactionError(
            f"pinned preconditions need {pinned_tokens} tokens > budget {budget}; "
            "refusing lossy compaction, escalate to external memory or checkpoint"
        )

    if fidelity_score < threshold:
        raise PreconditionCompactionError(
            f"fidelity {fidelity_score:.2f} below gate {threshold:.2f} over eligible span"
        )

    # Pinned spans carried verbatim; only eligible spans are summarized.
    return {"pinned": pinned, "summarize": eligible}
