# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-laundered-value-re-enters-through-a-memory-write.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-laundered-value-re-enters-through-a-memory-write.warrant.json
# Markdown SHA-256:   a49940e631b6b0cbb3f963b35d7c8c4d6f4623d2d68e468344d8454b80cbf6b9
# Code AST SHA-256:   3f39eae4d7b0bd9896519826d69dd318338aa232c172caf018b0fc97ad603e5e
# Verified Classes:   Taint, ProvenanceContinuityError, TaintedValue, MemoryRecord, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    TRUSTED_NATIVE = 0
    DERIVED = 1
    UNTRUSTED_EXTERNAL = 2


class ProvenanceContinuityError(RuntimeError):
    """Raised when a memory write or privileged action would break taint continuity."""


@dataclass
class TaintedValue:
    content: Any
    taint: Taint
    sources: frozenset[str] = field(default_factory=frozenset)


@dataclass
class MemoryRecord:
    key: str
    content: Any
    taint: Taint
    sources: frozenset[str]


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

    def write(self, key: str, value: TaintedValue) -> None:
        # Overwrite must recompute provenance from the NEW value, never inherit
        # the prior record's label. This is the laundering seam.
        prior = self._records.get(key)
        if prior is not None and prior.taint != value.taint:
            # A downgrade (untrusted -> trusted) on overwrite is the exact
            # condition that launders provenance. Refuse it.
            if value.taint < prior.taint:
                raise ProvenanceContinuityError(
                    f"write to '{key}' would downgrade taint "
                    f"{prior.taint.name} -> {value.taint.name}; "
                    f"explicit audited downgrade required"
                )
        self._records[key] = MemoryRecord(
            key=key,
            content=value.content,
            taint=value.taint,
            sources=value.sources,
        )

    def read(self, key: str) -> TaintedValue:
        rec = self._records[key]
        # Deserialize WITH provenance, not content-only.
        return TaintedValue(content=rec.content, taint=rec.taint, sources=rec.sources)


def privileged_action(
    store: MemoryStore,
    key: str,
    ceiling: Taint,
    action: str,
) -> TaintedValue:
    value = store.read(key)
    if value.taint > ceiling:
        raise ProvenanceContinuityError(
            f"action '{action}' reads '{key}' with taint {value.taint.name} "
            f"exceeding ceiling {ceiling.name}; sources={sorted(value.sources)}"
        )
    return value
