# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-agent-span-when-tool-call-attributes-and-token-cost-telemetry-disagree-at-the-emission-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-agent-span-when-tool-call-attributes-and-token-cost-telemetry-disagree-at-the-emission-boundary.warrant.json
# Markdown SHA-256:   a3a83918c01e7d0aa766a9637ad1d8f7503e64f054df46a207a9d54d590553f3
# Code AST SHA-256:   7105d3f9451587a6bc820bc39ff4c09696b882749824ef600a81c1e897d2d7fe
# Verified Classes:   GenAIUsageInvariantError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAIUsageInvariantError(RuntimeError):
    """Raised when a GenAI span tree violates the non-cumulative-producer
    invariant for gen_ai.usage.* attributes at the emission boundary."""
    pass


def validate_usage_tree(span, tolerance=1e-6):
    """Enforce: a span's gen_ai.usage.cost must equal its own inference cost
    and must be disjoint from its descendants' costs.

    Returns the turn-total cost (root + all descendants), which is the value
    a consumer is expected to compute. Raises if the producer already
    propagated descendant usage upward (double-count).
    """
    own_cost = span.attributes.get("gen_ai.usage.cost")
    if own_cost is None:
        own_cost = 0.0

    descendant_total = 0.0
    for child in span.children:
        descendant_total += validate_usage_tree(child, tolerance)

    # If the producer propagated child usage into this span, own_cost will
    # already include descendant_total. Detect the overlap.
    if descendant_total > 0 and own_cost >= descendant_total - tolerance:
        # Ambiguous: could be legitimate (own cost happens to exceed children)
        # or propagated. Disambiguate via the disjointness declaration.
        declared_cumulative = span.attributes.get(
            "gen_ai.usage.aggregation", "per_span"
        ) == "cumulative"
        if not declared_cumulative:
            raise GenAIUsageInvariantError(
                f"span {span.name!r} (trace {span.trace_id}) reports "
                f"gen_ai.usage.cost={own_cost} which is >= descendant total "
                f"{descendant_total} without declaring "
                f"gen_ai.usage.aggregation='cumulative'. This is the "
                f"double-count boundary: a consumer summing descendants will "
                f"report {own_cost + descendant_total} instead of the true "
                f"turn cost. Strip descendant usage from this span or set "
                f"the aggregation attribute explicitly."
            )

    return own_cost + descendant_total


def emit_turn(span, exporter):
    try:
        turn_total = validate_usage_tree(span)
    except GenAIUsageInvariantError:
        # Quarantine: do not export a tree that would poison cost aggregation.
        exporter.quarantine(span)
        raise
    exporter.export(span, turn_total=turn_total)
