# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-evaluate-taint-at-the-mcp-transport-boundary-rather-than-trusting-the-policy-decision-cached-at-tool-schema-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-evaluate-taint-at-the-mcp-transport-boundary-rather-than-trusting-the-policy-decision-cached-at-tool-schema-negotiation.warrant.json
# Markdown SHA-256:   dab6ac6b79ab9a6fdaf38ddf1a67791eb07ace4edc52551e3e13e99dff4a3aea
# Code AST SHA-256:   8b84364173741f50b3d8cdb91a3b912fc5e46ec8b538de154275c806b1faa084
# Verified Classes:   Taint, StaleTaintVerdictError, Call, CachedVerdict, TaintAwarePEP
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, Tuple


class Taint(IntEnum):
    TRUSTED = 0
    INTERNAL = 1
    EXTERNAL = 2


class StaleTaintVerdictError(RuntimeError):
    """Raised when a cached allow/deny verdict is applied to a call whose
    taint-vector exceeds the taint-vector the verdict was computed against."""


@dataclass(frozen=True)
class Call:
    tool_id: str
    arg_shape: Tuple[str, ...]
    taint_vector: Tuple[Taint, ...]


@dataclass
class CachedVerdict:
    decision: str
    epoch: int
    max_taint: Taint


@dataclass
class TaintAwarePEP:
    # cache keyed on call-site shape only -- the buggy configuration
    cache: Dict[Tuple[str, Tuple[str, ...]], CachedVerdict] = field(default_factory=dict)
    taint_epoch: int = 0

    def record_taint_write(self) -> None:
        self.taint_epoch += 1

    def _policy(self, call: Call) -> str:
        # sensitive sink: deny if any argument is EXTERNAL
        if call.tool_id == "send_email" and max(call.taint_vector) >= Taint.EXTERNAL:
            return "deny"
        return "allow"

    def evaluate(self, call: Call) -> str:
        key = (call.tool_id, call.arg_shape)
        cached = self.cache.get(key)
        if cached is not None:
            # GUARD: refuse to trust a verdict whose taint coverage is stale
            if cached.epoch != self.taint_epoch and max(call.taint_vector) > cached.max_taint:
                raise StaleTaintVerdictError(
                    f"cached verdict for {call.tool_id} computed at epoch "
                    f"{cached.epoch} (max_taint={cached.max_taint.name}) applied to "
                    f"call at epoch {self.taint_epoch} with max_taint="
                    f"{max(call.taint_vector).name}; re-evaluate"
                )
            return cached.decision
        decision = self._policy(call)
        self.cache[key] = CachedVerdict(
            decision=decision,
            epoch=self.taint_epoch,
            max_taint=max(call.taint_vector),
        )
        return decision


def demo() -> None:
    pep = TaintAwarePEP()
    clean = Call("send_email", ("to", "body"), (Taint.TRUSTED, Taint.TRUSTED))
    assert pep.evaluate(clean) == "allow"  # warm cache

    pep.record_taint_write()  # instance ingests untrusted fetch_url output

    poisoned = Call("send_email", ("to", "body"), (Taint.EXTERNAL, Taint.EXTERNAL))
    # same shape -> same cache key -> would hit the stale ALLOW without the guard
    pep.evaluate(poisoned)  # raises StaleTaintVerdictError


if __name__ == "__main__":
    demo()
