# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-tool-contract-because-the-peer-s-advertised-capability-hash-diverges-from-its-execution-time-sch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-tool-contract-because-the-peer-s-advertised-capability-hash-diverges-from-its-execution-time-sch.warrant.json
# Markdown SHA-256:   c16cabd0b459c8eb75267d5e7980dc6af2143eb47bc20a2f9bfe1f8d4db35a2b
# Code AST SHA-256:   0eee36baa919f810a327bcaf3fbadaf6235aee9c46b8429ef8cde22e887f5385
# Verified Classes:   StaleDelegationContract, DelegationContract
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class StaleDelegationContract(RuntimeError):
    """Raised when a peer's execution-time schema diverges from the bound contract."""
    pass


@dataclass(frozen=True)
class DelegationContract:
    peer_id: str
    capability: str
    bound_hash: str
    schema_fields: frozenset


def hash_schema(schema: dict) -> str:
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()[:16]


def invoke_delegated(contract: DelegationContract, payload: dict, peer_response: dict) -> dict:
    """
    peer_response is the delegate's reply to a single invocation.
    Raises StaleDelegationContract when the reply carries schema-identity evidence
    that diverges from the bound contract.
    """
    # 1. Explicit hash echo, if the peer supports it — authoritative.
    echoed = peer_response.get("applied_schema_hash")
    if echoed is not None and echoed != contract.bound_hash:
        raise StaleDelegationContract(
            f"peer {contract.peer_id} executed against schema {echoed}, "
            f"bound contract is {contract.bound_hash}; re-negotiate before retry"
        )

    # 2. Symbol-level divergence: error names a field absent from bound schema.
    if peer_response.get("status") == "INVALID_ARGUMENT":
        named = set(peer_response.get("error_fields", []))
        unknown = named - contract.schema_fields
        if unknown:
            raise StaleDelegationContract(
                f"peer {contract.peer_id} rejected on unknown symbols {sorted(unknown)}; "
                f"capability {contract.capability} drifted from bound hash "
                f"{contract.bound_hash}; re-negotiate (do NOT retry identical payload)"
            )
        # Named fields all exist -> genuine bad argument, safe to surface to caller.
        return peer_response

    # 3. Transport-class errors do not implicate schema identity; caller may retry.
    return peer_response
