# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-tainted-memory-write-as-a-clean-read-label-laundering-across-the-memory-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-tainted-memory-write-as-a-clean-read-label-laundering-across-the-memory-tool-boundary.warrant.json
# Markdown SHA-256:   6496d582538e979d4c3c987f735eeaa21f1cc6f49c3d57ecd9913c2c8b8d7768
# Code AST SHA-256:   c04b74695cd1ea80f3aee36bbd6b0849456c98004ab47061f36ec1a4da46c712
# Verified Classes:   TaintError, Label, Record, MemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable

class TaintError(RuntimeError):
    """Raised when a memory write would upgrade trust or a read disagrees with provenance."""

class Label(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1

def join(labels: Iterable[Label]) -> Label:
    return Label(max(labels, default=Label.TRUSTED))

@dataclass
class Record:
    key: str
    value: str
    label: Label
    provenance: tuple[str, ...] = field(default_factory=tuple)

class MemoryStore:
    def __init__(self) -> None:
        self._records: dict[str, Record] = {}
        self._untrusted_sources: set[str] = set()

    def mark_source_untrusted(self, source_id: str) -> None:
        self._untrusted_sources.add(source_id)

    def store(self, key: str, value: str, *, input_labels: list[Label],
              provenance: tuple[str, ...]) -> Record:
        # A write never upgrades trust: label is the join of inputs only.
        derived = join(input_labels)
        if any(p in self._untrusted_sources for p in provenance):
            derived = Label.UNTRUSTED
        rec = Record(key=key, value=value, label=derived, provenance=provenance)
        self._records[key] = rec
        return rec

    def read(self, key: str) -> Record:
        rec = self._records[key]
        # Reconcile label against provenance; provenance wins on disagreement.
        prov_taint = Label.UNTRUSTED if any(
            p in self._untrusted_sources for p in rec.provenance
        ) else Label.TRUSTED
        if rec.label == Label.TRUSTED and prov_taint == Label.UNTRUSTED:
            raise TaintError(
                f"label-laundering detected on read of {key!r}: "
                f"stored TRUSTED but provenance reaches untrusted source"
            )
        return rec
