# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-memory-write-before-it-becomes-a-durable-provenance-laundering-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-memory-write-before-it-becomes-a-durable-provenance-laundering-channel.warrant.json
# Markdown SHA-256:   fd34768f8adcc61436243d526298a905d2546a59128c45c3e97ebd5d478a3275
# Code AST SHA-256:   2bdd0cff9866407e63a2c568c70a1b4d67aaabf8b1a1ffeb97a9ae4e351e0a45
# Verified Classes:   Trust, ProvenanceViolation, TaintedSegment, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Trust(Enum):
    UNTRUSTED = 0
    TRUSTED = 1


class ProvenanceViolation(RuntimeError):
    """Raised when a memory write would launder taint by dropping the label join
    or discarding derivation edges during a lossy transformation."""
    pass


@dataclass
class TaintedSegment:
    text: str
    label: Trust
    source_hash: str


@dataclass
class MemoryRecord:
    text: str
    label: Trust
    derived_from: set = field(default_factory=set)
    instruction_shaped: bool = False


def join_labels(segments):
    # Least-upper-bound in the trust lattice: any untrusted input taints the output.
    return Trust.UNTRUSTED if any(s.label is Trust.UNTRUSTED for s in segments) else Trust.TRUSTED


def commit_memory_write(output_text, inputs, claimed_label, derived_from,
                        is_transforming, instruction_shaped=False):
    expected = join_labels(inputs)
    expected_edges = {s.source_hash for s in inputs}

    if is_transforming and claimed_label is Trust.TRUSTED and expected is Trust.UNTRUSTED:
        raise ProvenanceViolation(
            "Transforming write claims TRUSTED but inputs include untrusted sources; "
            "this would launder taint through distillation."
        )

    if not expected_edges.issubset(derived_from):
        missing = expected_edges - derived_from
        raise ProvenanceViolation(
            f"Derivation edges dropped during write: missing {sorted(missing)}; "
            "record cannot be audited or re-evaluated."
        )

    if is_transforming and instruction_shaped and claimed_label is Trust.TRUSTED:
        raise ProvenanceViolation(
            "Instruction-shaped output from a transforming write must be quarantined "
            "regardless of computed label."
        )

    return MemoryRecord(
        text=output_text,
        label=expected,
        derived_from=derived_from,
        instruction_shaped=instruction_shaped,
    )


def quarantine_or_commit(record_kwargs):
    try:
        return ("committed", commit_memory_write(**record_kwargs))
    except ProvenanceViolation as e:
        return ("quarantined", str(e))
