# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-tool-call-span-reports-attributes-after-the-parent-agent-span-has-already.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-tool-call-span-reports-attributes-after-the-parent-agent-span-has-already.warrant.json
# Markdown SHA-256:   3abe80de05c6f1143d3f98fc5fa8559dc9be9ce2cb47c4e62e890a6d5a4c9c75
# Code AST SHA-256:   5976aac837c82bc747a1a3ef2d49e29acae65afa3b862c2143b3f625abb9091d
# Verified Classes:   UsageReconciliationError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageReconciliationError(RuntimeError):
    """Raised when a parent agent span's usage aggregate does not match
    the finalized usage of its terminal tool-call children."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    operation: str
    input_tokens: int = 0
    output_tokens: int = 0
    ended: bool = False
    usage_finalized: bool = False


def close_agent_span(
    parent: Span,
    children: list[Span],
    aggregate_on_parent: bool,
) -> Span:
    if aggregate_on_parent:
        unfinalized = [c for c in children if not (c.ended and c.usage_finalized)]
        if unfinalized:
            raise UsageReconciliationError(
                f"parent {parent.span_id} cannot aggregate: "
                f"{len(unfinalized)} child span(s) not finalized "
                f"({[c.span_id for c in unfinalized]}); "
                f"close-order barrier violated, refusing to emit partial usage"
            )
        child_in = sum(c.input_tokens for c in children)
        child_out = sum(c.output_tokens for c in children)
        if (parent.input_tokens, parent.output_tokens) != (child_in, child_out):
            raise UsageReconciliationError(
                f"parent {parent.span_id} usage "
                f"({parent.input_tokens},{parent.output_tokens}) != "
                f"child sum ({child_in},{child_out})"
            )
    else:
        # Backend-aggregation path: parent MUST NOT carry partial usage.
        if parent.input_tokens or parent.output_tokens:
            raise UsageReconciliationError(
                f"parent {parent.span_id} carries usage under backend-aggregation "
                f"mode; must be absent to avoid double-count with late children"
            )
    parent.ended = True
    return parent
