# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-attribution-from-silently-mispricing-agent-tool-call-trees-under-concurrent-retries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-attribution-from-silently-mispricing-agent-tool-call-trees-under-concurrent-retries.warrant.json
# Markdown SHA-256:   3825c86e1bd5eb9ba80bdc899a18b7d6e5e890263225f1537ca3d538a27a863f
# Code AST SHA-256:   4430a81cb0a0c62eed27b49725c4db6042687a841c5fe5c4913537e753c0a98b
# Verified Classes:   GenAiAttributionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAiAttributionError(RuntimeError):
    """Raised when a trace violates the single-attribution invariant for gen_ai usage."""


def validate_usage_attribution(spans: list[dict]) -> None:
    """
    Enforce: every gen_ai span carrying usage must be either (a) the sole
    span for its operation in the trace, or (b) a retry sibling that is
    explicitly linked from a consuming parent. Otherwise cost aggregation
    will double-count.
    """
    by_op: dict[str, list[dict]] = {}
    for s in spans:
        op = s.get("attributes", {}).get("gen_ai.operation.name")
        if op and "gen_ai.usage.input_tokens" in s.get("attributes", {}):
            by_op.setdefault(op, []).append(s)

    for op, group in by_op.items():
        if len(group) == 1:
            continue
        # Multiple billable spans for one operation: require a consumption link
        # from a parent to exactly one of them, and a retry discriminator on the rest.
        consumed = [s for s in group if s.get("consumed_by_parent_span_id")]
        if len(consumed) != 1:
            raise GenAiAttributionError(
                f"operation {op!r} has {len(group)} billable spans but "
                f"{len(consumed)} consumption links; cost will be misattributed"
            )
        for s in group:
            if s is consumed[0]:
                continue
            if not s.get("attributes", {}).get("gen_ai.tool.call.retry_count"):
                raise GenAiAttributionError(
                    f"operation {op!r} has an unlinked billable span "
                    f"span_id={s.get('span_id')!r} without a retry discriminator; "
                    "it will be summed into cost alongside the consumed attempt"
                )
