# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-span-attributes-when-a-single-model-invocation-is-retried-across-fallback-providers-and-the.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-span-attributes-when-a-single-model-invocation-is-retried-across-fallback-providers-and-the.warrant.json
# Markdown SHA-256:   4591b98fb722f63a9984867f8737c107bb84f16b6c622f716385eb759b095ed9
# Code AST SHA-256:   f5830eca0e2450f70dd6c537fc5dd6862a09afe84fcf3b21586be8571898e143
# Verified Classes:   ReconciliationInvariantError, Attempt, ToolExecution
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReconciliationInvariantError(RuntimeError):
    """Raised when the GenAI span tree violates the logical-invocation accounting invariant."""


@dataclass
class Attempt:
    invocation_id: str
    provider: str
    model: str
    input_tokens: int
    output_tokens: int
    status: str  # "ok" | "abandoned" | "rate_limited" | "timeout"
    requested_tool_ids: list[str] = field(default_factory=list)


@dataclass
class ToolExecution:
    invocation_id: str
    tool_call_id: str


def reconcile(
    attempts: list[Attempt],
    tool_executions: list[ToolExecution],
) -> dict:
    # Invariant 1: every attempt belongs to exactly one logical invocation,
    # and we must be able to identify that invocation without span parentage.
    if not attempts:
        raise ReconciliationInvariantError("no attempts to reconcile")

    inv_ids = {a.invocation_id for a in attempts}
    if len(inv_ids) != 1:
        raise ReconciliationInvariantError(
            f"attempts span {len(inv_ids)} logical invocations; "
            "invocation id must be agent-owned, not inherited from parentage"
        )
    invocation_id = inv_ids.pop()

    # Invariant 2: exactly one attempt is the "serving" attempt. Usage from
    # abandoned/rate-limited attempts is real spend but NOT attributable to the
    # logical call's output. If more than one attempt is "ok", we have a hedge
    # that must be resolved before accounting, or the tree is corrupt.
    ok_attempts = [a for a in attempts if a.status == "ok"]
    if len(ok_attempts) != 1:
        raise ReconciliationInvariantError(
            f"invocation {invocation_id} has {len(ok_attempts)} serving attempts; "
            "hedged or duplicated 'ok' attempts cannot be summed"
        )
    serving = ok_attempts[0]

    # Invariant 3: every tool execution must have been requested by the
    # serving attempt. A tool call id from a discarded attempt is provider-scoped
    # and must not be honored.
    serving_tool_ids = set(serving.requested_tool_ids)
    for te in tool_executions:
        if te.invocation_id != invocation_id:
            raise ReconciliationInvariantError(
                f"tool execution {te.tool_call_id} bound to invocation "
                f"{te.invocation_id}, not {invocation_id}"
            )
        if te.tool_call_id not in serving_tool_ids:
            raise ReconciliationInvariantError(
                f"tool {te.tool_call_id} was executed but never requested by the "
                f"serving attempt ({serving.provider}/{serving.model}); "
                "likely a late-arriving response from an abandoned attempt"
            )

    return {
        "invocation_id": invocation_id,
        "serving_model": serving.model,
        "gen_ai.usage.input_tokens": serving.input_tokens,
        "gen_ai.usage.output_tokens": serving.output_tokens,
        "attempts_total": len(attempts),
        "abandoned_usage_excluded": sum(
            a.input_tokens + a.output_tokens
            for a in attempts
            if a.status != "ok"
        ),
    }
