# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-token-accounting-spans-across-a-retried-tool-call-double-counting-span-parent-loss-and-the-gen-ai-usage-reco.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-token-accounting-spans-across-a-retried-tool-call-double-counting-span-parent-loss-and-the-gen-ai-usage-reco.warrant.json
# Markdown SHA-256:   b8065ccdd5c438c5c2b04195bf3bd653715d6933960f6247b0b378db34121d6c
# Code AST SHA-256:   377aac70c1ebe80c4d9d7dcc25899bc1c3eec1aad93392415629780817d738e7
# Verified Classes:   TokenAccountingInvariantError, GenAISpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List

class TokenAccountingInvariantError(RuntimeError):
    """Raised when GenAI token-accounting spans violate the operation/attempt invariant."""
    pass

@dataclass
class GenAISpan:
    span_id: str
    trace_id: str
    operation_name: str          # e.g. "chat", "execute_tool"
    operation_id: str | None     # stable logical-op key; MUST be set on token spans
    attempt_index: int | None    # monotonic per operation; MUST be set on token spans
    parent_span_id: str | None
    input_tokens: int = 0
    output_tokens: int = 0

def reconcile(spans: List[GenAISpan], invoke_agent_trace_id: str) -> Dict[str, int]:
    """Sum usage per logical operation, enforcing the invariant.

    Invariant: every token-bearing span has operation_id + attempt_index,
    shares the invoke_agent trace, and is a descendant of it.
    """
    per_op: Dict[str, Dict[int, GenAISpan]] = {}
    for s in spans:
        if s.input_tokens == 0 and s.output_tokens == 0:
            continue
        if s.operation_id is None or s.attempt_index is None:
            raise TokenAccountingInvariantError(
                f"span {s.span_id} carries usage but lacks operation_id/attempt_index; "
                "cannot deduplicate retries"
            )
        if s.trace_id != invoke_agent_trace_id:
            raise TokenAccountingInvariantError(
                f"span {s.span_id} (op={s.operation_id}) is orphaned from invoke_agent "
                f"trace {invoke_agent_trace_id}; retry escaped parent context"
            )
        attempts = per_op.setdefault(s.operation_id, {})
        if s.attempt_index in attempts:
            prev = attempts[s.attempt_index]
            if (prev.input_tokens, prev.output_tokens) != (s.input_tokens, s.output_tokens):
                raise TokenAccountingInvariantError(
                    f"attempt {s.attempt_index} of op {s.operation_id} emitted divergent "
                    "usage for the same attempt index; attempt counter not monotonic"
                )
        attempts[s.attempt_index] = s

    totals: Dict[str, int] = {}
    for op_id, attempts in per_op.items():
        # Sum across attempts (each attempt burned real tokens), dedup by index.
        totals[op_id] = sum(a.input_tokens + a.output_tokens for a in attempts.values())
    return totals

def emit_retry_span(original: GenAISpan, new_span_id: str,
                    new_trace_id: str, new_attempt: int,
                    input_tokens: int, output_tokens: int) -> GenAISpan:
    """Construct a retried attempt span, preserving operation identity."""
    if new_trace_id != original.trace_id:
        # Do not silently detach; force caller to keep the invoke_agent trace.
        raise TokenAccountingInvariantError(
            f"retry of op {original.operation_id} moved to trace {new_trace_id}; "
            "must stay under invoke_agent trace to preserve cost attribution"
        )
    if new_attempt <= (original.attempt_index or 0):
        raise TokenAccountingInvariantError(
            f"retry attempt_index {new_attempt} not monotonic after {original.attempt_index}"
        )
    return GenAISpan(
        span_id=new_span_id,
        trace_id=new_trace_id,
        operation_name=original.operation_name,
        operation_id=original.operation_id,
        attempt_index=new_attempt,
        parent_span_id=original.parent_span_id,
        input_tokens=input_tokens,
        output_tokens=output_tokens,
    )
