# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-truncation-of-genai-agent-spans-when-tool-call-attributes-exceed-semantic-convention-limits.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-truncation-of-genai-agent-spans-when-tool-call-attributes-exceed-semantic-convention-limits.warrant.json
# Markdown SHA-256:   c019c3dbe6f0b90d2417dcd632fb6e2d67c8783f816fee00accf79f020d9dece
# Code AST SHA-256:   29bda3bc8669207f1c9827c5a6324378f3cfec8e51dcd77e561d2e8ecf678856
# Verified Classes:   GenAISpanAttributeTruncationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import json
from typing import Any, Mapping


class GenAISpanAttributeTruncationError(RuntimeError):
    """Raised when a GenAI tool-call span's argument attribute is truncated
    or schema-incomplete, making it unsafe for cost attribution joins."""
    pass


def assert_tool_call_arguments_intact(
    span_attributes: Mapping[str, Any],
    required_fields: tuple[str, ...],
    schema_max_serialized_bytes: int,
) -> dict:
    """
    Validate that gen_ai.tool.call.arguments is complete and schema-conformant.

    Detection rationale: the OTel SDK truncates attribute values silently at
    AttributeValueLengthLimit and reports nothing in dropped_attributes_count
    (which only counts *dropped* attributes, not *shortened* values). The only
    reliable signal is a parse-and-schema check against the tool contract.
    """
    raw = span_attributes.get("gen_ai.tool.call.arguments")
    tool_name = span_attributes.get("gen_ai.tool.name", "<unknown>")
    call_id = span_attributes.get("gen_ai.tool.call.id", "<missing>")

    if raw is None:
        raise GenAISpanAttributeTruncationError(
            f"tool={tool_name} call_id={call_id}: "
            f"gen_ai.tool.call.arguments attribute absent entirely"
        )

    # Length heuristic: at or near the schema maximum implies possible truncation
    # that may still land on a JSON-valid boundary.
    if len(raw) >= schema_max_serialized_bytes - 1:
        raise GenAISpanAttributeTruncationError(
            f"tool={tool_name} call_id={call_id}: "
            f"argument length {len(raw)} >= schema_max-1 "
            f"({schema_max_serialized_bytes}); suspect SDK truncation"
        )

    try:
        parsed = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise GenAISpanAttributeTruncationError(
            f"tool={tool_name} call_id={call_id}: "
            f"arguments do not parse as JSON ({exc}); "
            f"value is a truncated fragment"
        ) from exc

    if not isinstance(parsed, dict):
        raise GenAISpanAttributeTruncationError(
            f"tool={tool_name} call_id={call_id}: "
            f"arguments parsed to {type(parsed).__name__}, expected object"
        )

    missing = [f for f in required_fields if f not in parsed]
    if missing:
        raise GenAISpanAttributeTruncationError(
            f"tool={tool_name} call_id={call_id}: "
            f"parsed arguments missing required fields {missing}; "
            f"likely truncated at a JSON-valid boundary"
        )

    return parsed
