# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-taint-after-a-capability-scoped-egress-grant-and-why-the-guard-s-memoized-label-is-not-the-label.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-taint-after-a-capability-scoped-egress-grant-and-why-the-guard-s-memoized-label-is-not-the-label.warrant.json
# Markdown SHA-256:   ab273a932791a38395dbb8708d19f0c0516869a0370cadd23123d42a9264b122
# Code AST SHA-256:   11d99b6611d14606137003122468b7b96a43226a53e1ba835107c75353710aa1
# Verified Classes:   StaleTaintLabelError, TaintLabel, FrontierVersionedGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class StaleTaintLabelError(RuntimeError):
    """Raised when a memoized taint label is consulted after a grant
    has widened the egress frontier it depended on."""


@dataclass
class TaintLabel:
    value: str            # "CLEAN" | "UNTRUSTED"
    frontier_version: int # egress frontier at derivation time
    reachable_scopes: Set[str] = field(default_factory=set)


class FrontierVersionedGuard:
    def __init__(self) -> None:
        self._frontier_version: int = 0
        self._scope_versions: Dict[str, int] = {}
        self._cache: Dict[str, TaintLabel] = {}

    def derive(self, sig: str, value: str, scopes: Set[str]) -> TaintLabel:
        label = TaintLabel(
            value=value,
            frontier_version=self._frontier_version,
            reachable_scopes=set(scopes),
        )
        self._cache[sig] = label
        return label

    def grant(self, scope: str) -> None:
        # Widening the egress frontier invalidates every label whose
        # reachable scope set intersects the granted scope.
        self._frontier_version += 1
        self._scope_versions[scope] = self._frontier_version

    def lookup(self, sig: str) -> TaintLabel:
        label = self._cache.get(sig)
        if label is None:
            raise StaleTaintLabelError(f"no label for signature {sig!r}")
        for scope in label.reachable_scopes:
            live = self._scope_versions.get(scope, 0)
            if live > label.frontier_version:
                raise StaleTaintLabelError(
                    f"label for {sig!r} derived at frontier "
                    f"{label.frontier_version} but scope {scope!r} "
                    f"advanced to {live}; re-derive before egress"
                )
        return label


def egress_post(guard: FrontierVersionedGuard, sig: str, payload: str) -> None:
    label = guard.lookup(sig)
    if label.value == "UNTRUSTED":
        raise StaleTaintLabelError(
            f"blocked egress of UNTRUSTED payload via {sig!r}"
        )
    # ... transmit payload ...


# Reproduction of the observed failure, now bounded:
guard = FrontierVersionedGuard()
guard.derive("fetch_ticket", "UNTRUSTED", scopes={"notes:write", "http:post"})
guard.grant("notes:write")            # frontier widens
try:
    egress_post(guard, "fetch_ticket", "<attacker-controlled>")
except StaleTaintLabelError as exc:
    print(f"contained: {exc}")
