# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-before-emitting-them-or-the-token-accounting-silently-double-counts-retried-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-before-emitting-them-or-the-token-accounting-silently-double-counts-retried-tool.warrant.json
# Markdown SHA-256:   351ce2fd5b44d4719c2a689f195afef930e65a2ab262b157bee4a2aa1cd69b0a
# Code AST SHA-256:   8d50ed1249a2b72b40c0f724235fc4bccfa6f2c042f8cd8dad1c36df238f26c2
# Verified Classes:   GenAIUsageReconciliationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class GenAIUsageReconciliationError(RuntimeError):
    """Raised when a logical-step span tree cannot be reconciled into
    canonical context-usage and cost-usage token totals."""
    pass


def reconcile_agent_span_tree(step_span, attempt_spans):
    """
    step_span: the logical execute_tool / reasoning-step parent span.
    attempt_spans: list of physical attempt child spans, each possibly
    carrying gen_ai.usage.input_tokens / output_tokens.

    Returns (context_tokens, cost_tokens) where context_tokens is the
    winning attempt's usage (for budgeting) and cost_tokens is the sum
    over all attempts (for billing).
    """
    if not attempt_spans:
        raise GenAIUsageReconciliationError(
            f"logical step {step_span.get('name')} has no attempt spans; "
            "cannot determine canonical usage"
        )

    winners = [s for s in attempt_spans if s.get("gen_ai.attempt.discarded") is not True]
    if len(winners) != 1:
        raise GenAIUsageReconciliationError(
            f"logical step {step_span.get('name')} has {len(winners)} "
            f"non-discarded attempts; expected exactly 1. Ambiguous rollup."
        )

    winner = winners[0]
    ctx_in = winner.get("gen_ai.usage.input_tokens")
    ctx_out = winner.get("gen_ai.usage.output_tokens")
    if ctx_in is None or ctx_out is None:
        raise GenAIUsageReconciliationError(
            f"winning attempt for {step_span.get('name')} is missing usage "
            "attributes; cannot emit canonical context tokens"
        )

    cost_in = 0
    cost_out = 0
    for s in attempt_spans:
        # Absent usage on a failed attempt is NOT zero; skip, do not add 0.
        si = s.get("gen_ai.usage.input_tokens")
        so = s.get("gen_ai.usage.output_tokens")
        if si is not None:
            cost_in += si
        if so is not None:
            cost_out += so

    return (ctx_in + ctx_out, cost_in + cost_out)
