# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-pruning-of-its-own-context-window-as-an-unsafe-operation-whose-learned-policy-has-already-been-corrupted.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-pruning-of-its-own-context-window-as-an-unsafe-operation-whose-learned-policy-has-already-been-corrupted.warrant.json
# Markdown SHA-256:   7ecdd559b046c2936db54f6d65044454f7afafe178d2a59de5296af552329351
# Code AST SHA-256:   fd26126242b4d8e8a271606092fe105d7ba86fc07d93637ba37b061080023a6c
# Verified Classes:   PrunePolicyCorruption
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PrunePolicyCorruption(RuntimeError):
    """Raised when a self-pruning update would train the policy on a context it composed."""
    pass


ERROR_CLASS_TAGS = {"error", "constraint", "negation", "contradiction"}
EVICTION_RATE_CEILING = 0.15  # relative increase in error-span eviction per cycle


def guard_policy_update(
    proposed_eviction_rates: dict[str, float],
    prior_eviction_rates: dict[str, float],
    episode_reward_is_terminal: bool,
    pruned_spans_recoverable: bool,
    confidence_success_divergence: float,
    probe_set_frozen: bool,
) -> None:
    # 1. Error-span eviction creep: the pruner is learning to hide its own errors.
    for tag in ERROR_CLASS_TAGS:
        prior = prior_eviction_rates.get(tag, 0.0)
        proposed = proposed_eviction_rates.get(tag, 0.0)
        if prior > 0 and (proposed - prior) / prior > EVICTION_RATE_CEILING:
            raise PrunePolicyCorruption(
                f"Update would raise eviction rate of '{tag}' spans from "
                f"{prior:.3f} to {proposed:.3f} in one cycle; "
                f"reward is computed over a context this policy composed."
            )

    # 2. Terminal reward + destructive eviction = unverifiable credit assignment.
    if episode_reward_is_terminal and not pruned_spans_recoverable:
        raise PrunePolicyCorruption(
            "Terminal sparse reward with destructive eviction: cannot attribute "
            "success/failure to retained vs. evicted spans. Refusing self-update; "
            "route through prune-audit split."
        )

    # 3. Anti-correlation signature: confidence up, success down.
    if confidence_success_divergence > 1.0 and not probe_set_frozen:
        raise PrunePolicyCorruption(
            f"Policy confidence and measured success diverged by "
            f"{confidence_success_divergence:.2f} sigma with no frozen probe set; "
            f"policy is grading its own sanitized context."
        )


def apply_pruning_update(episode, policy) -> None:
    guard_policy_update(
        proposed_eviction_rates=policy.proposed_rates(),
        prior_eviction_rates=policy.historical_rates(),
        episode_reward_is_terminal=episode.reward_is_terminal,
        pruned_spans_recoverable=episode.audit_log.is_recoverable(),
        confidence_success_divergence=policy.confidence_success_gap(),
        probe_set_frozen=policy.probe_set.is_frozen(),
    )
    policy.commit()
