# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-otel-genai-span-attributes-when-a-tool-call-span-is-emitted-before-its-parent-model-invocation-span-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-otel-genai-span-attributes-when-a-tool-call-span-is-emitted-before-its-parent-model-invocation-span-closes.warrant.json
# Markdown SHA-256:   c8b835371f8e0c53810d3c4de924eda4ae95134ecab3c0602b1247fe00c6684f
# Code AST SHA-256:   5514c9a4c7de718ce1391ec32a3895a1e6fd7582ff3de2d321477ff20d55eb1d
# Verified Classes:   UsageAttributionError, GenAISpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageAttributionError(RuntimeError):
    """Raised when a tool-call span is attributed against a non-final parent usage snapshot."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: Optional[str]
    operation: str                      # "chat" | "execute_tool"
    end_time: Optional[float] = None    # None while span is open
    usage_input_tokens: Optional[int] = None
    usage_output_tokens: Optional[int] = None
    partial_usage: bool = False

    def is_final(self) -> bool:
        return self.end_time is not None and not self.partial_usage


def attribute_tool_usage(child: GenAISpan, parent: GenAISpan) -> int:
    """Return input tokens attributable to a tool call, or fail loudly if parent usage is not final."""
    if child.operation != "execute_tool":
        raise UsageAttributionError(f"expected execute_tool child, got {child.operation!r}")
    if parent.operation != "chat":
        raise UsageAttributionError(f"expected chat parent, got {parent.operation!r}")
    if child.parent_span_id != parent.span_id:
        raise UsageAttributionError(
            f"span linkage mismatch: child.parent={child.parent_span_id} parent.span={parent.span_id}"
        )
    if not parent.is_final():
        raise UsageAttributionError(
            f"parent {parent.span_id} usage not final "
            f"(end_time={parent.end_time}, partial={parent.partial_usage}); "
            f"refusing to attribute child {child.span_id} against a live snapshot"
        )
    if parent.usage_input_tokens is None:
        raise UsageAttributionError(f"parent {parent.span_id} ended without gen_ai.usage.input_tokens")
    return parent.usage_input_tokens


# Trigger trace: reused chat span, child closes first, batch splits parent/child.
chat = GenAISpan(span_id="s1", parent_span_id=None, operation="chat")
tool = GenAISpan(span_id="s2", parent_span_id="s1", operation="execute_tool",
                 end_time=100.0, usage_input_tokens=0)
# parent still open at child-export time:
try:
    attribute_tool_usage(tool, chat)
except UsageAttributionError as e:
    # Correct behavior: fail instead of silently attributing 0 tokens.
    print("blocked:", e)

# Resolution path: parent ends with final usage.
chat.end_time = 900.0
chat.usage_input_tokens = 4120
chat.usage_output_tokens = 290
assert attribute_tool_usage(tool, chat) == 4120
