# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-an-agent-span-when-opentelemetry-genai-usage-attributes-disaggregate-below-the-parent-token-tot.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-an-agent-span-when-opentelemetry-genai-usage-attributes-disaggregate-below-the-parent-token-tot.warrant.json
# Markdown SHA-256:   b03a2205ce7c3b36d559800586562549766fd756ec5fc954c7e513c014c140cb
# Code AST SHA-256:   9eecedc165f56b0587914633ae6642fa44e990c83b1f9e76f8abf3c9b6ef4e5f
# Verified Classes:   AgentSpanUsageInconsistency
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AgentSpanUsageInconsistency(RuntimeError):
    """Raised when a parent agent span's reported GenAI usage does not bound
    the sum of its descendant spans' usage at close time."""
    pass


def close_agent_span(span, own_input: int, own_output: int,
                     descendant_usage: list[tuple[int, int]],
                     descendants_open: bool) -> dict:
    """Seal a GenAI invoke_agent span only if token conservation holds.

    Invariant: parent_input >= sum(child_input) and
               parent_output >= sum(child_output),
    with the residual attributed to the parent's own reasoning turns.
    """
    if descendants_open:
        # Parent lifecycle forced closure before children drained.
        # Must not seal an authoritative total.
        span.set_attribute("gen_ai.usage.incomplete", True)
        raise AgentSpanUsageInconsistency(
            "parent span closing while descendant usage spans remain open; "
            "totals are non-authoritative and must not be aggregated"
        )

    child_in = sum(u[0] for u in descendant_usage)
    child_out = sum(u[1] for u in descendant_usage)
    parent_in = own_input
    parent_out = own_output

    if parent_in < child_in or parent_out < child_out:
        # Accounting base diverged (compaction reset, async late child,
        # or double-attribution at a leaf). Reconcile by lifting the
        # parent to the observed descendant sum, then flag.
        reconciled_in = max(parent_in, child_in)
        reconciled_out = max(parent_out, child_out)
        span.set_attribute("gen_ai.usage.input_tokens", reconciled_in)
        span.set_attribute("gen_ai.usage.output_tokens", reconciled_out)
        span.set_attribute("gen_ai.usage.reconciled", True)
        raise AgentSpanUsageInconsistency(
            f"parent usage ({parent_in},{parent_out}) did not bound "
            f"descendant sum ({child_in},{child_out}); "
            f"sealed reconciled totals ({reconciled_in},{reconciled_out}) "
            f"and marked span non-authoritative for cost aggregation"
        )

    span.set_attribute("gen_ai.usage.input_tokens", parent_in)
    span.set_attribute("gen_ai.usage.output_tokens", parent_out)
    span.set_attribute("gen_ai.usage.reconciled", False)
    return {"input_tokens": parent_in, "output_tokens": parent_out,
            "residual_input": parent_in - child_in,
            "residual_output": parent_out - child_out}
