# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-dynamically-resolved-capability-descriptor-after-registry-mediated-discovery.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-dynamically-resolved-capability-descriptor-after-registry-mediated-discovery.warrant.json
# Markdown SHA-256:   a787ee26d1cf41969898783fa22d449d0f94bada34d5eb2470c9b28855d0a25a
# Code AST SHA-256:   37a25d623ad758b0dd57fb50b229afb828c34b2512627762a5e36abf5347c7e6
# Verified Classes:   DescriptorDriftError, CapabilityDescriptor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DescriptorDriftError(RuntimeError):
    """Raised when a resolved capability descriptor no longer matches the peer's actual schema."""


@dataclass(frozen=True)
class CapabilityDescriptor:
    peer_id: str
    schema: dict
    protocol_version: str

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


def build_invocation_payload(
    resolved: CapabilityDescriptor,
    live: CapabilityDescriptor,
    payload: dict,
) -> dict:
    """
    Guard: a registry-resolved descriptor may select a peer, but the payload
    must be constructed against the schema the peer re-asserts at call time.
    """
    if resolved.peer_id != live.peer_id:
        raise DescriptorDriftError(
            f"identity mismatch: registry={resolved.peer_id} live={live.peer_id}"
        )
    if resolved.schema_hash() != live.schema_hash():
        raise DescriptorDriftError(
            "schema drift between registry descriptor and live peer; "
            "quarantine peer and re-negotiate before constructing payload"
        )
    unknown = set(payload) - set(live.schema.get("properties", {}))
    if unknown:
        raise DescriptorDriftError(
            f"payload fields not in live schema: {sorted(unknown)}"
        )
    return payload


def validate_response(resolved: CapabilityDescriptor, response: dict) -> None:
    """A 200 response whose shape contradicts the confirmed schema is drift, not success."""
    required = set(resolved.schema.get("required", []))
    missing = required - set(response)
    if missing:
        raise DescriptorDriftError(
            f"successful response missing required fields: {sorted(missing)}"
        )
