# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-terminal-genai-span-when-tool-call-attributes-and-token-counters-disagree-at-close-time.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-terminal-genai-span-when-tool-call-attributes-and-token-counters-disagree-at-close-time.warrant.json
# Markdown SHA-256:   2b3fb916ce24d07a47c4c91dc716a13667a4a692f5dd78ff537e724eb8fdb801
# Code AST SHA-256:   8e692840e0298d4dea2de21072024b99873bb17f69868bb8d4232557bd2481ad
# Verified Classes:   GenAIUsageReconciliationError, UsageBlock, ProviderProfile
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class GenAIUsageReconciliationError(RuntimeError):
    """Raised when a terminal GenAI span cannot account for its token residual."""


@dataclass(frozen=True)
class UsageBlock:
    input_tokens: int
    output_tokens: int
    reasoning_tokens: int = 0
    cache_read_tokens: int = 0
    system_tokens: int = 0


@dataclass(frozen=True)
class ProviderProfile:
    name: str
    streaming: bool
    parallel_tool_calls: bool

    def slack(self, parent_input: int) -> int:
        # Streaming providers finalize usage before argument streaming completes;
        # parallel tool calls widen the bound because call-id reuse is common.
        base = max(64, int(parent_input * 0.05))
        if self.streaming:
            base += 128
        if self.parallel_tool_calls:
            base += 256
        return base


def reconcile_terminal_span(
    parent: UsageBlock,
    child_sum: UsageBlock,
    profile: ProviderProfile,
    usage_source: str = "provider",
) -> None:
    if usage_source != "provider":
        # Local estimates are advisory; invariant does not apply.
        return

    parent_total = parent.input_tokens + parent.output_tokens
    child_total = child_sum.input_tokens + child_sum.output_tokens
    named_residual = (
        parent.reasoning_tokens
        + parent.cache_read_tokens
        + parent.system_tokens
    )
    residual = parent_total - child_total - named_residual
    slack = profile.slack(parent.input_tokens)

    if residual > slack:
        raise GenAIUsageReconciliationError(
            f"unattributable residual {residual} tokens exceeds slack {slack} "
            f"for provider={profile.name} streaming={profile.streaming} "
            f"parallel={profile.parallel_tool_calls}; "
            f"refusing to emit terminal span"
        )
    if residual < -slack:
        raise GenAIUsageReconciliationError(
            f"children over-count parent by {-residual} tokens beyond slack {slack}; "
            f"possible duplicate tool-call spans"
        )


def close_agent_span(
    parent: UsageBlock,
    child_sum: UsageBlock,
    profile: ProviderProfile,
    usage_source: str = "provider",
) -> dict:
    try:
        reconcile_terminal_span(parent, child_sum, profile, usage_source)
    except GenAIUsageReconciliationError as exc:
        return {
            "status": "ERROR",
            "error.type": "gen_ai.usage.reconciliation_failed",
            "gen_ai.usage.reconciled": False,
            "gen_ai.agent.close_failed": str(exc),
        }
    return {
        "status": "OK",
        "gen_ai.usage.reconciled": True,
        "gen_ai.usage.input_tokens": parent.input_tokens,
        "gen_ai.usage.output_tokens": parent.output_tokens,
    }
