# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-provenance-after-a-tool-call-returns-unlabeled-content-and-why-label-propagation-silently-fails-at-the-tool-bou.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-provenance-after-a-tool-call-returns-unlabeled-content-and-why-label-propagation-silently-fails-at-the-tool-bou.warrant.json
# Markdown SHA-256:   544c284f7d75b4a7479dc84962bc9c7b3c5cfc0fe6e92f59d4e44fa908e257e8
# Code AST SHA-256:   98ddb080d178cef26e3cd6dfd2b6597845d5ca60e16173a6ebe6f14fabb3c59e
# Verified Classes:   TaintLaunderingError, Segment, Context
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

TRUST_ORDER = {"TRUSTED": 0, "UNTRUSTED": 1}


class TaintLaunderingError(RuntimeError):
    """Raised when a segment is inserted into context without a transported
    or re-derived provenance label — i.e., the taint boundary was crossed
    by transport-as-re-derivation."""


@dataclass
class Segment:
    content: str
    label: str
    source_id: Optional[str] = None


@dataclass
class Context:
    segments: list = field(default_factory=list)
    _by_id: dict = field(default_factory=dict)

    def add_labeled(self, seg: Segment) -> None:
        if seg.source_id:
            self._by_id[seg.source_id] = seg
        self.segments.append(seg)

    def join_label(self, input_ids: list) -> str:
        labels = [self._by_id[i].label for i in input_ids]
        return max(labels, key=lambda l: TRUST_ORDER[l])

    def insert_derived(self, content: str, input_ids: list, derived_by: str) -> None:
        # The invariant: a derived string's label is the join of its inputs,
        # NOT the trust level of the code that derived it.
        if not input_ids:
            raise TaintLaunderingError(
                f"derived segment from {derived_by!r} has no recorded lineage; "
                "cannot re-derive taint label"
            )
        label = self.join_label(input_ids)
        self.add_labeled(Segment(content=content, label=label, source_id=None))


def run_tool_roundtrip(ctx: Context, raw_id: str, summarize_fn, summarize_id: str) -> None:
    raw = ctx._by_id[raw_id]
    # summarize_fn is trusted code, but it computes on untrusted input.
    summary = summarize_fn(raw.content)
    if summary == raw.content:
        # Verbatim passthrough: transport the label.
        ctx.add_labeled(Segment(content=summary, label=raw.label, source_id=summarize_id))
        return
    # Non-verbatim: must re-derive from lineage, never default to TRUSTED.
    ctx.insert_derived(summary, input_ids=[raw_id], derived_by="summarize")
    # Assert the result did not silently become trusted.
    if ctx._by_id.get(summarize_id) is None and ctx.segments[-1].label == "TRUSTED" and raw.label == "UNTRUSTED":
        raise TaintLaunderingError(
            "summarizer output of untrusted content was tagged TRUSTED; "
            "taint boundary crossed at tool return"
        )
