# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-taint-flag-it-never-observed-provenance-laundering-across-retrieval-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-taint-flag-it-never-observed-provenance-laundering-across-retrieval-boundaries.warrant.json
# Markdown SHA-256:   49c69536666f3148346398ae7efec3ca4bc3e0cab2f364e3bbf505101008f348
# Code AST SHA-256:   9ca6f1c2fed681e1744d07ec6eb36b6a149d09b66f97192cef7782dbbc1145f6
# Verified Classes:   TaintLaunderingError, Artifact, TaintStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact would be stored with taint lower than
    the join of its inputs, or when a tool call is justified by an artifact
    whose transitive taint exceeds the tool's trust ceiling."""


@dataclass(frozen=True)
class Artifact:
    artifact_id: str
    taint: FrozenSet[str]              # set of source labels, e.g. {"external:web"}
    derived_from: FrozenSet[str] = field(default_factory=frozenset)


class TaintStore:
    def __init__(self) -> None:
        self._artifacts: dict[str, Artifact] = {}

    def write(self, art: Artifact) -> None:
        # Fail-closed: recompute the join over declared parents and refuse
        # any write whose taint understates it. No default taint exists.
        if not art.taint and art.derived_from:
            raise TaintLaunderingError(
                f"artifact {art.artifact_id} has parents {sorted(art.derived_from)} "
                f"but empty taint; derived artifacts must declare inherited taint"
            )
        joined: set[str] = set()
        for parent_id in art.derived_from:
            parent = self._artifacts.get(parent_id)
            if parent is None:
                raise TaintLaunderingError(
                    f"artifact {art.artifact_id} cites unknown parent {parent_id}"
                )
            joined |= parent.taint
        if not joined.issubset(art.taint):
            raise TaintLaunderingError(
                f"artifact {art.artifact_id} taint {sorted(art.taint)} "
                f"understates join of parents {sorted(joined)} — laundering"
            )
        self._artifacts[art.artifact_id] = art

    def transitive_taint(self, artifact_id: str) -> FrozenSet[str]:
        seen: set[str] = set()
        stack = [artifact_id]
        acc: set[str] = set()
        while stack:
            aid = stack.pop()
            if aid in seen:
                continue
            seen.add(aid)
            art = self._artifacts.get(aid)
            if art is None:
                raise TaintLaunderingError(f"unknown artifact {aid} in taint closure")
            acc |= art.taint
            stack.extend(art.derived_from)
        return frozenset(acc)


def guard_tool_call(
    store: TaintStore,
    artifact_id: str,
    tool_ceiling: FrozenSet[str],
    tool_name: str,
) -> None:
    # Recompute from the DAG; never trust the artifact's own flag alone.
    effective = store.transitive_taint(artifact_id)
    if not effective.issubset(tool_ceiling):
        raise TaintLaunderingError(
            f"tool {tool_name} justified by {artifact_id} carries transitive "
            f"taint {sorted(effective)} exceeding ceiling {sorted(tool_ceiling)}"
        )
