Skip to content

The platform for continuously improving AI agents.

16.6 KB
Raw Blame
import json
import logging
from contextlib import contextmanager, suppress
from functools import lru_cache
from time import perf_counter
from uuid import UUID

from celery.signals import worker_process_shutdown, worker_shutdown
from django.conf import settings
from django.db import transaction
from opentelemetry import trace
from opentelemetry.context import Context, attach, detach
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

from overbae.models import ResearchAction, ResearchAssignment
from overmind import attrs, tracing

logger = logging.getLogger(__name__)
PROPAGATOR = TraceContextTextMapPropagator()
PAYLOAD_LIMIT = 512 * 1024


def flush(**kwargs):
    try:
        tracing.flush_traces(timeout_millis=1000)
    except Exception:
        logger.warning("Research telemetry shutdown flush failed")


# Prefork recycling exits without Python's atexit exporter shutdown.
worker_process_shutdown.connect(flush, weak=False)
worker_shutdown.connect(flush, weak=False)


def configure():
    key = settings.RESEARCH_TELEMETRY_API_KEY
    endpoint = settings.RESEARCH_TELEMETRY_API_URL
    project = settings.RESEARCH_TELEMETRY_PROJECT_ID
    if not all((key, endpoint, project)):
        return False
    return configure_exporter(key, endpoint, project)


@lru_cache(maxsize=1)
def configure_exporter(key, endpoint, project):
    # Never inherit the SDK's cloud destination or a developer's saved credentials.
    return tracing.init(
        overmind_api_key=key,
        overmind_base_url=endpoint,
        project_id=project,
        redact_keys=("encrypted_content", "reasoning_details", "reasoning_content", "reasoning"),
        service_name="overmind-research",
        providers=None,
        export_orphan_spans=True,
    )


def captures(project_id):
    return (
        settings.RESEARCH_TELEMETRY_CAPTURE_PAYLOADS
        and str(project_id) == settings.RESEARCH_TELEMETRY_PROJECT_ID
    )


def structured_payload(value):
    if isinstance(value, list):
        return [structured_payload(item) for item in value]
    if not isinstance(value, dict):
        return value
    result = {}
    for key, item in value.items():
        if (
            key in {"content", "arguments", "raw"}
            and isinstance(item, str)
            and item.lstrip().startswith(("{", "["))
        ):
            with suppress(ValueError):
                item = json.loads(item)
        result[key] = structured_payload(item)
    return result


def set_payload(span, key, value):
    if not span.is_recording() or value is None:
        return
    try:
        serialized = tracing.serialize(structured_payload(value))
        encoded = serialized.encode("utf-8")
        if len(encoded) > PAYLOAD_LIMIT:
            serialized = json.dumps(
                {
                    "truncated": True,
                    "bytes": len(encoded),
                    "preview": encoded[:PAYLOAD_LIMIT].decode("utf-8", errors="ignore"),
                },
                ensure_ascii=False,
            )
        span.set_attribute(key, serialized)
    except Exception:
        logger.warning("Research telemetry payload capture failed")


def identity(assignment, agent=None):
    attributes = {
        "research.assignment.id": str(assignment.pk),
        "research.project.id": str(assignment.project_id),
        "research.specification.fingerprint": assignment.fingerprint,
    }
    if assignment.experiment_revision_id:
        attributes["research.revision.id"] = str(assignment.experiment_revision_id)
    if controller := assignment.specification.get("task", {}).get("controller_assignment"):
        attributes["research.controller.id"] = str(controller)
    trigger = assignment.specification.get("task", {}).get("trigger", {})
    for key in ("fire", "trigger", "event"):
        if trigger.get(key):
            attributes[f"research.automation.{key}.id"] = str(trigger[key])
    if agent is not None:
        attributes.update({"research.agent.id": str(agent.pk), "research.agent.role": agent.role})
    return attributes


def parent(assignment):
    # Every span reads the trace root; only the first one may lock the assignment to create it.
    context = (
        ResearchAssignment.objects.filter(pk=assignment.pk)
        .values_list("trace_context", flat=True)
        .first()
    )
    return context or start_trace(assignment)


@transaction.atomic
def start_trace(assignment):
    saved = ResearchAssignment.objects.select_for_update().get(pk=assignment.pk)
    if not saved.trace_context:
        controller = saved.specification.get("task", {}).get("controller_assignment")
        inherited = (
            ResearchAssignment.objects.filter(pk=controller, project_id=saved.project_id)
            .values_list("trace_context", flat=True)
            .first()
            if controller
            else None
        )
        token = attach(PROPAGATOR.extract(inherited) if inherited else Context())
        try:
            with tracing.start_span("research.assignment", attributes=identity(saved)) as span:
                if span.is_recording():
                    if captures(saved.project_id):
                        set_payload(span, "inputs", saved.specification)
                    PROPAGATOR.inject(saved.trace_context)
                    saved.save(update_fields=["trace_context"])
        finally:
            detach(token)
    return saved.trace_context


@contextmanager
def span(name, assignment, *, agent=None, attributes=None, started_at=None, completed_at=None):
    manager = None
    token = None
    current = trace.INVALID_SPAN
    try:
        if configure():
            root = PROPAGATOR.extract(parent(assignment))
            current_context = trace.get_current_span().get_span_context()
            if current_context.trace_id != trace.get_current_span(root).get_span_context().trace_id:
                token = attach(root)
            values = {
                attrs.SPAN_TYPE: "function",
                **identity(assignment, agent),
                **(attributes or {}),
            }
            current = tracing.get_tracer().start_span(
                name,
                attributes=values,
                start_time=int(started_at.timestamp() * 1e9) if started_at else None,
            )
            manager = trace.use_span(current, record_exception=False, set_status_on_exception=False)
            current = manager.__enter__()
    except Exception:
        # Telemetry must neither interrupt work nor expose credentials in an exception log.
        logger.warning("Research telemetry unavailable")
        manager = None
    try:
        yield current
    except BaseException as exc:
        try:
            current.set_status(trace.Status(trace.StatusCode.ERROR, type(exc).__name__))
        except Exception:
            logger.warning("Research telemetry status failed")
        raise
    finally:
        try:
            if manager is not None:
                # Arbitrary tool/provider exception text can contain source data or secrets.
                manager.__exit__(None, None, None)
                current.end(end_time=int(completed_at.timestamp() * 1e9) if completed_at else None)
        except Exception:
            logger.warning("Research telemetry finalization failed")
        finally:
            if token is not None:
                try:
                    detach(token)
                except Exception:
                    logger.warning("Research telemetry context cleanup failed")


def action_completed(action, *, inputs=None, outputs=None):
    started = perf_counter()
    try:
        if configure():
            emit_action(action.pk, started, inputs=inputs, outputs=outputs)
    except Exception:
        logger.warning("Research action telemetry unavailable")


def event_recorded(event):
    started = perf_counter()
    try:
        attributes = {"research.event.id": event.pk, "research.event.kind": event.kind}
        for key in ("node", "scope", "state", "attempt", "run", "revision", "action"):
            value = event.payload.get(key)
            if isinstance(value, (str, int)):
                attributes[f"research.event.{key}"] = value
        with span(
            "research.event", event.assignment, agent=event.agent, attributes=attributes
        ) as emitted:
            if captures(event.assignment.project_id):
                set_payload(
                    emitted,
                    "inputs" if event.kind in {"request_received", "agent_message"} else "outputs",
                    event.payload,
                )
            emitted.set_attribute("research.telemetry.setup_ms", (perf_counter() - started) * 1000)
    except Exception:
        logger.warning("Research event telemetry unavailable")


def node_retained(node):
    try:
        if not configure():
            return
        assignment = node.execution.assignment
        with span(
            f"research.node.{node.node}",
            assignment,
            attributes={
                attrs.SPAN_TYPE: "workflow",
                "research.node.id": node.node,
                "research.node.receipt": str(node.pk),
                "research.node.scope": str(node.scope_id),
                "research.node.attempt": node.attempt,
                "research.node.state": node.state,
            },
            started_at=node.started_at or node.completed_at,
            completed_at=node.completed_at,
        ) as emitted:
            if captures(assignment.project_id):
                set_payload(emitted, "inputs", node.inputs)
                set_payload(
                    emitted,
                    "outputs",
                    {"outputs": node.outputs, **({"error": node.error} if node.error else {})},
                )
            if node.state in {"failed", "cancelled"}:
                emitted.set_status(trace.Status(trace.StatusCode.ERROR, node.state))
    except Exception:
        logger.warning("Research node telemetry unavailable")


def workshop_delegation(task):
    if not task.request_key.startswith("research:") or not captures(task.project_id):
        return None
    try:
        if configure():
            return (
                ResearchAction.objects.select_related("agent__assignment")
                .filter(
                    pk=UUID(task.request_key.removeprefix("research:")),
                    tool="workshop",
                    agent__assignment__project_id=task.project_id,
                )
                .first()
            )
    except Exception:
        logger.warning("Research Workshop telemetry unavailable")
    return None


@contextmanager
def workshop_call(delegation, task, action, name, inputs):
    if delegation is None:
        yield trace.INVALID_SPAN
        return
    attributes = {
        "research.action.id": str(delegation.pk),
        "workshop.task.id": str(task.pk),
        "workshop.action.id": str(action.pk),
        attrs.SPAN_TYPE: "llm_call" if name == "model" else "tool_call",
    }
    if name == "model":
        attributes[attrs.LLM_MODEL] = inputs["model"]
    else:
        attributes[attrs.TOOL_NAME] = name
    with span(
        f"research.workshop.{name}",
        delegation.agent.assignment,
        agent=delegation.agent,
        attributes=attributes,
    ) as emitted:
        set_payload(emitted, "inputs", inputs)
        yield emitted


def workshop_result(emitted, result):
    if not emitted.is_recording():
        return
    set_payload(emitted, "outputs", result)
    body = result.get("body") or {}
    for source, target in (
        ("input_tokens", attrs.LLM_PROMPT_TOKENS),
        ("output_tokens", attrs.LLM_COMPLETION_TOKENS),
    ):
        value = (body.get("usage") or {}).get(source)
        if isinstance(value, int):
            emitted.set_attribute(target, value)
    if (
        result.get("error")
        or result.get("unknown")
        or result.get("cancelled")
        or (result.get("status") and result["status"] != 200)
    ):
        emitted.set_status(trace.Status(trace.StatusCode.ERROR))


@transaction.atomic
def emit_action(identifier, started, *, inputs=None, outputs=None):
    # Serialize duplicate deliveries independently of the caller's stale model instance.
    action = (
        ResearchAction.objects.select_for_update(of=("self",))
        .select_related("agent__assignment")
        .get(pk=identifier)
    )
    if action.trace_context:
        return
    attributes = {
        "research.action.id": str(action.pk),
        "research.action.tool": action.tool,
        "research.action.fingerprint": action.fingerprint,
        "research.action.state": action.state,
    }
    for key in ("context_estimated_tokens", "tool_schema_estimated_tokens"):
        if isinstance(action.arguments.get(key), int):
            attributes[f"research.{key}"] = action.arguments[key]
    operation = action.arguments.get("operation") or action.arguments.get("name")
    if operation:
        attributes["research.action.operation"] = operation
    if action.experiment_node:
        attributes["research.node.id"] = action.experiment_node
    if action.experiment_revision_id:
        attributes["research.revision.id"] = str(action.experiment_revision_id)
    result = action.result if isinstance(action.result, dict) else {}
    for key in ("campaign", "decision", "execution", "investigation", "control", "verification"):
        value = result.get(key)
        identifier = value.get("id") if isinstance(value, dict) else value
        if isinstance(identifier, str):
            with suppress(ValueError):
                attributes[f"research.{key}.id"] = str(UUID(identifier))
    model_call = action.tool in {"model", "prediction_model"}
    attributes[attrs.SPAN_TYPE] = "llm_call" if model_call else "tool_call"
    if model_call:
        requested = action.arguments.get("model") or result.get("model")
        if requested:
            attributes[attrs.LLM_MODEL] = str(requested)
        for source, target in (
            ("served_model", attrs.LLM_RESPONSE_MODEL),
            ("provider", attrs.LLM_PROVIDER),
            ("prompt_tokens", attrs.LLM_PROMPT_TOKENS),
            ("completion_tokens", attrs.LLM_COMPLETION_TOKENS),
            ("cached_tokens", attrs.LLM_CACHE_READ_TOKENS),
        ):
            if action.usage.get(source) is not None:
                attributes[target] = action.usage[source]
        if action.cost_usd is not None:
            attributes[attrs.LLM_COST] = float(action.cost_usd)
    else:
        attributes[attrs.TOOL_NAME] = action.tool
    outputs = result.get("outputs")
    for port, binding in (outputs if isinstance(outputs, dict) else {}).items():
        if isinstance(binding, dict):
            for key in ("artifact", "fingerprint", "cell", "job", "evaluation", "deployment"):
                if binding.get(key):
                    attributes[f"research.output.{port}.{key}"] = str(binding[key])
    if action.started_at and action.completed_at:
        attributes["research.action.duration_ms"] = (
            action.completed_at - action.started_at
        ).total_seconds() * 1000
    for key in ("prompt_tokens", "completion_tokens", "cached_tokens", "response_ms"):
        value = action.usage.get(key)
        if isinstance(value, (int, float)) and not isinstance(value, bool):
            attributes[f"research.usage.{key}"] = value
    for key in ("provider", "served_model", "provider_id", "service_tier"):
        if value := action.usage.get(key):
            attributes[f"research.provider.{key}"] = str(value)
    if action.cost_usd is not None:
        attributes["research.cost.recorded_usd"] = float(action.cost_usd)
    estimate = action.usage.get("cost_estimate") or {}
    if isinstance(estimate, dict) and estimate.get("estimated_usd") is not None:
        attributes["research.cost.estimated_usd"] = float(estimate["estimated_usd"])
    attributes["research.cost.known"] = action.cost_usd is not None
    with span(
        "research.action",
        action.agent.assignment,
        agent=action.agent,
        attributes=attributes,
        started_at=action.started_at or action.created_at,
        completed_at=action.completed_at,
    ) as emitted:
        if captures(action.agent.assignment.project_id):
            set_payload(emitted, "inputs", action.arguments if inputs is None else inputs)
            set_payload(emitted, "outputs", action.result if outputs is None else outputs)
        if action.state in {"failed", "unknown", "denied"}:
            emitted.set_status(trace.Status(trace.StatusCode.ERROR, action.state))
        if emitted.is_recording():
            context = {}
            PROPAGATOR.inject(context)
            ResearchAction.objects.filter(pk=action.pk).update(trace_context=context)
            action.trace_context = context
        emitted.set_attribute("research.telemetry.setup_ms", (perf_counter() - started) * 1000)