# 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-and-the-summary-evicts-the-pending-call-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-tool-call-and-the-summary-evicts-the-pending-call-ledger.warrant.json
# Markdown SHA-256:   c3379c59a553240b29d8b2250bc6a8f25b8147b59fb7025af2fcf064fe101092
# Code AST SHA-256:   0496fbeb1615f2d21f0116354e7cd94163b12e15e762c5d1e5b0861b041b7ae7
# Verified Classes:   CompactionViolation, CallStatus, LedgerEntry, PendingCallLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict


class CompactionViolation(RuntimeError):
    """Raised when context compaction is attempted across a non-quiescent ledger."""
    pass


class CallStatus(Enum):
    ISSUED = "issued"        # sent, result not yet returned
    RETURNED = "returned"    # result arrived, not yet committed/consumed
    CONSUMED = "consumed"    # result committed to durable state


@dataclass
class LedgerEntry:
    call_id: str
    tool: str
    args_hash: str
    status: CallStatus


@dataclass
class PendingCallLedger:
    entries: Dict[str, LedgerEntry] = field(default_factory=dict)

    def issue(self, call_id: str, tool: str, args_hash: str) -> None:
        self.entries[call_id] = LedgerEntry(call_id, tool, args_hash, CallStatus.ISSUED)

    def returned(self, call_id: str) -> None:
        self.entries[call_id].status = CallStatus.RETURNED

    def consume(self, call_id: str) -> None:
        self.entries[call_id].status = CallStatus.CONSUMED

    def non_quiescent(self) -> list[LedgerEntry]:
        return [e for e in self.entries.values() if e.status is not CallStatus.CONSUMED]


def maybe_compact(utilization: float, threshold: float, ledger: PendingCallLedger,
                  can_externalize: bool) -> str:
    """Compaction is admissible only at a quiescent point, OR when the ledger
    can be externalized atomically out-of-context before the semantic region
    is summarized. Utilization alone is never sufficient."""
    if utilization < threshold:
        return "no-op"

    stuck = ledger.non_quiescent()
    if not stuck:
        return "compact:quiescent"

    if can_externalize:
        # Ledger routed around the summarizer, persisted verbatim, re-hydrated post-compaction.
        return "compact:externalized"

    # Unsound path: would summarize in-flight transactions and lose correlation IDs.
    ids = ", ".join(e.call_id for e in stuck)
    raise CompactionViolation(
        f"compaction blocked: {len(stuck)} non-quiescent call(s) [{ids}] would be "
        f"summarized mid-transaction; drain or externalize the ledger first"
    )
