# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-gen-ai-usage-input-tokens-when-a-retried-model-span-double-counts-a-parent-agent-span-s-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-gen-ai-usage-input-tokens-when-a-retried-model-span-double-counts-a-parent-agent-span-s-budget.warrant.json
# Markdown SHA-256:   6dcb0394546240381e4312367ee2bb3d1430f68fc4b2e68504e845262743238f
# Code AST SHA-256:   9efef21133dff8b56b557505716d4b3fdce0d07608719e1d0ed3c0943e1dba34
# Verified Classes:   TokenAggregationAmbiguity
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TokenAggregationAmbiguity(RuntimeError):
    """Raised when a parent agent span cannot emit a scalar token count
    because descendant model spans share invocation identities or
    consumed partial output across a fallback boundary."""
    pass


def aggregate_parent_tokens(child_spans: list[dict]) -> dict:
    """
    child_spans: list of GenAI chat spans, each with keys
      invocation_id, input_tokens, output_tokens,
      retry_outcome ("consumed" | "discarded" | "partial_consumed"),
      billing_status ("billed" | "unbilled")
    Returns a dict suitable for parent span attributes, either with a
    scalar "gen_ai.usage.input_tokens" or a breakdown, never both.
    """
    if not child_spans:
        return {"gen_ai.usage.input_tokens": 0, "gen_ai.usage.output_tokens": 0}

    by_invocation: dict[str, list[dict]] = {}
    for span in child_spans:
        by_invocation.setdefault(span["invocation_id"], []).append(span)

    has_partial = any(
        s["retry_outcome"] == "partial_consumed" for s in child_spans
    )
    has_duplicate_invocation = any(
        len(spans) > 1 for spans in by_invocation.values()
    )

    # Attribution mode: one consumed span per invocation id.
    attributable_in = 0
    attributable_out = 0
    for inv_id, spans in by_invocation.items():
        consumed = [s for s in spans if s["retry_outcome"] == "consumed"]
        if len(consumed) > 1:
            raise TokenAggregationAmbiguity(
                f"invocation {inv_id} has {len(consumed)} consumed spans; "
                "attribution is undefined"
            )
        if consumed:
            attributable_in += consumed[0]["input_tokens"]
            attributable_out += consumed[0]["output_tokens"]

    # Billing mode: every billed span counts, duplicates included.
    billed_in = sum(
        s["input_tokens"] for s in child_spans if s["billing_status"] == "billed"
    )
    billed_out = sum(
        s["output_tokens"] for s in child_spans if s["billing_status"] == "billed"
    )

    if has_partial or has_duplicate_invocation:
        # Scalar is undefined; emit breakdown and omit the scalar.
        return {
            "gen_ai.usage.input_tokens.breakdown": [
                {
                    "invocation.id": inv_id,
                    "attributable": {
                        "input": sum(
                            s["input_tokens"]
                            for s in spans
                            if s["retry_outcome"] == "consumed"
                        ),
                        "output": sum(
                            s["output_tokens"]
                            for s in spans
                            if s["retry_outcome"] == "consumed"
                        ),
                    },
                    "billed": {
                        "input": sum(
                            s["input_tokens"]
                            for s in spans
                            if s["billing_status"] == "billed"
                        ),
                        "output": sum(
                            s["output_tokens"]
                            for s in spans
                            if s["billing_status"] == "billed"
                        ),
                    },
                    "attempts": len(spans),
                }
                for inv_id, spans in by_invocation.items()
            ],
            "gen_ai.usage.aggregation.mode": "breakdown",
        }

    if attributable_in != billed_in and not has_duplicate_invocation:
        # No retries, but billed != attributable: a provider edge case
        # (e.g. cached prompt billing). Surface it rather than hide it.
        raise TokenAggregationAmbiguity(
            f"billed input {billed_in} != attributable input {attributable_in} "
            "with no retry duplication; provider billing semantics diverge"
        )

    return {
        "gen_ai.usage.input_tokens": attributable_in,
        "gen_ai.usage.output_tokens": attributable_out,
        "gen_ai.usage.billed.input_tokens": billed_in,
        "gen_ai.usage.billed.output_tokens": billed_out,
        "gen_ai.usage.aggregation.mode": "scalar",
    }
