:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(logs): stop reporting an exception for filter-less attribute lookups (#122807)
Vasco de Krijger2e6bb0ac4d51
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex da4b26478de6..146a2ddaa3a2 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -1510,6 +1510,19 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):return filter_groupreturn {"type": "AND", "values": []}+ @staticmethod+ def _filter_group_from_query_params(request: Request) -> PropertyGroupFilter | None:+ try:+ filter_group = json.loads(request.GET.get("filterGroup") or "null")+ except ValueError:+ return None+ if not isinstance(filter_group, dict | list) or not filter_group:+ return None+ try:+ return PropertyGroupFilter.model_validate(LogsViewSet._normalize_filter_group(filter_group))+ except ValidationError:+ return None+@staticmethoddef _require_dict_query(query_data: object) -> None:"""Guard against a non-object `query` field crashing on the first `.get()` call below."""@@ -2096,10 +2109,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):serviceNames = json.loads(request.GET.get("serviceNames", "[]"))except json.JSONDecodeError:serviceNames = []- try:- filterGroup = self.get_model(json.loads(request.GET.get("filterGroup", "{}")), PropertyGroupFilter)- except (json.JSONDecodeError, ValidationError, ValueError, ParseError):- filterGroup = None+ filterGroup = self._filter_group_from_query_params(request)attributeType = request.GET.get("attribute_type", "log")# I don't know why went with 'log' and 'resource' not 'log_attribute' and 'log_resource_attribute'@@ -2180,10 +2190,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):serviceNames = json.loads(request.GET.get("serviceNames", "[]"))except json.JSONDecodeError:serviceNames = []- try:- filterGroup = self.get_model(json.loads(request.GET.get("filterGroup", "{}")), PropertyGroupFilter)- except (json.JSONDecodeError, ValidationError, ValueError, ParseError):- filterGroup = None+ filterGroup = self._filter_group_from_query_params(request)attributeType = request.GET.get("attribute_type", "log")# I don't know why went with 'log' and 'resource' not 'log_attribute' and 'log_resource_attribute'diff --git a/products/logs/backend/test/test_log_values_attributes.py b/products/logs/backend/test/test_log_values_attributes.pyindex 5e8cfc177f27..41b7f16283c8 100644--- a/products/logs/backend/test/test_log_values_attributes.py+++ b/products/logs/backend/test/test_log_values_attributes.py@@ -1,5 +1,6 @@import osimport json+from types import SimpleNamespacefrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import patch@@ -371,6 +372,61 @@ class TestLogValuesAttributesQueryErrors(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["error"], str(error))+ @parameterized.expand(+ [+ ("values", "LogValuesQueryRunner", {"key": "service.name", "attribute_type": "resource"}),+ ("attributes", "LogAttributesQueryRunner", {"attribute_type": "resource"}),+ ]+ )+ def test_filter_group_param_is_optional_and_accepts_a_flat_list(self, endpoint, runner_name, params):+ flat_filter_group = [{"type": "log", "key": "severity_level", "value": ["error"], "operator": "exact"}]+ with (+ patch(f"products.logs.backend.presentation.views.api.{runner_name}") as runner_class,+ patch("posthog.api.mixins.capture_exception") as capture_exception,+ ):+ runner_class.return_value.calculate.return_value = SimpleNamespace(results=[], count=0)++ response = self.client.get(f"/api/projects/{self.team.pk}/logs/{endpoint}", params)+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertIsNone(runner_class.call_args.kwargs["query"].filterGroup)++ response = self.client.get(+ f"/api/projects/{self.team.pk}/logs/{endpoint}",+ {**params, "filterGroup": json.dumps(flat_filter_group)},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ filter_group = runner_class.call_args.kwargs["query"].filterGroup+ self.assertEqual(filter_group.values[0].values[0].key, "severity_level")++ capture_exception.assert_not_called()++ @parameterized.expand(+ [+ ("empty_string", ""),+ ("empty_object", "{}"),+ ("empty_list", "[]"),+ ("not_json", "not json"),+ ("scalar", "5"),+ ("group_without_values", json.dumps({"type": "AND"})),+ ("integer_past_the_digit_limit", "[" + "1" * 5000 + "]"),+ ]+ )+ def test_malformed_filter_group_param_means_no_filter(self, _name, filter_group):+ with (+ patch("products.logs.backend.presentation.views.api.LogAttributesQueryRunner") as runner_class,+ patch("posthog.api.mixins.capture_exception") as capture_exception,+ ):+ runner_class.return_value.calculate.return_value = SimpleNamespace(results=[], count=0)++ response = self.client.get(+ f"/api/projects/{self.team.pk}/logs/attributes",+ {"attribute_type": "resource", "filterGroup": filter_group},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertIsNone(runner_class.call_args.kwargs["query"].filterGroup)+ capture_exception.assert_not_called()+class TestLogAttributesIlikeEscaping(ClickhouseTestMixin, APIBaseTest):CLASS_DATA_LEVEL_SETUP = True