# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-self-rewrite-when-its-context-controller-evicts-the-invariant-it-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-self-rewrite-when-its-context-controller-evicts-the-invariant-it-depends-on.warrant.json
# Markdown SHA-256:   fa401138dc20d1ecce22d1f2b16a0f803c971b9cb1ed9d24c0e299324a80ebe2
# Code AST SHA-256:   fa499ea50eec851dba9658930d74f40385c76a03256acbf64eb1a491938c594e
# Verified Classes:   ControlPlaneEvictionError, ContextController
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ControlPlaneEvictionError(RuntimeError):
    """Raised when a self-editing context controller attempts to evict a span
    that belongs to its own control plane (policy or pinned invariants)."""
    pass


class ContextController:
    def __init__(self, budget_tokens, mutable_spans, control_plane_spans):
        # control_plane_spans are structurally outside the budgeted region.
        self.budget = budget_tokens
        self.mutable = list(mutable_spans)          # scorers iterate only this
        self.control = dict(control_plane_spans)    # immutable; never scored

    def _tokens(self):
        return sum(len(s) for s in self.mutable)

    def compact(self, eviction_candidates, keep_manifest):
        """eviction_candidates: spans the scorer proposes to drop.
        Must never intersect the control plane."""
        control_keys = set(self.control.keys())
        for span_id in eviction_candidates:
            if span_id in control_keys:
                raise ControlPlaneEvictionError(
                    f"refusing to evict control-plane span {span_id!r}: "
                    "policy/invariant is not a retention candidate"
                )
        # Apply eviction only to mutable region.
        for span_id in eviction_candidates:
            self.mutable = [s for s in self.mutable if s.get("id") != span_id]
            keep_manifest.append(span_id)

        if self._tokens() > self.budget:
            # Fail closed: cannot satisfy budget without touching control plane.
            raise ControlPlaneEvictionError(
                f"budget {self.budget} unreachable from mutable region alone "
                f"({self._tokens()} tokens remain); escalate, do not reach into control plane"
            )
        return keep_manifest

    def verify_invariants(self):
        for key, val in self.control.items():
            if key not in self.control or self.control[key] is not val:
                raise ControlPlaneEvictionError(f"pinned invariant {key!r} mutated")
        return True
