# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-token-accounting-drift-between-parent-agent-spans-and-child-tool-call-spans-in-opentelemetry-genai-telemetry.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-token-accounting-drift-between-parent-agent-spans-and-child-tool-call-spans-in-opentelemetry-genai-telemetry.warrant.json
# Markdown SHA-256:   640ead890fe45be00c97c30875788448160eda7ce380345e9b3faa481c54a918
# Code AST SHA-256:   2c75e4ff8f29e0706449b9ba694177bc62295ca41165e4991668bef29380bf45
# Verified Classes:   TokenAggregationAmbiguity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TokenAggregationAmbiguity(RuntimeError):
    """Raised when a span tree carries token attributes on both the root
    invoke_agent span and its descendants without a declared aggregation
    convention, making the reconstructed total non-deterministic."""
    pass


TOKEN_ATTRS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")
AGG_ATTR = "gen_ai.agent.token_aggregation"  # "inclusive" | "exclusive"


def _has_tokens(span) -> bool:
    return any(span.attributes.get(a) for a in TOKEN_ATTRS)


def _tokens(span) -> int:
    return sum(int(span.attributes.get(a, 0)) for a in TOKEN_ATTRS)


def reconstruct_agent_tokens(root_span, descendants) -> int:
    """Reconstruct the authoritative token total for an invoke_agent tree.

    Fails closed on ambiguity rather than guessing, because a wrong total
    either aborts a healthy run early or lets a run overrun budget.
    """
    root_has = _has_tokens(root_span)
    child_has = any(_has_tokens(d) for d in descendants)

    if not root_has and not child_has:
        return 0
    if root_has and not child_has:
        return _tokens(root_span)
    if not root_has and child_has:
        return sum(_tokens(d) for d in descendants)

    # Both root and descendants carry tokens: convention must be declared.
    convention = root_span.attributes.get(AGG_ATTR)
    if convention == "inclusive":
        return _tokens(root_span)  # children already folded into root
    if convention == "exclusive":
        return _tokens(root_span) + sum(_tokens(d) for d in descendants)
    raise TokenAggregationAmbiguity(
        f"root span {root_span.context.span_id} and descendants both carry "
        f"gen_ai.usage.* but no {AGG_ATTR}; refusing to sum (would drift "
        f"by up to {sum(_tokens(d) for d in descendants)} tokens)"
    )


def enforce_budget(root_span, descendants, budget_tokens: int) -> None:
    try:
        used = reconstruct_agent_tokens(root_span, descendants)
    except TokenAggregationAmbiguity:
        # Fail closed: treat ambiguous traces as over budget so the run
        # halts at a checkpoint instead of silently overrunning.
        raise
    if used > budget_tokens:
        raise TokenAggregationAmbiguity(
            f"budget exceeded: {used} > {budget_tokens} (reconstructed, "
            f"convention={root_span.attributes.get(AGG_ATTR)!r})"
        )
