# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-accounting-when-a-retried-tool-call-double-counts-tokens-across-a-re-parented-span.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-accounting-when-a-retried-tool-call-double-counts-tokens-across-a-re-parented-span.warrant.json
# Markdown SHA-256:   1f614d0d9c388f822ba32581d9db618464dc9ff7d2546fbe60750b9b0953cd3c
# Code AST SHA-256:   a3120e64ef95a19dfcdc0ee4c5b41cf36fa474a1011f637594971d6b92e7d8d4
# Verified Classes:   SpanAccountingError, GenAISpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class SpanAccountingError(RuntimeError):
    pass

@dataclass
class GenAISpan:
    span_id: str
    parent_id: Optional[str]
    operation: str            # "chat" | "execute_tool"
    status: str               # "OK" | "ERROR"
    task_id: Optional[str] = None
    tool_call_id: Optional[str] = None
    input_tokens: int = 0
    output_tokens: int = 0

def validate_span(span: GenAISpan, known_tasks: set[str]) -> None:
    if span.operation == "chat":
        if span.task_id is None or span.task_id not in known_tasks:
            raise SpanAccountingError(
                f"chat span {span.span_id} lacks a joinable gen_ai.task.id; "
                "re-parented retries will orphan usage"
            )
        if span.input_tokens < 0 or span.output_tokens < 0:
            raise SpanAccountingError(f"negative usage on {span.span_id}")
    elif span.operation == "execute_tool":
        if span.input_tokens or span.output_tokens:
            raise SpanAccountingError(
                f"tool span {span.span_id} owns model tokens; "
                "usage must live on the issuing chat span"
            )
        if span.tool_call_id is None:
            raise SpanAccountingError(
                f"tool span {span.span_id} missing gen_ai.tool.call.id; "
                "retry dedup impossible"
            )
    else:
        raise SpanAccountingError(f"unknown operation {span.operation}")

def reconcile_task_usage(spans: list[GenAISpan], task_id: str) -> int:
    total = 0
    for s in spans:
        if s.operation == "chat" and s.task_id == task_id:
            # status-agnostic: a failed tool must not drop the chat span's usage
            total += s.input_tokens + s.output_tokens
    if total == 0:
        raise SpanAccountingError(f"no chat usage found for task {task_id}")
    return total
