# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-output-before-taint-propagation-the-classifier-verdict-derivation-order-race-in-taint-aware-sandboxes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-output-before-taint-propagation-the-classifier-verdict-derivation-order-race-in-taint-aware-sandboxes.warrant.json
# Markdown SHA-256:   06b2ede5d9a5b4a257b28db25fb2fce8d1e1916701377b37b86929c8dbc5a5e4
# Code AST SHA-256:   f6703e9cd623a4cb6996626d9406db20904eaceff1eb398ccd4a03b8a6f3273c
# Verified Classes:   TaintLaunderingError, Artifact
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact would be admitted clean despite a tainted ancestor."""

@dataclass
class Artifact:
    node_id: str
    parent: Optional["Artifact"]
    lossy_from_parent: bool          # True if transform was not offset-preserving
    local_verdict: str               # "clean" | "tainted" from classifier on this node
    admitted_taint: Optional[str] = None
    field: dict = field(default_factory=dict)

def inherited_taint(a: Artifact) -> str:
    chain = []
    cur = a
    while cur is not None:
        chain.append(cur)
        cur = cur.parent
    taint = "clean"
    for node in reversed(chain):
        if node.local_verdict == "tainted":
            taint = "tainted"
        if taint == "tainted" and node.lossy_from_parent:
            # lossy edge under a tainted parent: cannot span-quarantine, escalate
            taint = "tainted"
    return taint

def admit(a: Artifact) -> Artifact:
    inherited = inherited_taint(a)
    # A fresh 'clean' verdict must never downgrade inherited taint.
    if inherited == "tainted" and a.local_verdict == "clean":
        # either admit with inherited taint, or quarantine — never admit clean
        a.admitted_taint = "tainted"
        return a
    a.admitted_taint = inherited
    return a

def admit_or_quarantine(a: Artifact, allow_tainted: bool) -> Artifact:
    admitted = admit(a)
    if admitted.admitted_taint == "tainted" and not allow_tainted:
        raise TaintLaunderingError(
            f"node {a.node_id}: derived artifact from tainted ancestor "
            f"(lossy={a.lossy_from_parent}, local={a.local_verdict}) "
            f"refused admission; would launder taint to descendants"
        )
    return admitted

# Trace: raw fetch tainted -> html_to_text (lossy) -> chunk (span overlap empty)
raw   = Artifact("raw",   None, False, "tainted")
text  = Artifact("text",  raw,  True,  "clean")   # stripping dropped flagged span
chunk = Artifact("chunk7", text, True,  "clean")   # span map stale, overlap empty

admit_or_quarantine(chunk, allow_tainted=False)   # raises TaintLaunderingError
