# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-parent-child-span-orphaning-when-an-agent-s-tool-call-span-outlives-its-parent-turn-under-opentelemetry-genai-semantic-conven.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-parent-child-span-orphaning-when-an-agent-s-tool-call-span-outlives-its-parent-turn-under-opentelemetry-genai-semantic-conven.warrant.json
# Markdown SHA-256:   6e80b44919511f7c4b1b61ed6453571ca65b7237d441cbaa098bb9c4fe384c3d
# Code AST SHA-256:   de808ac4cc5c7b50420c9d39a616d00d419efadf5cae1c1da7188cf15173e4b1
# Verified Classes:   OrphanedToolSpanError, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class OrphanedToolSpanError(RuntimeError):
    """Raised when a tool-call span's turn-scoped accounting cannot be
    resolved because the parent turn span is absent and no redundant
    turn-correlation attribute was emitted."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: str | None
    trace_id: str
    operation: str                      # gen_ai.operation.name
    turn_id: str | None = None          # redundant correlation attr
    input_tokens: int = 0               # gen_ai.usage.input_tokens
    output_tokens: int = 0              # gen_ai.usage.output_tokens
    tool_name: str | None = None        # gen_ai.tool.name
    ended: bool = False
    detached_completion: bool = False


def attribute_turn_tokens(spans: list[GenAISpan], trace_id: str) -> dict[str, int]:
    """Sum token usage per turn, hierarchy-independently.

    Invariant: every span that consumed model tokens must be attributable
    to a turn via turn_id, NOT via parent_span_id, because the parent
    turn span may have been exported and evicted before a long-running
    tool child ends.
    """
    present = {s.span_id for s in spans if s.trace_id == trace_id}
    totals: dict[str, int] = {}

    for s in spans:
        if s.trace_id != trace_id:
            continue
        # Parent-based attribution is only valid if the parent is present
        # in this ingestion partition.
        if s.parent_span_id is not None and s.parent_span_id not in present:
            if s.turn_id is None:
                raise OrphanedToolSpanError(
                    f"span {s.span_id} (op={s.operation}, tool={s.tool_name}) "
                    f"references absent parent {s.parent_span_id} and carries "
                    f"no turn_id; token accounting for trace {trace_id} is "
                    f"unresolvable without a redundant correlation attribute"
                )
            s.detached_completion = True
        if s.turn_id is not None and (s.input_tokens or s.output_tokens):
            totals[s.turn_id] = (
                totals.get(s.turn_id, 0) + s.input_tokens + s.output_tokens
            )
    return totals


def enforce_hierarchy_invariant(spans: list[GenAISpan], trace_id: str) -> None:
    """Pre-export guard: every descendant must carry turn_id so that
    parent absence cannot orphan its accounting."""
    for s in spans:
        if s.trace_id != trace_id:
            continue
        if s.parent_span_id is not None and s.turn_id is None:
            raise OrphanedToolSpanError(
                f"span {s.span_id} has parent {s.parent_span_id} but no "
                f"turn_id; if the parent flushes first, this span's "
                f"tool attribution and token accounting will detach"
            )
