# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-federated-capability-advertisement-before-invoking-a-remote-agent-across-an-organizational-trust-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-federated-capability-advertisement-before-invoking-a-remote-agent-across-an-organizational-trust-anchor.warrant.json
# Markdown SHA-256:   05bfa38673347b57155ffb4068de7c684fd440cc646f5b6efc6b0c9b6ff0d2e5
# Code AST SHA-256:   e6c344cc96c49dbf26886ea266f4d407f5e3a5bebfe931c464cad48af923b503
# Verified Classes:   DescriptorBindingError, Warrant, LiveDescriptor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class DescriptorBindingError(RuntimeError):
    """Raised when a federated capability descriptor cannot be bound to a live endpoint."""
    pass


@dataclass(frozen=True)
class Warrant:
    capability_name: str
    descriptor_hash: str          # sha256 of the descriptor bytes at attestation time
    anchor_sig: str
    issued_at: float
    expires_at: float


@dataclass(frozen=True)
class LiveDescriptor:
    capability_name: str
    schema_version: int
    input_schema: dict
    validation_precedes_side_effect: bool
    descriptor_hash: str


def bind_and_invoke(
    warrant: Warrant,
    cached_descriptor: LiveDescriptor,
    fetch_live,                     # callable: () -> LiveDescriptor
    now: float,
    invoke,                         # callable: (descriptor, payload) -> result
    payload: dict,
) -> object:
    # 1. Warrant must be temporally valid.
    if now >= warrant.expires_at:
        raise DescriptorBindingError(
            f"warrant for {warrant.capability_name} expired at {warrant.expires_at}"
        )

    # 2. The cached descriptor must match the warrant's attested hash.
    #    A mismatch here means the cache was tampered with or the warrant
    #    was issued against a different descriptor than the one cached.
    if cached_descriptor.descriptor_hash != warrant.descriptor_hash:
        raise DescriptorBindingError(
            f"cached descriptor hash {cached_descriptor.descriptor_hash} "
            f"does not match warrant hash {warrant.descriptor_hash}"
        )

    # 3. Re-fetch the live descriptor. This is the step that catches drift.
    live = fetch_live()
    if live.capability_name != warrant.capability_name:
        raise DescriptorBindingError(
            f"live capability name {live.capability_name} differs from "
            f"warrant capability {warrant.capability_name}"
        )

    # 4. If the live descriptor drifted from the cached/warranted one,
    #    the planner must recompile. Refuse to invoke against a stale schema.
    if live.descriptor_hash != cached_descriptor.descriptor_hash:
        raise DescriptorBindingError(
            f"descriptor drift detected for {live.capability_name}: "
            f"warranted v{cached_descriptor.schema_version} "
            f"({cached_descriptor.descriptor_hash[:12]}), "
            f"live v{live.schema_version} ({live.descriptor_hash[:12]}); "
            f"planner must recompile before invocation"
        )

    # 5. Side-effect ordering invariant. If the remote does not guarantee
    #    validation-before-side-effect, we cannot rely on a 422 being safe.
    #    In that case, the planner must have explicitly opted in to the risk.
    if not live.validation_precedes_side_effect:
        if not payload.get("_accept_side_effect_before_validation"):
            raise DescriptorBindingError(
                f"{live.capability_name} does not guarantee validation precedes "
                f"side effects; refusing invocation without explicit opt-in"
            )

    # 6. Pin the descriptor version in the request so the remote can reject
    #    a mid-flight drift (the residual re-fetch race).
    pinned = dict(payload)
    pinned["_pin_descriptor_hash"] = live.descriptor_hash

    return invoke(live, pinned)
