# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-session-mid-tool-call-and-the-summarizer-s-preserve-all-pending-actions-guarantee-silently-drops-the-argument.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-session-mid-tool-call-and-the-summarizer-s-preserve-all-pending-actions-guarantee-silently-drops-the-argument.warrant.json
# Markdown SHA-256:   34a0b0bbd8ce0a4db96e42cf0c2f208ab19462b5c61e42a68bbeb7af0cb5d0a2
# Code AST SHA-256:   6f1c8ee2b5724032b5d81823db43996448cedf6b1133a397dc8e0de3f0f2a550
# Verified Classes:   CompactionBoundaryError, FrozenCall, CallLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field
from typing import Any


class CompactionBoundaryError(RuntimeError):
    """Raised when compaction crosses an open call without a replayable binding."""
    pass


@dataclass
class FrozenCall:
    call_id: str
    tool: str
    exact_args: dict[str, Any]  # byte-reproducible, not paraphrased
    status: str = "frozen"      # frozen -> resolved | abandoned


@dataclass
class CallLedger:
    # Lives OUTSIDE the summarized transcript. Compaction never rewrites this.
    calls: dict[str, FrozenCall] = field(default_factory=dict)

    def open(self, call_id: str, tool: str, exact_args: dict[str, Any]) -> None:
        self.calls[call_id] = FrozenCall(call_id, tool, exact_args, status="open")

    def freeze_open_calls(self) -> list[str]:
        frozen = []
        for c in self.calls.values():
            if c.status == "open":
                c.status = "frozen"
                frozen.append(c.call_id)
        return frozen

    def resolve(self, call_id: str, result: Any) -> FrozenCall:
        c = self.calls.get(call_id)
        if c is None:
            raise CompactionBoundaryError(
                f"result for unknown call_id {call_id!r}: compaction dropped the binding"
            )
        if c.status != "frozen":
            raise CompactionBoundaryError(
                f"call {call_id!r} resolved in status {c.status!r}; expected 'frozen'"
            )
        c.status = "resolved"
        return c


def compact_session(
    transcript: str,
    ledger: CallLedger,
    summarize,
    headroom_tokens: int,
    max_tool_timeout_s: float,
    token_rate_per_s: float,
) -> str:
    """Compact, but refuse to cross an open call unless it is replayable from the ledger."""
    open_ids = [c.call_id for c in ledger.calls.values() if c.status == "open"]

    if open_ids:
        # Quiesce-then-compact is sound only if headroom outlasts the slowest tool.
        if headroom_tokens < max_tool_timeout_s * token_rate_per_s:
            frozen = ledger.freeze_open_calls()
            if not frozen:
                raise CompactionBoundaryError("open calls present but none could be frozen")
            # Frozen calls are carried verbatim; the summary must not paraphrase them.
            carry = json.dumps(
                [{"call_id": c.call_id, "tool": c.tool, "args": c.exact_args}
                 for c in ledger.calls.values() if c.status == "frozen"],
                sort_keys=True,
            )
            summary = summarize(transcript)
            return f"{summary}\n\n<frozen_calls>{carry}</frozen_calls>"
        # Headroom is sufficient: defer compaction until calls resolve.
        return transcript  # caller retries at next quiescent boundary

    return summarize(transcript)


def on_tool_result(ledger: CallLedger, call_id: str, result: Any,
                   model_reissued: bool) -> FrozenCall:
    """Resume path: bind result to the frozen call, never to a reconstructed one."""
    if model_reissued:
        raise CompactionBoundaryError(
            f"model re-issued call {call_id!r} after compaction; "
            f"arguments were reconstructed from summary, not replayed from ledger"
        )
    return ledger.resolve(call_id, result)
