# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-taint-from-a-context-provenance-graph-instead-of-trusting-the-recorded-label.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-taint-from-a-context-provenance-graph-instead-of-trusting-the-recorded-label.warrant.json
# Markdown SHA-256:   4901b75d41c34a6edfa86d245ddacbdb193c27fd4ef9d4566d8e7288ad3a57ae
# Code AST SHA-256:   cf646676ada03ebc25c0941020a9c34192804d1f99865478ce303c9ccb8a2749
# Verified Classes:   Taint, StaleTaintLabelError, Node, ProvenanceGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, List, Set


class Taint(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1  # lattice join = max


class StaleTaintLabelError(RuntimeError):
    """Raised when a cached taint label is older than an ancestor mutation
    and re-derivation was not permitted or exceeded its bound."""


@dataclass
class Node:
    node_id: str
    label: Taint
    label_epoch: int
    mutation_epoch: int
    parents: List[str] = field(default_factory=list)


class ProvenanceGraph:
    def __init__(self) -> None:
        self.nodes: Dict[str, Node] = {}
        self._epoch = 0

    def bump_epoch(self) -> int:
        self._epoch += 1
        return self._epoch

    def add_edge(self, child: str, parent: str) -> None:
        # Any structural mutation invalidates descendant labels.
        self.nodes[child].parents.append(parent)
        self.nodes[child].mutation_epoch = self.bump_epoch()

    def _max_ancestor_epoch(self, node_id: str, depth: int, seen: Set[str]) -> int:
        if depth == 0 or node_id in seen:
            return -1
        seen.add(node_id)
        node = self.nodes[node_id]
        worst = node.mutation_epoch
        for p in node.parents:
            worst = max(worst, self._max_ancestor_epoch(p, depth - 1, seen))
        return worst

    def resolve_taint(self, node_id: str, max_depth: int = 8) -> Taint:
        node = self.nodes[node_id]
        ancestor_epoch = self._max_ancestor_epoch(node_id, max_depth, set())
        if node.label_epoch >= ancestor_epoch:
            return node.label  # label is still supported by the graph
        # Graph moved under the label: re-derive, bounded.
        derived = self._recompute(node_id, max_depth, set())
        if derived is None:
            raise StaleTaintLabelError(
                f"label for {node_id} invalidated by ancestor mutation at "
                f"epoch {ancestor_epoch}; re-derivation exceeded depth {max_depth}"
            )
        return derived

    def _recompute(self, node_id: str, depth: int, seen: Set[str]):
        if depth == 0 or node_id in seen:
            return None  # cannot bound the join -> caller must fail closed
        seen.add(node_id)
        node = self.nodes[node_id]
        join = node.label
        for p in node.parents:
            sub = self._recompute(p, depth - 1, seen)
            if sub is None:
                return None
            join = Taint(max(join, sub))
        return join


def gate_action(graph: ProvenanceGraph, node_id: str, action: str) -> None:
    taint = graph.resolve_taint(node_id)
    if taint is Taint.UNTRUSTED and action in {"shell", "network_write", "file_write"}:
        raise StaleTaintLabelError(
            f"refusing {action!r}: node {node_id} re-derives to UNTRUSTED "
            f"from its provenance closure"
        )
