# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-provenance-loss-when-otel-genai-span-correlation-aliases-a-re-entrant-tool-call-across-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-provenance-loss-when-otel-genai-span-correlation-aliases-a-re-entrant-tool-call-across-agent-hops.warrant.json
# Markdown SHA-256:   f1d4323be1f5939c47892250f072ccd63cd0652d5dfc63da6e287fd80609a920
# Code AST SHA-256:   4c27a0d24f6f7d6634b50a5ffb48363e24d5baa36018a7db6e1c40820b60e0d0
# Verified Classes:   TaintProvenanceAliasingError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintProvenanceAliasingError(RuntimeError):
    """Raised when span-identity injectivity cannot be proven, so a
    topology-derived taint verdict would be unsound."""


@dataclass
class Span:
    trace_id: str
    span_id: str
    tool_call_id: str
    call_index: int
    carries_taint: bool = False
    taint_sources: list[str] = field(default_factory=list)


def assert_injective_span_identity(
    spans: Iterable[Span],
    server_invocation_count: dict[str, int],
) -> None:
    """Verify that logical tool invocations map 1:1 onto span identities.

    Compares the pipeline's distinct span identities per tool.call.id against
    an independent server-side invocation ledger. Any mismatch means the
    topology join may alias a re-entrant call onto a clean ancestor.
    """
    by_call_id: dict[str, set[str]] = {}
    for s in spans:
        by_call_id.setdefault(s.tool_call_id, set()).add(s.span_id)

    for call_id, span_ids in by_call_id.items():
        observed = len(span_ids)
        ledger = server_invocation_count.get(call_id.split("-")[0], 0)
        if observed != ledger:
            raise TaintProvenanceAliasingError(
                f"span identity not injective for tool.call.id={call_id!r}: "
                f"pipeline saw {observed} distinct span(s), server ledger "
                f"recorded {ledger} invocation(s). A re-entrant call has "
                f"aliased onto a clean ancestor; taint provenance is "
                f"indeterminate and no containment verdict may be emitted."
            )


def resolve_taint_verdict(spans: list[Span], ledger: dict[str, int]) -> str:
    try:
        assert_injective_span_identity(spans, ledger)
    except TaintProvenanceAliasingError:
        return "indeterminate"
    return "tainted" if any(s.carries_taint for s in spans) else "clean"
