# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-whose-policy-scope-was-widened-after-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-whose-policy-scope-was-widened-after-negotiation.warrant.json
# Markdown SHA-256:   0a81d63e82cb8a9f75bde7795762f724798c770151eab8d32c7fc00d7381f2a1
# Code AST SHA-256:   0796638db969763e323be40ecc65a405a8e4d3e9aa4a3ad52910da38ca37f35d
# Verified Classes:   ScopeWidenedAfterNegotiationError, MissingNegotiationSnapshotError, Grant, NegotiatedGrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ScopeWidenedAfterNegotiationError(RuntimeError):
    """Raised when a federated grant's resolved scope exceeds its negotiation-time snapshot."""
    pass


class MissingNegotiationSnapshotError(RuntimeError):
    """Raised when a grant carries no recorded negotiation-time resolved scope."""
    pass


@dataclass(frozen=True)
class Grant:
    grant_id: str
    capability: str
    policy_ref: str
    warrant: str


@dataclass
class NegotiatedGrant:
    grant: Grant
    negotiated_scope: FrozenSet[str] = field(default_factory=frozenset)
    negotiated_at: float = 0.0


def negotiate(grant: Grant, resolve_scope, now: float) -> NegotiatedGrant:
    # Snapshot the resolved set as inline data at negotiation time.
    resolved = frozenset(resolve_scope(grant.policy_ref, now))
    return NegotiatedGrant(grant=grant, negotiated_scope=resolved, negotiated_at=now)


def authorize_execution(n: NegotiatedGrant, resolve_scope, now: float) -> None:
    if not n.negotiated_scope:
        raise MissingNegotiationSnapshotError(
            f"grant {n.grant.grant_id}: no negotiation-time scope snapshot; "
            f"widening is undetectable, refusing execution"
        )
    current = frozenset(resolve_scope(n.grant.policy_ref, now))
    widened = current - n.negotiated_scope
    if widened:
        raise ScopeWidenedAfterNegotiationError(
            f"grant {n.grant.grant_id}: policy_ref {n.grant.policy_ref!r} "
            f"resolved to scope widened by {sorted(widened)} since negotiation; "
            f"refusing execution and requiring renegotiation"
        )
    # current is equal to or narrower than the snapshot: safe to execute.
    return None


def route_egress(n: NegotiatedGrant, route_scope: FrozenSet[str], payload_tags: FrozenSet[str]) -> None:
    # Router compares against the NEGOTIATED snapshot, not its own resolution.
    if not payload_tags <= (route_scope & n.negotiated_scope):
        raise ScopeWidenedAfterNegotiationError(
            f"grant {n.grant.grant_id}: payload tags {sorted(payload_tags)} "
            f"exceed negotiated-scope ∩ route-scope; egress blocked"
        )


# --- reproduction of the observed trace ---
POLICY = {"records-reader@v3": {"public"}}

def resolve_scope(policy_ref: str, now: float) -> set:
    return set(POLICY.get(policy_ref, set()))

t_neg = 1000.0
t_exec = 2000.0

g = Grant("g-77", "read:records", "records-reader@v3", "warrant-abc")
n = negotiate(g, resolve_scope, t_neg)              # snapshot = {"public"}

# Org A patches the SAME reference in place; warrant remains valid.
POLICY["records-reader@v3"] = {"public", "internal"}

try:
    authorize_execution(n, resolve_scope, t_exec)   # detects widening -> raises
except ScopeWidenedAfterNegotiationError as e:
    print("execution refused:", e)
