# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-preempt-a-low-priority-sub-agent-to-preserve-a-shared-context-budget-and-why-does-cooperative-yielding-always-arrive-too-late.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-preempt-a-low-priority-sub-agent-to-preserve-a-shared-context-budget-and-why-does-cooperative-yielding-always-arrive-too-late.warrant.json
# Markdown SHA-256:   6279469e8a9a796f0b9b4de61b6d6eac17fa12e603a660492e993431bf4d3657
# Code AST SHA-256:   068cc48b7ffe5353250175a155e4c176322c7931b585eab30160b3fc253df880
# Verified Classes:   FloorBreachPreemptionRequired, BudgetLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class FloorBreachPreemptionRequired(RuntimeError):
    """Raised when an in-flight low-priority commit would breach a higher-priority floor."""
    pass


class BudgetLedger:
    def __init__(self, total: int):
        self.total = total
        self.committed = 0
        self.liabilities = {}  # agent_id -> upper-bound tokens in flight
        self.floors = {}       # agent_id -> reserved floor tokens

    def register(self, agent_id: str, priority: int, floor: int):
        self.floors[agent_id] = floor

    def dispatch_liability(self, agent_id: str, transport_max: Optional[int]):
        # If transport has no cap, the liability is the whole budget.
        self.liabilities[agent_id] = transport_max if transport_max is not None else self.total

    def clear_liability(self, agent_id: str):
        self.liabilities.pop(agent_id, None)

    def _floor_breach_if_committed(self, agent_id: str, size: int) -> Optional[str]:
        projected = self.committed + size
        for other, floor in self.floors.items():
            if other == agent_id:
                continue
            # Outstanding liabilities of OTHER agents also consume budget.
            outstanding = sum(
                v for k, v in self.liabilities.items() if k != agent_id
            )
            if projected + outstanding > self.total - floor:
                return other
        return None

    def admit_commit(self, agent_id: str, size: int) -> None:
        """Commit-time admission gate. Atomic with ledger mutation in production."""
        breached = self._floor_breach_if_committed(agent_id, size)
        if breached is not None:
            # Cooperative yield is too late: the result already returned.
            raise FloorBreachPreemptionRequired(
                f"commit of {size} tokens by {agent_id} would breach "
                f"floor of {breached}; preempt (cancel or quarantine), do not wait"
            )
        self.committed += size
        self.clear_liability(agent_id)


def on_tool_result(ledger: BudgetLedger, agent_id: str, result_tokens: int):
    try:
        ledger.admit_commit(agent_id, result_tokens)
    except FloorBreachPreemptionRequired:
        # Quarantine the append outside the shared window; evict lower-priority
        # re-derivable content, then re-attempt admission.
        raise
    return "admitted"
