fix: stop reporting failed AI provider model tests to Sentry (#6759)

* fix: stop reporting failed AI provider model tests to Sentry

* fix: drop unreachable Google provider errors from model test Sentry reports
This commit is contained in:
Peter Evans authored and GitHub committed 2026-11-23 11:20:59 +00:00
1 parent d7f936c55f
commit d36bbe377e
8 files changed
+306 -11

No files matched your search

@@ -10,9 +10,13 @@ from baserow.core.generative_ai.capabilities import (
ModelToolCallingNotSupportedError,
test_model_text_and_tool_calling,
)
from baserow.core.generative_ai.exceptions import get_user_friendly_error_message
from baserow.core.generative_ai.exceptions import (
get_provider_api_error_types,
get_user_friendly_error_message,
)
from baserow.core.models import Workspace
from baserow.core.psycopg import is_unique_violation_error
from baserow.core.sentry import ignore_sentry_exceptions
from .constants import (
AI_PROVIDER_FEATURE_AI_AGENT,
@@ -1110,14 +1114,18 @@ class AIProviderHandler:
configured_model.model_identifier
for configured_model in provider.models.all()
]
result = cls._test_model(
provider.provider_type,
model.model_identifier,
settings_override,
cls.secret_values(provider.api_key, provider.extra_settings),
model.id,
model.feature_types,
)
# A provider error is a test result shown to the user, not a server
# error, so it isn't reported to Sentry. Other errors captured by the
# Sentry client integrations still are.
with ignore_sentry_exceptions(get_provider_api_error_types):
result = cls._test_model(
provider.provider_type,
model.model_identifier,
settings_override,
cls.secret_values(provider.api_key, provider.extra_settings),
model.id,
model.feature_types,
)
model.last_test_at = result["tested_at"]
model.last_test_status = result["status"]
model.last_test_error = result["error"]
@@ -25,6 +25,28 @@ class GenerativeAIPromptError(Exception):
"""Raised when an error occurs while prompting the model."""
def get_provider_api_error_types() -> tuple[type[Exception], ...]:
"""
The errors raised when a request fails at the provider, for the provider SDKs
whose Sentry integration captures client errors before re-raising them: OpenAI
(also used by the OpenAI-compatible providers), Anthropic and Google. They
cover an unreachable host, a timeout, an invalid key, a rate limit and every
error status the provider answers with, 4xx included, so a request rejected by
the provider is dropped too. That's fine where the error is shown to the user,
like when testing a model.
:return: The base error classes of these SDKs. Google doesn't wrap transport
failures in its own errors, so the `httpx2` transport error is included.
"""
from anthropic import APIError as AnthropicAPIError
from google.genai.errors import APIError as GoogleAPIError
from httpx2 import TransportError as GoogleTransportError
from openai import APIError as OpenAIAPIError
return (OpenAIAPIError, AnthropicAPIError, GoogleAPIError, GoogleTransportError)
def get_user_friendly_error_message(exc: Exception) -> str:
"""
Extract a concise, user-facing message from a provider SDK exception.
+41 -1
View File
@@ -1,6 +1,7 @@
import logging
import re
from typing import Any
from contextlib import contextmanager
from typing import Any, Callable, Iterator
from urllib.parse import urlparse
from django.conf import settings
@@ -152,3 +153,42 @@ def patch_user_model_str():
User = get_user_model()
User.__str__ = lambda self: str(self.id)
@contextmanager
def ignore_sentry_exceptions(
exception_types: tuple[type[BaseException], ...]
| Callable[[], tuple[type[BaseException], ...]],
) -> Iterator[None]:
"""
Drops the Sentry events of the given exception types that are captured inside
the block. Other exceptions, messages and transactions are still sent. Use it
around code that reports these errors back to the user, like a connection test
of an AI provider, because the AI client integrations of Sentry capture every
client error before the calling code can handle it.
:param exception_types: The exceptions, including their subclasses, to drop.
Can be a function returning them, which is only called when Sentry is
enabled, so the modules they come from aren't imported otherwise.
"""
if not settings.SENTRY_DSN:
yield
return
if callable(exception_types):
exception_types = exception_types()
import sentry_sdk
def drop_ignored_exceptions(
event: dict[str, Any], hint: dict[str, Any]
) -> dict[str, Any] | None:
exc_info = hint.get("exc_info")
if exc_info and isinstance(exc_info[1], exception_types):
return None
return event
with sentry_sdk.new_scope() as scope:
scope.add_event_processor(drop_ignored_exceptions)
yield
@@ -141,6 +141,20 @@ class StreamingAPIClient(APIClient):
return response
@pytest.fixture
def sentry_events(settings):
"""
Enables Sentry and collects the events it would send, see
`collect_sentry_events`.
"""
from baserow.test_utils.sentry import TEST_SENTRY_DSN, collect_sentry_events
settings.SENTRY_DSN = TEST_SENTRY_DSN
with collect_sentry_events() as events:
yield events
@pytest.fixture()
def api_client():
return StreamingAPIClient()
+47
View File
@@ -0,0 +1,47 @@
from contextlib import contextmanager
from typing import Any, Iterator, Sequence
import sentry_sdk
from sentry_sdk.integrations import Integration
from sentry_sdk.transport import Transport
TEST_SENTRY_DSN = "https://public@example.invalid/1"
class CollectingSentryTransport(Transport):
"""Keeps the events Sentry would send instead of sending them."""
def __init__(self, options=None):
super().__init__(options)
self.events: list[dict[str, Any]] = []
def capture_envelope(self, envelope):
self.events.extend(
item.payload.json for item in envelope.items if item.type == "event"
)
@contextmanager
def collect_sentry_events(
integrations: Sequence[Integration] = (),
) -> Iterator[list[dict[str, Any]]]:
"""
Sends the Sentry events captured inside the block to the returned list instead
of to Sentry. Set `settings.SENTRY_DSN` too for code that checks it.
:param integrations: The Sentry integrations to enable, none by default.
"""
transport = CollectingSentryTransport()
client = sentry_sdk.Client(
dsn=TEST_SENTRY_DSN,
transport=transport,
default_integrations=False,
integrations=list(integrations),
)
try:
with sentry_sdk.isolation_scope() as scope:
scope.set_client(client)
yield transport.events
finally:
client.close()
@@ -3,7 +3,12 @@ from unittest.mock import patch
from django.db import DEFAULT_DB_ALIAS
from django.shortcuts import reverse
import httpx
import httpx2
import openai
import pytest
import sentry_sdk
from google.genai import errors as google_errors
from rest_framework.status import (
HTTP_200_OK,
HTTP_201_CREATED,
@@ -1398,6 +1403,76 @@ def test_saved_models_are_tested_in_one_request_and_results_are_persisted(
]
def _openai_connection_error():
return openai.APIConnectionError(
request=httpx.Request("POST", "https://does-not-exist.invalid/v1/responses")
)
def _google_server_error():
return google_errors.ServerError(
504, {"error": {"message": "Deadline expired before operation could complete."}}
)
def _google_connect_error():
# google-genai doesn't wrap transport failures in its own errors.
return httpx2.ConnectError("[Errno 8] nodename nor servname provided")
def _google_read_timeout():
return httpx2.ReadTimeout("The read operation timed out")
@pytest.mark.django_db
@pytest.mark.parametrize(
"make_error,reported",
[
(_openai_connection_error, False),
(_google_server_error, False),
(_google_connect_error, False),
(_google_read_timeout, False),
# An error that doesn't come from the provider is still reported.
(lambda: TypeError("unexpected keyword argument 'timeout'"), True),
],
)
def test_failing_model_test_reports_only_non_provider_errors_to_sentry(
api_client, staff_headers, sentry_events, make_error, reported
):
provider = AIProviderConfig.objects.create(provider_type="mistral", api_key="key")
model = AIProviderModel.objects.create(
provider_config=provider,
model_identifier="mistral-large",
feature_types=[AI_PROVIDER_FEATURE_AI_FIELDS],
)
error = make_error()
def prompt_failing_provider(*args, **kwargs):
# Like the Sentry AI client integrations, which capture the client error
# before re-raising it to the caller.
sentry_sdk.capture_exception(error)
raise error
with patch(
"baserow.core.generative_ai.generative_ai_model_types."
"MistralGenerativeAIModelType.prompt",
side_effect=prompt_failing_provider,
):
response = api_client.post(
reverse("api:ai_provider:test_models"),
{"model_ids": [model.id]},
format="json",
**staff_headers,
)
assert response.status_code == HTTP_200_OK
[result] = response.json()["results"]
assert result["status"] == "failure"
assert [event["exception"]["values"][-1]["type"] for event in sentry_events] == (
[type(error).__name__] if reported else []
)
@pytest.mark.django_db
def test_testing_models_pins_provider_reads_to_primary(api_client, staff_headers):
with (
+81 -1
View File
@@ -6,14 +6,18 @@ import sys
from unittest.mock import patch
import pytest
import sentry_sdk
from asgiref.sync import async_to_sync
from sentry_sdk.envelope import Envelope
from baserow.core.sentry import (
before_send,
drop_expected_asyncio_disconnect_events,
ignore_sentry_exceptions,
log_sentry_event_to_console,
)
from baserow.core.sentry_transport import ConsoleSentryTransport
from baserow.test_utils.sentry import TEST_SENTRY_DSN, collect_sentry_events
def test_sentry_sdk_is_not_loaded_when_sentry_is_disabled():
@@ -25,9 +29,14 @@ from django.conf import settings
settings.configure(SENTRY_DSN="")
from baserow.core.sentry import setup_user_in_sentry
from baserow.core.sentry import ignore_sentry_exceptions, setup_user_in_sentry
def get_exception_types():
raise AssertionError("Only called when Sentry is enabled.")
setup_user_in_sentry(SimpleNamespace(id=1))
with ignore_sentry_exceptions(get_exception_types):
pass
assert not any(
module == "sentry_sdk" or module.startswith("sentry_sdk.")
for module in sys.modules
@@ -244,3 +253,74 @@ def test_sentry_hooks_redact_private_link_tokens():
"Referer": "http://localhost:3000/template/slug/private-link/[Filtered]",
"X-Link": "next=%2Flogin%3Foriginal%3D%252Fprivate-link%252F[Filtered]",
}
class _ProviderError(Exception):
pass
class _ProviderConnectionError(_ProviderError):
pass
def _sent(events):
return [
event.get("message") or event["exception"]["values"][-1]["value"]
for event in events
]
def test_ignore_sentry_exceptions_drops_only_the_given_types_inside_the_block(
sentry_events,
):
with ignore_sentry_exceptions((_ProviderError,)):
sentry_sdk.capture_exception(_ProviderConnectionError("dropped subclass"))
sentry_sdk.capture_exception(ValueError("kept other type"))
sentry_sdk.capture_message("kept message")
sentry_sdk.capture_exception(_ProviderError("kept outside"))
assert _sent(sentry_events) == ["kept other type", "kept message", "kept outside"]
def test_ignore_sentry_exceptions_drops_logged_exceptions_of_the_given_types(
settings,
):
from sentry_sdk.integrations.logging import LoggingIntegration
settings.SENTRY_DSN = TEST_SENTRY_DSN
log = logging.getLogger("baserow.test_ignore_sentry_exceptions")
with collect_sentry_events(
[LoggingIntegration(event_level=logging.ERROR)]
) as events:
with ignore_sentry_exceptions((_ProviderError,)):
for error in (_ProviderError("dropped"), ValueError("kept")):
try:
raise error
except Exception:
log.exception("Probe failed")
assert _sent(events) == ["kept"]
def test_ignore_sentry_exceptions_reaches_async_to_sync_probes(sentry_events):
async def probe():
# The AI provider probes run their client calls through async_to_sync,
# in another thread.
sentry_sdk.capture_exception(_ProviderError("dropped"))
sentry_sdk.capture_exception(ValueError("kept"))
with ignore_sentry_exceptions((_ProviderError,)):
async_to_sync(probe)()
assert _sent(sentry_events) == ["kept"]
def test_ignore_sentry_exceptions_resolves_lazy_types_only_with_sentry(
sentry_events,
):
with ignore_sentry_exceptions(lambda: (_ProviderError,)):
sentry_sdk.capture_exception(_ProviderError("dropped"))
sentry_sdk.capture_exception(ValueError("kept"))
assert _sent(sentry_events) == ["kept"]
@@ -0,0 +1,9 @@
{
"type": "bug",
"message": "Stop reporting failed AI provider model tests as server errors",
"issue_origin": "github",
"issue_number": null,
"domain": "core",
"bullet_points": [],
"created_at": "2026-11-18"
}