# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-label-laundering-when-a-tainted-tool-output-is-re-derived-through-a-clean-summarizer-the-implicit-join-taint-collapse-in-d.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-label-laundering-when-a-tainted-tool-output-is-re-derived-through-a-clean-summarizer-the-implicit-join-taint-collapse-in-d.warrant.json
# Markdown SHA-256:   94d96736add93096202d0488524c0e05252303c5ad6293212830990c7413d8ce
# Code AST SHA-256:   b513057a883f83b5836546e5865e061835bcf0a727b6a4428b4544c3701c5d42
# Verified Classes:   TaintCollapseError, UnknownProvenanceError, Labeled
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintCollapseError(RuntimeError):
    """Raised when a model-produced value's label under-approximates its read set."""
    pass


class UnknownProvenanceError(TaintCollapseError):
    """Raised when a derivation's read set cannot be materialized (fail-closed)."""
    pass


@dataclass(frozen=True)
class Labeled:
    value: str
    label: str  # "LOW" or "HIGH"
    read_set: frozenset = field(default_factory=frozenset)

    def join(self, other: "Labeled") -> "Labeled":
        label = "HIGH" if "HIGH" in (self.label, other.label) else "LOW"
        return Labeled(
            value=self.value,
            label=label,
            read_set=self.read_set | other.read_set | {other.label},
        )


def join_read_set(inputs: Iterable[Labeled]) -> str:
    inputs = list(inputs)
    if not inputs:
        raise UnknownProvenanceError("empty read set: cannot prove LOW")
    return "HIGH" if any(i.label == "HIGH" for i in inputs) else "LOW"


def model_derive(prompt_segments: Iterable[Labeled], output_text: str) -> Labeled:
    """Wrap a model call. Label = join over the actual prompt read set.

    The output channel is irrelevant; only the read set matters.
    """
    segments = list(prompt_segments)
    try:
        derived_label = join_read_set(segments)
    except UnknownProvenanceError:
        # Fail closed: unknown provenance is treated as HIGH.
        derived_label = "HIGH"
    read_set = frozenset(s.value for s in segments if s.label == "HIGH")
    return Labeled(value=output_text, label=derived_label, read_set=read_set)


def write_memory(record: Labeled, partition: str) -> None:
    """Enforce that a LOW partition only accepts LOW-labeled records."""
    if partition == "LOW" and record.label == "HIGH":
        raise TaintCollapseError(
            f"refusing LOW memory write of HIGH-derived content; "
            f"read_set={sorted(record.read_set)}"
        )
    if partition == "LOW" and not record.read_set and record.label == "LOW":
        # A LOW record with no read-set evidence is unproven, not clean.
        raise UnknownProvenanceError(
            "LOW write without materialized read set: provenance unproven"
        )
    # persist according to partition
    return None


def run_pipeline(fetch_ticket, summarize, memory) -> None:
    ticket = fetch_ticket("T-4412")  # Labeled(value=..., label="HIGH", ...)
    # summarize receives the ticket as part of its prompt read set.
    summary = model_derive(
        prompt_segments=[ticket, Labeled("summarize this ticket", "LOW")],
        output_text=summarize(ticket.value),
    )
    # The summary is HIGH because the read set contains a HIGH segment,
    # even if the injected instruction was paraphrased away.
    if summary.label == "HIGH":
        write_memory(summary, partition="HIGH")  # quarantined, not LOW
    else:
        write_memory(summary, partition="LOW")
