# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-own-causal-trace-when-opentelemetry-genai-spans-re-parent-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-own-causal-trace-when-opentelemetry-genai-spans-re-parent-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   e37b1f10bc7379c317ac04963980a792d8e6be172ac8be6405c2dfb3fa70b47b
# Code AST SHA-256:   630da0af55d2add128679f6cacf385a588f361fa43fde0b81e505221079602ee
# Verified Classes:   GenAiUsageAttributionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAiUsageAttributionError(RuntimeError):
    """Raised when a tool-call span carries token usage that duplicates an ancestor generation span."""
    pass


TOKEN_BEARING_OPS = {"chat", "invoke_agent", "embeddings"}


def validate_usage_attribution(span, ancestors):
    """
    span: dict with keys 'span_id', 'operation_name', 'usage_input', 'usage_output'
    ancestors: list of dicts (same shape) forming the parent chain, nearest first
    """
    op = span["operation_name"]
    has_usage = span.get("usage_input", 0) > 0 or span.get("usage_output", 0) > 0

    if op == "execute_tool" and has_usage:
        for anc in ancestors:
            if anc["operation_name"] in TOKEN_BEARING_OPS and (
                anc.get("usage_input", 0) > 0 or anc.get("usage_output", 0) > 0
            ):
                raise GenAiUsageAttributionError(
                    f"tool span {span['span_id']} (op={op}) records usage "
                    f"({span['usage_input']} in / {span['usage_output']} out) but ancestor "
                    f"{anc['span_id']} (op={anc['operation_name']}) already owns a token-bearing "
                    f"generation on the same accounting path; emit a child 'chat' span instead."
                )

    # A nested chat span under a tool span is legal, but must not share the tool's usage.
    if op in TOKEN_BEARING_OPS and ancestors:
        nearest = ancestors[0]
        if nearest["operation_name"] == "execute_tool" and (
            nearest.get("usage_input", 0) > 0 or nearest.get("usage_output", 0) > 0
        ):
            raise GenAiUsageAttributionError(
                f"chat span {span['span_id']} nested under usage-bearing tool span "
                f"{nearest['span_id']}; token attribution is ambiguous and will double-count."
            )
    return True


def aggregate_cost(spans):
    """Sum usage only over token-bearing ops, deduplicated by span identity."""
    seen = set()
    total_in = total_out = 0
    for s in spans:
        if s["operation_name"] not in TOKEN_BEARING_OPS:
            continue
        key = (s["span_id"], s["operation_name"])
        if key in seen:
            continue
        seen.add(key)
        total_in += s.get("usage_input", 0)
        total_out += s.get("usage_output", 0)
    return total_in, total_out
