# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-span-tree-token-accounting-divergence-when-genai-semantic-conventions-permit-both-cumulative-and-per-turn-usage-attribut.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-span-tree-token-accounting-divergence-when-genai-semantic-conventions-permit-both-cumulative-and-per-turn-usage-attribut.warrant.json
# Markdown SHA-256:   c84902cc00c842709307eafcbabf05b19beec637216e1badb821cf96b5e6bff9
# Code AST SHA-256:   d63e26f03c06ecb911996c1c01482c5a83a69668298daa0b5f6c03111a3c4cfc
# Verified Classes:   UsageSemanticsUnresolved
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UsageSemanticsUnresolved(RuntimeError):
    """Raised when a span tree's token aggregation semantics cannot be determined."""
    pass


def reconcile_usage(parent_span, leaf_spans, response_ids, quiescent):
    """Classify a parent span's usage as cumulative or delta.

    Returns (semantics, total_input, total_output) or raises
    UsageSemanticsUnresolved when the tree cannot disambiguate.
    """
    if not quiescent:
        raise UsageSemanticsUnresolved(
            "tree not quiescent; child spans may still arrive"
        )

    if len(response_ids) != len(set(response_ids)):
        raise UsageSemanticsUnresolved(
            "duplicate gen_ai.response.id detected; retried span inflates leaf sum"
        )

    leaf_in = sum(s.usage.input_tokens for s in leaf_spans)
    leaf_out = sum(s.usage.output_tokens for s in leaf_spans)
    p_in = parent_span.usage.input_tokens
    p_out = parent_span.usage.output_tokens

    if p_in == leaf_in and p_out == leaf_out:
        # Parent equals leaf sum: cumulative rollup.
        return ("cumulative", p_in, p_out)

    if p_in > 0 and leaf_in > p_in:
        # Parent's own call is additive on top of children.
        return ("delta", p_in + leaf_in, p_out + leaf_out)

    # Any other relationship (e.g. parent exceeds leaf sum with no
    # cache/retry explanation) is undefined from this tree alone.
    raise UsageSemanticsUnresolved(
        f"parent=({p_in},{p_out}) leaf_sum=({leaf_in},{leaf_out}); "
        "cannot classify as cumulative or delta"
    )
