# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-negotiation-deadlock-under-partial-observability-the-phantom-capability-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-negotiation-deadlock-under-partial-observability-the-phantom-capability-boundary.warrant.json
# Markdown SHA-256:   502f7347270a4c37b134e5ce99498769dd33aace72b6e40d270009f3831e6dd4
# Code AST SHA-256:   3f5c49e71fb1b202efb7a7e1401153b7f55fb74f39d0fbdecbd8430087cabbe8
# Verified Classes:   NegotiationDeadlockError, Advertisement, NegotiationState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Optional


class NegotiationDeadlockError(RuntimeError):
    """Raised when a capability negotiation cannot make progress under partial observability."""
    pass


@dataclass(frozen=True)
class Advertisement:
    capability: str
    binding_epoch: int          # monotonic; bumps when live binding state changes
    budget_delta: int           # remaining capacity at send time


@dataclass
class NegotiationState:
    peer: str
    capability: str
    last_seen_epoch: int = -1
    last_failure_epoch: int = -1
    defer_cycles: int = 0
    escalation_owner: bool = False
    max_defer_cycles: int = 5


def evaluate_advertisement(state: NegotiationState, adv: Advertisement) -> str:
    """Return 'schedule', 'defer', or 'unavailable'. Raise on unresolvable livelock."""
    if adv.capability != state.capability:
        raise NegotiationDeadlockError(
            f"capability mismatch: expected {state.capability}, got {adv.capability}"
        )

    # Stale advertisement: peer's binding epoch predates our last known failure.
    if adv.binding_epoch < state.last_failure_epoch:
        return "unavailable"

    # No observable state change since last cycle -> deferral is not progress.
    if adv.binding_epoch == state.last_seen_epoch and adv.budget_delta <= 0:
        state.defer_cycles += 1
        if state.escalation_owner and state.defer_cycles > state.max_defer_cycles:
            raise NegotiationDeadlockError(
                f"livelock on ({state.peer}, {state.capability}): "
                f"{state.defer_cycles} defer cycles at epoch {adv.binding_epoch}, "
                f"no budget, escalation owner cannot force progress"
            )
        return "defer"

    state.last_seen_epoch = adv.binding_epoch
    state.defer_cycles = 0
    return "schedule" if adv.budget_delta > 0 else "defer"


def negotiate(state: NegotiationState, adv: Advertisement) -> str:
    try:
        return evaluate_advertisement(state, adv)
    except NegotiationDeadlockError:
        # Convert deadlock into a terminal, schedulable failure rather than retrying.
        state.last_failure_epoch = max(state.last_failure_epoch, adv.binding_epoch)
        return "unavailable"
