Skip to content

The platform for continuously improving AI agents.

Report operator failures to New Relic with their IDs (#360)

Freyam Mehtaeaceb54338f0
diff --git a/.agents/skills/backend-architecture/SKILL.md b/.agents/skills/backend-architecture/SKILL.md
index 978932c9..1c2ab891 100644
--- a/.agents/skills/backend-architecture/SKILL.md
+++ b/.agents/skills/backend-architecture/SKILL.md
@@ -26,6 +26,7 @@ Single Django app `overbae`, project-scoped tenancy.
- **Measured, not invented.** Missing usage, progress, scores or telemetry stay unknown or null. Never fill a percentage, a zero score, an ETA or a cost from elapsed time or a guess.
- **Status writes use `.filter().update()`.** No Django signals fire; reload the row and wire side effects at the call site.
- **Model IDs**: platform models (judges, generation, Jev) live in `core/model_registry.py`; the training and serving catalog lives in `modal/models.json`, read through `modal/model_registry.py`. Jev decisions go through `core/decisions.py`.
+- **Operator telemetry goes to New Relic.** `core/telemetry.py` annotates each request (`RequestTelemetry` middleware, MCP auth) and each Celery task (the `Task` base in `celery.py`) with its IDs and release, and its `LogContext` filter puts the same IDs and the New Relic trace on every JSON log line. A caught failure is an ERROR log or `report_failure`; a Celery hard time-limit kill is reported from the parent (`TaskRequest`). Health checks are left out. `tests/test_operator_telemetry.py` runs the agent against a fake collector.
- **Modal code ships separately.** Changes under `overbae/modal/`, `modal_shared/` or `services/sft_assets/` reach running jobs only after `modal deploy`; training and serving pin immutable releases.
## Reference files
diff --git a/.github/workflows/deploy-api.yml b/.github/workflows/deploy-api.yml
index 5e5434a7..aecbe467 100644
--- a/.github/workflows/deploy-api.yml
+++ b/.github/workflows/deploy-api.yml
@@ -87,6 +87,8 @@ jobs:
org.opencontainers.image.description=Overmind production API and background workers
org.opencontainers.image.vendor=Overmind Platform
context: .
+ build-args: |
+ RELEASE=${{ env.IMAGE_TAG }}
push: true
# Avoid extra untagged manifest rows in ECR from attestations
provenance: false
diff --git a/AGENTS.md b/AGENTS.md
index 6c529e71..3d4c2973 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -29,6 +29,7 @@ This file is the playbook every task needs; Claude Code, Codex and Cursor read i
- Platform model IDs (judges, generation, Jev) live in `overbae/core/model_registry.py`; the training and serving catalog lives in `overbae/modal/models.json`. Jev decisions use `overbae/core/decisions.py`.
- Tenancy is project-scoped with no org layer. A view that accepts guest writes opts in with `guest_allowed = True`, never with a permission class or middleware.
- OTLP ingest never creates a capability, a scan never deletes one, and `DELETE` is a soft delete. On OTLP spans, wire identity is `overmind.capability.id` alone.
+- Operator alerts come from New Relic: every `overbae.*` ERROR log becomes a New Relic error grouped by its unformatted message, so pass IDs as log args, never in an f-string. A caught failure with no log calls `telemetry.report_failure` (`overbae/core/telemetry.py`).
- Celery routing must agree across `CELERY_TASK_ROUTES`, `make worker`, docker-compose and `docker/worker-topology.json`. Only prefork pools enforce `time_limit`. `tests/test_celery_topology.py` checks compose and `make worker` against the routes.
- Two authors do interpretation, code and semantic work: a customer's coding agent over MCP, and the platform assistant in the Console (`services/assistant/`). Both call the same domain services; deterministic, lineage-bound operations stay in the platform. The assistant's turn runs in a worker, never in a sandbox; a project workspace (`services/workspaces/`) only runs code.
- Work-starting operations take a project-scoped request key: an identical retry returns the same record, and a changed payload conflicts. An unknown provider acknowledgement is reconciled from its saved call ID, never resubmitted.
diff --git a/Dockerfile b/Dockerfile
index 1cb5cbed..8b013d9c 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -102,5 +102,8 @@ RUN python manage.py collectstatic --noinput 2>/dev/null || true
EXPOSE 8000
+ARG RELEASE=
+ENV OVERMIND_RELEASE=${RELEASE}
+
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
CMD ["gunicorn", "overbae.asgi:application", "--worker-class", "uvicorn_worker.UvicornWorker", "--workers", "2", "--bind", "0.0.0.0:8000", "--timeout", "120", "--graceful-timeout", "30", "--access-logfile", "-"]
diff --git a/overbae/api/exception_handler.py b/overbae/api/exception_handler.py
index 6e54aa23..e0738b7f 100644
--- a/overbae/api/exception_handler.py
+++ b/overbae/api/exception_handler.py
@@ -6,6 +6,7 @@ renders a string-arg ``ValidationError`` as a bare array. ``IntegrityError``
(slug/name races the serializer validators cannot see) becomes 409, not 500.
"""
+import contextlib
import logging
import uuid
@@ -15,6 +16,8 @@ from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
+from overbae.core import telemetry
+
logger = logging.getLogger(__name__)
@@ -43,6 +46,10 @@ def api_exception_handler(exc, context):
)
error_id = uuid.uuid4().hex[:12]
+ # The failure may be the database itself, and reading the user can authenticate again;
+ # the error log and the JSON response must not depend on it.
+ with contextlib.suppress(Exception):
+ telemetry.annotate(**telemetry.request_attributes(context["request"]), error_id=error_id)
logger.exception("Unhandled API error [%s] in %s", error_id, view_name)
data = {
"detail": f"The server hit an unexpected error (ref {error_id}).",
diff --git a/overbae/api/health.py b/overbae/api/health.py
index bedb3020..8109dc65 100644
--- a/overbae/api/health.py
+++ b/overbae/api/health.py
@@ -4,11 +4,15 @@ from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
+from overbae.core import telemetry
+
@api_view(["GET"])
@permission_classes([AllowAny])
@extend_schema(exclude=True)
def health_check(request):
+ # The ALB and ECS check this every few seconds; New Relic data is billed by the GB.
+ telemetry.ignore_transaction()
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
return Response({"status": "healthy"})
diff --git a/overbae/celery.py b/overbae/celery.py
index 005bba7a..6443d20e 100644
--- a/overbae/celery.py
+++ b/overbae/celery.py
@@ -3,11 +3,49 @@ import logging.config
import os
from celery import Celery
+from celery import Task as CeleryTask
from celery.signals import setup_logging
+from celery.worker.request import Request
+
+from overbae.core import telemetry
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "overbae.settings")
-app = Celery("overbae")
+
+class TaskRequest(Request):
+ def on_timeout(self, soft, timeout):
+ super().on_timeout(soft, timeout)
+ if not soft:
+ # The parent kills the child process, so the task itself never sees this.
+ telemetry.report_failure(
+ "Celery task exceeded its hard time limit",
+ task=self.name,
+ task_id=self.id,
+ time_limit_s=timeout,
+ queue=(self.delivery_info or {}).get("routing_key"),
+ )
+
+
+class Task(CeleryTask):
+ Request = TaskRequest
+
+ def __call__(self, *args, **kwargs):
+ # New Relic opens the task's transaction around this call.
+ with telemetry.scope():
+ telemetry.annotate(
+ task=self.name,
+ queue=(self.request.delivery_info or {}).get("routing_key"),
+ retries=self.request.retries,
+ **{
+ name: value
+ for name, value in kwargs.items()
+ if name.endswith("_id") and isinstance(value, str | int)
+ },
+ )
+ return super().__call__(*args, **kwargs)
+
+
+app = Celery("overbae", task_cls=Task)
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks(["overbae.tasks"])
diff --git a/overbae/core/telemetry.py b/overbae/core/telemetry.py
new file mode 100644
index 00000000..bd1013f0
--- /dev/null
+++ b/overbae/core/telemetry.py
@@ -0,0 +1,168 @@
+"""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))
diff --git a/overbae/innermind/runs.py b/overbae/innermind/runs.py
index de01341c..6303c92d 100644
--- a/overbae/innermind/runs.py
+++ b/overbae/innermind/runs.py
@@ -15,7 +15,7 @@ from django.db import transaction
from django.db.models import Q
from django.utils import timezone
-from overbae.core import async_loop
+from overbae.core import async_loop, telemetry
from overbae.innermind import classes, comparison, dataset, generation
from overbae.innermind.metrics import FAIL_BELOW
from overbae.models import EvalMatrix, EvalRun, EvalRunRow, EvalSet, FinetuningJob
@@ -316,6 +316,13 @@ def row_scores(run: EvalRun) -> dict[int, float | None]:
}
+def _reaped(run_id, reason: str, **kwargs) -> bool:
+ failed = fail(run_id, reason, **kwargs)
+ if failed:
+ telemetry.report_failure("Evaluation run reaped", eval_run_id=run_id, reason=reason)
+ return failed
+
+
def reap_stalled() -> int:
now = timezone.now()
reaped = 0
@@ -333,7 +340,7 @@ def reap_stalled() -> int:
# A scorer that beat again since the read keeps its run.
still = silent & Q(scoring_task_id=token)
if started is not None and attempts >= SCORING_ATTEMPTS:
- reaped += fail(run_id, f"scoring stopped {attempts} times", where=still)
+ reaped += _reaped(run_id, f"scoring stopped {attempts} times", where=still)
continue
# The dispatcher hands the run to a new scorer; the old token can no longer save.
running.filter(still, pk=run_id).update(
@@ -344,7 +351,7 @@ def reap_stalled() -> int:
):
if generation.wait_is_healthy(run_id):
continue
- reaped += fail(
+ reaped += _reaped(
run_id, f"evaluation stalled for over {int(STALL.total_seconds() // 60)} minutes"
)
# tasks.innermind imports this module.
@@ -355,7 +362,7 @@ def reap_stalled() -> int:
).values_list("pk", "updated_at"):
if updated < now - PENDING_LIMIT:
never_started = Q(status=EvalRun.Status.PENDING, updated_at__lt=now - PENDING_LIMIT)
- reaped += fail(run_id, "The run never started. Re-launch it.", where=never_started)
+ reaped += _reaped(run_id, "The run never started. Re-launch it.", where=never_started)
continue
# start() claims the run once, so a duplicate start does nothing.
result = run_eval_run.delay(eval_run_id=str(run_id))
diff --git a/overbae/services/assistant/turn.py b/overbae/services/assistant/turn.py
index 6b293015..879790c9 100644
--- a/overbae/services/assistant/turn.py
+++ b/overbae/services/assistant/turn.py
@@ -19,6 +19,7 @@ from django.contrib.auth import get_user_model
from django.db import transaction
from django.utils import timezone
+from overbae.core import telemetry
from overbae.core.llms import IncompleteCompletionError, call_llm_tools, stream_llm_tools
from overbae.core.model_registry import TaskType, model_chain
from overbae.models import (
@@ -129,6 +130,7 @@ def resume_lost() -> int:
state=State.RUNNING, updated_at__lt=timezone.now() - LEASE
).values_list("pk", flat=True)
for thread_id in lost:
+ telemetry.report_failure("Assistant turn lost its worker", thread_id=thread_id)
run_turn.delay(str(thread_id))
return len(lost)
diff --git a/overbae/services/mcp/auth.py b/overbae/services/mcp/auth.py
index 46baaf6c..e36d9b9b 100644
--- a/overbae/services/mcp/auth.py
+++ b/overbae/services/mcp/auth.py
@@ -13,6 +13,7 @@ from starlette.responses import JSONResponse
from starlette.types import Receive, Scope, Send
from overbae.api.authentication import APITokenBackend
+from overbae.core import telemetry
from overbae.models import APIToken, Project
from overbae.services.mcp.context import MCPContext, bind_context
from overbae.services.mcp.errors import MCPError, error_payload
@@ -156,5 +157,10 @@ class MCPAuthMiddleware:
)
await response(scope, receive, send)
return
- with bind_context(context):
+ with telemetry.scope(), bind_context(context):
+ telemetry.annotate(
+ user_id=context.user.pk,
+ project_id=context.project.pk if context.project else None,
+ auth_kind=type(context.token).__name__,
+ )
await self.app(scope, receive, send)
diff --git a/overbae/services/mcp/catalog.py b/overbae/services/mcp/catalog.py
index 23680f13..56439837 100644
--- a/overbae/services/mcp/catalog.py
+++ b/overbae/services/mcp/catalog.py
@@ -13,6 +13,7 @@ from asgiref.sync import sync_to_async
from mcp import types
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
+from overbae.core import telemetry
from overbae.services.activity import mcp_succeeded
from overbae.services.feedback import agent_reports_allowed
from overbae.services.mcp import mutations
@@ -247,6 +248,7 @@ class ToolCatalog:
context = await sync_to_async(project_context, thread_sensitive=True)(
context, arguments.pop("project_id", None)
)
+ telemetry.annotate(project_id=context.project.pk, mcp_tool=name)
request_key = (
arguments.pop("request_key", None) if entry.definition.receipt_supported else None
)
diff --git a/overbae/settings.py b/overbae/settings.py
index 2c0f808f..fb32a75b 100644
--- a/overbae/settings.py
+++ b/overbae/settings.py
@@ -72,6 +72,7 @@ MIDDLEWARE = [
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
+ "overbae.core.telemetry.RequestTelemetry",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
@@ -686,6 +687,7 @@ LOGGING = {
},
},
"filters": {
+ "telemetry": {"()": "overbae.core.telemetry.LogContext"},
"skip_health": {
"()": "django.utils.log.CallbackFilter",
"callback": lambda record: "GET /health" not in record.getMessage(),
@@ -695,6 +697,11 @@ LOGGING = {
"console": {
"class": "logging.StreamHandler",
"formatter": "verbose" if DEBUG else "json",
+ "filters": ["telemetry"],
+ },
+ "newrelic_errors": {
+ "class": "overbae.core.telemetry.NewRelicErrors",
+ "level": "ERROR",
},
},
"root": {
@@ -719,7 +726,7 @@ LOGGING = {
"propagate": False,
},
"overbae": {
- "handlers": ["console"],
+ "handlers": ["console", "newrelic_errors"],
"level": os.environ.get("OVERBAE_LOG_LEVEL", "INFO"),
"propagate": False,
},
diff --git a/overbae/tasks/datasets.py b/overbae/tasks/datasets.py
index f23d13a9..9f1d59a4 100644
--- a/overbae/tasks/datasets.py
+++ b/overbae/tasks/datasets.py
@@ -9,6 +9,8 @@ from celery import Task, shared_task
from django.db import transaction
from django.utils import timezone
+from overbae.core import telemetry
+
logger = logging.getLogger(__name__)
LAND_SOFT_LIMIT = 55 * 60
@@ -464,15 +466,24 @@ def reap_stuck_runs() -> dict[str, Any]:
.filter(import_run__isnull=True, split_imports__isnull=True)
)
with transaction.atomic():
- found = list(
- stuck.select_for_update(skip_locked=True, of=("self",)).values_list("id", flat=True)
+ rows = list(
+ stuck.select_for_update(skip_locked=True, of=("self",)).values_list(
+ "id", "project_id"
+ )
)
+ found = [dataset_id for dataset_id, _ in rows]
Dataset.objects.filter(pk__in=found, state=state).update(
state=Dataset.State.ERROR,
error="The worker stopped before this finished.",
updated_at=now,
)
ids += found
+ for dataset_id, project_id in rows:
+ telemetry.report_failure(
+ "Dataset landing reaped after its worker stopped",
+ dataset_id=dataset_id,
+ project_id=project_id,
+ )
for dataset_id in ids:
_emit(
dataset_id, {"type": "run_failed", "error": "The worker stopped before this finished."}
diff --git a/tests/coverage_map.py b/tests/coverage_map.py
index 0ac9b854..923f1a7d 100644
--- a/tests/coverage_map.py
+++ b/tests/coverage_map.py
@@ -263,6 +263,13 @@ COVERAGE_MAP: dict[str, Entry] = {
"API responses are gzip-compressed for a client that accepts it, and an event "
"stream is never compressed, so each event reaches the page when it is sent.",
),
+ "operator-telemetry": Entry(
+ S3,
+ CONTRACT,
+ "New Relic receives each request's and task's IDs and release, every caught failure "
+ "and error log as an error grouped by its message, failures from outside a "
+ "transaction, and no health-check transactions.",
+ ),
"workspaces": Entry(
S3,
CONTRACT,
diff --git a/tests/fakes/newrelic.py b/tests/fakes/newrelic.py
new file mode 100644
index 00000000..25578750
--- /dev/null
+++ b/tests/fakes/newrelic.py
@@ -0,0 +1,117 @@
+"""A local HTTPS New Relic collector: it answers the agent's handshake and keeps what it sends."""
+
+from __future__ import annotations
+
+import datetime
+import gzip
+import json
+import ssl
+import threading
+import zlib
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from urllib.parse import parse_qs, urlparse
+
+from cryptography import x509
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import ec
+from cryptography.x509.oid import NameOID
+
+
+def _certificate(directory: Path) -> tuple[Path, Path]:
+ key = ec.generate_private_key(ec.SECP256R1())
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")])
+ now = datetime.datetime.now(datetime.UTC)
+ cert = (
+ x509.CertificateBuilder()
+ .subject_name(name)
+ .issuer_name(name)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - datetime.timedelta(minutes=1))
+ .not_valid_after(now + datetime.timedelta(hours=1))
+ .add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost")]), critical=False)
+ .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
+ .sign(key, hashes.SHA256())
+ )
+ cert_path, key_path = directory / "collector.pem", directory / "collector.key"
+ cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
+ key_path.write_bytes(
+ key.private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ )
+ )
+ return cert_path, key_path
+
+
+def _decode(body: bytes, encoding: str | None):
+ if encoding == "gzip":
+ body = gzip.decompress(body)
+ elif encoding == "deflate":
+ body = zlib.decompress(body)
+ return json.loads(body) if body else None
+
+
+class FakeCollector:
+ def __init__(self, directory: Path):
+ self.ca_bundle, key = _certificate(directory)
+ self.received: dict[str, list] = {}
+ collector = self
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_POST(self): # noqa: N802
+ method = parse_qs(urlparse(self.path).query).get("method", [""])[0]
+ body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
+ collector.received.setdefault(method, []).append(
+ _decode(body, self.headers.get("Content-Encoding"))
+ )
+ answers = {
+ "preconnect": {"redirect_host": "localhost"},
+ "connect": {"agent_run_id": "fake-run", "messages": []},
+ }
+ payload = json.dumps({"return_value": answers.get(method)}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, *_):
+ pass
+
+ self.server = ThreadingHTTPServer(("localhost", 0), Handler)
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.minimum_version = ssl.TLSVersion.TLSv1_2
+ context.load_cert_chain(self.ca_bundle, key)
+ self.server.socket = context.wrap_socket(self.server.socket, server_side=True)
+ self.port = self.server.server_address[1]
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+
+ def agent_environment(self) -> dict[str, str]:
+ return {
+ "NEW_RELIC_LICENSE_KEY": "0" * 40,
+ "NEW_RELIC_APP_NAME": "Overmind Console (test)",
+ "NEW_RELIC_HOST": "localhost",
+ "NEW_RELIC_PORT": str(self.port),
+ "NEW_RELIC_CA_BUNDLE_PATH": str(self.ca_bundle),
+ }
+
+ def error_events(self) -> list[tuple[dict, dict]]:
+ """(intrinsics, custom attributes) for each error event the agent sent."""
+ return [
+ (event[0], event[1])
+ for payload in self.received.get("error_event_data", [])
+ for event in payload[2]
+ ]
+
+ def transaction_events(self) -> list[tuple[dict, dict]]:
+ return [
+ (event[0], event[1])
+ for payload in self.received.get("analytic_event_data", [])
+ for event in payload[2]
+ ]
+
+ def close(self) -> None:
+ self.server.shutdown()
diff --git a/tests/test_operator_telemetry.py b/tests/test_operator_telemetry.py
new file mode 100644
index 00000000..005666eb
--- /dev/null
+++ b/tests/test_operator_telemetry.py
@@ -0,0 +1,153 @@
+"""What the New Relic agent sends for the platform's own requests, tasks and caught failures.
+
+The agent runs in a child process: initializing it instruments every module it imports.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import textwrap
+
+import pytest
+from fakes.newrelic import FakeCollector
+
+pytestmark = pytest.mark.covers("operator-telemetry")
+
+AGENT_RUN = textwrap.dedent(
+ """
+ import logging
+
+ import newrelic.agent
+
+ newrelic.agent.initialize()
+ application = newrelic.agent.register_application(timeout=20.0)
+
+ from overbae.core import telemetry
+
+ logger = logging.getLogger("overbae.tasks.finetuning")
+ logger.addHandler(telemetry.NewRelicErrors())
+ logger.propagate = False
+
+ with newrelic.agent.BackgroundTask(application, name="reap_stuck_runs"), telemetry.scope():
+ telemetry.annotate(task="overbae.tasks.datasets.reap_stuck_runs", queue="control")
+ telemetry.report_failure(
+ "Dataset landing reaped after its worker stopped",
+ dataset_id="ds-1",
+ project_id="proj-1",
+ )
+
+ with newrelic.agent.BackgroundTask(application, name="poll_provider"), telemetry.scope():
+ telemetry.annotate(job_id="job-7")
+ logger.error("Provider poll failed for job %s", "job-7")
+ try:
+ raise TimeoutError("provider did not answer")
+ except TimeoutError:
+ logger.exception("Fine-tuning submission failed for job %s", "job-7")
+
+ from types import SimpleNamespace
+
+ request = SimpleNamespace(
+ resolver_match=SimpleNamespace(
+ route="api/^projects/(?P<project_id>[^/.]+)/datasets/$",
+ kwargs={"project_id": "proj-9"},
+ ),
+ user=SimpleNamespace(pk=42, is_authenticated=True),
+ GET={},
+ )
+
+ def view(request):
+ # Django runs process_view after resolving the URL, then the view.
+ middleware.process_view(request, None, (), {})
+ logging.getLogger("overbae.api.datasets").error("Dataset view failed for %s", "x")
+ return "response"
+
+ logging.getLogger("overbae.api.datasets").addHandler(telemetry.NewRelicErrors())
+ middleware = telemetry.RequestTelemetry(view)
+ with newrelic.agent.WebTransaction(application, {"REQUEST_METHOD": "GET", "PATH_INFO": "/"}):
+ middleware(request)
+
+ with newrelic.agent.BackgroundTask(application, name="health_check"):
+ telemetry.ignore_transaction()
+
+ # A Celery parent process: no transaction is open when the child is killed.
+ telemetry.report_failure(
+ "Celery task exceeded its hard time limit", task="overbae.tasks.x", time_limit_s=300
+ )
+
+ newrelic.agent.shutdown_agent(timeout=20.0)
+ """
+)
+
+
[email protected](scope="module")
+def sent(tmp_path_factory):
+ collector = FakeCollector(tmp_path_factory.mktemp("newrelic"))
+ environment = {
+ **os.environ,
+ **collector.agent_environment(),
+ "OVERMIND_RELEASE": "sha-test123",
+ "DJANGO_SETTINGS_MODULE": "tests.settings",
+ }
+ run = subprocess.run(
+ [sys.executable, "-c", AGENT_RUN],
+ env=environment,
+ capture_output=True,
+ text=True,
+ timeout=120,
+ check=False,
+ )
+ collector.close()
+ assert run.returncode == 0, run.stderr[-2000:]
+ return collector
+
+
+def _errors(sent, message):
+ return [
+ custom
+ for intrinsics, custom in sent.error_events()
+ if intrinsics["error.message"] == message
+ ]
+
+
+def test_caught_failure_carries_the_task_and_its_ids(sent):
+ (custom,) = _errors(sent, "Dataset landing reaped after its worker stopped")
+ assert custom["dataset_id"] == "ds-1"
+ assert custom["project_id"] == "proj-1"
+ assert custom["task"] == "overbae.tasks.datasets.reap_stuck_runs"
+ assert custom["release"] == "sha-test123"
+
+
+def test_error_logs_group_by_their_unformatted_message(sent):
+ (plain,) = _errors(sent, "Provider poll failed for job %s")
+ assert plain["job_id"] == "job-7"
+ (with_exception,) = _errors(sent, "provider did not answer")
+ assert with_exception["log_message"] == "Fine-tuning submission failed for job %s"
+ assert with_exception["job_id"] == "job-7"
+
+
+def test_an_error_logged_inside_a_view_names_its_route_and_project(sent):
+ (custom,) = _errors(sent, "Dataset view failed for %s")
+ assert custom["route"] == "/api/projects/(?P<project_id>[^/.]+)/datasets/"
+ assert custom["project_id"] == "proj-9"
+ assert custom["release"] == "sha-test123"
+
+
+def test_the_request_names_its_user_once_the_view_has_run(sent):
+ ((_, custom),) = [
+ event for event in sent.transaction_events() if event[1].get("project_id") == "proj-9"
+ ]
+ assert custom["user_id"] == 42
+
+
+def test_a_failure_outside_any_transaction_still_reaches_new_relic(sent):
+ (custom,) = _errors(sent, "Celery task exceeded its hard time limit")
+ assert custom["task"] == "overbae.tasks.x"
+ assert custom["time_limit_s"] == 300
+
+
+def test_health_checks_send_no_transaction(sent):
+ names = {intrinsics["name"] for intrinsics, _ in sent.transaction_events()}
+ assert "OtherTransaction/Function/reap_stuck_runs" in names
+ assert not any(name.endswith("health_check") for name in names)