# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-rewrite-the-eviction-rewrite-non-commutativity-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-rewrite-the-eviction-rewrite-non-commutativity-invariant.warrant.json
# Markdown SHA-256:   2266e3e36fd3fe4fc28fe8c4ae7e0cc29da6c0723e1e08cdc6be4649c3a55ef6
# Code AST SHA-256:   7fbdea4f9b32f0ba45cabf01e13ea228c9ed4cb1135125f6e6a6d07c964cf5ff
# Verified Classes:   ProvenanceEvictionError, Rewrite, ContextBuffer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceEvictionError(RuntimeError):
    """Raised when a context mutation would orphan a resident rewrite's provenance."""


@dataclass(frozen=True)
class Rewrite:
    rewrite_id: str
    text: str
    provenance: FrozenSet[str]  # span IDs the rewrite was conditioned on


@dataclass
class ContextBuffer:
    resident_spans: set = field(default_factory=set)
    rewrites: dict = field(default_factory=dict)
    audit_tier: set = field(default_factory=set)

    def apply_rewrite(self, rw: Rewrite) -> None:
        if not rw.provenance:
            raise ProvenanceEvictionError(
                f"rewrite {rw.rewrite_id!r} has empty provenance; refusing to commit"
            )
        missing = rw.provenance - self.resident_spans - self.audit_tier
        if missing:
            raise ProvenanceEvictionError(
                f"rewrite {rw.rewrite_id!r} cites non-resident spans {sorted(missing)}"
            )
        self.rewrites[rw.rewrite_id] = rw

    def evict(self, span_id: str) -> None:
        if span_id in self.audit_tier:
            self.resident_spans.discard(span_id)
            return
        blocking = [
            rid for rid, rw in self.rewrites.items() if span_id in rw.provenance
        ]
        if blocking:
            raise ProvenanceEvictionError(
                f"cannot evict span {span_id!r}: provenance of rewrites {sorted(blocking)}; "
                f"promote to audit tier or refuse"
            )
        self.resident_spans.discard(span_id)

    def promote_to_audit(self, span_id: str) -> None:
        if span_id not in self.resident_spans:
            raise ProvenanceEvictionError(f"span {span_id!r} not resident; cannot promote")
        self.audit_tier.add(span_id)


def commit_policy_step(buf: ContextBuffer, rw: Rewrite, evictions: list) -> None:
    # Order matters: commit rewrite first so its provenance protects spans from eviction.
    buf.apply_rewrite(rw)
    for span_id in evictions:
        try:
            buf.evict(span_id)
        except ProvenanceEvictionError:
            buf.promote_to_audit(span_id)
            buf.evict(span_id)


if __name__ == "__main__":
    buf = ContextBuffer(resident_spans={"s1", "s2", "s3"})
    rw = Rewrite("rw-1", "latency budget set to 850ms", frozenset({"s2"}))
    # s2 is the only span carrying the figure; evicting it would orphan rw-1.
    commit_policy_step(buf, rw, evictions=["s3", "s2"])
    assert "s2" in buf.audit_tier
    try:
        buf.apply_rewrite(Rewrite("rw-2", "inferred: budget raised", frozenset()))
    except ProvenanceEvictionError as e:
        print("refused:", e)
