# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-truncation-when-opentelemetry-genai-semantic-conventions-drop-tool-call-children-under-attribute-size-limits.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-truncation-when-opentelemetry-genai-semantic-conventions-drop-tool-call-children-under-attribute-size-limits.warrant.json
# Markdown SHA-256:   2b093727ffe2af9d37a53f1ca6e9cca91be09599b55d59dfe557a74e54ae518f
# Code AST SHA-256:   4c6f06e0f460cf34e6f8c894511b0b592233387af6a9982fb8c87d0f1895bbb1
# Verified Classes:   TurnGraphFidelityError, TurnRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TurnGraphFidelityError(RuntimeError):
    """Raised when an exported GenAI turn graph does not match the in-process execution graph."""


@dataclass
class TurnRecord:
    trace_id: str
    span_id: str
    operation_name: str
    tool_children_created: int
    tool_children_exported: int
    attribute_count_limit: int
    parent_attribute_count: int
    completion_mentions_tool_facts: bool
    truncation_marker_set: bool = False
    extra: dict = field(default_factory=dict)


def assert_turn_graph_faithful(turn: TurnRecord) -> None:
    """
    Enforce the GenAI turn-graph fidelity invariant before span export.

    Invariant: a chat span whose completion depends on tool results MUST either
    have all tool children exported, or carry an explicit truncation marker.
    """
    if turn.operation_name != "chat":
        return

    limit_fired = turn.parent_attribute_count >= turn.attribute_count_limit

    if turn.tool_children_created > turn.tool_children_exported:
        if not turn.truncation_marker_set:
            raise TurnGraphFidelityError(
                f"trace={turn.trace_id} span={turn.span_id}: "
                f"{turn.tool_children_created} tool children created but only "
                f"{turn.tool_children_exported} exported; attribute limit "
                f"{turn.attribute_count_limit} reached ({turn.parent_attribute_count} attrs). "
                f"Set gen_ai.tool.call.truncated=true and expected_count="
                f"{turn.tool_children_created} before export."
            )

    if (
        turn.tool_children_exported == 0
        and turn.completion_mentions_tool_facts
        and not turn.truncation_marker_set
    ):
        raise TurnGraphFidelityError(
            f"trace={turn.trace_id} span={turn.span_id}: zero exported tool children "
            f"but completion references tool-derived facts; graph is unfaithful "
            f"(limit_fired={limit_fired}). Escalate to re-execution queue."
        )
