# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-identity-spans-under-mismatched-genai-semantic-conventions-across-a-trace-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-identity-spans-under-mismatched-genai-semantic-conventions-across-a-trace-boundary.warrant.json
# Markdown SHA-256:   674a19bd7d357617138b119a9a07951abcc5382b5cfcfd40f4cb0c0f43c2a428
# Code AST SHA-256:   8f53e18f45c462d0863fdbc9d0150e6bb3a735297f84aeff8d530a339df385e7
# Verified Classes:   ConventionMismatchError, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass

SUPPORTED_CONVENTION = "1.27.0"

# Identity keys whose semantics differ across convention versions.
IDENTITY_KEYS = ("gen_ai.agent.name", "gen_ai.operation.name", "gen_ai.system")


class ConventionMismatchError(RuntimeError):
    """Raised when a downstream span consumer cannot honor the emitter's convention."""


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    convention_version: str
    attributes: dict


def resolve_agent_identity(inbound: SpanContext, consumer_convention: str) -> str:
    # The hop is only valid if both sides agree on the convention version.
    if inbound.convention_version != consumer_convention:
        raise ConventionMismatchError(
            f"trace {inbound.trace_id}: emitter convention "
            f"{inbound.convention_version!r} != consumer {consumer_convention!r}; "
            f"identity cannot be re-derived"
        )

    # Identity must be present on the owning span; never fall back across keys.
    agent = inbound.attributes.get("gen_ai.agent.name")
    if agent is None:
        # gen_ai.system is a provider, NOT an agent. Refuse the substitution.
        raise ConventionMismatchError(
            f"trace {inbound.trace_id}: gen_ai.agent.name absent; "
            f"refusing to substitute gen_ai.system="
            f"{inbound.attributes.get('gen_ai.system')!r} as agent identity"
        )
    return agent


def attribute_tool_call(inbound: SpanContext) -> str:
    try:
        return resolve_agent_identity(inbound, SUPPORTED_CONVENTION)
    except ConventionMismatchError:
        # Absence is a first-class value: record UNKNOWN, do not guess.
        return "UNKNOWN_AGENT"
