# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-stale-capability-warrant-after-a-registry-re-advertisement-race.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-stale-capability-warrant-after-a-registry-re-advertisement-race.warrant.json
# Markdown SHA-256:   a6b2113b3c66e85f6c837c6d9c72da94637ec5cf4238522dcc3c2cd52e28acbb
# Code AST SHA-256:   7cd8bec58273607bff98a9180e46896056b5c0f8a7cc238dd4a1fd59d9351009
# Verified Classes:   StaleCapabilityWarrantError, Descriptor, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleCapabilityWarrantError(RuntimeError):
    """Raised when a warrant's bound schema_hash does not match the descriptor
    resolved at execution time. This is the guard that converts silent
    schema-drift divergence into a hard, localized failure."""


@dataclass(frozen=True)
class Descriptor:
    peer_id: str
    schema: dict
    version: int

    @property
    def schema_hash(self) -> str:
        canon = repr(sorted(self.schema.items())).encode()
        return hashlib.sha256(canon).hexdigest()


@dataclass(frozen=True)
class Warrant:
    peer_id: str
    schema_hash: str
    issued_at: float
    ttl: float


def execute_with_pinned_warrant(
    warrant: Warrant,
    live_descriptor: Descriptor,
    now: float,
    args: dict,
) -> dict:
    # Identity must match.
    if live_descriptor.peer_id != warrant.peer_id:
        raise StaleCapabilityWarrantError(
            f"peer mismatch: warrant={warrant.peer_id} live={live_descriptor.peer_id}"
        )
    # TTL must be live; a version-tolerant check is explicitly NOT used here.
    if now > warrant.issued_at + warrant.ttl:
        raise StaleCapabilityWarrantError(
            f"warrant expired at {warrant.issued_at + warrant.ttl}, now={now}"
        )
    # The invariant: content-addressed equality, not version inequality.
    if live_descriptor.schema_hash != warrant.schema_hash:
        raise StaleCapabilityWarrantError(
            "schema_hash drift: warrant bound "
            f"{warrant.schema_hash[:12]} but live descriptor is "
            f"{live_descriptor.schema_hash[:12]} (version={live_descriptor.version}). "
            "Refusing to route args shaped for a different callable."
        )
    return {"peer": live_descriptor.peer_id, "args": args, "schema_hash": warrant.schema_hash}
