# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-a-model-driven-context-rewrite-so-that-pruning-cannot-invalidate-an-in-flight-tool-call-s-argument-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-a-model-driven-context-rewrite-so-that-pruning-cannot-invalidate-an-in-flight-tool-call-s-argument-binding.warrant.json
# Markdown SHA-256:   23dbc470b3f574b05cb70899d46a469a50c1362f04a5f766c03cfc8640201372
# Code AST SHA-256:   249af697bdca928b31e26f70229dd580e114be5584c51afe99cba3194afc777f
# Verified Classes:   ContextRewriteViolation, Span, PendingCall, RewriteProposal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ContextRewriteViolation(RuntimeError):
    """Raised when a model-driven rewrite would sever a pending argument binding."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str


@dataclass
class PendingCall:
    call_id: str
    tool: str
    binding_span_ids: frozenset[str]


@dataclass
class RewriteProposal:
    # span_id -> replacement text (or None to prune entirely)
    edits: dict[str, str | None]
    # spans the rewrite model claims it preserved verbatim
    preserved_verbatim: frozenset[str] = field(default_factory=frozenset)


def apply_self_edit(
    spans: dict[str, Span],
    pending: Iterable[PendingCall],
    proposal: RewriteProposal,
) -> dict[str, Span]:
    """
    Apply a model-driven rewrite only if every pending call's argument-binding
    spans survive verbatim (or are replaced by a lossless reference span).
    """
    pinned: set[str] = set()
    for call in pending:
        pinned |= set(call.binding_span_ids)

    severed: list[tuple[str, str]] = []
    for span_id in pinned:
        if span_id not in spans:
            severed.append((span_id, "unknown-span"))
            continue
        if span_id in proposal.edits:
            replacement = proposal.edits[span_id]
            # A pinned span may only be edited if the replacement is a
            # lossless reference (declared verbatim) — never a paraphrase.
            if span_id not in proposal.preserved_verbatim:
                severed.append((span_id, "paraphrased-or-pruned"))
        # if not edited at all, it survives — fine

    if severed:
        raise ContextRewriteViolation(
            "self-edit would sever pending argument bindings: "
            + ", ".join(f"{sid}({why})" for sid, why in severed)
        )

    new_spans: dict[str, Span] = {}
    for span_id, span in spans.items():
        if span_id in proposal.edits:
            replacement = proposal.edits[span_id]
            if replacement is None:
                continue  # unpinned span pruned; safe
            new_spans[span_id] = Span(span_id, replacement)
        else:
            new_spans[span_id] = span
    return new_spans


def safe_rewrite_or_defer(
    spans: dict[str, Span],
    pending: list[PendingCall],
    proposal: RewriteProposal,
    token_budget: int,
) -> dict[str, Span]:
    try:
        return apply_self_edit(spans, pending, proposal)
    except ContextRewriteViolation:
        # Pinned spans alone exceed budget: defer, do not prune through the pin.
        pinned_tokens = sum(
            len(spans[sid].text.split())
            for call in pending for sid in call.binding_span_ids if sid in spans
        )
        if pinned_tokens > token_budget:
            raise ContextRewriteViolation(
                f"pinned bindings ({pinned_tokens} tokens) exceed budget "
                f"({token_budget}); defer rewrite and complete or abandon "
                f"pending calls explicitly"
            )
        raise
