# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-provenance-label-before-it-crosses-a-memory-write-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-provenance-label-before-it-crosses-a-memory-write-boundary.warrant.json
# Markdown SHA-256:   4173bf6c5adc7871903aa98e8f43b2726929c1c6acda786cc93f5ce58e5e5a86
# Code AST SHA-256:   773d341baa467f5f98f84697262397fda9923987186b49dfae666fea2f49207c
# Verified Classes:   ProvenanceLaunderingError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

# Taint lattice: higher rank = more tainted. Join = max rank.
_RANK = {
    "trusted": 0,
    "untrusted:peer_agent": 1,
    "untrusted:tool_output": 2,
    "untrusted:web": 3,
}


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write would assign a label less tainted than its ancestry join."""
    pass


@dataclass
class Span:
    span_id: str
    label: str
    derived_from: tuple[str, ...] = field(default_factory=tuple)


def join_labels(labels: Iterable[str]) -> str:
    ranks = [_RANK.get(l) for l in labels]
    if any(r is None for r in ranks):
        # Unknown label: fail closed to most tainted.
        return "untrusted:web"
    return max(_RANK, key=lambda k: _RANK[k] if _RANK[k] == max(ranks) else -1)


def ancestry_closure(span: Span, store: dict[str, Span], seen: set[str] | None = None) -> set[str]:
    seen = seen or set()
    labels = {span.label}
    for parent_id in span.derived_from:
        if parent_id in seen:
            continue
        seen.add(parent_id)
        parent = store.get(parent_id)
        if parent is None:
            # Missing ancestry edge: cannot prove trust. Fail closed.
            labels.add("untrusted:web")
            continue
        labels |= ancestry_closure(parent, store, seen)
    return labels


def write_memory(new_span: Span, store: dict[str, Span], destination_privilege: str) -> Span:
    """Enforce monotone taint on memory write. Raises on laundering."""
    ancestry = ancestry_closure(new_span, store)
    required = join_labels(ancestry)

    if _RANK[new_span.label] < _RANK[required]:
        raise ProvenanceLaunderingError(
            f"span {new_span.span_id}: label {new_span.label!r} is less tainted than "
            f"ancestry join {required!r}; refusing to launder provenance"
        )

    if destination_privilege == "privileged" and _RANK[required] >= _RANK["untrusted:web"]:
        raise ProvenanceLaunderingError(
            f"span {new_span.span_id}: taint {required!r} may not enter privileged store"
        )

    store[new_span.span_id] = new_span
    return new_span
