# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-span-level-pii-redaction-as-non-composable-across-a-nested-trace-tree.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-span-level-pii-redaction-as-non-composable-across-a-nested-trace-tree.warrant.json
# Markdown SHA-256:   1ae6f11f84c00588a24419828471f1a92005f27dfa6a5ff7ac7c393447d97615
# Code AST SHA-256:   4ded522f64eeeb02336dbe9f46820e872e5d4f48910f32943133e42686383279
# Verified Classes:   TaintCompositionError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintCompositionError(RuntimeError):
    """Raised when a span would be exported despite an unresolved transitive taint."""
    pass


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_id: Optional[str]
    payload: str
    redaction_mode: str          # "lexical" | "ingestion" | "semantic"
    tainted_tokens: set = field(default_factory=set)


def transitive_taint(span: Span, spans_by_id: dict) -> set:
    """Walk parent edges; a span inherits the union of ancestor tainted tokens."""
    closure = set(span.tainted_tokens)
    cursor = span.parent_id
    seen = set()
    while cursor and cursor not in seen:
        seen.add(cursor)
        ancestor = spans_by_id.get(cursor)
        if ancestor is None:
            break
        closure |= ancestor.tainted_tokens
        cursor = ancestor.parent_id
    return closure


def assert_exportable(span: Span, spans_by_id: dict) -> None:
    closure = transitive_taint(span, spans_by_id)
    if not closure:
        return
    if span.redaction_mode == "ingestion":
        # Original never entered context; derivation edges cannot carry it.
        return
    if span.redaction_mode == "semantic":
        # Model-assisted pass verified paraphrase coverage for this span.
        return
    # lexical-only redaction with a live taint closure: unsound to export.
    raise TaintCompositionError(
        f"span {span.span_id} in trace {span.trace_id} has taint closure "
        f"{sorted(closure)} but was redacted lexically; derivation may leak "
        f"across sibling/ancestor spans — refuse export"
    )


def export_trace(spans: list) -> list:
    by_id = {s.span_id: s for s in spans}
    exported = []
    for s in spans:
        assert_exportable(s, by_id)
        exported.append(s)
    return exported
