# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-re-summarization-stages-in-agent-trace-observability-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-re-summarization-stages-in-agent-trace-observability-pipelines.warrant.json
# Markdown SHA-256:   3654e860eae434643cc5a7da06a2d32dc3a34df34f091a61e43a79b2e0c13af0
# Code AST SHA-256:   f765db6202c02bfba088b0ee094fe321abee60a8fe03a05de0181c7e14298094
# Verified Classes:   TaintLaunderingError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a derived span's taint does not cover its inputs' taint,
    or when a derivation edge is created without an input manifest."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    taint: FrozenSet[str] = field(default_factory=frozenset)


def derive_span(
    span_id: str,
    input_manifest: list[Span] | None,
    declared_taint: FrozenSet[str],
) -> Span:
    """Create a derived span, enforcing the monotone-join invariant.

    The manifest must be explicit: scheduler-invoked stages have no ambient
    call stack, so an omitted manifest means the derivation edge is
    unrecordable and the span cannot be safely labeled.
    """
    if input_manifest is None:
        raise TaintLaunderingError(
            f"span {span_id!r} created without an input manifest; "
            "derivation edge is unrecordable and taint cannot be joined"
        )

    joined: FrozenSet[str] = frozenset().union(
        *(s.taint for s in input_manifest)
    )

    # Monotonicity: declared taint must cover the join. Growing is allowed
    # (over-approximation is auditable); shrinking is laundering.
    if not joined.issubset(declared_taint):
        raise TaintLaunderingError(
            f"span {span_id!r} declares taint {set(declared_taint)} "
            f"but inputs require {set(joined)}; "
            f"missing={set(joined) - set(declared_taint)}"
        )

    return Span(span_id=span_id, taint=declared_taint)


def write_episodic_memory(record_span: Span, payload: str) -> dict:
    """Taint-checked sink at the trust boundary. A clean label on a record
    whose derivation was tainted is the laundering signature."""
    if record_span.taint == frozenset():
        # Cannot distinguish "genuinely clean" from "laundered" here; the
        # upstream constructor must have already raised if laundering
        # occurred. This guard catches records that bypassed derivation.
        raise TaintLaunderingError(
            f"memory record {record_span.span_id!r} has empty taint; "
            "refusing to persist an unprovenanced record to episodic memory"
        )
    return {"span_id": record_span.span_id, "taint": sorted(record_span.taint), "payload": payload}
