The platform for continuously improving AI agents.
"""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)
"""
)
@pytest.fixture(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)