Skip to content

The platform for continuously improving AI agents.

33.7 KB
Raw Blame
"""OTLP trace ingestion.

Post-processing is strictly per-span: spans arrive in any order and batch, so
nothing here may wait for a sibling or the trace root.
"""

from __future__ import annotations

import base64
import json
import logging
import uuid
import zlib
from datetime import UTC, datetime, timedelta
from typing import Any

from django.db import DataError, transaction
from django.http import HttpResponseBase, JsonResponse
from django.utils import timezone
from drf_spectacular.utils import extend_schema
from google.protobuf import json_format
from opentelemetry.proto.collector.trace.v1 import trace_service_pb2
from opentelemetry.proto.trace.v1.trace_pb2 import ResourceSpans
from rest_framework.decorators import api_view, permission_classes
from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import IsAuthenticated

from overbae.api import overmind_attrs as oc_attrs
from overbae.api.scoping import project_ids_for
from overbae.core.utils import safe_float, safe_int, safe_json
from overbae.innermind import evidence
from overbae.models import (
    APIToken,
    Capability,
    Conversation,
    Project,
    ProjectMembership,
    Span,
)
from overbae.models.traces import usage_slice
from overbae.services.activity import record
from overbae.services.capabilities import identity
from overbae.services.span_pricing import (
    COMPLETION_TOKEN_KEYS,
    MODEL_KEYS,
    PROMPT_TOKEN_KEYS,
    stamp_span_cost,
)

logger = logging.getLogger(__name__)


def _get_attr(mapping: dict[str, Any] | None, primary: str, *legacy: str) -> Any:
    """First non-empty value across *primary* then the *legacy* keys."""
    if not mapping:
        return None
    for key in (primary, *legacy):
        val = mapping.get(key)
        if val not in (None, "", [], {}):
            return val
    return None


# OTel marks "no parent" with eight zero bytes.
_EMPTY_PARENT_SPAN_ID = b"\x00" * 8
# An end time this far ahead of the server clock is not used as the last activity.
_CLOCK_SKEW = timedelta(minutes=5)


def _any_value_to_python(value) -> Any:
    kind = value.WhichOneof("value")
    match kind:
        case "string_value":
            return value.string_value
        case "int_value":
            return value.int_value
        case "double_value":
            return value.double_value
        case "bool_value":
            return value.bool_value
        case "array_value":
            return [_any_value_to_python(item) for item in value.array_value.values]
        case "kvlist_value":
            return {kv.key: _any_value_to_python(kv.value) for kv in value.kvlist_value.values}
        case "bytes_value":
            return value.bytes_value.hex()
        case _:
            return None


def _kv_list_to_dict(attributes) -> dict[str, Any]:
    return {attr.key: _any_value_to_python(attr.value) for attr in attributes}


# canonical key → alias priority order. Applied via setdefault so native keys
# win; lets OTel GenAI semconv and OpenInference spans land with usable evidence.
_GENAI_COALESCE: dict[str, tuple[str, ...]] = {
    oc_attrs.LLM_MODEL: ("gen_ai.request.model", "gen_ai.model", "llm.model_name"),
    oc_attrs.LLM_RESPONSE_MODEL: ("gen_ai.response.model",),
    oc_attrs.LLM_PROVIDER: ("gen_ai.provider.name", "gen_ai.system", "llm.provider", "llm.system"),
    oc_attrs.LLM_USAGE_PROMPT_TOKENS: (
        "gen_ai.usage.input_tokens",
        "gen_ai.usage.prompt_tokens",
        "llm.token_count.prompt",
    ),
    oc_attrs.LLM_USAGE_COMPLETION_TOKENS: (
        "gen_ai.usage.output_tokens",
        "gen_ai.usage.completion_tokens",
        "llm.token_count.completion",
    ),
    oc_attrs.LLM_USAGE_TOTAL_TOKENS: ("gen_ai.usage.total_tokens", "llm.token_count.total"),
    oc_attrs.LLM_CACHE_READ_TOKENS: (
        "gen_ai.usage.cache_read.input_tokens",
        "gen_ai.usage.cache_read_input_tokens",
        "gen_ai.usage.cache_read_tokens",
        "llm.token_count.prompt_details.cache_read",
    ),
    # The reported-cost keys the trace readers accept, so the rollup counts them too.
    oc_attrs.LLM_COST: (
        "gen_ai.usage.cost",
        "llm.usage.total_cost",
        "overmind.cost",
        "cost",
        "response_cost",
    ),
    oc_attrs.TOOL_NAME: ("gen_ai.tool.name",),
    oc_attrs.INPUT_DATA: ("input.value",),
    oc_attrs.OUTPUT_DATA: ("output.value",),
}


def _coalesce_genai_attrs(attrs: dict[str, Any]) -> dict[str, Any]:
    for canonical, aliases in _GENAI_COALESCE.items():
        for alias in aliases:
            value = attrs.get(alias)
            if value is not None and value != "":
                attrs.setdefault(canonical, value)
                break
    return attrs


def _span_event_to_dict(event) -> dict[str, Any]:
    return {
        "time_unix_nano": event.time_unix_nano,
        "name": event.name,
        "attributes": _kv_list_to_dict(event.attributes),
    }


def _span_link_to_dict(link) -> dict[str, Any]:
    return {
        "trace_id": link.trace_id.hex(),
        "span_id": link.span_id.hex(),
        "attributes": _kv_list_to_dict(link.attributes),
    }


def _parent_hex_or_none(span_proto) -> str | None:
    parent = span_proto.parent_span_id
    if not parent or parent == _EMPTY_PARENT_SPAN_ID:
        return None
    return parent.hex()


def _normalize_scope_name(name: str) -> str:
    """Legacy Traceloop scopes are renamed into the product namespace."""
    return (name or "").replace("@traceloop/", "@overmind/")


# Last-resort hints for _classify_span_type, when neither an explicit tag nor a
# GenAI ``execute_tool`` marker is present.
_TOOL_NAME_HINTS: tuple[str, ...] = (
    "tool",
    "function_call",
    "function.call",
    "execute_tool",
)


# Third-party instrumentors (openinference: langchain, llama-index, ...) stamp
# their own kind taxonomy; without this map every non-tool span of theirs fell
# through to the llm_call default.
_OPENINFERENCE_SPAN_TYPES: dict[str, str] = {
    "llm": "llm_call",
    "embedding": "llm_call",
    "tool": "tool_call",
    "retriever": "retrieval",
    "reranker": "retrieval",
    "chain": "workflow",
    "agent": "workflow",
    "guardrail": "workflow",
    "evaluator": "workflow",
}


def _classify_span_type(span_name: str, attrs: dict[str, Any]) -> str:
    """Heuristic ``Span.SpanType`` from the span's name and attributes.

    An explicit tag wins and passes through verbatim, so a future SDK enum
    lands in the column with no server change. Everything unmatched defaults to
    ``llm_call``, which is why ``span_type=llm_call`` is not evidence of one.
    """
    explicit = attrs.get(oc_attrs.SPAN_TYPE) or attrs.get("overmind.span_type") or attrs.get("type")
    if isinstance(explicit, str) and explicit:
        return explicit

    oi_kind = str(attrs.get("openinference.span.kind") or "").strip().lower()
    if oi_kind in _OPENINFERENCE_SPAN_TYPES:
        return _OPENINFERENCE_SPAN_TYPES[oi_kind]

    op = str(attrs.get("gen_ai.operation.name") or "").strip().lower()
    if op == "execute_tool" or attrs.get(oc_attrs.TOOL_NAME):
        return Span.SpanType.TOOL_CALL

    name = (span_name or "").lower()
    if any(hint in name for hint in _TOOL_NAME_HINTS):
        return Span.SpanType.TOOL_CALL

    return Span.SpanType.LLM_CALL


def _operation_from(name: str, attrs: dict[str, Any]) -> str:
    """Trimmed to the column width."""
    op = (
        attrs.get("gen_ai.operation.name")
        or attrs.get("operation")
        or attrs.get(oc_attrs.TOOL_NAME)
    )
    return str(op or name or "")[:512]


def resolve_project_for_ingest(request, resource_attrs: dict[str, Any]) -> Project | None:
    """Project-scoped keys pin ingest; account keys and sessions resolve from attrs or membership.
    A named project the caller cannot reach is refused, never replaced by another one."""
    if isinstance(request.auth, APIToken) and not request.auth.is_account_scoped:
        return request.auth.project

    explicit_id = _get_attr(resource_attrs, oc_attrs.PROJECT_ID, "overmind.project_id")
    if explicit_id:
        try:
            project_id = uuid.UUID(str(explicit_id))
        except ValueError:
            raise PermissionDenied("Project access denied.") from None
        project = Project.objects.filter(
            id=project_id, id__in=project_ids_for(request.user, request.auth)
        ).first()
        if project is None:
            raise PermissionDenied("Project access denied.")
        return project

    membership = (
        ProjectMembership.objects.filter(user=request.user)
        .select_related("project")
        .order_by("created_at")
        .first()
    )
    return membership.project if membership else None


def _normalize_product_attr_key(key: Any) -> str | None:
    """Canonical ``overmind.*`` key, or ``None`` when *key* is not a product tag.
    ``overclaw.*`` is the old prefix and still arrives from pinned SDKs."""
    if not isinstance(key, str):
        return None
    if key.startswith("overmind."):
        return key
    if key.startswith("overclaw."):
        return "overmind." + key.removeprefix("overclaw.")
    return None


# Capabilities sometimes embed ``overmind.*`` metadata inside these payloads (dict or
# JSON string) instead of stamping top-level span attributes, so they are scanned.
_PAYLOAD_ATTR_KEYS: tuple[str, ...] = (
    oc_attrs.INPUT_DATA,
    oc_attrs.OUTPUT_DATA,
    "overmind.input_data",
    "overmind.output_data",
    "inputs",
    "outputs",
    "traceloop.entity.input",
    "traceloop.entity.output",
)

# Guards against hostile or self-referential JSON; real payloads are 2–3 deep.
_MAX_PAYLOAD_DEPTH = 6


def _maybe_parse_json(value: Any) -> Any:
    if not isinstance(value, str):
        return value
    stripped = value.strip()
    if not stripped or stripped[0] not in '{["':
        return value
    parsed = safe_json(value)
    return parsed if parsed is not None else value


def _collect_overmind_tags(value: Any, out: dict[str, Any], depth: int = 0) -> None:
    """Harvest ``overmind.*`` keys out of a dict, list or JSON string. Anything
    unrecognisable is ignored — this walks untrusted payloads."""
    if depth > _MAX_PAYLOAD_DEPTH or value is None:
        return

    if isinstance(value, str):
        parsed = _maybe_parse_json(value)
        if parsed is not value:
            _collect_overmind_tags(parsed, out, depth + 1)
        return

    if isinstance(value, dict):
        for key, child in value.items():
            norm = _normalize_product_attr_key(key)
            if norm is not None:
                # Existing keys (added at higher priority) are preserved.
                out.setdefault(norm, child)
            _collect_overmind_tags(child, out, depth + 1)
        return

    if isinstance(value, (list, tuple)):
        for item in value:
            _collect_overmind_tags(item, out, depth + 1)


def _overmind_tags_from_span(span: Span) -> dict[str, Any]:
    """Every ``overmind.*`` tag visible on *span*.

    Priority runs lowest to highest: nested payloads, then resource attributes,
    then span attributes. The order of the three blocks below is the contract.
    """
    tags: dict[str, Any] = {}
    attrs = span.attributes or {}

    for key in _PAYLOAD_ATTR_KEYS:
        if key in attrs:
            _collect_overmind_tags(attrs[key], tags)

    for key, val in (span.resource_attrs or {}).items():
        norm = _normalize_product_attr_key(key)
        if norm is not None:
            tags[norm] = val

    for key, val in attrs.items():
        norm = _normalize_product_attr_key(key)
        if norm is not None:
            tags[norm] = val

    return tags


def _find_existing_capability_for_trace(trace_id: str, project: Project) -> Capability | None:
    """Subprocess-spawned spans inherit W3C ``TRACEPARENT`` but not OTel baggage, so
    they carry no capability identity. Reuse is only safe when the trace maps to
    exactly one capability — on a handoff trace an arbitrary pick would smear one
    capability's identity across the boundary."""
    if not trace_id:
        return None
    capability_ids = list(
        Span.objects.filter(trace_id=trace_id, capability__isnull=False, project=project)
        .values_list("capability_id", flat=True)
        .distinct()[:2]
    )
    if len(capability_ids) != 1:
        return None
    return Capability.objects.filter(pk=capability_ids[0], project=project).current().first()


def _resolve_capability(
    project: Project,
    resource_attrs: dict[str, Any],
    overmind_tags: dict[str, Any],
) -> Capability | None:
    """Attribute a span to a current capability, or to the graph floor.

    ``overmind.capability.id`` is the only mapping key; ``overmind.capability.name``
    is an accessibility label and never resolves. Span-level identity wins over
    resource identity: resource attributes are process-global (the FIRST
    ``overmind.init()`` pins them), so a multi-capability process stamping
    per-request identity must not be overridden.
    Ingest never creates a capability — an id the project does not have
    returns ``None`` and the span stays unbound, visibly."""
    resource_id = resource_attrs.get(oc_attrs.CAPABILITY_ID)
    tagged_id = overmind_tags.get(oc_attrs.CAPABILITY_ID)
    # Tags merge resource then span — a resource-only value is
    # indistinguishable from a span stamp unless it differs from the resource.
    span_level_id = tagged_id if tagged_id and tagged_id != resource_id else None
    for probe in (span_level_id, resource_id):
        if not probe:
            continue
        resolved = identity.lookup_id(project.id, str(probe))
        if resolved is not None:
            return resolved
    if tagged_id or resource_id:
        logger.info(
            "Unresolved capability id %r for project %s — span stays unbound",
            str(tagged_id or resource_id)[:64],
            project.slug,
        )
    return None


def _resolve_conversation(
    project: Project, span: Span, capability: Capability | None
) -> Conversation | None:
    """Sessions are project-wide; the ``capability`` FK is only a convenience pointer
    to the first capability seen."""
    external_id = _get_attr(
        span.attributes, oc_attrs.CONVERSATION_ID, oc_attrs.CONVERSATION_ID_LEGACY
    ) or _get_attr(span.resource_attrs, oc_attrs.CONVERSATION_ID, oc_attrs.CONVERSATION_ID_LEGACY)
    if not external_id or not isinstance(external_id, str):
        return None

    conversation, created = Conversation.objects.get_or_create(
        project=project, external_id=external_id[:512]
    )
    if created:
        logger.info("Auto-created session %s/%s", project.slug, external_id[:64])
    if capability is not None and conversation.capability_id is None:
        conversation.capability = capability
        conversation.save(update_fields=["capability"])
    return conversation


def _record_cli_version(capability: Capability, version: str) -> bool:
    """The latest span wins, so the Console can flag a capability whose most recent run
    used an outdated CLI."""
    version = (version or "")[:20]
    if not version or capability.cli_version == version:
        return False
    capability.cli_version = version
    return True


_TOTAL_TOKEN_KEYS = (
    oc_attrs.LLM_USAGE_TOTAL_TOKENS,
    oc_attrs.LLM_TOTAL_TOKENS,
    "gen_ai.usage.total_tokens",
    "llm.usage.total_tokens",
)


def _first_int(attrs: dict[str, Any], keys: tuple[str, ...]) -> int:
    for key in keys:
        value = safe_int(attrs.get(key))
        if value:
            return value
    return 0


def _build_span_usage(span: Span) -> dict[str, Any]:
    attrs = span.attributes or {}
    span_type = (span.span_type or "").lower()

    pt = _first_int(attrs, PROMPT_TOKEN_KEYS)
    ct = _first_int(attrs, COMPLETION_TOKEN_KEYS)
    tt = _first_int(attrs, _TOTAL_TOKEN_KEYS)

    model = _get_attr(attrs, *MODEL_KEYS)
    cost = safe_float(attrs.get(oc_attrs.LLM_COST))

    llm_calls = 1 if span_type == Span.SpanType.LLM_CALL else 0
    tool_calls = 1 if span_type in (Span.SpanType.TOOL_CALL, "tool") else 0

    models = {model: 1} if model else {}

    if not any((pt, ct, tt, cost, llm_calls, tool_calls, models)):
        return {}

    return {
        "prompt_tokens": pt,
        "completion_tokens": ct,
        "total_tokens": tt or (pt + ct),
        "cost_usd": round(safe_float(cost), 6) if cost else 0.0,
        "llm_calls": llm_calls,
        "tool_calls": tool_calls,
        "models": models,
    }


def _apply_runtime_summaries(
    capability: Capability, span: Span, overmind_tags: dict[str, Any]
) -> bool:
    """Cumulative counters accumulate across spans, deduped by ``span_id`` so a
    re-ingest of the same batch stays idempotent."""
    dirty = False

    span_usage = _build_span_usage(span)
    if span_usage:
        existing = dict(capability.usage_stats or {})
        seen: list[str] = list(existing.get("_spans") or [])
        if span.span_id not in seen:
            for key in (
                "prompt_tokens",
                "completion_tokens",
                "total_tokens",
                "llm_calls",
                "tool_calls",
            ):
                existing[key] = (existing.get(key) or 0) + span_usage.get(key, 0)
            if span_usage.get("cost_usd"):
                existing["cost_usd"] = round(
                    safe_float(existing.get("cost_usd")) + safe_float(span_usage["cost_usd"]),
                    6,
                )
            merged_models = dict(existing.get("models") or {})
            for model, n in (span_usage.get("models") or {}).items():
                merged_models[model] = merged_models.get(model, 0) + n
            if merged_models:
                existing["models"] = merged_models

            seen.append(span.span_id)
            # Capped so the JSON blob stays bounded.
            existing["_spans"] = seen[-2000:]
            existing["updated_at"] = timezone.now().isoformat()
            capability.usage_stats = existing
            dirty = True

    if span.end_time_ns:
        end_dt = datetime.fromtimestamp(span.end_time_ns / 1_000_000_000, tz=UTC)
        # ``last_activity_at`` only moves forward: one span from a clock ahead would pin it.
        if end_dt > timezone.now() + _CLOCK_SKEW:
            return dirty
        if capability.last_activity_at is None or end_dt > capability.last_activity_at:
            capability.last_activity_at = end_dt
            dirty = True

    return dirty


def process_span(span_id: str, project_id: str | None = None):
    """Project a single span onto its Capability row.

    Idempotent, because the task is retried and the same batch is re-exported:
    Capability fields are last-write-wins and the usage counters dedupe by ``span_id``.
    """
    qs = Span.objects.filter(pk=span_id).select_related("project")
    if project_id:
        qs = qs.filter(project_id=project_id)
    span: Span = qs.first()
    if span is None:
        logger.warning("process_span: span %s not found, skipping", span_id)
        return

    project = span.project
    resource_attrs = dict(span.resource_attrs or {})
    overmind_tags = _overmind_tags_from_span(span)

    with transaction.atomic():
        capability = _resolve_capability(project, resource_attrs, overmind_tags)
        named = any(
            attrs.get(key)
            for attrs in (resource_attrs, overmind_tags)
            for key in (oc_attrs.CAPABILITY_ID, oc_attrs.CAPABILITY_NAME)
        )
        # Only a span that names no capability joins its trace's: one that names another
        # stays unbound rather than bound to the wrong one.
        if capability is None and not named:
            capability = _find_existing_capability_for_trace(span.trace_id, project)
        if capability is not None:
            dirty = _record_cli_version(capability, span.scope_version)
            dirty |= _apply_runtime_summaries(capability, span, overmind_tags)
            if dirty:
                capability.save()

        conversation = _resolve_conversation(project, span, capability)

    fields_to_persist: list[str] = []
    if capability and span.capability_id != capability.pk:
        span.capability = capability
        fields_to_persist.append("capability")
    if conversation and span.conversation_id != conversation.pk:
        span.conversation = conversation
        fields_to_persist.append("conversation")
    if fields_to_persist:
        span.save(update_fields=fields_to_persist)

    logger.info(
        "Processed span %s trace=%s → capability=%s",
        span_id,
        span.trace_id,
        capability.slug if capability else None,
    )


def _fit(field: str, value: str) -> str:
    """OTLP sets no length on names; one long name must not reject its whole batch."""
    return value[: Span._meta.get_field(field).max_length]


def _build_span(
    span_proto,
    project: Project,
    resource_attrs: dict[str, Any],
    scope_name: str,
    scope_version: str,
) -> Span:
    start = span_proto.start_time_unix_nano
    end = span_proto.end_time_unix_nano
    duration = max(end - start, 0) if end and start else 0
    attrs = _coalesce_genai_attrs(_kv_list_to_dict(span_proto.attributes))
    stamp_span_cost(attrs, start_time_ns=start)

    return Span(
        span_id=span_proto.span_id.hex(),
        trace_id=span_proto.trace_id.hex(),
        parent_span_id=_parent_hex_or_none(span_proto),
        project=project,
        span_type=_classify_span_type(span_proto.name, attrs),
        operation=_fit("operation", _operation_from(span_proto.name or "", attrs)),
        name=_fit("name", span_proto.name or ""),
        kind=int(span_proto.kind),
        start_time_ns=start,
        end_time_ns=end,
        duration_ns=duration,
        status_code=int(span_proto.status.code),
        status_message=span_proto.status.message or "",
        service_name=_fit("service_name", str(resource_attrs.get("service.name") or "")),
        resource_attrs=resource_attrs,
        scope_name=_fit("scope_name", _normalize_scope_name(scope_name)),
        scope_version=_fit("scope_version", scope_version or ""),
        attributes=attrs,
        usage=usage_slice(attrs),
        events=[_span_event_to_dict(e) for e in span_proto.events],
        links=[_span_link_to_dict(link) for link in span_proto.links],
    )


def _build_spans_for_resource(
    request,
    resource_span: ResourceSpans,
) -> tuple[list[Span], Project | None] | JsonResponse:
    resource_attrs = _kv_list_to_dict(resource_span.resource.attributes)
    project = resolve_project_for_ingest(request, resource_attrs)
    if project is None:
        logger.warning("No project for user %s, skipping resource_span", request.user)
        return [], None

    allowed_ids = {str(pid) for pid in project_ids_for(request.user, request.auth)}
    if str(project.id) not in allowed_ids:
        return JsonResponse({"error": "Project access denied."}, status=403)

    spans: list[Span] = []
    for scope_span in resource_span.scope_spans:
        scope_name = scope_span.scope.name
        scope_version = scope_span.scope.version
        for span_proto in scope_span.spans:
            spans.append(
                _build_span(span_proto, project, resource_attrs, scope_name, scope_version)
            )
    return spans, project


# Updated when the same ``span_id`` is re-ingested. The linkage FKs
# (capability / conversation) are owned by ``process_span`` and must stay out.
_SPAN_UPSERT_FIELDS = [
    "name",
    "kind",
    "span_type",
    "operation",
    "parent_span_id",
    "start_time_ns",
    "end_time_ns",
    "duration_ns",
    "status_code",
    "status_message",
    "service_name",
    "resource_attrs",
    "scope_name",
    "scope_version",
    "attributes",
    "usage",
    "events",
    "links",
    # Reset only when the evidence changed; a span re-sent unchanged keeps its score.
    "eval_attributes",
    "eval_claimed_at",
]
_EVAL_FIELDS = frozenset({"eval_attributes", "eval_claimed_at"})


# The OpenTelemetry Collector's default request limit. Parsed spans take several times
# their wire size in memory, so the limit holds after decompression too.
MAX_EXPORT_BYTES = 20 * 1024 * 1024


def _decoded_request_body(request) -> bytes:
    if safe_int(request.headers.get("Content-Length")) > MAX_EXPORT_BYTES:
        raise _TooLargeError
    raw = request.read(MAX_EXPORT_BYTES + 1)
    if len(raw) > MAX_EXPORT_BYTES:
        raise _TooLargeError
    if "gzip" not in request.headers.get("Content-Encoding", ""):
        return raw
    stream = zlib.decompressobj(16 + zlib.MAX_WBITS)
    try:
        body = stream.decompress(raw, MAX_EXPORT_BYTES + 1)
    except zlib.error as exc:
        raise _MalformedBodyError(f"Invalid gzip body: {exc}") from exc
    if len(body) > MAX_EXPORT_BYTES:
        raise _TooLargeError
    if not stream.eof:
        raise _MalformedBodyError("Invalid gzip body: incomplete or truncated stream")
    return body


class _MalformedBodyError(Exception):
    pass


class _TooLargeError(Exception):
    pass


def _hex_id_to_base64(holder: dict, *keys: str) -> None:
    for key in keys:
        if isinstance(holder.get(key), str):
            holder[key] = base64.b64encode(bytes.fromhex(holder[key])).decode()


def _hex_ids_to_base64(export: dict) -> dict:
    """OTLP/JSON writes trace and span ids as hex; proto3 JSON reads bytes as base64.
    Only Span and Link ids convert, so unknown fields stay ignorable."""
    for resource_spans in export.get("resourceSpans") or []:
        for scope_spans in resource_spans.get("scopeSpans") or []:
            for span in scope_spans.get("spans") or []:
                _hex_id_to_base64(span, "traceId", "spanId", "parentSpanId")
                for link in span.get("links") or []:
                    _hex_id_to_base64(link, "traceId", "spanId")
    return export


def _parse_export(request, body: bytes) -> trace_service_pb2.ExportTraceServiceRequest:
    export_request = trace_service_pb2.ExportTraceServiceRequest()
    if request.content_type.split(";", 1)[0].strip().lower() == "application/json":
        json_format.ParseDict(
            _hex_ids_to_base64(json.loads(body)), export_request, ignore_unknown_fields=True
        )
    else:
        export_request.ParseFromString(body)
    return export_request


@api_view(["POST"])
@permission_classes([IsAuthenticated])
@extend_schema(exclude=True)
def otlp_traces(request):
    try:
        body = _decoded_request_body(request)
    except _MalformedBodyError as exc:
        return JsonResponse({"error": str(exc)}, status=400)
    except _TooLargeError:
        return JsonResponse(
            {"error": f"OTLP export exceeds {MAX_EXPORT_BYTES} bytes; send smaller batches."},
            status=413,
        )

    try:
        export_request = _parse_export(request, body)
    except Exception as exc:
        # The parser's message can quote the rejected payload, so log only its type.
        logger.error(
            "Failed to parse OTLP export: %s (%s, %d bytes)",
            type(exc).__name__,
            request.content_type,
            len(body),
        )
        return JsonResponse({"error": "Invalid OTLP export."}, status=400)

    all_spans: list[Span] = []
    for resource_span in export_request.resource_spans:
        outcome = _build_spans_for_resource(request, resource_span)
        if isinstance(outcome, HttpResponseBase):
            return outcome
        spans, project = outcome
        if project is None:
            continue
        all_spans.extend(spans)

    return JsonResponse(accept_spans(all_spans))


def span_from_record(project: Project, record: dict[str, Any]) -> Span:
    """A product ``Span`` from a collector ``SpanRecord``. No protobuf on this path."""
    attrs = _coalesce_genai_attrs(dict(record.get("attributes") or {}))
    start = int(record["start_time_ns"])
    end = int(record["end_time_ns"])
    stamp_span_cost(attrs, start_time_ns=start)
    name = str(record.get("name") or "")
    parent = record.get("parent_span_id") or None
    duration = record.get("duration_ns")
    if duration is None:
        duration = max(end - start, 0)
    return Span(
        span_id=str(record["span_id"]),
        trace_id=str(record["trace_id"]),
        parent_span_id=parent,
        project=project,
        span_type=_classify_span_type(name, attrs),
        operation=_fit("operation", _operation_from(name, attrs)),
        name=_fit("name", name),
        kind=int(record.get("kind") or 0),
        start_time_ns=start,
        end_time_ns=end,
        duration_ns=int(duration),
        status_code=int(record.get("status_code") or 0),
        status_message=str(record.get("status_message") or ""),
        service_name=_fit("service_name", str(record.get("service_name") or "")),
        resource_attrs=dict(record.get("resource_attrs") or {}),
        scope_name=_fit("scope_name", _normalize_scope_name(str(record.get("scope_name") or ""))),
        scope_version=_fit("scope_version", str(record.get("scope_version") or "")),
        attributes=attrs,
        usage=usage_slice(attrs),
        events=list(record.get("events") or []),
        links=list(record.get("links") or []),
    )


def project_span_records(project: Project, records: list[dict[str, Any]]) -> dict[str, int]:
    """The collector's product write. The project id is the one it already authorized."""
    return accept_spans([span_from_record(project, record) for record in records])


def accept_spans(all_spans: list[Span]) -> dict[str, int]:
    """Upsert, bind capability and conversation, then enqueue scoring.

    One poison span must not fail the batch: exporters retry a 500 forever.
    """
    storable = [span for span in all_spans if _storable(span)]
    rejected = len(all_spans) - len(storable)
    all_spans = storable
    unscored: list[Span] = []
    if all_spans:
        with transaction.atomic():
            all_spans, unscored, refused = _persist_storable_spans(all_spans)
            rejected += refused

            for project_id in {span.project_id for span in all_spans}:
                record(
                    key=f"first-trace:{project_id}",
                    project_id=project_id,
                    kind="first_trace",
                    action="Received first trace",
                )

    post_processed = 0
    for span in all_spans:
        try:
            process_span(span.span_id, str(span.project_id))
            post_processed += 1
        except Exception:
            logger.exception("post-processing failed for span %s", span.span_id)

    enqueue_scoring(unscored)
    return {
        "spans_ingested": len(all_spans),
        "spans_post_processed": post_processed,
        "spans_rejected": rejected,
    }


_TEXT_FIELDS = (
    "name",
    "span_type",
    "operation",
    "status_message",
    "service_name",
    "scope_name",
    "scope_version",
)


def _storable(span: Span) -> bool:
    """span_id is the primary key across projects: an absent or all-zero id would make one
    row every exporter overwrites. PostgreSQL text holds no NUL byte."""
    return bool(
        span.span_id.strip("0")
        and span.trace_id.strip("0")
        and not any("\x00" in getattr(span, field) for field in _TEXT_FIELDS)
    )


def _persist_storable_spans(spans: list[Span]) -> tuple[list[Span], list[Span], int]:
    """A span whose JSON PostgreSQL refuses (a NUL escape) is rejected alone: the batch is
    retried in halves until only refused spans are left out."""
    try:
        with transaction.atomic():
            return _persist_owned_spans(spans)
    except DataError:
        if len(spans) == 1:
            return [], [], 1
    middle = len(spans) // 2
    kept, unscored, rejected = _persist_storable_spans(spans[:middle])
    more, pending, refused = _persist_storable_spans(spans[middle:])
    return kept + more, unscored + pending, rejected + refused


def _persist_owned_spans(spans: list[Span]) -> tuple[list[Span], list[Span], int]:
    """``span_id`` is the primary key across projects. Insert-or-skip, then update only
    rows this batch's project owns, so a concurrent first writer keeps its span.
    A stored score whose evidence is unchanged is left in place.

    Returns the owned spans, the ones that still need scoring, and how many were rejected.
    """
    batch: dict[str, Span] = {}
    rejected = 0
    for span in spans:
        held = batch.get(span.span_id)
        if held is not None and held.project_id != span.project_id:
            rejected += 1
            continue
        batch[span.span_id] = span
    ids = list(batch)
    existing = set(Span.objects.filter(span_id__in=ids).values_list("span_id", flat=True))
    Span.objects.bulk_create(list(batch.values()), ignore_conflicts=True)
    owners = dict(
        Span.objects.select_for_update()
        .filter(span_id__in=ids)
        .values_list("span_id", "project_id")
    )
    kept = [span for span in batch.values() if owners.get(span.span_id) == span.project_id]
    rejected += len(batch) - len(kept)
    owned_existing = [span for span in kept if span.span_id in existing]
    unchanged = evidence.scored_unchanged(owned_existing)
    refresh = [span for span in owned_existing if span.span_id not in unchanged]
    preserve = [span for span in owned_existing if span.span_id in unchanged]
    if refresh:
        Span.objects.bulk_update(refresh, _SPAN_UPSERT_FIELDS, batch_size=500)
    if preserve:
        Span.objects.bulk_update(
            preserve,
            [field for field in _SPAN_UPSERT_FIELDS if field not in _EVAL_FIELDS],
            batch_size=500,
        )
    if rejected:
        logger.warning("OTLP ingest rejected %d span(s) owned by another project", rejected)
    unscored = [span for span in kept if span.span_id not in unchanged]
    return kept, unscored, rejected


def enqueue_scoring(spans: list[Span]) -> None:
    """Also called by connector sync, whose ``bulk_create`` has no other enqueue path.
    A broker hiccup never fails ingest; the beat sweep re-drives unscored spans."""
    # overbae.tasks imports this module at package init.
    from overbae.tasks.innermind import enqueue_span_scoring  # noqa: PLC0415

    try:
        enqueue_span_scoring([(span.trace_id, span.span_id) for span in spans])
    except Exception:  # noqa: BLE001
        logger.warning("Failed to enqueue scoring for %d spans", len(spans), exc_info=True)