# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-completed-gen-ai-agent-span-when-tool-call-child-spans-were-evicted-from-the-sdk-s-batch-processor.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-completed-gen-ai-agent-span-when-tool-call-child-spans-were-evicted-from-the-sdk-s-batch-processor.warrant.json
# Markdown SHA-256:   a35c16afb47670b301006667b147984c0491a614f8fb4842db1d352db40b9f28
# Code AST SHA-256:   38529f04c5fe8f2882126b3f02c41bfd4acfba493bd303909a466cbbe9402dde
# Verified Classes:   TraceIncompletenessError, AgentSpanClosure
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceIncompletenessError(RuntimeError):
    """Raised when an agent span cannot be emitted without violating the
    referential-completeness invariant of the GenAI semantic conventions."""
    pass


@dataclass
class AgentSpanClosure:
    dispatched_tool_calls: int
    observed_child_spans: int
    aggregate_usage_present: bool
    dropped_span_delta: int


def classify_agent_span(closure: AgentSpanClosure) -> str:
    """Return the emission decision for a closing gen_ai.agent span.

    Decisions: 'emit', 'emit_unverified', 'quarantine'.
    Raises TraceIncompletenessError only when the runtime cannot make a
    sound decision (missing child-count tracking while eviction occurred).
    """
    child_mismatch = closure.observed_child_spans < closure.dispatched_tool_calls
    eviction_observed = closure.dropped_span_delta > 0

    if not closure.aggregate_usage_present:
        # Parent usage is self-consistent; eviction of children is benign.
        return "emit"

    if child_mismatch and eviction_observed:
        # Aggregate usage present AND we can prove children were lost.
        return "quarantine"

    if child_mismatch and not eviction_observed:
        # Mismatch without eviction signal: cannot distinguish a bug in
        # child-span creation from silent loss. Refuse to assert either way.
        raise TraceIncompletenessError(
            f"agent dispatched {closure.dispatched_tool_calls} tool calls but "
            f"only {closure.observed_child_spans} child spans observed with no "
            f"drop signal; cannot emit a truthful invoke_agent span"
        )

    if eviction_observed and closure.dispatched_tool_calls > 0 and not child_mismatch:
        # Eviction happened but child count matches: eviction hit non-agent
        # spans. Parent is still consistent; emit but mark usage unverified.
        return "emit_unverified"

    return "emit"


def build_agent_span_attributes(closure: AgentSpanClosure) -> dict:
    decision = classify_agent_span(closure)
    attrs = {
        "gen_ai.operation.name": "invoke_agent",
        "gen_ai.agent.id": "research-agent-v3",
    }
    if decision == "quarantine":
        attrs["otel.status_code"] = "ERROR"
        attrs["otel.status_description"] = "child_spans_evicted"
        attrs["gen_ai.agent.trace_incomplete"] = True
        # Strip aggregate usage; move to a locally-ignored attribute so cost
        # pipelines do not attribute tokens to a topology that does not exist.
        attrs["agent.local.aggregate_tokens"] = closure.aggregate_usage_present
    elif decision == "emit_unverified":
        attrs["gen_ai.agent.usage_unverified"] = True
    return attrs
