# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-taint-after-a-policy-cache-hit-the-stale-taint-admission-gap-in-tool-invocation-gating.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-taint-after-a-policy-cache-hit-the-stale-taint-admission-gap-in-tool-invocation-gating.warrant.json
# Markdown SHA-256:   257cd9f0c9cee409b43600ed9b3921b081c8795e9f72eb9839a9420f4f0141a3
# Code AST SHA-256:   1553140c1f0b8a283bb6158fc5b8c0f38826d84d93765a019bb18c59aa356146
# Verified Classes:   StaleTaintAdmissionError, Invocation, RuleSet, PEPCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class StaleTaintAdmissionError(RuntimeError):
    """Raised when a PEP would serve or store a decision whose cache key
    is not complete with respect to the active rule set, taint epoch,
    or provenance identity."""


@dataclass(frozen=True)
class Invocation:
    tool: str
    args: dict
    taint_labels: FrozenSet[str]
    provenance_digest: str          # identity of the derivation chain
    taint_epoch: int                # monotonic; bumped on rule/trust change


@dataclass(frozen=True)
class RuleSet:
    # fields any active rule predicate reads; the key MUST cover these
    referenced_fields: FrozenSet[str]
    current_epoch: int
    evaluate: Callable[[Invocation], bool]  # True == allow


@dataclass
class PEPCache:
    store: dict = field(default_factory=dict)

    def _key(self, inv: Invocation) -> tuple:
        # NOTE: deliberately does NOT include recipient/host/path unless
        # the schema says so -- completeness is asserted separately.
        return (
            inv.tool,
            frozenset(inv.args.keys()),
            inv.taint_labels,
            inv.provenance_digest,
            inv.taint_epoch,
        )

    def _assert_key_complete(self, inv: Invocation, rules: RuleSet) -> None:
        missing = rules.referenced_fields - frozenset(inv.args.keys())
        if missing:
            raise StaleTaintAdmissionError(
                f"key schema omits rule-referenced fields {sorted(missing)}; "
                f"refusing to cache decision for tool={inv.tool}"
            )
        if inv.taint_epoch != rules.current_epoch:
            raise StaleTaintAdmissionError(
                f"taint epoch mismatch: invocation={inv.taint_epoch} "
                f"rules={rules.current_epoch}; derivation drift"
            )
        if not inv.provenance_digest:
            raise StaleTaintAdmissionError(
                "provenance digest absent; classification-only key would "
                "alias distinct derivation paths"
            )

    def decide(self, inv: Invocation, rules: RuleSet) -> bool:
        key = self._key(inv)
        if key in self.store:
            return self.store[key]
        decision = rules.evaluate(inv)
        # write-time completeness gate: a miss is cheap, a stale hit is not
        try:
            self._assert_key_complete(inv, rules)
        except StaleTaintAdmissionError:
            return decision          # return, but do NOT cache
        self.store[key] = decision
        return decision
