# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-tool-call-the-dangling-invocation-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-tool-call-the-dangling-invocation-invariant.warrant.json
# Markdown SHA-256:   19fa2ffa796d9836ede682e2c4a84b6bd3d84d128f7b1ed8810f465c172e681b
# Code AST SHA-256:   1091082d5ddcc2ce57c29bf4e51d71a2a84f3fd3f7295751bc13517eb23742cd
# Verified Classes:   DanglingInvocationError, ToolCall, History
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DanglingInvocationError(RuntimeError):
    """Raised when a compaction pass would split a tool_use/tool_result pair,
    or when the pinned open-call mass makes the token deficit unreachable."""


@dataclass
class ToolCall:
    call_id: str
    resolved: bool = False


@dataclass
class History:
    total_tokens: int
    open_calls: list[ToolCall] = field(default_factory=list)
    pinned_tokens: int = 0          # tokens occupied by open calls' messages
    soft_threshold: int = 100_000   # trigger point
    hard_limit: int = 128_000       # provider window


def compact(history: History, summarizer) -> History:
    """Compact history under the open-call-set invariant.

    Precondition (the invariant): compaction may not evict a tool_use whose
    tool_result has not yet been appended, nor append a tool_result whose
    tool_use is not retained. We enforce the *feasibility* half here: if the
    pinned open-call region alone cannot be brought under threshold, compaction
    must block rather than corrupt.
    """
    deficit = history.total_tokens - history.soft_threshold

    # Open calls are atomic units; they are pinned verbatim, never summarized.
    evictable_mass = history.total_tokens - history.pinned_tokens

    if history.open_calls and evictable_mass < deficit:
        # Compaction cannot satisfy both the token budget and call-pair
        # atomicity. Block: let the call resolve, or cancel and synthesize
        # an explicit error tool_result to close the pair.
        raise DanglingInvocationError(
            f"cannot compact: {len(history.open_calls)} open call(s) pin "
            f"{history.pinned_tokens} tokens; evictable mass {evictable_mass} "
            f"< deficit {deficit}. Suspend compaction and resolve calls "
            f"{[c.call_id for c in history.open_calls]} first."
        )

    # Summarize only the evictable region; carry open calls verbatim.
    summary_tokens = summarizer.summarize(
        history,
        pin_ids=[c.call_id for c in history.open_calls],
    )
    new_total = summary_tokens + history.pinned_tokens

    if new_total > history.hard_limit:
        raise DanglingInvocationError(
            f"post-compaction size {new_total} exceeds hard limit "
            f"{history.hard_limit}; pinned open calls dominate."
        )

    return History(
        total_tokens=new_total,
        open_calls=history.open_calls,   # preserved, unresolved
        pinned_tokens=history.pinned_tokens,
        soft_threshold=history.soft_threshold,
        hard_limit=history.hard_limit,
    )


def reconcile_result(history: History, call_id: str, result_tokens: int) -> History:
    """Close an open call by appending its tool_result against the retained
    tool_use. Fails if the call was evicted (dangling result)."""
    match: Optional[ToolCall] = next(
        (c for c in history.open_calls if c.call_id == call_id), None
    )
    if match is None:
        raise DanglingInvocationError(
            f"tool_result for {call_id} has no retained tool_use; "
            f"compaction evicted the invocation. Transcript is corrupt."
        )
    match.resolved = True
    history.open_calls = [c for c in history.open_calls if not c.resolved]
    history.pinned_tokens = max(0, history.pinned_tokens - result_tokens)
    history.total_tokens += result_tokens
    return history
