# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-divergence-when-opentelemetry-genai-spans-conflate-retry-attempts-with-logical-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-divergence-when-opentelemetry-genai-spans-conflate-retry-attempts-with-logical-tool-calls.warrant.json
# Markdown SHA-256:   f369e4a3560a21ce6c5e3c67456493b818615a80f23840dee3b095ee13c23bb7
# Code AST SHA-256:   ef19ea0ea77eea6bcd9f9f34e251a55e3979525cd645fd767ca072db931d527e
# Verified Classes:   TelemetryAccountingDivergence, GenAISpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TelemetryAccountingDivergence(RuntimeError):
    """Raised when GenAI span usage attributes cannot be reconciled to logical operations."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: str | None
    operation_name: str          # "chat" | "execute_tool"
    tool_name: str | None
    input_tokens: int
    output_tokens: int
    attempt_index: int | None     # None => conventions do not carry a discriminator
    is_terminal: bool | None      # None => terminality unknowable from span
    start_ms: int
    end_ms: int


def reconcile_logical_operation(spans: list[GenAISpan]) -> dict:
    """
    Reconcile per-span usage attributes to a single logical operation.
    Raises if the span set cannot be proven to map one-to-one to logical ops.
    """
    if not spans:
        raise TelemetryAccountingDivergence("empty span set: no logical operation to reconcile")

    # Structural signal: siblings sharing a parent with identical tool/model
    # and non-overlapping intervals are retry-as-sibling candidates.
    siblings = [s for s in spans if s.parent_span_id == spans[0].parent_span_id]
    if len(siblings) > 1:
        tool_names = {s.tool_name for s in siblings}
        if len(tool_names) == 1:
            # Multiple spans, same tool, same parent: this is the boundary case.
            if any(s.attempt_index is None for s in siblings):
                raise TelemetryAccountingDivergence(
                    "retry-as-sibling detected (identical tool_name, shared parent, "
                    "multiple spans) but no gen_ai.attempt.index discriminator present; "
                    "usage attributes are an attempt log, not a cost ledger"
                )
            if any(s.is_terminal is None for s in siblings):
                raise TelemetryAccountingDivergence(
                    "attempt discriminator present but terminality flag absent; "
                    "cannot separate semantic output accounting from billing accounting"
                )

    # Amplification ratio: sum of input tokens over max single-attempt input.
    max_input = max(s.input_tokens for s in spans)
    total_input = sum(s.input_tokens for s in spans)
    if max_input == 0:
        raise TelemetryAccountingDivergence("zero input tokens across all attempts: span set is malformed")
    amplification = total_input / max_input

    if amplification > 1.5 and any(s.attempt_index is None for s in spans):
        raise TelemetryAccountingDivergence(
            f"prompt-token amplification {amplification:.2f}x with no attempt "
            f"discriminator; cost normalization will over-report by this factor"
        )

    semantic_output = sum(s.output_tokens for s in spans if s.is_terminal)
    billing_input = total_input
    return {
        "logical_input_tokens": max_input,
        "billing_input_tokens": billing_input,
        "semantic_output_tokens": semantic_output,
        "amplification_ratio": amplification,
        "attempts": len(spans),
    }
