# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-before-a-tool-boundary-and-when-is-label-propagation-safe-to-defer.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-before-a-tool-boundary-and-when-is-label-propagation-safe-to-defer.warrant.json
# Markdown SHA-256:   479b3e8a2c089ff494c8e550f2c0900dce2423dcb9460f9ae66c58df0938c1a0
# Code AST SHA-256:   0c2797b9e0555e68d1ec53f02bf0a82fabeb97fdcefa4aed5c3f89da224fec2f
# Verified Classes:   TaintLaunderingError, Segment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class TaintLaunderingError(RuntimeError):
    """Raised when a derived context segment would carry a weaker trust label than its parents."""

TRUST_ORDER = {"untrusted": 0, "trusted": 1}  # higher = more trusted

@dataclass
class Segment:
    seg_id: str
    trust: str
    parents: tuple = field(default_factory=tuple)

def join_trust(parents: list) -> str:
    """Meet-join: the derived label is the most restrictive of all parents."""
    if not parents:
        # No parents => a fresh runtime-constructed segment. Defaulting to
        # 'trusted' here is the exact laundering bug; require explicit origin.
        raise TaintLaunderingError("segment has no derivation parents; cannot assign trust")
    return min((p.trust for p in parents), key=lambda t: TRUST_ORDER[t])

def derive(child_id: str, parents: list, claimed_trust: Optional[str] = None) -> Segment:
    """Create a derived segment, enforcing label inheritance."""
    inherited = join_trust(parents)
    if claimed_trust is not None and TRUST_ORDER[claimed_trust] > TRUST_ORDER[inherited]:
        raise TaintLaunderingError(
            f"segment {child_id}: claimed trust {claimed_trust!r} exceeds "
            f"inherited {inherited!r} from parents {[p.seg_id for p in parents]}"
        )
    return Segment(seg_id=child_id, trust=inherited, parents=tuple(p.seg_id for p in parents))

def guard_sink(segment: Segment, sink: str, effect_bearing: bool) -> None:
    """Block effect-bearing sinks from consuming untrusted segments without declassification."""
    if effect_bearing and segment.trust == "untrusted":
        raise TaintLaunderingError(
            f"refusing effect-bearing sink {sink!r} with untrusted segment {segment.seg_id!r}; "
            f"declassify explicitly or route to sandbox"
        )

# Trace of the observed failure, now caught:
web = Segment(seg_id="fetch:1", trust="untrusted")
# BUGGY path would be: summary = Segment("summary:1", trust="trusted")  # no parents
summary = derive("summary:1", parents=[web], claimed_trust="trusted")   # -> raises
