# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-federation-warrant-has-been-silently-downgraded-across-an-org-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-federation-warrant-has-been-silently-downgraded-across-an-org-boundary.warrant.json
# Markdown SHA-256:   b5b9843cc7a2d2102d4105d2ce4c8c5db70abb529129793e66e3865e6e1716d9
# Code AST SHA-256:   b0effacc23fc8e72dfe52278990d4b4438f24b0ff08cfb30093ea2b7c4d3021a
# Verified Classes:   FederationAttenuationError, PolicyEnvelope, ExecutionReceipt
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class FederationAttenuationError(RuntimeError):
    """Raised when a peer's interpreted policy is not a subset of the origin's warrant."""


@dataclass(frozen=True)
class PolicyEnvelope:
    predicate_terms: FrozenSet[str]   # canonicalized term ids
    max_items: int
    export_scope: str                 # org id that owns "outside" semantics


@dataclass(frozen=True)
class ExecutionReceipt:
    status: str
    interpreted_policy: PolicyEnvelope
    policy_digest: str


def validate_receipt(origin: PolicyEnvelope, receipt: ExecutionReceipt,
                     origin_digest: str) -> None:
    if receipt.status != "success":
        return  # loud failures are handled by the caller's error path

    if receipt.policy_digest == origin_digest:
        return  # digests agree; no attenuation channel

    peer = receipt.interpreted_policy

    # Subset check: peer must not be wider on any dimension.
    wider_terms = peer.predicate_terms - origin.predicate_terms
    if wider_terms:
        raise FederationAttenuationError(
            f"peer predicate widened beyond warrant: {sorted(wider_terms)}"
        )

    if peer.max_items > origin.max_items:
        raise FederationAttenuationError(
            f"peer item cap {peer.max_items} exceeds warrant cap {origin.max_items}"
        )

    if peer.export_scope != origin.export_scope:
        raise FederationAttenuationError(
            f"export scope divergence: origin={origin.export_scope!r} "
            f"peer={peer.export_scope!r}; liability unassignable"
        )

    # Incomparable-but-narrower is benign; log as mapping note, not error.
