# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-editing-context-policy-that-prunes-its-own-rewrite-instructions-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-editing-context-policy-that-prunes-its-own-rewrite-instructions-mid-flight.warrant.json
# Markdown SHA-256:   52441549fc490f0a1e274f8bc7c4541fc7def87e6fb0b242aa2839aabf02a318
# Code AST SHA-256:   e26090f5036f99e99bb630db168e14a0c432e24a29674febfdc47733d404b267
# Verified Classes:   ControlPlaneAliasingError, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ControlPlaneAliasingError(RuntimeError):
    """Raised when a self-edit pass would evaluate its own governing policy."""


@dataclass(frozen=True)
class ContextWindow:
    # Immutable control region: the pruner can never address these keys.
    control_keys: FrozenSet[str]
    # Mutable data region: segment id -> text.
    segments: dict
    # The policy currently in force, stored out-of-band.
    active_policy: dict
    last_threshold: float


def assert_policy_disjoint(window: ContextWindow, write_set: FrozenSet[str]) -> None:
    overlap = window.control_keys & write_set
    if overlap:
        raise ControlPlaneAliasingError(
            f"self-edit write set intersects control region: {sorted(overlap)}"
        )


def prune(window: ContextWindow, relevance, write_set: FrozenSet[str]) -> ContextWindow:
    # Guard 1: policy must be outside the edit domain.
    assert_policy_disjoint(window, write_set)

    threshold = window.active_policy["eviction_threshold"]

    # Guard 2: refuse if the policy has drifted from the recorded threshold.
    if abs(threshold - window.last_threshold) > window.active_policy["tolerance"]:
        raise ControlPlaneAliasingError(
            f"policy threshold drifted {window.last_threshold} -> {threshold}; "
            "policy was likely summarized or evicted"
        )

    survivors = {
        k: v
        for k, v in window.segments.items()
        if k in window.control_keys or relevance(v) >= threshold
    }

    # Guard 3: the pass must not have removed any control key.
    if not window.control_keys <= survivors.keys():
        raise ControlPlaneAliasingError("prune pass removed a control-region key")

    return ContextWindow(
        control_keys=window.control_keys,
        segments=survivors,
        active_policy=window.active_policy,
        last_threshold=threshold,
    )
