# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-when-a-tool-re-serializes-its-own-output.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-when-a-tool-re-serializes-its-own-output.warrant.json
# Markdown SHA-256:   7b8d1880050b5b3b891d879139754ad49b1cceca0e91b012db8bd2d3cba5da5c
# Code AST SHA-256:   36fd210f601be5ae7041be70387910bc10083fd5d38d6292938071df7e13ba27
# Verified Classes:   TaintLaunderingError, Part, DeclassifyWarrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a value reaches a cross-domain sink without a clean lineage."""


@dataclass(frozen=True)
class Part:
    id: str
    source: str  # "untrusted", "model", "internal", "tool:<name>"
    lineage: FrozenSet[str] = field(default_factory=frozenset)  # ids of parts that conditioned this


@dataclass(frozen=True)
class DeclassifyWarrant:
    value_id: str
    sink: str
    policy: str
    signer: str


def lineage_closure(part: Part, parts: dict[str, Part]) -> FrozenSet[str]:
    """Transitive closure of part ids reachable via lineage edges."""
    seen: set[str] = set()
    stack = [part.id]
    while stack:
        pid = stack.pop()
        if pid in seen:
            continue
        seen.add(pid)
        node = parts.get(pid)
        if node is None:
            continue
        stack.extend(node.lineage)
    return frozenset(seen)


def gate_egress(
    value: Part,
    sink: str,
    parts: dict[str, Part],
    warrants: list[DeclassifyWarrant],
) -> None:
    """Fail closed unless every untrusted ancestor is covered by a warrant for this sink."""
    closure = lineage_closure(value, parts)
    untrusted_ancestors = {
        pid for pid in closure
        if parts.get(pid) is not None and parts[pid].source == "untrusted"
    }
    covered = {
        w.value_id for w in warrants
        if w.sink == sink and w.value_id in untrusted_ancestors
    }
    uncovered = untrusted_ancestors - covered
    if uncovered:
        raise TaintLaunderingError(
            f"egress to {sink!r} blocked: value {value.id!r} has untrusted lineage "
            f"{sorted(uncovered)!r} with no declassify warrant for this sink"
        )
    # A model-emitted value with unknown lineage is also untrusted by default.
    if value.source == "model" and not closure:
        raise TaintLaunderingError(
            f"egress to {sink!r} blocked: model value {value.id!r} has empty lineage; "
            f"cannot prove it is not a laundered copy of untrusted content"
        )
