# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-token-accounting-spans-as-non-authoritative-when-tool-call-attributes-are-emitted-asy.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-token-accounting-spans-as-non-authoritative-when-tool-call-attributes-are-emitted-asy.warrant.json
# Markdown SHA-256:   f2673f896c1299de0951453227f4b621c31fe866c6a4de248b1ef9d83b2c6763
# Code AST SHA-256:   2ae1eeb9d708d8a3cc2b067302e510e7f54dd6332bdb30cf423935fca0a85039
# Verified Classes:   TokenAccountingClosureError, GenAISpan, ClosureWatermark
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TokenAccountingClosureError(RuntimeError):
    """Raised when a GenAI token-accounting record is finalized before causal closure."""


@dataclass
class GenAISpan:
    span_id: str
    parent_id: Optional[str]
    operation_name: str
    end_time: float
    input_tokens: int = 0
    output_tokens: int = 0
    tool_call_id: Optional[str] = None
    tool_name: Optional[str] = None
    deferred: bool = False


@dataclass
class ClosureWatermark:
    batch_flush_interval: float = 5.0
    clock_skew_margin: float = 1.0
    # tool_call_id -> latest observed child end_time
    child_end: dict = field(default_factory=dict)

    def observe_child(self, span: GenAISpan) -> None:
        if span.tool_call_id is None:
            return
        prev = self.child_end.get(span.tool_call_id, 0.0)
        self.child_end[span.tool_call_id] = max(prev, span.end_time)

    def is_closed(self, parent: GenAISpan, expected_tool_calls: set, now: float) -> bool:
        if parent.deferred:
            return False
        for call_id in expected_tool_calls:
            end = self.child_end.get(call_id)
            if end is None:
                return False
            if now < end + self.batch_flush_interval + self.clock_skew_margin:
                return False
        return True


def finalize_token_record(
    parent: GenAISpan,
    expected_tool_calls: set,
    watermark: ClosureWatermark,
    now: Optional[float] = None,
) -> dict:
    now = time.time() if now is None else now
    if parent.operation_name != "chat":
        raise TokenAccountingClosureError(
            f"span {parent.span_id} is not a chat span; token accounting undefined"
        )
    if not watermark.is_closed(parent, expected_tool_calls, now):
        raise TokenAccountingClosureError(
            f"span {parent.span_id} not causally closed: "
            f"expected {sorted(expected_tool_calls)}, "
            f"observed {sorted(watermark.child_end)}; "
            f"token counts are lower bounds until watermark passes"
        )
    return {
        "span_id": parent.span_id,
        "input_tokens": parent.input_tokens,
        "output_tokens": parent.output_tokens,
        "tool_calls": sorted(expected_tool_calls),
        "authoritative": True,
    }
