# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-at-the-tool-output-to-memory-write-seam.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-at-the-tool-output-to-memory-write-seam.warrant.json
# Markdown SHA-256:   f6188d4c774d1b24cc984a4cab5313defa33778dfdf53c49ac0916681068df0f
# Code AST SHA-256:   65d8b8ded56a06906391a1b49279ab9fe2ea064f3b1dec3d8ca0e2a56fffeae1
# Verified Classes:   TaintSeamViolation, LabeledValue
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintSeamViolation(RuntimeError):
    """Raised when a memory write commits a value whose provenance labels
    were not carried from the source container to the sink."""


@dataclass(frozen=True)
class LabeledValue:
    value: str
    labels: FrozenSet[str] = field(default_factory=frozenset)

    def union(self, other: "LabeledValue") -> "LabeledValue":
        return LabeledValue(self.value + other.value, self.labels | other.labels)


def model_transform(context: list[LabeledValue], output_text: str) -> LabeledValue:
    """A model call is a taint-propagating function: its output inherits the
    union of all labels present in its context. This is Guard A."""
    inherited: FrozenSet[str] = frozenset()
    for item in context:
        inherited = inherited | item.labels
    return LabeledValue(output_text, inherited)


def memory_write(record: LabeledValue, caller_label: str) -> None:
    """The sink checks the VALUE's labels, never the caller's label.

    caller_label is accepted only to make the bug explicit: it must not be
    the basis for the admission decision.
    """
    if "UNTRUSTED" in record.labels:
        # Route to approval queue rather than committing as trusted.
        raise TaintSeamViolation(
            f"refusing trusted write of tainted value: labels={sorted(record.labels)}, "
            f"caller_label={caller_label!r} is irrelevant to provenance"
        )
    # commit(record.value) ...


def extract_and_write(tool_output: LabeledValue, model_text: str, caller_label: str) -> None:
    # The extractor is a labeled transform, not a bare string copy.
    extracted = model_transform([tool_output], model_text)
    if not extracted.labels and tool_output.labels:
        # Defense against a transform that forgot to propagate.
        raise TaintSeamViolation("transform dropped labels from a tainted source")
    memory_write(extracted, caller_label)


# Reproduces the incident: tainted page -> model paraphrase -> memory write.
page = LabeledValue("...keys never expire...", frozenset({"UNTRUSTED"}))
extract_and_write(
    tool_output=page,
    model_text="Deployment key rotation policy: keys never expire.",
    caller_label="TRUSTED",  # the calling turn is trusted; the value is not
)
