# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-prompt-injection-taint-labels-through-tool-outputs-but-drops-them-at-the-memory-write-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-prompt-injection-taint-labels-through-tool-outputs-but-drops-them-at-the-memory-write-boundary.warrant.json
# Markdown SHA-256:   a0aa42a9fddad5f074ab7178d85f96e4c10a95bbf731372c65e0228c41b36102
# Code AST SHA-256:   7628512cae2da1e7924b4136ccbee7021b13fd8f26b6a818f151c14b9ed02201
# Verified Classes:   TaintLaunderingError, LabeledSegment, LabeledRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

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


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would persist a record whose label is
    weaker than the join of its source segments' labels."""
    pass


@dataclass(frozen=True)
class LabeledSegment:
    content: str
    trust: str  # "internal" | "untrusted"
    taint: frozenset[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class LabeledRecord:
    content: str
    trust: str
    taint: frozenset[str]


def join_labels(segments: Iterable[LabeledSegment]) -> tuple[str, frozenset[str]]:
    segs = list(segments)
    if not segs:
        return "internal", frozenset()
    worst = max(segs, key=lambda s: TRUST_ORDER[s.trust]).trust
    taint = frozenset().union(*(s.taint for s in segs))
    return worst, taint


def consolidate(segments: list[LabeledSegment], store_has_provenance: bool) -> LabeledRecord:
    trust, taint = join_labels(segments)
    summary = " | ".join(s.content for s in segments)  # distillation stand-in
    if trust == "untrusted" and not store_has_provenance:
        # Fail closed: do not silently downgrade to internal.
        raise TaintLaunderingError(
            f"refusing to persist untrusted record (taint={sorted(taint)}) "
            f"into a store without a provenance field; would launder taint"
        )
    return LabeledRecord(content=summary, trust=trust, taint=taint)


def memory_write(record: LabeledRecord, existing_trust: str | None) -> LabeledRecord:
    # Defense in depth: if a caller hands us a record whose trust is weaker
    # than a label it claims to carry, reject.
    if existing_trust is not None and TRUST_ORDER[record.trust] < TRUST_ORDER[existing_trust]:
        raise TaintLaunderingError(
            f"record trust {record.trust!r} weaker than incoming {existing_trust!r}"
        )
    return record
