# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-completion-as-a-false-invariant-when-tool-call-attributes-are-finalized-before-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-completion-as-a-false-invariant-when-tool-call-attributes-are-finalized-before-t.warrant.json
# Markdown SHA-256:   c0a71aa453317b88b724cb6c2fb23f4eb8b86c573d2b9af013ef27af79b82510
# Code AST SHA-256:   aa77d0d1990cecea313e67a46f242f97b2bd99d9078c214ea625bce13b64ba02
# Verified Classes:   SpanLifecycleViolation, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class SpanLifecycleViolation(RuntimeError):
    """Raised when a tool span's completion cannot be trusted as a result record."""


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    operation: str  # "chat" | "execute_tool"
    end_ns: int
    tool_call_id: Optional[str] = None
    tool_result: Optional[str] = None
    error_type: Optional[str] = None
    status: str = "UNSET"  # "UNSET" | "OK" | "ERROR"
    finish_reasons: list[str] = field(default_factory=list)


def validate_tool_span_completion(
    chat_span: Span,
    tool_spans: list[Span],
    message_list_call_ids: set[str],
) -> None:
    """Enforce: every tool call referenced by a chat span has a trustworthy result.

    A tool span is trustworthy only if it ends before its parent chat span,
    carries an explicit result or error, and the call id appears in the
    assembled message list the next model invocation will consume.
    """
    if "tool_calls" not in chat_span.finish_reasons:
        return

    by_call_id = {s.tool_call_id: s for s in tool_spans if s.parent_id == chat_span.span_id}

    for call_id in _referenced_call_ids(chat_span, tool_spans):
        span = by_call_id.get(call_id)
        if span is None:
            raise SpanLifecycleViolation(
                f"chat span {chat_span.span_id} references tool call {call_id} "
                f"with no child execute_tool span"
            )

        if span.end_ns > chat_span.end_ns:
            # Result observed after the parent that consumed it: impossible.
            raise SpanLifecycleViolation(
                f"tool span {span.span_id} for call {call_id} ends "
                f"{span.end_ns - chat_span.end_ns}ns after parent chat span "
                f"{chat_span.span_id}; result cannot have been consumed"
            )

        has_outcome = span.tool_result is not None or span.error_type is not None
        if not has_outcome and span.status == "UNSET":
            raise SpanLifecycleViolation(
                f"tool span {span.span_id} for call {call_id} ended with no "
                f"result, no error, and UNSET status: indeterminate completion "
                f"must not be treated as success"
            )

        if call_id not in message_list_call_ids:
            raise SpanLifecycleViolation(
                f"tool call {call_id} has a completed span but no corresponding "
                f"tool-role message; the next chat span will reason over a "
                f"context missing this result"
            )


def _referenced_call_ids(chat_span: Span, tool_spans: list[Span]) -> set[str]:
    return {
        s.tool_call_id
        for s in tool_spans
        if s.parent_id == chat_span.span_id and s.tool_call_id is not None
    }
