# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-grant-across-a-federated-a2a-gateway-whose-rate-governor-is-keyed-on-a-different-identity-than-t.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-grant-across-a-federated-a2a-gateway-whose-rate-governor-is-keyed-on-a-different-identity-than-t.warrant.json
# Markdown SHA-256:   fb37b3a0398f2d02f91bec9e60b964aee0f1b6e414a81146a085e9ca783fbfc1
# Code AST SHA-256:   b583e2c88c392d97d0195d7f22d164b56d4d3208b4aecc3b39e09a6fcb74f362
# Verified Classes:   MeteringIdentityUnresolved, RateDecision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class MeteringIdentityUnresolved(RuntimeError):
    """Raised when a federated gateway cannot attribute a rate decision to a
    validated warrant leaf subject. Fail closed; never fall back to the
    transport principal, which collapses N callers into one bucket."""


@dataclass(frozen=True)
class RateDecision:
    allowed: bool
    scope: str          # "warrant:<sub>" or "transport"
    leaf_subject: str | None


def meter_federated_call(
    warrant_chain: list[dict],
    transport_principal: str,
    governor_buckets: dict[str, int],
) -> RateDecision:
    # 1. Validate the chain BEFORE metering. An unvalidated `sub` can be
    #    forged to reset a counter (identity-escape via injection).
    if not warrant_chain or not _chain_is_valid(warrant_chain):
        raise MeteringIdentityUnresolved(
            f"warrant chain from transport principal {transport_principal!r} "
            "failed validation; refusing to meter on an unverified subject"
        )

    leaf = warrant_chain[-1].get("sub")
    if not leaf:
        raise MeteringIdentityUnresolved(
            f"leaf warrant from {transport_principal!r} carries no subject; "
            "governor cannot attribute consumption and must not fall back "
            "to the transport principal"
        )

    # 2. Meter on the WARRANT subject, not the transport principal.
    budget = governor_buckets.get(leaf)
    if budget is None:
        raise MeteringIdentityUnresolved(
            f"no governor bucket provisioned for warrant subject {leaf!r}; "
            f"transport principal {transport_principal!r} is admission-only"
        )

    if budget <= 0:
        return RateDecision(allowed=False, scope=f"warrant:{leaf}", leaf_subject=leaf)

    governor_buckets[leaf] = budget - 1
    return RateDecision(allowed=True, scope=f"warrant:{leaf}", leaf_subject=leaf)


def _chain_is_valid(chain: list[dict]) -> bool:
    # Signature, expiry, and delegation-depth checks elided; must be a real
    # cryptographic validation before any metering decision is trusted.
    return all(link.get("sig") and link.get("sub") for link in chain)
