# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-spans-when-a-tool-call-graph-is-flattened-by-async-fan-out-and-token-counts-are-double-attributed.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-spans-when-a-tool-call-graph-is-flattened-by-async-fan-out-and-token-counts-are-double-attributed.warrant.json
# Markdown SHA-256:   fdcc1130bc85f3d485a4e7f479268994eb95782a32d9a184e6e40d392365f79e
# Code AST SHA-256:   0cce398c4b68ab4da66feac4c0e86815d226c3e27fdc8fe738e17e8a4dc7640a
# Verified Classes:   SpanAttributionError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class SpanAttributionError(RuntimeError):
    """Raised when a GenAI trace cannot be reconciled to a single cost attribution."""
    pass


def reconcile_genai_trace(spans: list[dict], tolerance: int = 0) -> dict:
    """
    Reconcile gen_ai.usage.* across a tool-call trace.

    spans: list of dicts with keys span_id, parent_span_id, operation,
           input_tokens, output_tokens, tool_call_ids (list), cache_read_input_tokens.
    Returns marginal attribution per span. Raises SpanAttributionError if the
    causal edges required for attribution are absent or inconsistent.
    """
    by_id = {s["span_id"]: s for s in spans}
    chats = [s for s in spans if s["operation"] == "chat"]
    tools = [s for s in spans if s["operation"] == "tool"]
    roots = [s for s in spans if s["parent_span_id"] is None]
    if len(roots) != 1:
        raise SpanAttributionError(f"expected exactly one root span, got {len(roots)}")

    # 1. Every tool span must be causally linked to a chat span by tool_call_id.
    chat_call_ids = {}
    for c in chats:
        for cid in c.get("tool_call_ids", []):
            if cid in chat_call_ids:
                raise SpanAttributionError(
                    f"tool_call_id {cid} emitted by two chat spans "
                    f"{chat_call_ids[cid]} and {c['span_id']}"
                )
            chat_call_ids[cid] = c["span_id"]

    for t in tools:
        cid = t.get("tool_call_id")
        if cid is None:
            raise SpanAttributionError(
                f"tool span {t['span_id']} has no tool_call_id; cannot attribute"
            )
        if cid not in chat_call_ids:
            raise SpanAttributionError(
                f"tool span {t['span_id']} references unknown tool_call_id {cid}"
            )
        # Flattened fan-out detection: tool span must sit under its issuing chat span.
        if t["parent_span_id"] != chat_call_ids[cid]:
            raise SpanAttributionError(
                f"tool span {t['span_id']} parent={t['parent_span_id']} but issuing "
                f"chat span is {chat_call_ids[cid]}; trace is flattened, "
                f"tree-position aggregation would misattribute tokens"
            )

    # 2. Recover marginal input tokens per chat span (prefix re-billing correction).
    chats_sorted = sorted(chats, key=lambda s: s.get("start_time_ns", 0))
    marginals = {}
    prior = 0
    for c in chats_sorted:
        marginal = c["input_tokens"] - prior - c.get("cache_read_input_tokens", 0)
        if marginal < 0:
            raise SpanAttributionError(
                f"chat span {c['span_id']} reports input_tokens={c['input_tokens']} "
                f"less than prior cumulative {prior}; usage attributes are "
                f"not monotonic, cannot derive marginal cost"
            )
        marginals[c["span_id"]] = marginal
        prior = c["input_tokens"]

    # 3. Root cumulative must equal the sum of marginals plus first full input.
    root = roots[0]
    expected = sum(marginals.values()) + (chats_sorted[0]["input_tokens"] if chats_sorted else 0)
    if abs(root["input_tokens"] - expected) > tolerance:
        raise SpanAttributionError(
            f"root cumulative input_tokens={root['input_tokens']} but reconciled "
            f"sum={expected}; trace mixes cumulative and per-call semantics"
        )

    return {
        "marginal_input_tokens": marginals,
        "tool_output_tokens": {t["span_id"]: t.get("output_tokens", 0) for t in tools},
        "reconciled_total": expected,
    }
