# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-taint-through-memory-write-provenance-labels.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-taint-through-memory-write-provenance-labels.warrant.json
# Markdown SHA-256:   04400b287d31dcb62c3edc85dd1c900dd3ebae5386624bfd66d8a9614ea6cac8
# Code AST SHA-256:   bf463189481e80456007214d45c70373f455163e89d3a7937e19d3416a0f4eb9
# Verified Classes:   ProvenanceLaunderingError, MemoryRecord, WriteRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

# Taint lattice: clean < untrusted. Join is set union of source tags.
CLEAN: FrozenSet[str] = frozenset()

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory record's stored provenance is weaker than the
    join of the provenance of the inputs that produced its value."""
    pass

@dataclass
class MemoryRecord:
    key: str
    value: str
    stored_provenance: FrozenSet[str]   # what the store claims
    writer: str

@dataclass
class WriteRequest:
    key: str
    value: str
    input_labels: FrozenSet[str]        # provenance of the actual inputs
    writer: str

def write(store: dict, req: WriteRequest) -> MemoryRecord:
    # Correct behavior: stored provenance is the JOIN of input labels and writer.
    joined = req.input_labels | frozenset({f"writer:{req.writer}"})
    rec = MemoryRecord(req.key, req.value, joined, req.writer)
    store[req.key] = rec
    return rec

def audit_read(store: dict, key: str, expected_inputs: FrozenSet[str]) -> MemoryRecord:
    rec = store.get(key)
    if rec is None:
        raise ProvenanceLaunderingError(f"missing record {key!r}")
    # The invariant: stored provenance must dominate every contributing input.
    missing = expected_inputs - rec.stored_provenance
    if missing:
        raise ProvenanceLaunderingError(
            f"record {key!r} laundered taint: stored={sorted(rec.stored_provenance)} "
            f"but inputs {sorted(missing)} are not represented. "
            f"Content derived from untrusted sources carries a clean label."
        )
    return rec

def demo_laundering() -> None:
    store: dict = {}
    # Clean write, then a tainted overwrite whose input labels are dropped
    # by a buggy upsert path that preserves the prior record's metadata.
    write(store, WriteRequest("notes", "clean", CLEAN, "agent"))
    store["notes"].value = "injected instruction"   # buggy metadata-preserving upsert
    # Audit with the true inputs of the overwrite: should raise, and does.
    audit_read(store, "notes", frozenset({"untrusted:web"}))

if __name__ == "__main__":
    demo_laundering()
