# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-labels-when-opentelemetry-genai-span-attributes-are-aggregated-across-a-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-labels-when-opentelemetry-genai-span-attributes-are-aggregated-across-a-fan-out.warrant.json
# Markdown SHA-256:   6ac53faaf39b180e9c2b2f9fbb6cc2fae8ee7caea9a14b91a6ec04424f5ed614
# Code AST SHA-256:   7bfbfedc714dcb1b9221591f2ffc76aacc56a6b21e3f3f9205a192ad9ea0c5c8
# Verified Classes:   TaintAggregationError, ChildSpan, ParentPrompt
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintAggregationError(RuntimeError):
    """Raised when a parent prompt's re-derived taint set does not cover
    the taint labels of every child span whose output is present in it."""


@dataclass
class ChildSpan:
    span_id: str
    output: str
    taint_labels: frozenset


@dataclass
class ParentPrompt:
    span_id: str
    segments: list  # list[ChildSpan] actually concatenated into the prompt
    declared_taint: frozenset = field(default_factory=frozenset)


def _present(segment: ChildSpan, prompt_text: str) -> bool:
    # A segment is "present" only if its exact bytes survived into the prompt.
    # Hash-based containment avoids substring false positives from truncation.
    return hashlib.sha256(segment.output.encode()).hexdigest() in {
        hashlib.sha256(prompt_text[i:i + len(segment.output)].encode()).hexdigest()
        for i in range(0, max(1, len(prompt_text) - len(segment.output) + 1))
    }


def rederive_taint(prompt_text: str, candidates: list[ChildSpan]) -> frozenset:
    derived = set()
    for seg in candidates:
        if _present(seg, prompt_text):
            derived |= set(seg.taint_labels)
    return frozenset(derived)


def assert_taint_covered(prompt: ParentPrompt, prompt_text: str) -> frozenset:
    required = rederive_taint(prompt_text, prompt.segments)
    if not required.issubset(prompt.declared_taint):
        missing = required - prompt.declared_taint
        raise TaintAggregationError(
            f"parent span {prompt.span_id} declares taint {sorted(prompt.declared_taint)} "
            f"but prompt contains bytes from spans requiring {sorted(missing)}; "
            f"re-derive at the merge boundary before the next tool call"
        )
    return required
