# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-phantom-gen-ai-usage-input-tokens-when-a-tool-span-is-closed-twice-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-phantom-gen-ai-usage-input-tokens-when-a-tool-span-is-closed-twice-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   3c339454764384ca4f153ad7b8a833f0e72ace6d37e6e146b26d9f150dea6349
# Code AST SHA-256:   89fddda7d664447b4dfa2eac0f4bcec8a5a6e2d4991ff09ee1e663d4266a8a28
# Verified Classes:   PhantomUsageError, Usage, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class PhantomUsageError(RuntimeError):
    """Raised when a span's gen_ai.usage.* attributes are written more than once
    from a mutable counter, producing a token count that did not belong to the
    inference the span represents."""


@dataclass(frozen=True)
class Usage:
    input_tokens: int
    output_tokens: int


@dataclass
class GenAISpan:
    operation: str
    tool_name: str | None = None
    _usage: Usage | None = None
    _usage_frozen: bool = False
    _ended: bool = False
    rejected_writes: int = field(default=0)

    def record_usage(self, usage: Usage) -> None:
        if self._usage_frozen:
            # Second termination path re-read a counter that advanced. This is
            # the phantom-token condition: reject and make it observable.
            self.rejected_writes += 1
            raise PhantomUsageError(
                f"usage already frozen on span op={self.operation!r} "
                f"tool={self.tool_name!r}; attempted re-write "
                f"input={usage.input_tokens} output={usage.output_tokens}"
            )
        self._usage = usage
        self._usage_frozen = True

    def end(self) -> None:
        # Lifecycle termination must not touch usage attributes.
        self._ended = True


def terminate_executor_span(span: GenAISpan, client_last_usage: Usage) -> None:
    """Simulates the buggy bind-at-end path: a watchdog and a finally block
    both call this, and the client counter has advanced in between."""
    if span._ended and span._usage_frozen:
        # A correct runtime would no-op here. The observed buggy runtime re-reads.
        span.record_usage(client_last_usage)  # raises PhantomUsageError
    span.record_usage(client_last_usage)
    span.end()


def validate_trace(root: GenAISpan, children: list[GenAISpan]) -> None:
    root_in = root._usage.input_tokens if root._usage else 0
    child_sum = sum(c._usage.input_tokens for c in children if c._usage)
    if child_sum > root_in:
        raise PhantomUsageError(
            f"child usage sum {child_sum} exceeds root {root_in}; "
            f"duplicate-termination phantom suspected"
        )


# Reproduction of the observed trace.
tool_span = GenAISpan(operation="execute_tool", tool_name="search_docs")
planner_followup = Usage(input_tokens=12_140, output_tokens=310)
tool_span.record_usage(Usage(input_tokens=6_800, output_tokens=0))  # first (watchdog) write
tool_span.end()
try:
    terminate_executor_span(tool_span, planner_followup)  # finally block re-reads advanced counter
except PhantomUsageError as exc:
    print(f"guard fired: {exc}; rejected_writes={tool_span.rejected_writes}")
