# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-taint-through-a-multi-hop-tool-invocation-graph-when-a-single-poisoned-leaf-re-enters-the-reasoning-loop-as-trusted-s.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-taint-through-a-multi-hop-tool-invocation-graph-when-a-single-poisoned-leaf-re-enters-the-reasoning-loop-as-trusted-s.warrant.json
# Markdown SHA-256:   95a9c0015d211262654606d224eba0d51a7a4980b94221b862441c2cc8237cc2
# Code AST SHA-256:   8fe12edae8660ceb4cbba237ba09e78ddbfbdcfb6a1bc330aefa761d112b9b36
# Verified Classes:   TaintLaunderingError, TaintId, HopResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a generative hop shrinks its taint set without a declassifier clearance."""


@dataclass(frozen=True)
class TaintId:
    digest: str

    @staticmethod
    def content_addressed(normalized_leaf: str) -> "TaintId":
        return TaintId(hashlib.sha256(normalized_leaf.encode()).hexdigest())


@dataclass
class HopResult:
    taint_in: set[TaintId]
    taint_out: set[TaintId]
    is_generative: bool
    declassifier_cleared: set[TaintId] = field(default_factory=set)


def propagate(hop: HopResult) -> set[TaintId]:
    """Enforce derived-taint closure across a single hop in the invocation graph."""
    if not hop.is_generative:
        # Pure transformation: labels pass through mechanically.
        return hop.taint_in | hop.taint_out

    laundered = hop.taint_in - hop.taint_out - hop.declassifier_cleared
    if laundered:
        raise TaintLaunderingError(
            f"generative hop dropped taint {sorted(t.digest[:8] for t in laundered)} "
            f"without declassifier clearance; surviving imperatives may reach sinks"
        )
    return hop.taint_out | hop.declassifier_cleared


def guarded_sink(derived_taint: set[TaintId], side_effecting: bool) -> None:
    if side_effecting and derived_taint:
        raise TaintLaunderingError(
            f"side-effecting sink reached with inherited taint "
            f"{sorted(t.digest[:8] for t in derived_taint)}"
        )
