# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-routes-a-federated-capability-request-across-an-org-boundary-and-the-policy-evaluator-s-decision-diverges-from-the-capab.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-routes-a-federated-capability-request-across-an-org-boundary-and-the-policy-evaluator-s-decision-diverges-from-the-capab.warrant.json
# Markdown SHA-256:   e91284919274e6d45c9dbeb4025aee90e9bf7ebb1df17225932919e29c6a730b
# Code AST SHA-256:   3d8b98b659ef6242598365b0b3a598d2387c8209c9e14c698152dc415367f5cc
# Verified Classes:   FederationPolicyDivergence, NegotiatedSchema
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal


class FederationPolicyDivergence(RuntimeError):
    """Raised when a peer's policy denial reason is outside the negotiated
    schema's reason vocabulary, making retry/fallback classification unsafe."""


@dataclass(frozen=True)
class NegotiatedSchema:
    capability: str
    version: str
    preconditions: frozenset[str]
    reason_vocabulary: frozenset[str]  # closed-world; must be exhaustive
    retryable_reasons: frozenset[str]


def classify_denial(
    schema: NegotiatedSchema,
    reason_code: str,
    peer_id: str,
) -> Literal["retry", "terminal", "divergence"]:
    # Guardrail: the reason vocabulary must be closed. If the peer did not
    # publish one, negotiation should have failed; if we got here anyway,
    # we cannot classify and must not guess.
    if not schema.reason_vocabulary:
        raise FederationPolicyDivergence(
            f"peer {peer_id} negotiated {schema.capability}@{schema.version} "
            f"without a reason vocabulary; denial {reason_code!r} is unclassifiable"
        )

    if reason_code not in schema.reason_vocabulary:
        # The exact failure: policy evaluator denied on grounds the schema
        # never expressed. Treating this as retryable caused the trace above.
        raise FederationPolicyDivergence(
            f"peer {peer_id} denied {schema.capability}@{schema.version} with "
            f"reason {reason_code!r} outside negotiated vocabulary "
            f"{sorted(schema.reason_vocabulary)}; halting to avoid routing "
            f"around an unexpressed policy"
        )

    if reason_code in schema.retryable_reasons:
        return "retry"
    return "terminal"


def select_fallback(
    failed: NegotiatedSchema,
    candidates: list[NegotiatedSchema],
) -> NegotiatedSchema:
    # A weaker schema cannot be assumed to enforce the stronger peer's policy.
    # Exclude any candidate whose preconditions are a strict subset.
    for cand in candidates:
        if cand.preconditions < failed.preconditions:
            continue
        if cand.reason_vocabulary != failed.reason_vocabulary:
            continue  # vocabulary mismatch: fallback would re-introduce divergence
        return cand
    raise FederationPolicyDivergence(
        f"no fallback peer for {failed.capability}@{failed.version} preserves "
        f"preconditions {sorted(failed.preconditions)} and reason vocabulary; "
        f"escalating rather than degrading policy enforcement"
    )
