# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-spans-before-its-token-accounting-closes-the-orphaned-tool-call-span-and-the-double-count-invariant-under-ge.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-spans-before-its-token-accounting-closes-the-orphaned-tool-call-span-and-the-double-count-invariant-under-ge.warrant.json
# Markdown SHA-256:   79baaa2717c6745e5d152199df8ca560d56a0b96da5f17971dde36205ceea88e
# Code AST SHA-256:   949f546bb5c362f59a8944cc83b782f56d0839f0dabff5bda3146a5ca9455717
# Verified Classes:   GenAIAccountingInvariantError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class GenAIAccountingInvariantError(RuntimeError):
    """Raised when a GenAI span set violates the tool-call/token attribution invariant."""


@dataclass
class GenAISpan:
    name: str
    parent_id: Optional[str]
    attributes: dict = field(default_factory=dict)
    ended: bool = False

    def set_attribute(self, key: str, value) -> None:
        # Spec-compliant exporters drop writes after End. We model that here
        # so the accounting bug is reproducible, not hidden.
        if self.ended:
            return
        self.attributes[key] = value

    def end(self) -> None:
        self.ended = True


def reconcile_turn(chat_span: GenAISpan, tool_spans: list[GenAISpan]) -> None:
    """
    Enforce: every genai.tool.name child span must be attributable to a
    non-zero genai.usage.output_tokens on its parent chat span, and the
    total-token equality must hold. Called at export time, before flush.
    """
    if not chat_span.ended:
        raise GenAIAccountingInvariantError(
            f"chat span {chat_span.name!r} reconciled before End; usage may be incomplete"
        )

    out = chat_span.attributes.get("genai.usage.output_tokens")
    inp = chat_span.attributes.get("genai.usage.input_tokens")
    tot = chat_span.attributes.get("genai.usage.total_tokens")

    if tool_spans and (out is None or out == 0):
        raise GenAIAccountingInvariantError(
            f"orphaned tool-call spans: {len(tool_spans)} child span(s) under "
            f"{chat_span.name!r} but genai.usage.output_tokens={out!r}; "
            "chat span was ended before the terminal usage frame was attributed"
        )

    if inp is not None and out is not None and tot is not None:
        if tot != inp + out:
            raise GenAIAccountingInvariantError(
                f"token equality violated on {chat_span.name!r}: "
                f"total={tot} != input={inp} + output={out}"
            )

    for tool in tool_spans:
        if tool.parent_id is None:
            raise GenAIAccountingInvariantError(
                f"tool span {tool.attributes.get('genai.tool.name')!r} has no parent SpanContext"
            )


def example_failure() -> None:
    chat = GenAISpan(name="chat gpt-x", parent_id=None)
    chat.set_attribute("genai.usage.input_tokens", 1200)
    chat.set_attribute("genai.operation.name", "chat")
    chat.end()  # ended on generation end, BEFORE usage frame arrived

    # Late usage write is silently dropped because the span is Ended.
    chat.set_attribute("genai.usage.output_tokens", 412)
    chat.set_attribute("genai.usage.total_tokens", 1612)

    tool = GenAISpan(
        name="execute_tool search",
        parent_id="chat-span-id",
        attributes={"genai.tool.name": "search", "genai.tool.call.id": "call_abc"},
    )
    tool.end()

    reconcile_turn(chat, [tool])  # raises


if __name__ == "__main__":
    try:
        example_failure()
    except GenAIAccountingInvariantError as exc:
        print(f"REJECTED AT EXPORT: {exc}")
