# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-atomicity-when-auto-compaction-fires-between-a-side-effecting-call-and-its-result-receipt.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-atomicity-when-auto-compaction-fires-between-a-side-effecting-call-and-its-result-receipt.warrant.json
# Markdown SHA-256:   31fa0c06721067fd7fb6221b41933fe42ebfda038ea01611515e978e400af687
# Code AST SHA-256:   18103d0715a626d925f03ad1d45759e23bbef9b33434e64b258cbe8d524205ef
# Verified Classes:   CompactionAtomicityError, ToolCall, CompactionScheduler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CompactionAtomicityError(RuntimeError):
    """Raised when a compaction pass would cross a pending tool call."""
    pass


@dataclass
class ToolCall:
    call_id: str
    tool: str
    args: dict
    idempotency_key: str
    position: int


@dataclass
class CompactionScheduler:
    soft_token_threshold: int
    pending_calls: dict = field(default_factory=dict)  # call_id -> ToolCall

    def on_call_emitted(self, call: ToolCall) -> None:
        self.pending_calls[call.call_id] = call

    def on_receipt_arrived(self, call_id: str) -> None:
        # Receipt binds back to the call it answers; only then is it safe to compact past it.
        self.pending_calls.pop(call_id, None)

    def safe_cursor(self, tokens_used: int) -> int:
        """Return the highest token index compaction may consume up to."""
        if not self.pending_calls:
            return tokens_used
        # Fence at the earliest pending call: never consume its position or beyond.
        earliest = min(c.position for c in self.pending_calls.values())
        return min(tokens_used, earliest - 1)

    def plan_compaction(self, tokens_used: int) -> dict:
        if tokens_used < self.soft_token_threshold:
            return {"action": "none"}

        cursor = self.safe_cursor(tokens_used)

        if self.pending_calls and cursor < self.soft_token_threshold:
            # Deferral would exceed budget AND fencing would starve compaction.
            # Only the Annotate policy can proceed, and it must emit structured records.
            records = [
                {
                    "call_id": c.call_id,
                    "tool": c.tool,
                    "args_hash": hashlib.sha256(
                        repr(sorted(c.args.items())).encode()
                    ).hexdigest()[:16],
                    "idempotency_key": c.idempotency_key,
                    "status": "in_flight",
                }
                for c in self.pending_calls.values()
            ]
            return {
                "action": "compact_with_pending_records",
                "cursor": tokens_used,
                "pending_records": records,
            }

        if cursor < tokens_used:
            return {"action": "compact_fenced", "cursor": cursor}

        return {"action": "compact_full", "cursor": cursor}


def run_compaction_pass(scheduler: CompactionScheduler, tokens_used: int) -> dict:
    plan = scheduler.plan_compaction(tokens_used)

    if plan["action"] == "compact_with_pending_records":
        # Guardrail: the summarizer MUST NOT paraphrase these records.
        for rec in plan["pending_records"]:
            if rec["status"] != "in_flight" or not rec["idempotency_key"]:
                raise CompactionAtomicityError(
                    f"pending call {rec['call_id']} lacks idempotency key; "
                    f"compaction would orphan its receipt and permit duplicate side effects"
                )
        return plan

    if plan["action"] in ("compact_fenced", "compact_full"):
        for call in scheduler.pending_calls.values():
            if call.position <= plan["cursor"]:
                raise CompactionAtomicityError(
                    f"cursor {plan['cursor']} crosses pending call {call.call_id} "
                    f"at position {call.position}; defer or fence required"
                )
        return plan

    return plan
