# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-shared-substrate-context-budget-arbitration-from-silently-starving-a-sub-agent-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-shared-substrate-context-budget-arbitration-from-silently-starving-a-sub-agent-mid-tool-call.warrant.json
# Markdown SHA-256:   2da61ab2eea35ff8e48e5667e9bbd8cb0bbadc21e4085f639809e5a4db07a013
# Code AST SHA-256:   480a8ea1388a61eb0bdbf3e3577852e8e683a8db9a6e8255faf75b9c3095ed0a
# Verified Classes:   SharedSubstrateLeaseError, Reservation, Arbiter
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SharedSubstrateLeaseError(RuntimeError):
    """Raised when a reservation is revoked or overwritten while a tool call is in flight."""
    pass


class Reservation:
    def __init__(self, agent_id: str, base: int, size: int):
        self.agent_id = agent_id
        self.base = base
        self.size = size
        self.call_token = None          # live tool call, if any
        self.revoked = False

    def region(self):
        return range(self.base, self.base + self.size)


class Arbiter:
    def __init__(self):
        self.reservations: dict[str, Reservation] = {}

    def emit_tool_call(self, agent_id: str) -> None:
        res = self.reservations[agent_id]
        # Deposit call-token: reservation is now held-in-flight, non-reclaimable.
        res.call_token = f"{agent_id}:call"

    def tool_result(self, agent_id: str) -> None:
        res = self.reservations[agent_id]
        res.call_token = None           # Clear: back to reclaimable.

    def reclaim(self, agent_id: str, need: int) -> int:
        res = self.reservations[agent_id]
        # INVARIANT: never reclaim a reservation with a live call-token.
        if res.call_token is not None:
            raise SharedSubstrateLeaseError(
                f"refusing to reclaim {need} from {agent_id}: "
                f"tool call {res.call_token} in flight (held-in-flight, not held-idle)"
            )
        take = min(need, res.size)
        res.size -= take
        return take

    def write_result(self, agent_id: str, payload: int) -> None:
        res = self.reservations[agent_id]
        if res.revoked or payload > res.size:
            raise SharedSubstrateLeaseError(
                f"agent {agent_id} writing {payload} into slot of size {res.size}: "
                f"stale reservation — result has no exclusive landing region"
            )
        # write lands in res.region() exclusively
