# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-federated-capability-grant-when-policy-negotiation-converges-on-asymmetric-obligation-sets.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-federated-capability-grant-when-policy-negotiation-converges-on-asymmetric-obligation-sets.warrant.json
# Markdown SHA-256:   60fcf4d33dd2c4c108c8a30e110a322709e33b18ab6fde94e6da9fe96fce6e0a
# Code AST SHA-256:   be0ced4edc8c8da30ddb17c7e3e758354623b3390291ec5f27611fb1b7fce22a
# Verified Classes:   FederatedGrantInvalid, ObligationSet, FederatedGrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class FederatedGrantInvalid(RuntimeError):
    """Raised when a negotiated capability grant's obligation sets diverge."""
    pass


@dataclass
class ObligationSet:
    obligations: dict = field(default_factory=dict)

    def canonical_digest(self) -> str:
        # Sorted-key JSON is the shared canonicalization contract.
        canonical = json.dumps(self.obligations, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class FederatedGrant:
    agreement_id: str          # sha256 over transcript — NOT sufficient
    provider_digest: str | None  # sha256 over provider's canonical obligation set
    consumer_obligations: ObligationSet


def validate_grant_before_execution(grant: FederatedGrant) -> None:
    """
    Enforce the invariant: a converged negotiation is valid only if the
    consumer's derived obligation set matches the provider's, by digest,
    and the provider actually published a digest.
    """
    if grant.provider_digest is None:
        raise FederatedGrantInvalid(
            f"agreement {grant.agreement_id}: provider emitted no obligations_digest; "
            "cannot audit against an unstated obligation set"
        )

    local = grant.consumer_obligations.canonical_digest()
    if local != grant.provider_digest:
        raise FederatedGrantInvalid(
            f"agreement {grant.agreement_id}: obligation-set divergence "
            f"(consumer={local[:12]} provider={grant.provider_digest[:12]}); "
            "canonicalization mismatch likely — do not execute"
        )


def execute_capability(grant: FederatedGrant, call_fn) -> object:
    validate_grant_before_execution(grant)
    return call_fn()
