# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-prune-context-that-is-load-bearing-for-its-own-pruning-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-prune-context-that-is-load-bearing-for-its-own-pruning-policy.warrant.json
# Markdown SHA-256:   f1516780d40e5851318a0d179de13a50e6895737a09650399eae2a55bf3d7fbc
# Code AST SHA-256:   2132e3affb4c4ec13d8991bd2e96d57af20252a2ebb40b1d1c77aa3711846eac
# Verified Classes:   AnchorEvictionError, Chunk, Window
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Sequence

class AnchorEvictionError(RuntimeError):
    """Raised when a prune batch would evict or destabilize a policy-bearing anchor."""
    pass

@dataclass
class Chunk:
    id: str
    text: str
    policy_bearing: bool = False

@dataclass
class Window:
    chunks: list[Chunk] = field(default_factory=list)

def score(chunk: Chunk, window: Window) -> float:
    # window-dependent scorer: presence of policy-bearing chunks shifts scores
    base = len(chunk.text) / 1000.0
    anchor_bonus = 0.15 if any(c.policy_bearing for c in window.chunks) else 0.0
    return min(1.0, base + anchor_bonus)

def prune(window: Window, tau_margin: float = 0.20) -> Window:
    anchors = [c for c in window.chunks if c.policy_bearing]
    if not anchors:
        raise AnchorEvictionError(
            "no identifiable policy-bearing anchor; refusing to self-prune"
        )
    scores = {c.id: score(c, window) for c in window.chunks}
    tau = sorted(scores.values())[len(scores) // 2]
    survivors = [c for c in window.chunks if c.policy_bearing or scores[c.id] >= tau]

    # re-score against the post-prune window; if the threshold moved too far
    # the deletion destroyed its own justification and must be rolled back
    post = Window(survivors)
    post_scores = {c.id: score(c, post) for c in post.chunks}
    post_tau = sorted(post_scores.values())[len(post_scores) // 2]
    if post_tau > tau * (1 + tau_margin):
        raise AnchorEvictionError(
            f"threshold inflated {tau:.3f}->{post_tau:.3f} after prune; "
            f"deletion invalidated its own scoring basis, rolling back"
        )
    return post
