# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-capability-scope-after-a-policy-translation-gateway-rewrites-a-peer-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-capability-scope-after-a-policy-translation-gateway-rewrites-a-peer-warrant.warrant.json
# Markdown SHA-256:   4dbc3495fa76d0ecc541b0f082168aa8e9f7d90836d7bf9a2aebc0ffead61f6d
# Code AST SHA-256:   1763e0faf95f0851889c77cbd4e7857b36081d3f97047867a88a2a80d11fd7cb
# Verified Classes:   ScopeDerivationError, Warrant, TranslationResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class ScopeDerivationError(RuntimeError):
    """Raised when a caller attempts to attenuate from a grant that is not the
    authoritative root after policy-gateway translation."""
    pass


@dataclass(frozen=True)
class Warrant:
    capability: str
    constraints: FrozenSet[str]          # e.g. frozenset({"tenant=self"})
    collections: FrozenSet[str] = frozenset()
    root_id: str = ""


@dataclass
class TranslationResult:
    translated: Warrant
    residue: FrozenSet[str]              # source constraints with no target image
    widened: bool                        # gateway default-filled a restrictive predicate


def establish_peering(caller_grant: Warrant, gateway) -> TranslationResult:
    """Round-trip the grant through the PTG and classify the translation."""
    result = gateway.translate(caller_grant)
    if result.widened and not result.residue:
        # A widening with no recorded residue is an unaccounted authority
        # expansion; refuse to peer rather than trust an opaque transform.
        raise ScopeDerivationError(
            f"gateway widened {caller_grant.capability!r} without recording "
            f"translation residue; cannot bound effective scope"
        )
    return result


def mint_sub_warrant(
    peering: TranslationResult,
    cached_grant: Warrant,
    requested: FrozenSet[str],
) -> Warrant:
    """Attenuate from the authoritative root, never from the stale cache."""
    root = peering.translated
    if peering.widened or peering.residue:
        if cached_grant.root_id != root.root_id:
            # Caller is still attenuating from its pre-translation grant.
            raise ScopeDerivationError(
                f"attenuation from stale root {cached_grant.root_id!r}; "
                f"authoritative root is {root.root_id!r} after translation "
                f"(residue={sorted(peering.residue)!r})"
            )
    if not requested <= root.collections:
        raise ScopeDerivationError(
            f"requested collections {sorted(requested)!r} not within "
            f"translated extent {sorted(root.collections)!r}"
        )
    return Warrant(
        capability=root.capability,
        constraints=root.constraints,
        collections=requested,
        root_id=root.root_id,
    )
