# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-token-accounting-when-a-streaming-tool-call-span-is-retried-after-partial-emission.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-token-accounting-when-a-streaming-tool-call-span-is-retried-after-partial-emission.warrant.json
# Markdown SHA-256:   1f442798acb7c715bf155df11422f32e98064693e02256d47228ee5ccde197b5
# Code AST SHA-256:   1155992efcc26d3354689fabf1e67a8ddafb9af84519dd599857608f0d86cd01
# Verified Classes:   GenAiSpanAccountingError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class GenAiSpanAccountingError(RuntimeError):
    """Raised when a GenAI span tree cannot be reconciled to billed token totals."""


def reconcile_retry_group(leaf_spans: list[dict], parent: dict) -> dict:
    """
    Reconcile a retry group of gen_ai.chat leaf spans against its parent.
    Each leaf must describe exactly one provider invocation.
    Returns aggregate dict; raises on any invariant violation.
    """
    if not leaf_spans:
        raise GenAiSpanAccountingError("retry group has no leaf spans; cannot reconcile")

    for i, leaf in enumerate(leaf_spans):
        if "gen_ai.usage.input_tokens" not in leaf:
            raise GenAiSpanAccountingError(
                f"leaf {i} missing gen_ai.usage.input_tokens; "
                "partial attempts must emit an explicit partial marker, not omit the field"
            )
        if leaf.get("gen_ai.retry.attempt_index") != i:
            raise GenAiSpanAccountingError(
                f"leaf {i} has attempt_index {leaf.get('gen_ai.retry.attempt_index')}; "
                "attempt indices must be contiguous from 0"
            )
        # A leaf that carries aggregate attributes is a conflated span.
        if any(k.startswith("gen_ai.retry.aggregate.") for k in leaf):
            raise GenAiSpanAccountingError(
                f"leaf {i} carries aggregate attributes; "
                "aggregates belong on the parent only"
            )

    # Parent must NOT carry gen_ai.usage.* — that would conflate one invocation with many.
    if any(k.startswith("gen_ai.usage.") for k in parent):
        raise GenAiSpanAccountingError(
            "parent span carries gen_ai.usage.*; "
            "parent must use gen_ai.retry.aggregate.* to stay distinguishable from a leaf"
        )

    agg_input = sum(leaf["gen_ai.usage.input_tokens"] for leaf in leaf_spans)
    agg_output = sum(leaf.get("gen_ai.usage.output_tokens", 0) for leaf in leaf_spans)

    if parent.get("gen_ai.retry.aggregate.input_tokens") != agg_input:
        raise GenAiSpanAccountingError(
            f"parent aggregate input_tokens={parent.get('gen_ai.retry.aggregate.input_tokens')} "
            f"!= sum of leaves={agg_input}; trace will under- or over-report billing"
        )
    if parent.get("gen_ai.retry.aggregate.output_tokens") != agg_output:
        raise GenAiSpanAccountingError(
            f"parent aggregate output_tokens={parent.get('gen_ai.retry.aggregate.output_tokens')} "
            f"!= sum of leaves={agg_output}"
        )

    return {
        "attempt_count": len(leaf_spans),
        "billed_input_tokens": agg_input,
        "billed_output_tokens": agg_output,
        "prompt_size_tokens": leaf_spans[-1]["gen_ai.usage.input_tokens"],  # last attempt's prompt
    }
