# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-auto-compaction-from-silently-invalidating-in-flight-tool-call-references.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-auto-compaction-from-silently-invalidating-in-flight-tool-call-references.warrant.json
# Markdown SHA-256:   9784779095c3ca2e7a4098a807d343e516816bda19045fa4096f78a2e9ba56e5
# Code AST SHA-256:   17ec08154eedf9c8627c598b76bb29276d41c7e7afd503ebc749fcdbea4583ca
# Verified Classes:   DanglingToolReferenceError, CompactionOverflow, Block, Transcript, ExecutionLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class DanglingToolReferenceError(RuntimeError):
    """Raised when a compaction plan would sever a tool_use/tool_result pairing
    or evict an in-flight call whose result has not yet been appended."""


class CompactionOverflow(RuntimeError):
    """Raised when the pinned open-reference set cannot fit in the window and
    compaction must be deferred to a checkpoint-and-resume boundary."""


@dataclass(frozen=True)
class Block:
    kind: str                      # "tool_use" | "tool_result" | "text"
    call_id: Optional[str] = None
    args: Optional[str] = None     # only for tool_use
    result: Optional[str] = None   # only for tool_result


@dataclass
class Transcript:
    blocks: list[Block] = field(default_factory=list)

    def open_reference_ids(self) -> set[str]:
        uses = {b.call_id for b in self.blocks if b.kind == "tool_use"}
        results = {b.call_id for b in self.blocks if b.kind == "tool_result"}
        # pending calls (use without result) AND orphan results (result without use)
        return (uses - results) | (results - uses)


def plan_compaction(
    transcript: Transcript,
    evict_indices: set[int],
    window_tokens: int,
    current_tokens: int,
    reserved_for_pins: int,
) -> set[int]:
    """Return the actually-evictable index set, or raise if the plan is invalid.

    Invariant enforced: compaction is a no-op on the open-reference set O(T).
    """
    open_ids = transcript.open_reference_ids()
    pins: set[int] = set()

    for i, b in enumerate(transcript.blocks):
        if b.call_id in open_ids:
            pins.add(i)

    # In-flight exclusion: no pinned (open-reference) block may be evicted.
    violated = pins & evict_indices
    if violated:
        raise DanglingToolReferenceError(
            f"compaction would evict open-reference blocks at indices "
            f"{sorted(violated)} (call_ids="
            f"{sorted(transcript.blocks[i].call_id for i in violated)}); "
            f"defer or pin these verbatim"
        )

    # Pairing closure: for any retained tool_use, its result must also be
    # retained, and vice versa. Check the retained set after eviction.
    retained = [i for i in range(len(transcript.blocks)) if i not in evict_indices]
    uses = {transcript.blocks[i].call_id for i in retained
            if transcript.blocks[i].kind == "tool_use"}
    results = {transcript.blocks[i].call_id for i in retained
               if transcript.blocks[i].kind == "tool_result"}
    if uses != results:
        raise DanglingToolReferenceError(
            f"half-triple after compaction: uses_only={sorted(uses - results)}, "
            f"results_only={sorted(results - uses)}"
        )

    # Reserved-budget check: pins must fit in the non-reclaimable budget.
    if reserved_for_pins < 0 or reserved_for_pins > window_tokens:
        raise CompactionOverflow(
            f"pinned open-reference budget {reserved_for_pins} exceeds window "
            f"{window_tokens}; checkpoint-and-resume required"
        )
    if current_tokens > window_tokens - reserved_for_pins and not evict_indices:
        raise CompactionOverflow(
            "window saturated by pinned open references; cannot compact safely"
        )

    return evict_indices


def canonical_args_hash(tool_name: str, args: str) -> str:
    return hashlib.sha256(f"{tool_name}\x00{args}".encode()).hexdigest()


class ExecutionLedger:
    """Survives compaction and resume; gates re-execution of non-idempotent tools."""

    def __init__(self) -> None:
        self._seen: dict[str, str] = {}

    def execute_once(self, tool_name: str, args: str, run) -> str:
        key = canonical_args_hash(tool_name, args)
        if key in self._seen:
            return self._seen[key]
        out = run(tool_name, args)
        self._seen[key] = out
        return out
