# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-prompt-rewriting-as-a-transactional-boundary-rather-than-a-best-effort-optimization.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-prompt-rewriting-as-a-transactional-boundary-rather-than-a-best-effort-optimization.warrant.json
# Markdown SHA-256:   70bf160f27488d5766a946a68da747a59b3f23d35d7cdde7b526236bec3551e4
# Code AST SHA-256:   b946ba29f25af241b8e9000bd04c6df31e3c1d844bc772437b07b1542118dd59
# Verified Classes:   ContextRewriteBoundaryError, ContextState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set


class ContextRewriteBoundaryError(RuntimeError):
    """Raised when a context rewrite would orphan an open commitment."""
    pass


@dataclass
class ContextState:
    epoch: int = 0
    open_commitments: Set[str] = field(default_factory=set)  # in-flight calls, pending plan steps
    utilization: float = 0.0


def apply_rewrite(state: ContextState, removes_tokens: bool, is_system_prompt: bool) -> ContextState:
    if removes_tokens and state.open_commitments:
        # A destructive rewrite with any open commitment violates atomicity.
        raise ContextRewriteBoundaryError(
            f"refusing destructive rewrite at epoch {state.epoch}: "
            f"open commitments {sorted(state.open_commitments)} would be orphaned"
        )
    new_epoch = state.epoch + (1 if is_system_prompt else 0)
    if is_system_prompt and state.open_commitments:
        # Even append-only system-prompt rewrites cannot cross an in-flight generation.
        raise ContextRewriteBoundaryError(
            f"system prompt rewrite at epoch {state.epoch} with in-flight work "
            f"{sorted(state.open_commitments)}; queue until turn boundary"
        )
    return ContextState(
        epoch=new_epoch,
        open_commitments=set(state.open_commitments),
        utilization=state.utilization,
    )


def prune_under_budget(state: ContextState, target: float) -> ContextState:
    if state.utilization <= target:
        return state
    # Hard budget exceeded mid-turn: fail closed rather than silently truncate.
    if state.open_commitments:
        raise ContextRewriteBoundaryError(
            f"budget {state.utilization:.2f} > {target:.2f} with open commitments; "
            f"fail closed instead of truncating"
        )
    return apply_rewrite(state, removes_tokens=True, is_system_prompt=False)


# Example: the observed lost-update sequence.
state = ContextState(epoch=3, open_commitments={"edit_file:X", "plan:run-tests-X"}, utilization=0.86)
try:
    state = prune_under_budget(state, target=0.85)
except ContextRewriteBoundaryError as e:
    # Recoverable: abort the turn, surface the error, retry after result is folded in.
    print(f"turn aborted safely: {e}")
