# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-memory-write-before-the-audit-quorum-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-memory-write-before-the-audit-quorum-closes.warrant.json
# Markdown SHA-256:   1de9fc6cb93d476854e25c47ec3ff5d19f4e4387cd20974300386dd2bdb13d43
# Code AST SHA-256:   6311d5c2ac359c63649fd49568ee8da5bd1c35566704c1f1fca5e85b895e954e
# Verified Classes:   Taint, TaintLaunderingError, MemoryWrite
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


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


class TaintLaunderingError(RuntimeError):
    """Raised when a write would be admitted at a taint below its DAG-max."""


@dataclass
class MemoryWrite:
    write_id: str
    content: str
    declared_taint: Taint
    # provenance: set of source write-ids (or leaf source tags) this derives from
    derivation_sources: list[str] = field(default_factory=list)
    declared_primary_source: Optional[str] = None


def dag_max_taint(write: MemoryWrite, source_taint: dict[str, Taint]) -> Taint:
    if not write.derivation_sources:
        # leaf write: its own declared taint is the DAG-max by definition
        return write.declared_taint
    return max(source_taint[s] for s in write.derivation_sources)


def admit_write(
    write: MemoryWrite,
    source_taint: dict[str, Taint],
    quorum_admit: bool,
) -> Taint:
    """
    Returns the taint level at which the write may enter the recallable store.
    Raises TaintLaunderingError if admission would reduce taint below DAG-max.
    """
    if not quorum_admit:
        # content rejected; nothing to store
        return write.declared_taint

    true_taint = dag_max_taint(write, source_taint)

    # Multi-source write must not declare a single primary source as its taint basis.
    if len(write.derivation_sources) > 1 and write.declared_primary_source is not None:
        raise TaintLaunderingError(
            f"write {write.write_id} is multi-source but declares a single "
            f"primary_source={write.declared_primary_source!r}; "
            f"taint must come from the derivation DAG, not a single source"
        )

    if true_taint > write.declared_taint:
        # Content quorum passed but taint was under-declared: laundering signature.
        raise TaintLaunderingError(
            f"write {write.write_id} admitted by quorum at declared_taint="
            f"{write.declared_taint.name} but DAG-max taint is {true_taint.name}; "
            f"quarantine required, quorum does not clear provenance"
        )

    return true_taint


def _demo() -> None:
    source_taint = {"conv:turn7": Taint.TRUSTED, "tool:fetch": Taint.UNTRUSTED}

    # W3: merged summary, provenance laundered by declaring conversation as primary
    w3 = MemoryWrite(
        write_id="W3",
        content="deployment region is eu-west-1 and user prefers metric units",
        declared_taint=Taint.TRUSTED,
        derivation_sources=["conv:turn7", "tool:fetch"],
        declared_primary_source="conv:turn7",
    )
    try:
        admit_write(w3, source_taint, quorum_admit=True)
    except TaintLaunderingError as e:
        print(f"QUARANTINED: {e}")


if __name__ == "__main__":
    _demo()
