# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-quarantine-boundary-has-leaked-during-context-admission.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-quarantine-boundary-has-leaked-during-context-admission.warrant.json
# Markdown SHA-256:   405fcfb65fef07ffff8f1d6d34a6b89aacb68b0134db492ed2f4f8bdba49d645
# Code AST SHA-256:   bc117ef45c53d8bd2cbff035ea02cfe2dd2ef087192eab6492d624273df0b88f
# Verified Classes:   TaintBoundaryViolation, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintBoundaryViolation(RuntimeError):
    """Raised when a span crosses the admission membrane without a valid
    declassification path or with a broken derivation edge."""
    pass


@dataclass
class Span:
    span_id: str
    tainted: bool
    derived_from: tuple[str, ...] = ()
    declassified_by: Optional[str] = None


def admission_predicate(span: Span, registry: dict[str, Span]) -> bool:
    """Admit only if span and all ancestors are clean, or an explicit
    declassification event covers the span."""
    if span.declassified_by is not None:
        return True
    if span.tainted:
        return False
    # Walk derivation graph; fail closed on any missing edge.
    for parent_id in span.derived_from:
        parent = registry.get(parent_id)
        if parent is None:
            raise TaintBoundaryViolation(
                f"span {span.span_id} references unknown ancestor {parent_id}; "
                "derivation graph incomplete, admission fails closed"
            )
        if not admission_predicate(parent, registry):
            return False
    return True


def admit_to_context(span: Span, registry: dict[str, Span]) -> Span:
    if not admission_predicate(span, registry):
        raise TaintBoundaryViolation(
            f"span {span.span_id} is tainted or has a tainted ancestor "
            "and carries no declassification event; refusing admission"
        )
    return span
