# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-across-tool-call-dataflow-when-provenance-is-laundered-through-a-summarization-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-across-tool-call-dataflow-when-provenance-is-laundered-through-a-summarization-hop.warrant.json
# Markdown SHA-256:   5f2f61f9106fb54d2ce006505ff09f0e0b29d0acdd16a197b35be0136b596560
# Code AST SHA-256:   25e085c02628240304f78f7dce69f923f2cf56a7ab0764102ca4c3b062a953ac
# Verified Classes:   TaintLaunderingError, ProvenanceLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a sink consumes data whose provenance DAG reaches an UNTRUSTED ancestor."""
    pass


UNTRUSTED = "UNTRUSTED"
TRUSTED = "TRUSTED"
SENSITIVE_SINKS = {"email.send", "http.post", "shell.exec", "file.write"}


class ProvenanceLedger:
    def __init__(self):
        self._labels = {}      # segment_id -> label
        self._parents = {}     # segment_id -> set of parent segment_ids
        self._next = 0

    def ingest(self, label, parents=()):
        sid = f"seg-{self._next}"
        self._next += 1
        self._labels[sid] = label
        self._parents[sid] = set(parents)
        return sid

    def derive(self, parent_ids):
        # Generative hop: output inherits the UNION of parent labels.
        # Never reset to TRUSTED because bytes changed.
        if not parent_ids:
            raise TaintLaunderingError("derive() requires at least one parent edge")
        label = UNTRUSTED if any(self._labels[p] == UNTRUSTED for p in parent_ids) else TRUSTED
        return self.ingest(label, parents=parent_ids)

    def ancestors(self, sid, seen=None):
        seen = seen or set()
        if sid in seen:
            return seen
        seen.add(sid)
        for p in self._parents.get(sid, ()):
            self.ancestors(p, seen)
        return seen

    def check_sink(self, sink, arg_segment_id):
        if sink not in SENSITIVE_SINKS:
            return
        for anc in self.ancestors(arg_segment_id):
            if self._labels.get(anc) == UNTRUSTED:
                raise TaintLaunderingError(
                    f"sink {sink!r} blocked: arg {arg_segment_id!r} descends from "
                    f"UNTRUSTED ancestor {anc!r} (laundering via generative hop)"
                )


def run_summarize_then_send(ledger: ProvenanceLedger):
    # 1. untrusted ingest
    s0 = ledger.ingest(UNTRUSTED)
    # 2. summarization hop: output label = union(parents), NOT reset
    s1 = ledger.derive([s0])
    # 3. planner routes the summary into a sensitive sink
    ledger.check_sink("email.send", s1)  # raises: laundering blocked
