# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-driven-context-rewrite-that-would-orphan-a-live-tool-call-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-driven-context-rewrite-that-would-orphan-a-live-tool-call-continuation.warrant.json
# Markdown SHA-256:   29a44025e275a6733d561e37112d92e0a16fe70a0943f16b4eb6e3e7faeeb21b
# Code AST SHA-256:   772e520c475a9994c370f5d4cc490f7e9dff0a945d6bfc5f5ad8c83c539f1437
# Verified Classes:   ContextRewriteViolation, Span, PrunePlan
# 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-proposed prune plan would orphan a live continuation."""


@dataclass
class Span:
    index: int
    kind: str            # "tool_use" | "tool_result" | "text" | "summary"
    refs: set[str] = field(default_factory=set)   # identifiers this span defines
    uses: set[str] = field(default_factory=set)   # identifiers this span consumes
    pair_id: str | None = None


@dataclass
class PrunePlan:
    drop: set[int]
    summarize: set[int]


def validate_prune_plan(spans: list[Span], plan: PrunePlan) -> set[int]:
    """
    Returns the set of indices that are actually safe to drop.
    Raises ContextRewriteViolation if the plan severs a live call/result pair
    or drops the sole retained source of an identifier still in use.
    """
    by_index = {s.index: s for s in spans}
    retained = [s for s in spans if s.index not in plan.drop and s.index not in plan.summarize]

    # 1. Call/result atomicity: a pair may be dropped only as a whole.
    pair_members: dict[str, set[int]] = {}
    for s in spans:
        if s.pair_id is not None:
            pair_members.setdefault(s.pair_id, set()).add(s.index)
    for pid, members in pair_members.items():
        dropped = members & plan.drop
        if dropped and dropped != members:
            raise ContextRewriteViolation(
                f"plan severs tool pair {pid!r}: drops {sorted(dropped)} "
                f"but retains {sorted(members - dropped)}"
            )

    # 2. Referential closure: no retained span may use an identifier whose
    #    only retained source lives inside a dropped/summarized span.
    removed = plan.drop | plan.summarize
    retained_sources: set[str] = set()
    for s in retained:
        retained_sources |= s.refs
    for s in retained:
        orphaned = {u for u in s.uses if u not in retained_sources}
        # An orphan is only fatal if its source was in fact removed.
        for u in s.uses:
            source_was_removed = any(
                u in by_index[i].refs for i in removed if i in by_index
            )
            if source_was_removed and u not in retained_sources:
                raise ContextRewriteViolation(
                    f"span {s.index} uses {u!r}, whose only source is being "
                    f"removed; re-fetch required before rewrite"
                )

    # 3. Continuation safety: a tool_use awaiting a result is never droppable.
    for s in spans:
        if s.kind == "tool_use" and s.pair_id is not None:
            has_result = any(
                t.kind == "tool_result" and t.pair_id == s.pair_id for t in spans
            )
            if not has_result and s.index in plan.drop:
                raise ContextRewriteViolation(
                    f"span {s.index} is an open tool_use with no result; "
                    f"cannot drop a pending continuation"
                )

    return set(plan.drop)


def apply_plan(spans: list[Span], plan: PrunePlan) -> list[Span]:
    safe = validate_prune_plan(spans, plan)
    return [s for s in spans if s.index not in safe and s.index not in plan.summarize]
