# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-trust-broker-has-silently-downgraded-its-policy-warrant-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-trust-broker-has-silently-downgraded-its-policy-warrant-mid-handoff.warrant.json
# Markdown SHA-256:   1c527aa09aa5899614af7d1fe7189511858e44c5fa9a1d276e3bc2b97bb19856
# Code AST SHA-256:   a4bf15accf6cdadd5676d2b41e1fbb181fcf83482c2fb879097a5a9cd6dfbb5c
# Verified Classes:   WarrantScopeDivergence, Scope, Warrant, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class WarrantScopeDivergence(RuntimeError):
    """Raised when an attestation narrows scope relative to the presented warrant."""


@dataclass(frozen=True)
class Scope:
    dimensions: dict = field(default_factory=dict)

    def minus(self, other: "Scope") -> dict:
        # Dimensions present here but strictly narrower (or absent) in `other`.
        delta = {}
        for k, v in self.dimensions.items():
            if k not in other.dimensions:
                delta[k] = (v, None)
            elif other.dimensions[k] != v:
                delta[k] = (v, other.dimensions[k])
        return delta


@dataclass(frozen=True)
class Warrant:
    scope: Scope
    epoch: int
    signer: str


@dataclass(frozen=True)
class Attestation:
    scope: Scope
    epoch: int
    signer: str
    downgrade_reason: str | None = None


def validate_attestation(
    presented: Warrant,
    attestation: Attestation,
    downgrade_tolerance: dict | None = None,
) -> None:
    """Fail closed if the attestation silently narrows the presented warrant."""
    if attestation.epoch <= presented.epoch:
        raise WarrantScopeDivergence(
            f"stale attestation: epoch {attestation.epoch} <= {presented.epoch}"
        )
    if attestation.signer != presented.signer:
        raise WarrantScopeDivergence(
            f"signer mismatch: {attestation.signer} != {presented.signer}"
        )

    delta = presented.scope.minus(attestation.scope)
    if not delta:
        return  # identity holds; proceed

    # Narrowing is only permitted when the caller pre-declared tolerance
    # for each narrowing dimension and the attested value is within floor.
    tolerated = downgrade_tolerance or {}
    for dim, (warrant_val, attested_val) in delta.items():
        if dim not in tolerated:
            raise WarrantScopeDivergence(
                f"silent downgrade on '{dim}': warrant={warrant_val} "
                f"attested={attested_val} reason={attestation.downgrade_reason} "
                f"epoch={presented.epoch}->{attestation.epoch}"
            )
        floor = tolerated[dim]
        if attested_val is None or attested_val < floor:
            raise WarrantScopeDivergence(
                f"downgrade on '{dim}' below declared floor {floor}: "
                f"attested={attested_val}"
            )
    # Tolerated narrowing: caller explicitly authorized this delta.
    return


# Example trace reproducing the observed failure:
presented = Warrant(scope=Scope({"transfer": True, "max": 5000, "region": "EU"}),
                    epoch=41, signer="beta")
attestation = Attestation(scope=Scope({"transfer": True, "max": 2000, "region": "EU"}),
                          epoch=42, signer="beta", downgrade_reason="policy_reload")
validate_attestation(presented, attestation)  # raises WarrantScopeDivergence
