# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-an-opentelemetry-genai-execute-tool-span-when-the-tool-call-s-token-accounting-is-reported-asyn.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-an-opentelemetry-genai-execute-tool-span-when-the-tool-call-s-token-accounting-is-reported-asyn.warrant.json
# Markdown SHA-256:   6c665152258e9d0933ade2437205ebbc1ff652fe5788103b20fd35f6414f322d
# Code AST SHA-256:   15d6ffe77dff900f3d65515cc5a2b70020677344a9029c3406e6ce16e49985bc
# Verified Classes:   UsageAttributionError, ToolSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class UsageAttributionError(RuntimeError):
    """Raised when an execute_tool span cannot be safely ended with known usage state."""


@dataclass
class ToolSpan:
    call_id: str
    metered: bool
    returned_at: Optional[float] = None
    usage_applied: bool = False
    pending: bool = False
    ended: bool = False
    attributes: dict = field(default_factory=dict)


T_USAGE_MAX = 3.0  # contractual SLA for out-of-band usage delivery, seconds


def on_tool_return(span: ToolSpan, now: float) -> None:
    span.returned_at = now
    if span.metered and not span.usage_applied:
        span.pending = True
        span.attributes["gen_ai.usage.pending"] = True
        # Do NOT end the span here. It stays open-pending-usage.


def apply_usage(span: ToolSpan, input_tokens: int, output_tokens: int) -> None:
    if span.ended:
        # Late usage on an ended span is the silent-drop failure mode.
        raise UsageAttributionError(
            f"usage for {span.call_id} arrived after span end; "
            f"would be silently dropped by SDK"
        )
    span.attributes["gen_ai.usage.input_tokens"] = input_tokens
    span.attributes["gen_ai.usage.output_tokens"] = output_tokens
    span.usage_applied = True
    span.pending = False
    span.attributes.pop("gen_ai.usage.pending", None)


def try_end(span: ToolSpan, now: float) -> str:
    if span.ended:
        raise UsageAttributionError(f"double-end on {span.call_id}")

    waited = now - (span.returned_at or now)

    if span.metered and not span.usage_applied:
        if waited < T_USAGE_MAX:
            # Hold: refuse to close, keep span open-pending-usage.
            return "held_pending_usage"
        # SLA breached: force-end but flag incomplete so under-count is observable.
        span.attributes["gen_ai.usage.attribution_failed"] = True
        span.ended = True
        return "ended_attribution_failed"

    span.ended = True
    return "ended_complete"
