# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-for-cost-accounting-when-tool-call-emission-is-d.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-for-cost-accounting-when-tool-call-emission-is-d.warrant.json
# Markdown SHA-256:   73b43534c747eacc1ba474c68f3cd8db719ee6139bc8fdf41efe35ad66795557
# Code AST SHA-256:   29cfba733fb6649ea84c820ee53a7641327a9e46f071c300a480ea63b3a500c1
# Verified Classes:   SpanProvenanceError, GenAISpan, SpanProcessor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanProvenanceError(RuntimeError):
    """Raised when a GenAI span cannot prove in-process ownership of its lifecycle."""
    pass


@dataclass
class GenAISpan:
    trace_id: str
    step_index: int
    response_id: Optional[str]
    opened_by_pid: int
    closed_by_pid: Optional[int] = None
    resumed_from_checkpoint: bool = False
    usage_input_tokens: Optional[int] = None
    usage_output_tokens: Optional[int] = None
    open_child_tool_spans: int = 0
    unverified: bool = False


@dataclass
class SpanProcessor:
    emitted_response_ids: dict = field(default_factory=dict)  # trace_id -> set of response_ids

    def close_span(self, span: GenAISpan, current_pid: int) -> None:
        span.closed_by_pid = current_pid

        # Invariant 1: open and close must be same process instance.
        if span.opened_by_pid != span.closed_by_pid:
            span.unverified = True
            raise SpanProvenanceError(
                f"span {span.trace_id}/{span.step_index} opened by pid "
                f"{span.opened_by_pid} but closed by {span.closed_by_pid}; "
                f"usage attributes are non-authoritative"
            )

        # Invariant 2: no rehydrated context may carry usage.
        if span.resumed_from_checkpoint and (
            span.usage_input_tokens is not None or span.usage_output_tokens is not None
        ):
            span.unverified = True
            raise SpanProvenanceError(
                f"span {span.trace_id}/{span.step_index} resumed from checkpoint "
                f"carries usage attributes it cannot have observed"
            )

        # Invariant 3: no orphaned tool children at close.
        if span.open_child_tool_spans > 0:
            span.unverified = True
            raise SpanProvenanceError(
                f"span {span.trace_id}/{span.step_index} closed with "
                f"{span.open_child_tool_spans} orphaned tool spans; "
                f"parent usage accounting invalid"
            )

        # Invariant 4: response_id must be unique within trace.
        if span.response_id is not None:
            seen = self.emitted_response_ids.setdefault(span.trace_id, set())
            if span.response_id in seen:
                span.unverified = True
                raise SpanProvenanceError(
                    f"duplicate response_id {span.response_id} in trace "
                    f"{span.trace_id}; replay suspected, cost double-count risk"
                )
            seen.add(span.response_id)


def reconcile_cost(spans: list[GenAISpan]) -> dict:
    total = 0
    excluded = 0
    for s in spans:
        if s.unverified:
            excluded += 1
            continue
        total += (s.usage_input_tokens or 0) + (s.usage_output_tokens or 0)
    if excluded and total == 0:
        raise SpanProvenanceError(
            f"all {excluded} spans unverified; no authoritative cost basis available"
        )
    return {"authoritative_tokens": total, "excluded_spans": excluded}
