# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-self-referential-token-accounting-trap-in-model-driven-context-rewrites.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-self-referential-token-accounting-trap-in-model-driven-context-rewrites.warrant.json
# Markdown SHA-256:   661a8d877daac680a986c0e69ad5c92afca0370e4d62b08d876dc248fb9644a4
# Code AST SHA-256:   a097c9a20f608f73df16187f4cbb371a02e23a066492c710d1a21fea3e33963e
# Verified Classes:   RewriteRefused, Surrogate, ContextWindow
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class RewriteRefused(RuntimeError):
    """Raised when a self-context rewrite cannot be proven safe within budget."""
    pass


@dataclass
class Surrogate:
    text: str
    token_count: int          # measured, not estimated
    provenance: list[str]     # span ids this surrogate replaced
    rewrite_depth: int        # 0 = from raw transcript, 1 = rewrite of a rewrite


@dataclass
class ContextWindow:
    budget: int
    occupancy: int
    side_log: dict[str, str] = field(default_factory=dict)
    tombstones: list[str] = field(default_factory=list)


def safe_rewrite(
    window: ContextWindow,
    span_tokens: int,
    surrogate: Surrogate,
    slot_budget: int,
    expected_reread: Optional[int],
    margin: float = 0.25,
    max_rewrite_depth: int = 1,
) -> ContextWindow:
    """Commit a self-rewrite only if the post-state is provably smaller by the
    cost of the next reasoning step. Otherwise refuse and tombstone."""

    # Invariant 3: never rewrite a rewrite (depth > max) without provenance.
    if surrogate.rewrite_depth > max_rewrite_depth:
        raise RewriteRefused(
            f"rewrite depth {surrogate.rewrite_depth} exceeds limit "
            f"{max_rewrite_depth}; distillation loss is unobservable"
        )
    if surrogate.rewrite_depth > 0 and not surrogate.provenance:
        raise RewriteRefused("rewrite-of-rewrite lacks provenance markers")

    # Invariant 2: surrogate must fit its slot with margin, measured post-generation.
    if surrogate.token_count > slot_budget * (1.0 - margin):
        raise RewriteRefused(
            f"surrogate {surrogate.token_count} tokens overruns slot "
            f"{slot_budget} at margin {margin}; re-compress or reject"
        )

    # Invariant 1: cost attribution closure — hidden re-read tax must be bounded.
    if expected_reread is None:
        raise RewriteRefused(
            "E[re-read] unbounded; rewrite is net-zero at best — "
            "fall back to evict-only with tombstone"
        )
    net_saved = span_tokens - surrogate.token_count - expected_reread
    if net_saved <= 0:
        raise RewriteRefused(
            f"net savings {net_saved} <= 0 after re-read tax "
            f"{expected_reread}; rewrite does not buy a reasoning step"
        )

    # Invariant 4: occupancy is measured, and the pre-rewrite span is side-logged.
    for span_id in surrogate.provenance or ["span"]:
        window.side_log[span_id] = f"rewritten->{surrogate.token_count}tok"
    new_occupancy = window.occupancy - span_tokens + surrogate.token_count
    if new_occupancy >= window.budget:
        raise RewriteRefused(
            f"post-rewrite occupancy {new_occupancy} >= budget {window.budget}"
        )

    window.occupancy = new_occupancy
    window.tombstones.append(
        f"[rewrote {span_tokens}tok -> {surrogate.token_count}tok, "
        f"reread_tax={expected_reread}, depth={surrogate.rewrite_depth}]"
    )
    return window


def evict_only(window: ContextWindow, span_tokens: int, span_id: str) -> ContextWindow:
    """Safe fallback: drop a consumed span, leave a loud tombstone."""
    window.side_log[span_id] = "evicted"
    window.occupancy -= span_tokens
    window.tombstones.append(f"[evicted {span_tokens}tok span={span_id}; re-read if needed]")
    return window
