# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-mcp-capability-lease-after-a-partial-failure-stream-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-mcp-capability-lease-after-a-partial-failure-stream-reconnect.warrant.json
# Markdown SHA-256:   f87552d616c8990c74cb2c055ae02ae6fe63451e1a75c0cf3c29c75411e5eb18
# Code AST SHA-256:   0b1f5cb3f6ee49eec950438a447fe615282555e3c52e494c2e50cdc8c54f130b
# Verified Classes:   StaleCapabilityLease, CapabilityLease, ReconnectResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, Optional


class StaleCapabilityLease(RuntimeError):
    """Raised when a cached MCP capability cannot be fenced against the
    current server incarnation after a stream reconnect."""


@dataclass
class CapabilityLease:
    incarnation: Optional[str]          # server epoch/UUID; None == no witness
    capabilities: Dict[str, bool]       # e.g. {"resources.subscribe": True}
    channel_hwm: Dict[str, int] = field(default_factory=dict)  # per-channel high-water marks


@dataclass
class ReconnectResult:
    session_id: str
    incarnation: Optional[str]
    replayed_hwm: Dict[str, int]        # what the server could replay per channel
    capabilities: Dict[str, bool]


def validate_lease_after_reconnect(
    lease: CapabilityLease, reconnect: ReconnectResult
) -> CapabilityLease:
    """Fence a cached capability lease against a post-reconnect server state.

    Returns a (possibly narrowed) lease that is safe to use. Raises
    StaleCapabilityLease when the lease cannot be proven valid and the caller
    must perform a full renegotiation before issuing dependent requests.
    """
    # Guardrail 1: incarnation fencing. No witness == no proof == fail closed.
    if lease.incarnation is None or reconnect.incarnation is None:
        raise StaleCapabilityLease(
            "no incarnation witness; cannot distinguish benign reconnect from "
            "backend swap; full renegotiation required"
        )
    if lease.incarnation != reconnect.incarnation:
        raise StaleCapabilityLease(
            f"incarnation changed {lease.incarnation!r} -> "
            f"{reconnect.incarnation!r}; cached capabilities are void"
        )

    # Guardrail 2: per-channel continuity. A channel whose replay cannot cover
    # the client's high-water mark has silently lost events; any capability
    # backed by that channel is unverified.
    narrowed: Dict[str, bool] = dict(reconnect.capabilities)
    for channel, hwm in lease.channel_hwm.items():
        replayed = reconnect.replayed_hwm.get(channel, -1)
        if replayed < hwm:
            backing = _capability_backing(channel)
            if backing and narrowed.get(backing, False):
                narrowed[backing] = False  # demote to unverified
                raise StaleCapabilityLease(
                    f"channel {channel!r} replay gap (hwm={hwm}, "
                    f"replayed={replayed}); capability {backing!r} demoted, "
                    f"renegotiate before use"
                )

    return CapabilityLease(
        incarnation=reconnect.incarnation,
        capabilities=narrowed,
        channel_hwm=dict(reconnect.replayed_hwm),
    )


def _capability_backing(channel: str) -> Optional[str]:
    if channel.startswith("resources/updated:"):
        return "resources.subscribe"
    if channel == "tools/list_changed":
        return "tools.listChanged"
    if channel == "resources/list_changed":
        return "resources.listChanged"
    return None


def guarded_request(
    lease: CapabilityLease, capability: str, negative_response: bool
) -> None:
    """Issue a request gated on the lease; demote on negative response."""
    if not lease.capabilities.get(capability, False):
        raise StaleCapabilityLease(
            f"capability {capability!r} not held under current lease; "
            f"renegotiate before issuing request"
        )
    # Guardrail 3: observed -32601 / mismatch is ground truth over the cache.
    if negative_response:
        raise StaleCapabilityLease(
            f"server returned method-not-found for {capability!r} despite cached "
            f"lease; cache is stale, revoke and renegotiate"
        )
