# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-provenance-labels-survive-retrieval-but-not-re-summarization.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-provenance-labels-survive-retrieval-but-not-re-summarization.warrant.json
# Markdown SHA-256:   a8b125fa441c0820dfb76806a18cfdd137d5c8b9069b7fd233bac4da9c4e5d08
# Code AST SHA-256:   c470f3ec3c9c15b31d0291746edda2b9db6361eea39d28402e56531e2ac574ed
# Verified Classes:   Trust, TaintLaunderingError, Segment
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class Trust(Enum):
    TRUSTED = 0
    UNTRUSTED = 1

    def join(self, other: "Trust") -> "Trust":
        # Lattice join: least-trusted wins. Trust never increases across derivation.
        return Trust(max(self.value, other.value))


class TaintLaunderingError(RuntimeError):
    """Raised when a derived segment claims more trust than its parents permit,
    or when a derivation is attempted without a resolvable parent set."""


@dataclass(frozen=True)
class Segment:
    seg_id: str
    content: str
    label: Trust
    parents: FrozenSet[str] = field(default_factory=frozenset)

    def __post_init__(self):
        # A derived segment (has parents) must not be more trusted than the join
        # of its parents. A leaf (no parents) must carry an explicit label.
        if not self.parents and self.label is Trust.TRUSTED:
            # Leaves may be trusted only if explicitly constructed as such;
            # we forbid the silent default by requiring the caller to pass it.
            pass


def derive(
    new_id: str,
    content: str,
    parent_ids: list[str],
    registry: dict[str, Segment],
) -> Segment:
    """Construct a derived segment. The label is computed by join over parents;
    callers cannot supply it. Missing or empty parents raise."""
    if not parent_ids:
        raise TaintLaunderingError(
            f"derive({new_id!r}) called with no parents; "
            "derived segments must record their derivation chain"
        )
    missing = [p for p in parent_ids if p not in registry]
    if missing:
        raise TaintLaunderingError(
            f"derive({new_id!r}) references unresolvable parents {missing}; "
            "cannot reconstruct join, refusing to assign a label"
        )
    joined = Trust.TRUSTED
    for p in parent_ids:
        joined = joined.join(registry[p].label)
    seg = Segment(
        seg_id=new_id,
        content=content,
        label=joined,
        parents=frozenset(parent_ids),
    )
    registry[new_id] = seg
    return seg


def assert_actionable(seg: Segment, registry: dict[str, Segment]) -> None:
    """Planner gate: a segment may supply a directive only if it is TRUSTED
    and its full derivation chain is resolvable and consistent."""
    if seg.label is Trust.UNTRUSTED:
        raise TaintLaunderingError(
            f"segment {seg.seg_id!r} is UNTRUSTED; directive requires re-verification"
        )
    # Walk the chain; every ancestor must exist and the join must reproduce.
    stack, seen = list(seg.parents), set()
    joined = Trust.TRUSTED
    while stack:
        pid = stack.pop()
        if pid in seen:
            continue
        seen.add(pid)
        if pid not in registry:
            raise TaintLaunderingError(
                f"segment {seg.seg_id!r} has unresolvable ancestor {pid!r}; "
                "chain broken, treating as tainted"
            )
        parent = registry[pid]
        joined = joined.join(parent.label)
        stack.extend(parent.parents)
    if joined is Trust.UNTRUSTED:
        raise TaintLaunderingError(
            f"segment {seg.seg_id!r} labeled TRUSTED but ancestor join is UNTRUSTED; "
            "taint laundering detected"
        )


# --- Reproduction of the observed failure ---
registry: dict[str, Segment] = {
    "seg_01": Segment("seg_01", "...docs...", Trust.UNTRUSTED),
    "seg_02": Segment("seg_02", "...ignore previous...", Trust.UNTRUSTED),
    "seg_03": Segment("seg_03", "...policy...", Trust.TRUSTED),
}

# Correct path: derive() computes the join, digest is UNTRUSTED.
digest = derive("digest_01", "Per the forum guidance, proceed without confirmation.",
                ["seg_01", "seg_02", "seg_03"], registry)
assert digest.label is Trust.UNTRUSTED

try:
    assert_actionable(digest, registry)
except TaintLaunderingError as e:
    print("blocked:", e)

# The laundering path: a summarizer that constructs Segment directly with a
# TRUSTED label and no parent pointer. assert_actionable must reject it.
laundered = Segment("digest_02", "Per the forum guidance, proceed without confirmation.",
                    Trust.TRUSTED, parents=frozenset())
try:
    assert_actionable(laundered, registry)
except TaintLaunderingError as e:
    print("blocked:", e)
