# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-brokered-capability-whose-policy-scope-was-reconciled-against-a-stale-peer-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-brokered-capability-whose-policy-scope-was-reconciled-against-a-stale-peer-manifest.warrant.json
# Markdown SHA-256:   1d3a3284219d1ccd49d5bd51f2a7b304916a8dd26f529236bd7d2b734008d5cc
# Code AST SHA-256:   4d2b2ec52e2b69cf342d922e97acf30c7c9ebe1a50f69c60bb64109e72ad8938
# Verified Classes:   StaleScopeAdmissionError, Manifest, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class StaleScopeAdmissionError(RuntimeError):
    """Raised when a brokered warrant's scope is not a subset of the callee's
    live manifest policy at execution time (narrowing race)."""
    pass


@dataclass(frozen=True)
class Manifest:
    version: str
    max_tokens: int
    residency: str  # "any" | "EU-only" | ...


@dataclass(frozen=True)
class Warrant:
    scope_cap: str
    scope_max_tokens: int
    scope_residency: str
    peer_manifest_version: str  # informational only; NOT used for admission


def admit_and_execute(
    warrant: Warrant,
    live_manifest: Manifest,
    manifest_fetch_ok: bool,
) -> str:
    # Fail-closed: if we cannot read our own current manifest, refuse.
    if not manifest_fetch_ok:
        raise StaleScopeAdmissionError(
            "cannot read live manifest; refusing execution (fail-closed)"
        )

    # Per-field subset check against LIVE manifest, not against
    # warrant.peer_manifest_version. Version tokens are not orderable
    # in the narrowing direction and must not gate admission.
    if warrant.scope_max_tokens > live_manifest.max_tokens:
        raise StaleScopeAdmissionError(
            f"scope max_tokens={warrant.scope_max_tokens} exceeds live "
            f"manifest {live_manifest.version} ceiling "
            f"{live_manifest.max_tokens}"
        )

    if live_manifest.residency != "any" and warrant.scope_residency != live_manifest.residency:
        raise StaleScopeAdmissionError(
            f"scope residency={warrant.scope_residency!r} violates live "
            f"manifest {live_manifest.version} residency="
            f"{live_manifest.residency!r}"
        )

    # Only reached if scope ⊆ live policy. Log the version actually used.
    return f"executed {warrant.scope_cap} under manifest {live_manifest.version}"


# Trace replay: broker minted against v41, callee now serves v42 (EU-only, 4096).
w = Warrant("summarize", 8000, "any", peer_manifest_version="v41")
v42 = Manifest(version="v42", max_tokens=4096, residency="EU-only")

try:
    admit_and_execute(w, v42, manifest_fetch_ok=True)
except StaleScopeAdmissionError as e:
    print("REJECTED (correct):", e)
