# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-truncation-when-opentelemetry-genai-semantic-conventions-silently-drop-tool-call-arguments-at-the-4-kib-att.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-truncation-when-opentelemetry-genai-semantic-conventions-silently-drop-tool-call-arguments-at-the-4-kib-att.warrant.json
# Markdown SHA-256:   e609151d141c71b4d4391f08ec493b40adc24f22b3dcc378e8bebc912d4179ec
# Code AST SHA-256:   17d02fd90048303d64682abdf3d8d4410604a86c66213067c15ef263619afa67
# Verified Classes:   SpanPayloadTruncationError, ToolCallSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SpanPayloadTruncationError(RuntimeError):
    """Raised when a GenAI span attribute is detected as truncated or hash-mismatched."""
    pass


@dataclass
class ToolCallSpan:
    tool_name: str
    arguments: str            # the emitted gen_ai.tool.call.arguments value
    arguments_bytes: int      # companion: gen_ai.tool.call.arguments.bytes
    arguments_sha256: str     # companion: gen_ai.tool.call.arguments.sha256


# Effective narrowest hop limit observed in this deployment (collector transform processor).
NARROWEST_ATTRIBUTE_LIMIT_BYTES = 4096


def emit_tool_call_span(tool_name: str, full_arguments: str) -> ToolCallSpan:
    """Emit a span whose payload survives every hop, or externalize it.

    Invariant: the emitted attribute must be byte-identical to what executed,
    OR must be an explicit reference carrying the true length and hash.
    """
    encoded = full_arguments.encode("utf-8")
    n = len(encoded)
    digest = hashlib.sha256(encoded).hexdigest()

    if n <= NARROWEST_ATTRIBUTE_LIMIT_BYTES:
        return ToolCallSpan(tool_name, full_arguments, n, digest)

    # Externalize: emit a reference, never a truncated payload.
    ref = json.dumps({"_ref": f"blob://toolcalls/{digest}", "_bytes": n, "_sha256": digest})
    if len(ref.encode("utf-8")) > NARROWEST_ATTRIBUTE_LIMIT_BYTES:
        raise SpanPayloadTruncationError(
            f"externalized reference for {tool_name} is {len(ref)} bytes, "
            f"exceeds limit {NARROWEST_ATTRIBUTE_LIMIT_BYTES}; cannot emit faithfully"
        )
    return ToolCallSpan(tool_name, ref, n, digest)


def verify_received_span(span: ToolCallSpan) -> str:
    """Consumer-side check: reject spans whose payload was clipped at any hop."""
    received = span.arguments.encode("utf-8")
    if len(received) != span.arguments_bytes:
        raise SpanPayloadTruncationError(
            f"{span.tool_name}: received {len(received)} bytes, "
            f"span claims {span.arguments_bytes} — truncated at a hop"
        )
    if hashlib.sha256(received).hexdigest() != span.arguments_sha256:
        raise SpanPayloadTruncationError(
            f"{span.tool_name}: sha256 mismatch — payload altered or clipped to a valid prefix"
        )
    return span.arguments


if __name__ == "__main__":
    big = json.dumps({"path": "a.py", "content": "x" * 6000})
    s = emit_tool_call_span("write_file", big)
    verify_received_span(s)  # passes: reference is faithful

    # Simulate a collector that truncated a raw payload to 4096 bytes.
    clipped = ToolCallSpan("write_file", big[:4096], len(big.encode()), hashlib.sha256(big.encode()).hexdigest())
    verify_received_span(clipped)  # raises SpanPayloadTruncationError
