# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-single-agent-span-when-opentelemetry-genai-token-accounting-diverges-from-tool-call-attribute.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-single-agent-span-when-opentelemetry-genai-token-accounting-diverges-from-tool-call-attribute.warrant.json
# Markdown SHA-256:   b14eeb10243908a26c11662bad21c24c3d84be7ce5b641e3dac2f300a157b80a
# Code AST SHA-256:   6a48aac5b835e321e04168ae2dd2c20442b2ab0b2a21829282c7a4fe56a7815c
# Verified Classes:   GenAISpanAggregationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAISpanAggregationError(RuntimeError):
    """Raised when agent-span token/tool accounting cannot be safely aggregated."""
    pass


def emit_agent_span(step: dict, chat_spans: list, tool_spans: list) -> dict:
    attempts = {s["agent.attempt.index"] for s in chat_spans}
    call_ids = [t["gen_ai.tool.call.id"] for t in tool_spans]

    # Structural corruption: duplicate or orphan tool-call identity.
    if len(call_ids) != len(set(call_ids)):
        raise GenAISpanAggregationError(
            f"duplicate gen_ai.tool.call.id across retries in step {step['id']}: "
            f"{call_ids} — tool-call identity not stable across attempts"
        )
    emitted_calls = {c for s in chat_spans for c in s.get("tool_calls", [])}
    orphans = [cid for cid in call_ids if cid not in emitted_calls]
    if orphans:
        raise GenAISpanAggregationError(
            f"orphan execute_tool spans {orphans} in step {step['id']}: "
            f"tool executed but no chat span requested it — refusing to emit aggregate"
        )

    aborted = [s for s in chat_spans if s.get("status") == "ERROR"
               and s.get("gen_ai.usage.output_tokens") is None]
    if len(attempts) > 1 or aborted:
        # Attributable divergence: emit children, withhold parent aggregate.
        return {
            "gen_ai.operation.name": "invoke_agent",
            "agent.step.id": step["id"],
            "agent.aggregate_withheld": True,
            "agent.withhold_reason": "retry_or_aborted_attempt",
        }

    return {
        "gen_ai.operation.name": "invoke_agent",
        "agent.step.id": step["id"],
        "gen_ai.usage.input_tokens": sum(s["gen_ai.usage.input_tokens"] for s in chat_spans),
        "gen_ai.usage.output_tokens": sum(s["gen_ai.usage.output_tokens"] for s in chat_spans),
    }
