: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(tracing): status_code/kind span filters silently matched all rows (#63261)
Jon McCallumbae93cfac0a1
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex d07c8595eae5..03a6232b9599 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -9,7 +9,7 @@ import jsonimport base64import decimalimport datetime as dt-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, castfrom zoneinfo import ZoneInfofrom posthog.schema import (@@ -92,6 +92,41 @@ _STATUS_CODE_LABEL_TO_INTS: dict[str, list[int]] = {}+def _normalise_kind_values(values: list) -> list[str]:+ # span.kind → string-digit codes. Accept labels ("Server"), digit strings ("2"), ints, and+ # integer-valued floats (the API value union coerces JSON numbers to float). Unrecognised+ # values are dropped — never left in a form that silently matches every row. Mirrors+ # _normalise_status_code_values so both int columns are compared as digit strings.+ normalised: list[str] = []+ for v in values:+ if isinstance(v, bool):+ continue+ if isinstance(v, (int, float)):+ normalised.append(str(int(v)))+ elif isinstance(v, str) and v.isdigit():+ normalised.append(v)+ elif str(v) in _SPAN_KIND_LABEL_TO_INT:+ normalised.append(str(_SPAN_KIND_LABEL_TO_INT[str(v)]))+ return normalised+++def _normalise_status_code_values(values: list) -> list[str]:+ # span.status_code → string-digit codes. Accept labels ("OK"/"Error"), digit strings, ints,+ # and integer-valued floats; 'OK' expands to {0, 1}. Unrecognised values are dropped — never+ # left in a form that silently matches every row.+ normalised: list[str] = []+ for v in values:+ if isinstance(v, bool):+ continue+ if isinstance(v, (int, float)):+ normalised.append(str(int(v)))+ elif isinstance(v, str) and v.isdigit():+ normalised.append(v)+ elif str(v) in _STATUS_CODE_LABEL_TO_INTS:+ normalised.extend(str(code) for code in _STATUS_CODE_LABEL_TO_INTS[str(v)])+ return normalised++def translate_span_filter(span_filter: SpanPropertyFilter) -> None:"""Translate UI/API filter values into ClickHouse column representations, in place.@@ -103,9 +138,8 @@ def translate_span_filter(span_filter: SpanPropertyFilter) -> None:Idempotent — safe to call repeatedly on the same filter. Compare-mode invokes`_where_without_date_range()` once per window on the same `SpanPropertyFilter`- instances; without the post-translation guards on `kind`/`status_code` the second- pass would map the already-translated integers back to `[]` and silently drop the- filter for the compare window.+ instances, so `kind`/`status_code` normalisation must accept its own already-translated+ output (ints / digit strings) and not collapse it to `[]` on the second pass."""if span_filter.key in ("trace_id", "span_id"):# `_normalise_to_base64` is a no-op on already-base64 values (16/8-byte ids@@ -128,17 +162,12 @@ def translate_span_filter(span_filter: SpanPropertyFilter) -> None:if span_filter.key == "kind" and span_filter.value is not None:values: list = span_filter.value if isinstance(span_filter.value, list) else [span_filter.value]- if not all(isinstance(v, int) for v in values):- span_filter.value = [_SPAN_KIND_LABEL_TO_INT[str(v)] for v in values if str(v) in _SPAN_KIND_LABEL_TO_INT]+ # cast bridges list invariance: helper returns list[str], value's slot is the wider union.+ span_filter.value = cast("list[str | int | float]", _normalise_kind_values(values))if span_filter.key == "status_code" and span_filter.value is not None:values = span_filter.value if isinstance(span_filter.value, list) else [span_filter.value]- if not all(isinstance(v, str) and v.isdigit() for v in values):- expanded: list[int] = []- for v in values:- if str(v) in _STATUS_CODE_LABEL_TO_INTS:- expanded.extend(_STATUS_CODE_LABEL_TO_INTS[str(v)])- span_filter.value = [str(v) for v in expanded]+ span_filter.value = cast("list[str | int | float]", _normalise_status_code_values(values))class TraceSpansQueryRunnerMixin(QueryRunner):diff --git a/products/tracing/backend/tests/test_count_query_runner.py b/products/tracing/backend/tests/test_count_query_runner.pyindex 15dfef246b2e..19016c030c20 100644--- a/products/tracing/backend/tests/test_count_query_runner.py+++ b/products/tracing/backend/tests/test_count_query_runner.py@@ -102,3 +102,25 @@ class TestTraceSpansCount(ClickhouseTestMixin, APIBaseTest):self.assertEqual(res.status_code, 200, res.content)# One root span named process_query_model per trace.self.assertEqual(res.json(), {"count": NUM_TRACES})++ @parameterized.expand(+ [+ # Seed: every span is status_code=0 (Unset), kind=2 (Server). A status_code/kind+ # filter must RESTRICT the count, never silently match every row.+ ("status_code_int_2_matches_no_errors", "status_code", 2, 0),+ ("status_code_str_2_matches_no_errors", "status_code", "2", 0),+ ("status_code_int_0_matches_all_unset", "status_code", 0, NUM_TRACES * 3),+ ("kind_str_3_matches_no_clients", "kind", "3", 0),+ ("kind_int_2_matches_all_servers", "kind", 2, NUM_TRACES * 3),+ ]+ )+ def test_count_status_code_and_kind_filters_restrict(self, _name, key, value, expected_count):+ body = {+ "query": {+ "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO},+ "filterGroup": [{"key": key, "type": "span", "operator": "exact", "value": value}],+ }+ }+ res = self.client.post(f"/api/projects/{self.team.id}/tracing/spans/count/", body, format="json")+ self.assertEqual(res.status_code, 200, res.content)+ self.assertEqual(res.json(), {"count": expected_count})diff --git a/products/tracing/backend/tests/test_logic.py b/products/tracing/backend/tests/test_logic.pyindex e69de29bb2d1..1e45585cce72 100644--- a/products/tracing/backend/tests/test_logic.py+++ b/products/tracing/backend/tests/test_logic.py@@ -0,0 +1,53 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.schema import PropertyOperator, SpanPropertyFilter, SpanPropertyFilterType++from products.tracing.backend.logic import translate_span_filter+++def _span_filter(key: str, value: object) -> SpanPropertyFilter:+ return SpanPropertyFilter(+ key=key,+ operator=PropertyOperator.EXACT,+ type=SpanPropertyFilterType.SPAN,+ value=value,+ )+++class TestTranslateSpanFilter(SimpleTestCase):+ @parameterized.expand(+ [+ # status_code normalises to string-digit codes. Integers and digit strings+ # must survive — an integer must NOT collapse to [] (which filters nothing).+ ("status_code_int", "status_code", 2, ["2"]),+ ("status_code_int_zero", "status_code", 0, ["0"]),+ ("status_code_digit_string", "status_code", "2", ["2"]),+ ("status_code_error_label", "status_code", "Error", ["2"]),+ ("status_code_ok_label", "status_code", "OK", ["0", "1"]),+ ("status_code_list_ints", "status_code", [0, 2], ["0", "2"]),+ # kind normalises to string-digit codes (same form as status_code). Digit strings+ # and ints must survive — they must NOT collapse to [].+ ("kind_int", "kind", 2, ["2"]),+ ("kind_digit_string", "kind", "3", ["3"]),+ ("kind_server_label", "kind", "Server", ["2"]),+ ("kind_list_digit_strings", "kind", ["2", "3"], ["2", "3"]),+ ]+ )+ def test_normalises_status_code_and_kind_values(self, _name, key, value, expected):+ span_filter = _span_filter(key, value)+ translate_span_filter(span_filter)+ self.assertEqual(span_filter.value, expected)++ @parameterized.expand(+ [+ ("status_code", "status_code", 2, ["2"]),+ ("kind", "kind", "3", ["3"]),+ ]+ )+ def test_translation_is_idempotent(self, _name, key, value, expected):+ span_filter = _span_filter(key, value)+ translate_span_filter(span_filter)+ translate_span_filter(span_filter)+ self.assertEqual(span_filter.value, expected)