Skip to content

The platform for continuously improving AI agents.

10.4 KB
Raw Blame
"""Creating and landing trace datasets when traces live in the OTel collector."""

from __future__ import annotations

import json
import uuid

import httpx
import jwt
import pytest
from conftest import read_table
from django.conf import settings
from django.test import override_settings
from factories import make_project, make_user
from rest_framework.test import APIClient

from overbae.models import Capability, Dataset, ProjectMembership, Span
from overbae.services.datasets import land, paths, selection

pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]

COLLECTOR = "http://collector.test"
NS = 1_700_000_000_000_000_000


def _json_response(body: dict, status: int = 200) -> tuple[int, dict, bytes]:
    return (status, {"content-type": "application/json"}, json.dumps(body).encode())


def _collector_chat_spans(
    trace_id: str,
    *,
    text: str = "hello back",
    capability_id: str | None = None,
    conversation_id: str | None = "conv-99",
    error: bool = False,
    start_ns: int = NS,
) -> list[dict]:
    root_id = uuid.uuid4().hex[:16]
    root_attrs: dict = {"overmind.span.type": "entry_point"}
    if capability_id:
        root_attrs["overmind.capability.id"] = capability_id
    if conversation_id:
        root_attrs["gen_ai.conversation.id"] = conversation_id
    llm_attrs: dict = {
        "overmind.span.type": "llm_call",
        "gen_ai.input.messages": json.dumps(
            [{"role": "user", "parts": [{"type": "text", "content": "hi"}]}]
        ),
        "gen_ai.output.messages": json.dumps(
            [{"role": "assistant", "parts": [{"type": "text", "content": text}]}]
        ),
        "gen_ai.usage.input_tokens": 80,
        "gen_ai.usage.output_tokens": 20,
        "overmind.cost": 0.002,
        "gen_ai.request.model": "openai/gpt-5-mini",
    }
    if capability_id:
        llm_attrs["overmind.capability.id"] = capability_id
    return [
        {
            "spanId": root_id,
            "traceId": trace_id,
            "name": "agent.turn",
            "kind": 1,
            "startTimeNs": str(start_ns),
            "endTimeNs": str(start_ns + 1_000_000_000),
            "durationNs": "1000000000",
            "statusCode": 2 if error else 1,
            "statusMessage": "boom" if error else "",
            "serviceName": "frontdesk",
            "resourceAttributes": {},
            "scopeName": "overmind",
            "scopeVersion": "1.0.0",
            "attributes": root_attrs,
            "events": [],
            "links": [],
        },
        {
            "spanId": uuid.uuid4().hex[:16],
            "traceId": trace_id,
            "parentSpanId": root_id,
            "name": "frontdesk.llm",
            "kind": 3,
            "startTimeNs": str(start_ns + 10),
            "endTimeNs": str(start_ns + 500_000_000),
            "durationNs": "499999990",
            "statusCode": 1,
            "statusMessage": "",
            "serviceName": "frontdesk",
            "resourceAttributes": {},
            "scopeName": "overmind",
            "scopeVersion": "1.0.0",
            "attributes": llm_attrs,
            "events": [],
            "links": [],
        },
    ]


@override_settings(OTEL_URL=COLLECTOR)
def test_explicit_trace_ids_count_create_and_land_from_collector(scripted):
    user = make_user()
    project = make_project(owner=user)
    ProjectMembership.objects.get_or_create(project=project, user=user)
    capability = Capability.objects.create(project=project, name="Concierge", slug="concierge")

    t1, t2, missing = uuid.uuid4().hex, uuid.uuid4().hex, uuid.uuid4().hex
    store = {
        t1: _collector_chat_spans(t1, text="first", capability_id=str(capability.id)),
        t2: _collector_chat_spans(t2, text="second", error=True, conversation_id="conv-err"),
    }

    def handle(call):
        if call.path == "/api.v1.TraceService/GetTrace":
            tid = call.json["traceId"]
            spans = store.get(tid)
            if not spans:
                return _json_response({"code": "not_found", "message": "missing"}, status=404)
            return _json_response({"traceId": tid, "spanCount": len(spans), "spans": spans})
        return _json_response({"rows": [], "totalCount": "0"})

    api = scripted(COLLECTOR).then(handle)

    assert Span.objects.filter(project=project).count() == 0

    client = APIClient()
    client.force_authenticate(user=user)
    resp = client.post(
        "/api/datasets/",
        {
            "project": str(project.id),
            "name": "Collector traces",
            "source": {"traces": {"trace_ids": [t1, missing, t2]}},
        },
        format="json",
    )
    assert resp.status_code == 201, resp.content

    first_call = api.calls[0]
    assert first_call.headers["x-project-id"] == str(project.id)
    scheme, _, token = first_call.headers["authorization"].partition(" ")
    assert scheme == "Bearer"
    decoded = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
    assert decoded["user_id"] == user.id

    dataset = Dataset.objects.get(pk=resp.json()["id"])
    land.land_traces(dataset, {"trace_ids": [t1, missing, t2]})
    dataset.refresh_from_db()
    df = read_table(paths.cell_path(dataset.id, dataset.source.id))

    assert df["trace_id"].tolist() == [t1, t2]
    row0 = df.iloc[0]
    assert (row0["capability"], row0["capability_id"]) == ("Concierge", str(capability.id))
    assert row0["conversation_id"] == "conv-99"
    assert (row0["prompt_tokens"], row0["completion_tokens"]) == (80, 20)
    assert row0["cost_usd"] == pytest.approx(0.002)
    assert row0["model"] == "openai/gpt-5-mini"
    assert row0["messages"][-1]["content"] == "first"
    row1 = df.iloc[1]
    assert (row1["status"], row1["error"]) == ("error", "boom")
    assert row1["conversation_id"] == "conv-err"


@override_settings(OTEL_URL=COLLECTOR)
def test_filter_selection_translates_filters_exclusions_limit_and_pagination(scripted):
    user = make_user()
    project = make_project(owner=user)
    ProjectMembership.objects.get_or_create(project=project, user=user)
    cap_a = Capability.objects.create(project=project, name="A", slug="a")
    cap_b = Capability.objects.create(project=project, name="B", slug="b")

    t1, t2, t3 = uuid.uuid4().hex, uuid.uuid4().hex, uuid.uuid4().hex
    rows = [
        {
            "span": {
                "traceId": t1,
                "spanId": "1" * 16,
                "attributes": {"overmind.capability.id": str(cap_a.id)},
            }
        },
        {
            "span": {
                "traceId": t2,
                "spanId": "2" * 16,
                "attributes": {"overmind.capability.id": str(cap_b.id)},
            }
        },
        {
            "span": {
                "traceId": t3,
                "spanId": "3" * 16,
                "attributes": {"overmind.capability.id": str(cap_a.id)},
            }
        },
    ]

    def handle(call):
        body = call.json
        if body.get("traceId"):
            matched = [r for r in rows if r["span"]["traceId"] == body["traceId"]]
            return _json_response({"rows": matched, "totalCount": str(len(matched))})
        if body.get("pageSize") == 1:
            return _json_response({"rows": rows[:1], "totalCount": str(len(rows))})
        token = body.get("pageToken") or ""
        if token == "":
            return _json_response({"rows": rows[:2], "nextPageToken": "2", "totalCount": "3"})
        return _json_response({"rows": rows[2:], "nextPageToken": "", "totalCount": "3"})

    api = scripted(COLLECTOR).then(handle)

    source = selection.TraceSource.parse(
        {
            "filters": {
                "has_error": "true",
                "received_at__gte": "2026-12-01T00:00:00Z",
                "model": "openai/gpt-5-mini",
            },
            "search": "agent",
            "ordering": "duration_ns",
            "exclude_trace_ids": [t2],
            "limit": 2,
        }
    )
    assert source.count(project.id) == 2
    list_body = api.calls[0].json
    assert list_body["hasError"] is True
    assert list_body["model"] == "openai/gpt-5-mini"
    assert list_body["nameContains"] == "agent"
    assert list_body["orderBy"] == "ORDER_FIELD_DURATION"
    assert list_body["ascending"] is True
    assert int(list_body["startTimeNsGte"]) > 0

    assert list(source.iter_trace_ids(project.id)) == [t1, t3]

    by_cap = selection.TraceSource.parse({"filters": {"capability": str(cap_a.id)}})
    assert by_cap.count(project.id) == 2
    assert list(by_cap.iter_trace_ids(project.id)) == [t1, t3]

    other_project = selection.TraceSource.parse({"filters": {"project": str(uuid.uuid4())}})
    assert other_project.count(project.id) == 0

    with pytest.raises(selection.TraceSourceError):
        selection.TraceSource.parse({"filters": {"received_at__gte": "yesterday"}}).count(
            project.id
        )


@override_settings(OTEL_URL=COLLECTOR)
def test_falls_back_to_postgres_when_project_has_no_collector_traces(scripted):
    project = make_project()
    trace = uuid.uuid4().hex
    Span.objects.create(
        span_id=uuid.uuid4().hex[:16],
        trace_id=trace,
        project=project,
        span_type="entry_point",
        name="legacy.run",
        start_time_ns=NS,
        end_time_ns=NS + 1_000_000_000,
        duration_ns=1_000_000_000,
        status_code=1,
    )

    scripted(COLLECTOR).then(
        lambda call: (
            _json_response({"code": "not_found"}, status=404)
            if call.path.endswith("/GetTrace")
            else _json_response({"rows": [], "totalCount": "0"})
        )
    )

    source = selection.TraceSource.parse({"filters": {"project": str(project.id)}})
    assert source.count(project.id) == 1
    assert list(source.iter_trace_ids(project.id)) == [trace]

    dataset = Dataset.objects.create(project=project, name="legacy")
    land.land_traces(dataset, {"trace_ids": [trace]})
    df = read_table(paths.cell_path(dataset.id, dataset.source.id))
    assert df["trace_id"].tolist() == [trace]


@override_settings(OTEL_URL=COLLECTOR)
def test_collector_errors_surface_as_trace_source_and_land_errors(scripted):
    project = make_project()
    scripted(COLLECTOR).fail(httpx.ConnectError("collector down"))

    source = selection.TraceSource.parse({"trace_ids": [uuid.uuid4().hex]})
    with pytest.raises(selection.TraceSourceError, match="unreachable"):
        source.count(project.id)

    dataset = Dataset.objects.create(project=project, name="broken")
    with pytest.raises(land.LandError, match="unreachable"):
        land.land_traces(dataset, {"trace_ids": [uuid.uuid4().hex]})