# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-labels-from-silently-decoupling-from-their-opentelemetry-trace-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-labels-from-silently-decoupling-from-their-opentelemetry-trace-spans.warrant.json
# Markdown SHA-256:   3b88ab860f15650e13d29f997c7cafd2184dd2516101677fbecf1d6413548a0b
# Code AST SHA-256:   1e5732daf12dd819335d004dc3943a7e382637f8402dc1d64463ecbd7a650379
# Verified Classes:   TaintState, TaintPropagationError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum
from typing import Optional


class TaintState(Enum):
    CLEAN = "clean"
    TAINTED = "tainted"
    UNKNOWN = "unknown"


class TaintPropagationError(RuntimeError):
    """Raised when a span's taint state violates the propagation invariant."""


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    taint: TaintState
    declassified: bool = False
    content_hash: Optional[str] = None


def verify_monotonicity(span: Span, parent: Optional[Span]) -> None:
    """Enforce: a child may not report CLEAN under a TAINTED parent
    without an audited declassification event."""
    if parent is None:
        return
    if parent.taint is TaintState.TAINTED and span.taint is TaintState.CLEAN:
        if not span.declassified or not span.content_hash:
            raise TaintPropagationError(
                f"span {span.span_id} reports CLEAN under TAINTED parent "
                f"{parent.span_id} with no signed declassification attestation"
            )


def verify_presence(span: Span) -> None:
    """Enforce: absence of taint must never be coerced to CLEAN.
    Instrumentation must emit UNKNOWN when the carrier was dropped."""
    if span.taint is TaintState.CLEAN and span.content_hash is None:
        # CLEAN without a content hash means the label was defaulted,
        # not derived from an inspected, taint-free payload.
        raise TaintPropagationError(
            f"span {span.span_id} claims CLEAN without content attestation; "
            "treat as UNKNOWN and re-derive"
        )


def gate_tool_call(span: Span) -> bool:
    """Enforcement gate: only CLEAN with attestation may proceed."""
    try:
        verify_presence(span)
    except TaintPropagationError:
        return False
    return span.taint is TaintState.CLEAN


def export_span(span: Span, parent: Optional[Span]) -> None:
    verify_presence(span)
    verify_monotonicity(span, parent)
    # span is now safe to enqueue for the OTel exporter
