# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-tool-call-attribute-loss-in-opentelemetry-genai-agent-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-tool-call-attribute-loss-in-opentelemetry-genai-agent-spans.warrant.json
# Markdown SHA-256:   20eaa4fc4e48d251345f0e452911772ad30c435bc8322cb9dc85fe52c442d59a
# Code AST SHA-256:   e4f624a4ea1f242ccddda043d137bd4587e1fd224d5a8cbd503d84218b82ded3
# Verified Classes:   ToolCallCorrelationError, GenAISpanBatch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ToolCallCorrelationError(RuntimeError):
    """Raised when GenAI span cardinality indicates attribute loss with event duplication."""


@dataclass
class GenAISpanBatch:
    execute_tool_spans: int = 0
    distinct_tool_call_ids: int = 0
    inference_events: int = 0
    distinct_response_ids: int = 0
    stability_opt_in: bool = True
    tree_complete: bool = True


def check_tool_call_invariant(batch: GenAISpanBatch) -> None:
    if not batch.stability_opt_in:
        return  # older semconv regime: absence of tool.call.id is not a signal
    if not batch.tree_complete:
        return  # incomplete trees produce benign cardinality mismatch

    if batch.execute_tool_spans == 0:
        return

    id_coverage = batch.distinct_tool_call_ids / batch.execute_tool_spans
    event_duplication = (
        batch.inference_events / batch.distinct_response_ids
        if batch.distinct_response_ids
        else float("inf")
    )

    if id_coverage < 0.99 and event_duplication > 1.0:
        raise ToolCallCorrelationError(
            f"tool-call attribute loss co-occurring with event duplication: "
            f"id_coverage={id_coverage:.3f} (<0.99), "
            f"event_duplication={event_duplication:.3f} (>1.0); "
            f"token accounting will double-count retried invocations"
        )
