# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-genai-agent-span-has-silently-decoupled-its-tool-call-attributes-from-the-actual-model-invocation-it-claims-to-trac.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-genai-agent-span-has-silently-decoupled-its-tool-call-attributes-from-the-actual-model-invocation-it-claims-to-trac.warrant.json
# Markdown SHA-256:   3dd6e826a154143893d935c5c59f32b8b4883a68c700ff2b03a1d25f44e4fe86
# Code AST SHA-256:   899663679cf189aedea52e8ea274f8a9a8fcee48c89c027f42c2e36fc4c8b70f
# Verified Classes:   SpanCoherenceError, ToolCall, ModelResponse, ToolSpan, ParentSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class SpanCoherenceError(RuntimeError):
    """Raised when a GenAI agent span tree is structurally valid but causally decoupled."""


@dataclass
class ToolCall:
    call_id: str
    name: str


@dataclass
class ModelResponse:
    """The actual output the model emitted for one invocation."""
    tool_calls: list[ToolCall] = field(default_factory=list)
    output_tokens: int = 0


@dataclass
class ToolSpan:
    call_id: str
    tool_name: str


@dataclass
class ParentSpan:
    operation: str                      # "chat" | "invoke_agent"
    recorded_output_tokens: int
    children: list[ToolSpan] = field(default_factory=list)


def validate_coherence(parent: ParentSpan, response: ModelResponse) -> None:
    """
    Enforce the GenAI semantic-convention coherence invariant:
    every execute_tool child's call.id must be a member of the model's
    emitted tool_calls, and parent usage must not be a single scalar
    silently shared across multiple distinct model calls.
    """
    emitted_ids = {tc.call_id for tc in response.tool_calls}

    if len(parent.children) != len(response.tool_calls):
        raise SpanCoherenceError(
            f"child count {len(parent.children)} != model tool_calls "
            f"{len(response.tool_calls)} for span op={parent.operation}"
        )

    for child in parent.children:
        if child.call_id not in emitted_ids:
            raise SpanCoherenceError(
                f"call.id decoupled: child tool span id={child.call_id!r} "
                f"not in model-emitted ids={sorted(emitted_ids)!r} "
                f"(framework likely re-minted the id before dispatch)"
            )

    # Usage attribution: a parent carrying multiple children must not present
    # a single scalar that claims to be the sum of calls it does not own.
    if len(parent.children) > 1 and parent.recorded_output_tokens == response.output_tokens:
        raise SpanCoherenceError(
            "usage attribution decoupled: parent output_tokens equals a single "
            "response while multiple tool children are attributed to it; "
            "per-call usage must live on per-call spans"
        )


def ingest(parent: ParentSpan, response: ModelResponse) -> None:
    validate_coherence(parent, response)  # fail closed; caller quarantines on raise
    # ... persist to durable store only after coherence passes ...
