# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-model-driven-context-pruning-from-invalidating-outstanding-tool-call-references.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-model-driven-context-pruning-from-invalidating-outstanding-tool-call-references.warrant.json
# Markdown SHA-256:   4ccc0484a19088d1fa24be9d75c53211a160dc21b1755b32dc06a1d13401dd2c
# Code AST SHA-256:   115acdbfdbb52217e42c747d4f3c4b3a8d9552a459b489a600db5e1ba299335c
# Verified Classes:   PruneViolation, CallState, Invocation, ContextRuntime
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class PruneViolation(RuntimeError):
    """Raised when a proposed prune would orphan or duplicate a live tool call."""
    pass


class CallState(Enum):
    PENDING = "pending"
    RESOLVED = "resolved"
    ERRORED = "errored"
    CANCELLED = "cancelled"


@dataclass
class Invocation:
    call_id: str
    span_start: int
    span_end: int
    state: CallState = CallState.PENDING


@dataclass
class ContextRuntime:
    invocations: dict[str, Invocation] = field(default_factory=dict)

    def register(self, call_id: str, start: int, end: int) -> None:
        self.invocations[call_id] = Invocation(call_id, start, end)

    def resolve(self, call_id: str, ok: bool) -> None:
        inv = self.invocations.get(call_id)
        if inv is None:
            raise PruneViolation(f"result for unknown call_id {call_id!r}")
        if inv.state is not CallState.PENDING:
            raise PruneViolation(f"duplicate result for {call_id!r} in state {inv.state}")
        inv.state = CallState.RESOLVED if ok else CallState.ERRORED

    def validate_prune(self, span_start: int, span_end: int) -> None:
        """Veto any prune that touches a pending invocation or its sole record."""
        for inv in self.invocations.values():
            overlaps = not (inv.span_end <= span_start or inv.span_start >= span_end)
            if not overlaps:
                continue
            if inv.state is CallState.PENDING:
                raise PruneViolation(
                    f"prune [{span_start}:{span_end}] overlaps pending call "
                    f"{inv.call_id!r}; result would be orphaned"
                )
            # resolved calls: pruning the invocation record is allowed only
            # if the binding map survives elsewhere; here we require the
            # caller to pass preserve_bindings=True, simulated by retaining
            # the invocation object in the table.
        return None

    def prune(self, span_start: int, span_end: int, preserve_bindings: bool) -> None:
        self.validate_prune(span_start, span_end)
        if not preserve_bindings:
            for cid, inv in list(self.invocations.items()):
                overlaps = not (inv.span_end <= span_start or inv.span_start >= span_end)
                if overlaps:
                    raise PruneViolation(
                        f"prune would delete sole binding record for {cid!r}; "
                        f"re-issue risk"
                    )
        # span removal from the actual token buffer happens here


def apply_model_prune_plan(rt: ContextRuntime, plan, preserve_bindings: bool) -> None:
    if not plan:
        raise PruneViolation("empty prune plan submitted by model")
    for span_start, span_end in plan:
        rt.prune(span_start, span_end, preserve_bindings)


if __name__ == "__main__":
    rt = ContextRuntime()
    rt.register("call_a", 100, 140)
    rt.register("call_b", 141, 180)
    # model proposes collapsing both pending invocations into a summary line
    try:
        apply_model_prune_plan(rt, [(100, 180)], preserve_bindings=True)
    except PruneViolation as e:
        print("vetoed:", e)
    rt.resolve("call_a", ok=True)
    rt.resolve("call_b", ok=True)
    apply_model_prune_plan(rt, [(100, 180)], preserve_bindings=True)
    print("prune accepted after quiescence")
