# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-its-own-context-window-when-the-summarizer-s-own-output-is-a-function-of-the-span-it-is-about-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-its-own-context-window-when-the-summarizer-s-own-output-is-a-function-of-the-span-it-is-about-t.warrant.json
# Markdown SHA-256:   0790d2a3bab79e865d0f64c48475c9a6aa795fdef98aa789f4c1e60a9ec4a358
# Code AST SHA-256:   b7a598647f50a870da5708879e904979b025c0c1335576651d6e6a5b867cd39f
# Verified Classes:   SelfReferentialEviction
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SelfReferentialEviction(RuntimeError):
    """Raised when a context-pruning decision reads the span it is about to evict."""
    pass


def guarded_prune(span, query_builder, plan_summary, pinned_ids):
    """
    Refuse to evict a span when the relevance query is constructed from
    state that the span itself contributed to (self-referential eviction).
    """
    if span.id in pinned_ids:
        return "pinned"

    query = query_builder()
    if span.id in query.derived_from_span_ids:
        raise SelfReferentialEviction(
            f"span {span.id} contributes to its own relevance query; "
            f"pruning would create a self-referential fixed point. "
            f"Escalate to orchestrator for out-of-band checkpoint."
        )
    if plan_summary.derived_from(span.id):
        raise SelfReferentialEviction(
            f"plan summary is a function of span {span.id}; "
            f"eviction would let the span score itself out of existence."
        )

    score = query.score(span)
    if score < query.threshold:
        return "evict"
    return "keep"
