# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-opentelemetry-genai-span-attribute-cardinality-when-tool-call-arguments-are-attacker-influenced.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-opentelemetry-genai-span-attribute-cardinality-when-tool-call-arguments-are-attacker-influenced.warrant.json
# Markdown SHA-256:   ee921b7a37805dfac5c6a1100c83faeeb53f04988c5e6a37dfe7df252bc7f8d8
# Code AST SHA-256:   81e8ff0e9f50d940f71f56403458e300a0ecbc55601678eacdd9ba10ba3c1ac3
# Verified Classes:   SpanAttributeIntegrityError, ToolCallSpanPayload
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SpanAttributeIntegrityError(RuntimeError):
    """Raised when a GenAI tool-call span attribute cannot be proven faithful."""


@dataclass(frozen=True)
class ToolCallSpanPayload:
    call_id: str
    tool_name: str
    arguments: dict
    client_cap_bytes: int = 2048


def canonical_bytes(obj: dict) -> bytes:
    # Deterministic serialization: sorted keys, no whitespace, fixed separators.
    return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")


def build_span_attributes(payload: ToolCallSpanPayload) -> dict:
    raw = canonical_bytes(payload.arguments)
    digest = hashlib.sha256(raw).hexdigest()
    attrs = {
        "genai.tool.name": payload.tool_name,
        "genai.tool.call.id": payload.call_id,
        "genai.tool.call.arguments.sha256": digest,
        "genai.tool.call.arguments.bytes": len(raw),
    }
    if len(raw) <= payload.client_cap_bytes:
        attrs["genai.tool.call.arguments"] = raw.decode("utf-8")
        attrs["genai.tool.call.arguments.truncated"] = False
        return attrs

    # Over cap: never emit a silently truncated attribute. Emit a reference
    # and require the caller to have persisted the blob under the hash.
    attrs["genai.tool.call.arguments.truncated"] = True
    attrs["genai.tool.call.arguments.ref"] = f"blob://tool-calls/{digest}"
    return attrs


def verify_replay_matches_span(span_attrs: dict, replayed_arguments: dict) -> None:
    recorded_hash = span_attrs.get("genai.tool.call.arguments.sha256")
    if not recorded_hash:
        raise SpanAttributeIntegrityError(
            f"span for call {span_attrs.get('genai.tool.call.id')} has no content hash; "
            "cannot prove recorded arguments equal executed arguments"
        )
    replayed_hash = hashlib.sha256(canonical_bytes(replayed_arguments)).hexdigest()
    if replayed_hash != recorded_hash:
        raise SpanAttributeIntegrityError(
            f"replay divergence for call {span_attrs.get('genai.tool.call.id')}: "
            f"span hash {recorded_hash} != replay hash {replayed_hash}; "
            f"truncated={span_attrs.get('genai.tool.call.arguments.truncated')}"
        )
    if span_attrs.get("genai.tool.call.arguments.truncated") and "genai.tool.call.arguments.ref" not in span_attrs:
        raise SpanAttributeIntegrityError(
            "truncated attribute lacks blob reference; content is unrecoverable"
        )
