# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-corrupt-its-own-working-set-when-auto-compaction-summarizes-a-transcript-that-is-still-being-appended-to.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-corrupt-its-own-working-set-when-auto-compaction-summarizes-a-transcript-that-is-still-being-appended-to.warrant.json
# Markdown SHA-256:   e69c6544711e7fb90da0df7d56fd4e4f1bd45863552e1df67ebe87efc4ea489d
# Code AST SHA-256:   3a37a879c910d040c7dc31681489137d485cccc4fbce90c74d8bc5e715dba7df
# Verified Classes:   CompactionViolation, Handle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class CompactionViolation(RuntimeError):
    """Raised when live compaction would elide an outstanding obligation."""
    pass


@dataclass(frozen=True)
class Handle:
    kind: str      # "tool_use" | "dispatch" | "callback"
    handle_id: str


def pending_handles(transcript: Iterable[dict]) -> set[Handle]:
    """Collect every handle the runtime is still obligated to resolve."""
    open_uses: dict[str, Handle] = {}
    open_dispatches: dict[str, Handle] = {}
    for block in transcript:
        btype = block.get("type")
        if btype == "tool_use":
            open_uses[block["id"]] = Handle("tool_use", block["id"])
        elif btype == "tool_result":
            open_uses.pop(block.get("tool_use_id"), None)
        elif btype == "dispatch":
            open_dispatches[block["id"]] = Handle("dispatch", block["id"])
        elif btype == "join":
            open_dispatches.pop(block.get("dispatch_id"), None)
    return set(open_uses.values()) | set(open_dispatches.values())


def compact(transcript: list[dict], summarizer, max_drain_wait: float = 30.0) -> list[dict]:
    """
    Compact only against a quiescent transcript. If handles are outstanding,
    defer; if the drain window expires, record explicit timeout turns and
    re-check. Never install a summary that drops a pinned handle.
    """
    outstanding = pending_handles(transcript)
    if outstanding:
        # Bounded drain: wait, then convert each outstanding handle into an
        # explicit timeout turn so the transcript becomes a closed set.
        transcript = _drain(transcript, outstanding, max_drain_wait)
        outstanding = pending_handles(transcript)
        if outstanding:
            raise CompactionViolation(
                f"refusing to compact with {len(outstanding)} unresolved handles "
                f"after {max_drain_wait}s drain: "
                f"{sorted(h.handle_id for h in outstanding)}"
            )

    pinned = {h.handle_id for h in pending_handles(transcript)}  # empty, but explicit
    summary = summarizer(transcript)

    surviving = {b.get("id") for b in summary if b.get("id")}
    dropped = pinned - surviving
    if dropped:
        raise CompactionViolation(
            f"compaction elided pinned handles: {sorted(dropped)}"
        )
    return summary


def _drain(transcript: list[dict], outstanding: set[Handle], wait: float) -> list[dict]:
    """Convert unresolved handles into explicit timeout turns after wait."""
    out = list(transcript)
    for h in outstanding:
        out.append({
            "type": "timeout",
            "handle_id": h.handle_id,
            "kind": h.kind,
            "reason": f"drain window {wait}s expired before resolution",
        })
    return out
