The platform for continuously improving AI agents.
"""The platform's own telemetry: New Relic attributes, caught failures and log correlation.
Every request and task carries the IDs it acts on, failures the platform catches reach
New Relic as errors, and each log line names the same IDs and New Relic trace.
"""
from __future__ import annotations
import contextvars
import logging
import os
import re
import sys
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
from uuid import UUID
import newrelic.agent
RELEASE = os.environ.get("OVERMIND_RELEASE", "")
logger = logging.getLogger(__name__)
_attributes: contextvars.ContextVar[dict[str, Any] | None] = contextvars.ContextVar(
"telemetry_attributes", default=None
)
class PlatformError(Exception):
"""A failure the platform caught and handled. New Relic groups these by message."""
def _clean(attributes: dict[str, Any]) -> dict[str, Any]:
return {
name: str(value) if isinstance(value, UUID) else value
for name, value in attributes.items()
if value is not None and value != ""
}
@contextmanager
def scope() -> Iterator[None]:
"""Start a fresh attribute set for one request or task; worker threads are reused."""
token = _attributes.set({"release": RELEASE} if RELEASE else {})
try:
yield
finally:
_attributes.reset(token)
def annotate(**attributes: Any) -> None:
"""Attach IDs to the current New Relic transaction and to later log lines."""
values = _clean(attributes)
if not values:
return
_attributes.set({**(_attributes.get() or {}), **values})
newrelic.agent.add_custom_attributes(values.items())
def current() -> dict[str, Any]:
return dict(_attributes.get() or {})
def ignore_transaction() -> None:
newrelic.agent.ignore_transaction()
def report_failure(message: str, **attributes: Any) -> None:
"""Record a caught failure as a New Relic error.
``message`` must not contain IDs, so repeats group together; IDs go in ``attributes``.
Outside a transaction (a Celery parent process) the error goes to the application.
"""
try:
raise PlatformError(message)
except PlatformError:
notice(sys.exc_info(), attributes)
def notice(exc_info, attributes: dict[str, Any]) -> None:
values = {**current(), **_clean(attributes)}
application = None if newrelic.agent.current_transaction() else newrelic.agent.application()
newrelic.agent.notice_error(exc_info, attributes=values, application=application)
class NewRelicErrors(logging.Handler):
"""Error log records become New Relic errors, grouped by the unformatted message.
Records with an exception keep its class; the rest become a PlatformError.
"""
def emit(self, record: logging.LogRecord) -> None:
try:
attributes = {"logger": record.name, "log_message": str(record.msg)}
if record.exc_info and record.exc_info[0] is not None:
notice(record.exc_info, attributes)
else:
report_failure(str(record.msg), **attributes)
except Exception:
self.handleError(record)
class LogContext(logging.Filter):
"""Adds the request or task IDs and the New Relic trace to each JSON log line."""
def filter(self, record: logging.LogRecord) -> bool:
for name, value in current().items():
setattr(record, name, value)
linking = newrelic.agent.get_linking_metadata()
for key in ("trace.id", "span.id"):
if linking.get(key):
setattr(record, key.replace(".", "_"), linking[key])
return True
def _auth_kind(request) -> str:
auth = getattr(request, "auth", None)
if auth is not None:
return type(auth).__name__
user = getattr(request, "user", None)
return "session" if user is not None and user.is_authenticated else "anonymous"
def _project_id(request) -> Any:
# Only DRF views set request.auth; plain Django routes carry the project in the URL or query.
project_id = getattr(getattr(request, "auth", None), "project_id", None)
if project_id is None and request.resolver_match is not None:
project_id = request.resolver_match.kwargs.get("project_id")
return project_id or request.GET.get("project_id") or request.GET.get("project")
def _route(request) -> str | None:
match = request.resolver_match
if match is None:
return None
# DRF router routes anchor each part ("api/^projects/(?P<id>[^/.]+)/$"); keep inner carets.
return "/" + re.sub(r"(^|/)\^", r"\1", match.route).removesuffix("$")
def request_attributes(request) -> dict[str, Any]:
"""Route, user, project and auth kind, once DRF has authenticated the request."""
user = getattr(request, "user", None)
return {
"route": _route(request),
"user_id": user.pk if user is not None and user.is_authenticated else None,
"project_id": _project_id(request),
"auth_kind": _auth_kind(request),
}
class RequestTelemetry:
"""Names the route, user and project on each Django request's New Relic transaction."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
with scope():
response = self.get_response(request)
# DRF authenticates inside the view and mirrors user and auth onto this request.
annotate(**request_attributes(request))
return response
def process_view(self, request, view_func, view_args, view_kwargs):
# Errors logged while the view runs carry the route and URL project. The user waits:
# reading request.user here would load the session for every token-authenticated call.
annotate(route=_route(request), project_id=_project_id(request))