: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
feat(tracing): match attribute values when searching span attributes (#64044)
Frank Hamandf5fa04dcad67
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsxindex 0ef955665ed3..67c5f313bde7 100644--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx@@ -1041,6 +1041,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([type: TaxonomicFilterGroupType.SpanAttributes,endpoint: combineUrl(`api/environments/${projectId}/tracing/spans/attributes`, {attribute_type: 'span_attribute',+ search_values: 'true',...endpointFilters,}).url,valuesEndpoint: (key) =>@@ -1059,6 +1060,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([type: TaxonomicFilterGroupType.SpanResourceAttributes,endpoint: combineUrl(`api/environments/${projectId}/tracing/spans/attributes`, {attribute_type: 'span_resource_attribute',+ search_values: 'true',...endpointFilters,}).url,valuesEndpoint: (key) =>diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsxindex 29c28c8aaa4f..691c2d7a3e5c 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx@@ -597,6 +597,7 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomitype: TaxonomicFilterGroupType.SpanAttributes,endpoint: combineUrl(`api/environments/${projectId}/tracing/spans/attributes`, {attribute_type: 'span_attribute',+ search_values: 'true',...endpointFilters,}).url,valuesEndpoint: (key) =>@@ -615,6 +616,7 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomitype: TaxonomicFilterGroupType.SpanResourceAttributes,endpoint: combineUrl(`api/environments/${projectId}/tracing/spans/attributes`, {attribute_type: 'span_resource_attribute',+ search_values: 'true',...endpointFilters,}).url,valuesEndpoint: (key) =>diff --git a/products/logs/backend/log_attributes_query_runner.py b/products/logs/backend/log_attributes_query_runner.pyindex b064b233cb89..9051daa27142 100644--- a/products/logs/backend/log_attributes_query_runner.py+++ b/products/logs/backend/log_attributes_query_runner.py@@ -13,7 +13,7 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.filters.mixins.utils import cached_property-from products.logs.backend.logs_query_runner import LogsQueryRunnerMixin+from products.logs.backend.logs_query_runner import LogsQueryRunnerMixin, ilike_pattern# Read a max of 5GB from the table at a time - this should get us plenty of results# without having long and expensive attributes queries. Users can always search or add other@@ -77,7 +77,7 @@ class LogAttributesQueryRunner(AnalyticsQueryRunner[LogAttributesQueryResponse],)""",placeholders={- "search": ast.Constant(value=f"%{self.query.search}%"),+ "search": ast.Constant(value=ilike_pattern(self.query.search)),"exact": ast.Constant(value=self.query.search),"attributeType": ast.Constant(value=self.query.attributeType),"limit": ast.Constant(value=self.query.limit),@@ -143,7 +143,7 @@ class LogAttributesQueryRunner(AnalyticsQueryRunner[LogAttributesQueryResponse],OFFSET {offset}""",placeholders={- "search": ast.Constant(value=f"%{self.query.search}%"),+ "search": ast.Constant(value=ilike_pattern(self.query.search)),"exact": ast.Constant(value=self.query.search),"attributeType": ast.Constant(value=self.query.attributeType),"limit": ast.Constant(value=self.query.limit),diff --git a/products/logs/backend/log_values_query_runner.py b/products/logs/backend/log_values_query_runner.pyindex a8fdc81b1eed..8503498cd94f 100644--- a/products/logs/backend/log_values_query_runner.py+++ b/products/logs/backend/log_values_query_runner.py@@ -13,7 +13,7 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.filters.mixins.utils import cached_property-from products.logs.backend.logs_query_runner import LogsQueryRunnerMixin+from products.logs.backend.logs_query_runner import LogsQueryRunnerMixin, ilike_pattern# Read a max of 5GB from the table at a time - this should get us plenty of results# without having long and expensive attributes queries. Users can always search or add other@@ -63,7 +63,7 @@ class LogValuesQueryRunner(AnalyticsQueryRunner[LogValuesQueryResponse], LogsQue)""",placeholders={- "search": ast.Constant(value=f"%{self.query.search}%"),+ "search": ast.Constant(value=ilike_pattern(self.query.search)),"exact": ast.Constant(value=self.query.search),"attributeType": ast.Constant(value=self.query.attributeType),"attributeKey": ast.Constant(value=self.query.attributeKey),diff --git a/products/logs/backend/logs_query_runner.py b/products/logs/backend/logs_query_runner.pyindex 5fb497a87fcc..6f8ece4c53d5 100644--- a/products/logs/backend/logs_query_runner.py+++ b/products/logs/backend/logs_query_runner.py@@ -42,6 +42,12 @@ LIVE_LOGS_CHECKPOINT_QUERY = parse_select()+def ilike_pattern(search: str | None) -> str:+ # Escape ILIKE wildcards so a search for "%" matches a literal percent sign, not every row.+ escaped = (search or "").replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+ return f"%{escaped}%"++def _trace_id_normalise_to_base64(value: str) -> str:"""Accept either hex or base64 encoded trace_id/span_id values.diff --git a/products/logs/backend/test/test_log_values_attributes.py b/products/logs/backend/test/test_log_values_attributes.pyindex 76eb84fe63bd..60de971eb24d 100644--- a/products/logs/backend/test/test_log_values_attributes.py+++ b/products/logs/backend/test/test_log_values_attributes.py@@ -275,3 +275,61 @@ class TestLogValuesAttributesTimezones(ClickhouseTestMixin, APIBaseTest):trace_id_index, brokers_id_index, "trace_id should appear before brokers.0.id when searching for 'id'")self.assertLess(brokers_id_index, pid_index, "brokers.0.id should appear before pid when searching for 'id'")+++class TestLogAttributesIlikeEscaping(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ DATE_RANGE = '{"date_from": "2025-12-16T09:00:00Z", "date_to": "2025-12-16T11:00:00Z"}'++ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ # Two rows whose `promo.code` value differs only by the "%" — used to prove that a+ # "50%off" search escapes the wildcard instead of matching "50ABCoff" too.+ rows = [+ {"uuid": "019b2664-0000-7000-0000-000000000001", "value": "50%off"},+ {"uuid": "019b2664-0000-7000-0000-000000000002", "value": "50ABCoff"},+ ]+ sql = ""+ for i, row in enumerate(rows):+ sql += (+ json.dumps(+ {+ "uuid": row["uuid"],+ "team_id": cls.team.id,+ "timestamp": "2025-12-16 09:30:00.000000",+ "observed_timestamp": "2025-12-16 09:30:00.000000",+ "body": f"promo log {i}",+ "severity_text": "info",+ "severity_number": 9,+ "service_name": "promo-svc",+ "resource_attributes": {"service.name": "promo-svc"},+ "attributes_map_str": {"promo.code__str": row["value"]},+ }+ )+ + "\n"+ )+ sync_execute(f"INSERT INTO logs FORMAT JSONEachRow\n{sql}")++ def _attributes(self, params: dict) -> list[dict]:+ query_params = {"dateRange": self.DATE_RANGE, **params}+ response = self.client.get(f"/api/projects/{self.team.pk}/logs/attributes", query_params)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ return response.json()["results"]++ def test_attribute_value_search_escapes_ilike_wildcards(self):+ # "%" must match a literal percent — "50%off" must not wildcard-match "50ABCoff".+ results = self._attributes({"attribute_type": "log", "search": "50%off", "search_values": "true"})+ value_matches = [r["matchedValue"] for r in results if r["matchedOn"] == "value"]+ self.assertIn("50%off", value_matches)+ self.assertNotIn("50ABCoff", value_matches)++ def test_value_search_escapes_ilike_wildcards(self):+ # The /logs/values endpoint must escape the wildcard too.+ query_params = {"dateRange": self.DATE_RANGE, "key": "promo.code", "attribute_type": "log", "value": "50%off"}+ response = self.client.get(f"/api/projects/{self.team.pk}/logs/values", query_params)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ names = {r["name"] for r in response.json()["results"]}+ self.assertIn("50%off", names)+ self.assertNotIn("50ABCoff", names)diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex f9a4139b2b70..ecb2e00d8ca3 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -59,6 +59,17 @@ TIME_BUCKET_DATE_RANGE_WHERE = ("and toStartOfDay(time_bucket, 'UTC') <= toStartOfDay({date_to}, 'UTC')")+# Value-search probes attribute_value with ILIKE %search%, which scans far more rows than+# the key-only path. Require a meaningfully specific term so short prefixes (e.g. "id")+# don't trigger an expensive scan.+MIN_VALUE_SEARCH_LENGTH = 4+++def _ilike_pattern(search: str) -> str:+ # Escape ILIKE wildcards so a search for "%" matches a literal percent sign, not every row.+ escaped = search.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+ return f"%{escaped}%"+def _normalise_to_base64(value: str) -> str:try:@@ -736,7 +747,7 @@ def run_service_names_query(exprs.append(parse_expr("service_name ILIKE {search}",- placeholders={"search": ast.Constant(value=f"%{search}%")},+ placeholders={"search": ast.Constant(value=_ilike_pattern(search))},))@@ -776,10 +787,25 @@ def run_attribute_names_query(date_range: DateRange,attribute_type: str = "span_attribute",search: str = "",+ search_values: bool = False,limit: int = 100,offset: int = 0,) -> tuple[list[dict], int]:- """Return attribute names from trace_attributes table."""+ """Return attribute names from trace_attributes table.++ When search_values is set and the search term is specific enough, also match+ on attribute values so a user can find the key holding e.g. a trace_id.+ """+ if search_values and search and len(search) >= MIN_VALUE_SEARCH_LENGTH:+ return _run_attribute_names_value_search(+ team=team,+ date_range=date_range,+ attribute_type=attribute_type,+ search=search,+ limit=limit,+ offset=offset,+ )+query_date_range = QueryDateRange(date_range=date_range,team=team,@@ -806,14 +832,14 @@ def run_attribute_names_query(WHERE time_bucket >= {date_from_start_of_interval}AND time_bucket <= {date_to_start_of_interval} + {one_interval_period}AND attribute_type = {attributeType}- AND attribute_key LIKE {search}+ AND attribute_key ILIKE {search}GROUP BY team_id, attribute_keyORDER BY sum(attribute_count) desc, attribute_key ascOFFSET {offset})""",placeholders={- "search": ast.Constant(value=f"%{search}%"),+ "search": ast.Constant(value=_ilike_pattern(search)),"attributeType": ast.Constant(value=attribute_type),"limit": ast.Constant(value=limit),"offset": ast.Constant(value=offset),@@ -838,12 +864,121 @@ def run_attribute_names_query(count = 0if isinstance(response.results, list) and len(response.results) > 0 and len(response.results[0]) > 0:for name in response.results[0][0]:- results.append({"name": name, "propertyFilterType": property_filter_type})+ results.append({"name": name, "propertyFilterType": property_filter_type, "matchedOn": "key"})count = response.results[0][1] + offsetreturn results, count+def _run_attribute_names_value_search(+ team: "Team",+ date_range: DateRange,+ attribute_type: str,+ search: str,+ limit: int,+ offset: int,+) -> tuple[list[dict], int]:+ # UNION ALL of two branches:+ # (1) keys whose name matches the search+ # (2) keys whose values match the search but whose name does NOT match+ # The NOT-ILIKE on the value branch dedupes — a key never appears twice.+ # match_type lets the outer ORDER BY put key matches above value matches.+ query_date_range = QueryDateRange(+ date_range=date_range,+ team=team,+ interval=IntervalType.MINUTE,+ interval_count=10,+ now=dt.datetime.now(),+ timezone_info=ZoneInfo("UTC"),+ )++ property_filter_type = (+ attribute_type if attribute_type in ("span_attribute", "span_resource_attribute") else "span_attribute"+ )++ query = parse_select(+ """+ SELECT+ attribute_key,+ match_type,+ sample_value,+ total_count+ FROM (+ SELECT+ attribute_key,+ 'key' AS match_type,+ '' AS sample_value,+ sum(attribute_count) AS total_count+ FROM posthog.trace_attributes+ WHERE time_bucket >= {date_from_start_of_interval}+ AND time_bucket <= {date_to_start_of_interval} + {one_interval_period}+ AND attribute_type = {attributeType}+ AND attribute_key ILIKE {search}+ GROUP BY team_id, attribute_key++ UNION ALL++ SELECT+ attribute_key,+ 'value' AS match_type,+ argMax(attribute_value, attribute_count) AS sample_value,+ sum(attribute_count) AS total_count+ FROM posthog.trace_attributes+ WHERE time_bucket >= {date_from_start_of_interval}+ AND time_bucket <= {date_to_start_of_interval} + {one_interval_period}+ AND attribute_type = {attributeType}+ AND attribute_value ILIKE {search}+ AND attribute_key NOT ILIKE {search}+ GROUP BY team_id, attribute_key+ )+ ORDER BY+ match_type = 'key' DESC,+ total_count DESC,+ attribute_key ASC+ LIMIT {limit}+ OFFSET {offset}+ """,+ placeholders={+ "search": ast.Constant(value=_ilike_pattern(search)),+ "attributeType": ast.Constant(value=attribute_type),+ "limit": ast.Constant(value=limit),+ "offset": ast.Constant(value=offset),+ **query_date_range.to_placeholders(),+ },+ )++ response = execute_hogql_query(+ query_type="TracingAttributeNamesQuery",+ query=query,+ team=team,+ workload=Workload.LOGS,+ filters=HogQLFilters(dateRange=date_range),+ modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),+ settings=HogQLGlobalSettings(+ read_overflow_mode="break",+ max_bytes_to_read=5_000_000_000,+ ),+ )++ results = []+ if isinstance(response.results, list):+ for row in response.results:+ attribute_key, match_type, sample_value, _total_count = row+ matched_on_key = match_type == "key"+ results.append(+ {+ "name": attribute_key,+ "propertyFilterType": property_filter_type,+ "matchedOn": "key" if matched_on_key else "value",+ "matchedValue": None if matched_on_key else (sample_value or None),+ }+ )++ # Total count for value-search isn't separately computed; use the returned page+ # size plus offset as a lower bound — enough for the "load more" affordance.+ return results, len(results) + offset++def run_attribute_values_query(team: "Team",date_range: DateRange,@@ -884,7 +1019,7 @@ def run_attribute_values_query()""",placeholders={- "search": ast.Constant(value=f"%{search}%"),+ "search": ast.Constant(value=_ilike_pattern(search)),"attributeType": ast.Constant(value=attribute_type),"attributeKey": ast.Constant(value=attribute_key),"limit": ast.Constant(value=limit),diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex 70342acaa030..5fb2a3293cad 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -236,6 +236,11 @@ class _TracingServiceNamesQuerySerializer(serializers.Serializer):class _TracingAttributesQuerySerializer(serializers.Serializer):search = serializers.CharField(required=False, help_text="Search filter for attribute names.")+ search_values = serializers.BooleanField(+ required=False,+ default=False,+ help_text="When true, the search query also matches attribute values (not just keys), so a value such as a trace_id finds the key holding it.",+ )attribute_type = serializers.ChoiceField(choices=["span_attribute", "span_resource_attribute"],required=False,@@ -247,6 +252,27 @@ class _TracingAttributesQuerySerializer(serializers.Serializer):offset = serializers.IntegerField(required=False, min_value=0, help_text="Pagination offset (default: 0).")+class _TracingAttributeEntrySerializer(serializers.Serializer):+ name = serializers.CharField(help_text="Attribute key name.")+ propertyFilterType = serializers.CharField(+ help_text='Property filter type: "span_attribute" or "span_resource_attribute". Use this as the `type` field when filtering.',+ )+ matchedOn = serializers.ChoiceField(+ choices=["key", "value"],+ help_text='How the search query matched this row: "key" if the attribute key matched, "value" if a value matched.',+ )+ matchedValue = serializers.CharField(+ required=False,+ allow_null=True,+ help_text='Sample matching value — only set when matchedOn is "value".',+ )+++class _TracingAttributesResponseSerializer(serializers.Serializer):+ results = _TracingAttributeEntrySerializer(many=True, help_text="Available attribute keys matching the filters.")+ count = serializers.IntegerField(help_text="Total attribute keys matched (lower bound when searching values).")++class _TracingValuesQuerySerializer(serializers.Serializer):key = serializers.CharField(help_text="The attribute key to get values for.")attribute_type = serializers.ChoiceField(@@ -1060,11 +1086,15 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)status=status.HTTP_200_OK,)- @extend_schema(parameters=[_TracingAttributesQuerySerializer])+ @extend_schema(+ parameters=[_TracingAttributesQuerySerializer],+ responses={200: _TracingAttributesResponseSerializer},+ )@action(detail=False, methods=["get"], required_scopes=["tracing:read"])def attributes(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)search = request.GET.get("search", "")+ search_values = request.GET.get("search_values", "false").lower() == "true"limit = int(request.GET.get("limit", "100"))offset = int(request.GET.get("offset", "0"))@@ -1082,6 +1112,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)date_range=date_range,attribute_type=attribute_type,search=search,+ search_values=search_values,limit=limit,offset=offset,)diff --git a/products/tracing/backend/tests/test_attribute_value_search.py b/products/tracing/backend/tests/test_attribute_value_search.pynew file mode 100644index 000000000000..93d638765a6f--- /dev/null+++ b/products/tracing/backend/tests/test_attribute_value_search.py@@ -0,0 +1,131 @@+import datetime as dt++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from parameterized import parameterized++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.traces.spans import TRACE_ATTRIBUTES_DISTRIBUTED_TABLE_SQL+from posthog.clickhouse.traces.trace_attributes import TRACE_ATTRIBUTES_TABLE_SQL++DATE_FROM = "2026-06-02T07:00:00Z"+DATE_TO = "2026-06-02T09:00:00Z"++# A value that no attribute KEY contains — so it can only match on value.+TRACE_ID_VALUE = "abc123def456trace"+++class TestTracingAttributeValueSearch(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ sync_execute("DROP TABLE IF EXISTS trace_attributes_distributed")+ sync_execute("DROP TABLE IF EXISTS trace_attributes")+ sync_execute(TRACE_ATTRIBUTES_TABLE_SQL())+ sync_execute(TRACE_ATTRIBUTES_DISTRIBUTED_TABLE_SQL())++ bucket = dt.datetime(2026, 6, 2, 8, 0, 0).strftime("%Y-%m-%d %H:%M:%S")+ # attribute_type values mirror the deployed MVs in bin/clickhouse-logs.sql.+ rows = [+ # (key, value, count, type)+ ("http.target", TRACE_ID_VALUE, 10, "span_attribute"),+ ("custom.trace_ref", TRACE_ID_VALUE, 3, "span_attribute"),+ ("http.method", "GET", 50, "span_attribute"),+ ("user.trace_id", "unrelated-value", 5, "span_attribute"), # key contains "trace_id"+ ("k8s.pod.name", TRACE_ID_VALUE, 2, "span_resource_attribute"),+ ("service.version", "1.2.3", 20, "span_resource_attribute"),+ # ILIKE-escaping fixtures: "50%off" must not wildcard-match "50ABCoff".+ ("promo.code", "50%off", 4, "span_attribute"),+ ("promo.alt", "50ABCoff", 4, "span_attribute"),+ ]+ values_sql = ",".join(+ f"({cls.team.id}, '{bucket}', '{bucket}', 'svc', 0, '{k}', '{v}', {c}, '{t}')" for k, v, c, t in rows+ )+ sync_execute(+ "INSERT INTO trace_attributes (team_id, time_bucket, original_expiry_time_bucket, service_name, "+ "resource_fingerprint, attribute_key, attribute_value, attribute_count, attribute_type) VALUES "+ + values_sql+ )++ @classmethod+ def tearDownClass(cls):+ sync_execute("DROP TABLE IF EXISTS trace_attributes_distributed")+ sync_execute("DROP TABLE IF EXISTS trace_attributes")+ super().tearDownClass()++ def _attributes(self, params: dict) -> list[dict]:+ query_params = {"dateRange": f'{{"date_from": "{DATE_FROM}", "date_to": "{DATE_TO}"}}', **params}+ res = self.client.get(f"/api/projects/{self.team.id}/tracing/spans/attributes", query_params)+ self.assertEqual(res.status_code, 200, res.content)+ return res.json()["results"]++ @parameterized.expand(+ [+ # Value-only term, but value search disabled → no value matches surface.+ ("off_by_default", {"attribute_type": "span_attribute", "search": TRACE_ID_VALUE}),+ # search_values on, but term under the 4-char minimum → value search skipped.+ ("short_search", {"attribute_type": "span_attribute", "search": "abc", "search_values": "true"}),+ ]+ )+ def test_no_value_matches(self, _name, params):+ results = self._attributes(params)+ for entry in results:+ self.assertNotEqual(entry.get("matchedOn"), "value")++ def test_search_values_finds_match_on_value(self):+ results = self._attributes(+ {"attribute_type": "span_attribute", "search": TRACE_ID_VALUE, "search_values": "true"}+ )+ names = {r["name"] for r in results}+ self.assertIn("http.target", names)+ self.assertIn("custom.trace_ref", names)++ for entry in results:+ self.assertIn(entry["matchedOn"], ("key", "value"))+ if entry["matchedOn"] == "value":+ self.assertTrue(entry.get("matchedValue"))+ self.assertIn(TRACE_ID_VALUE.lower(), entry["matchedValue"].lower())++ self.assertTrue(any(r["matchedOn"] == "value" for r in results))++ def test_search_values_respects_attribute_type(self):+ # The same value lives on a resource attribute key — only returned for the resource type.+ results = self._attributes(+ {"attribute_type": "span_resource_attribute", "search": TRACE_ID_VALUE, "search_values": "true"}+ )+ names = {r["name"] for r in results}+ self.assertIn("k8s.pod.name", names)+ self.assertNotIn("http.target", names)++ def test_search_values_ranks_key_matches_first(self):+ # "trace" matches the key "user.trace_id" and the values of http.target / custom.trace_ref.+ results = self._attributes({"attribute_type": "span_attribute", "search": "trace", "search_values": "true"})+ match_kinds = [r["matchedOn"] for r in results]+ first_value_idx = next((i for i, m in enumerate(match_kinds) if m == "value"), None)+ if first_value_idx is not None:+ self.assertNotIn("key", match_kinds[first_value_idx:], "key matches must appear before value matches")++ def test_value_search_escapes_ilike_wildcards(self):+ # "%" is escaped to a literal — "50%off" must not wildcard-match "50ABCoff".+ results = self._attributes({"attribute_type": "span_attribute", "search": "50%off", "search_values": "true"})+ names = {r["name"] for r in results}+ self.assertIn("promo.code", names)+ self.assertNotIn("promo.alt", names)++ def test_key_search_is_case_insensitive(self):+ # Keys are stored lowercase; an upper-case search term must still match them (ILIKE).+ results = self._attributes({"attribute_type": "span_attribute", "search": "HTTP"})+ names = {r["name"] for r in results}+ self.assertIn("http.target", names)+ self.assertIn("http.method", names)+ self.assertTrue(all(r["matchedOn"] == "key" for r in results))++ def test_key_search_case_insensitive_with_value_search(self):+ # The value-search path matches keys case-insensitively too: "TRACE" matches the+ # key "user.trace_id" and the values of http.target / custom.trace_ref.+ results = self._attributes({"attribute_type": "span_attribute", "search": "TRACE", "search_values": "true"})+ by_name = {r["name"]: r for r in results}+ self.assertIn("user.trace_id", by_name)+ self.assertEqual(by_name["user.trace_id"]["matchedOn"], "key")diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex 59a9bd828f59..730e90c5eee2 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -165,6 +165,41 @@ export interface _TracingAttributeBreakdownRequestApi {query: _TracingAttributeBreakdownQueryBodyApi}+/**+ * * `key` - key+ * * `value` - value+ */+export type MatchedOnEnumApi = (typeof MatchedOnEnumApi)[keyof typeof MatchedOnEnumApi]++export const MatchedOnEnumApi = {+ Key: 'key',+ Value: 'value',+} as const++export interface _TracingAttributeEntryApi {+ /** Attribute key name. */+ name: string+ /** Property filter type: "span_attribute" or "span_resource_attribute". Use this as the `type` field when filtering. */+ propertyFilterType: string+ /** How the search query matched this row: "key" if the attribute key matched, "value" if a value matched.+ *+ * * `key` - key+ * * `value` - value */+ matchedOn: MatchedOnEnumApi+ /**+ * Sample matching value — only set when matchedOn is "value".+ * @nullable+ */+ matchedValue?: string | null+}++export interface _TracingAttributesResponseApi {+ /** Available attribute keys matching the filters. */+ results: _TracingAttributeEntryApi[]+ /** Total attribute keys matched (lower bound when searching values). */+ count: number+}+export interface _TracingCountBodyApi {/** Date range for the count. Defaults to last hour. */dateRange?: _TracingDateRangeApi@@ -450,6 +485,10 @@ export type TracingSpansAttributesRetrieveParams = {* @minLength 1*/search?: string+ /**+ * When true, the search query also matches attribute values (not just keys), so a value such as a trace_id finds the key holding it.+ */+ search_values?: boolean}export type TracingSpansAttributesRetrieveAttributeType =diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex f4d7ae483141..1a6b4d29c0bf 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -17,6 +17,7 @@ import type {_SymbolStatsResponseApi,_TracingAggregationRequestApi,_TracingAttributeBreakdownRequestApi,+ _TracingAttributesResponseApi,_TracingCountRequestApi,_TracingCountResponseApi,_TracingQueryRequestApi,@@ -82,8 +83,8 @@ export const tracingSpansAttributesRetrieve = async (projectId: string,params?: TracingSpansAttributesRetrieveParams,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getTracingSpansAttributesRetrieveUrl(projectId, params), {+): Promise<_TracingAttributesResponseApi> => {+ return apiMutator<_TracingAttributesResponseApi>(getTracingSpansAttributesRetrieveUrl(projectId, params), {...options,method: 'GET',})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 48a8e9a100b5..cd19b60e39ba 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -48826,6 +48826,30 @@ export namespace Schemas {query: _TracingAttributeBreakdownQueryBody;}+ export interface _TracingAttributeEntry {+ /** Attribute key name. */+ name: string;+ /** Property filter type: "span_attribute" or "span_resource_attribute". Use this as the `type` field when filtering. */+ propertyFilterType: string;+ /** How the search query matched this row: "key" if the attribute key matched, "value" if a value matched.+ *+ * * `key` - key+ * * `value` - value */+ matchedOn: MatchedOnEnum;+ /**+ * Sample matching value — only set when matchedOn is "value".+ * @nullable+ */+ matchedValue?: string | null;+ }++ export interface _TracingAttributesResponse {+ /** Available attribute keys matching the filters. */+ results: _TracingAttributeEntry[];+ /** Total attribute keys matched (lower bound when searching values). */+ count: number;+ }+export interface _TracingCountBody {/** Date range for the count. Defaults to last hour. */dateRange?: _TracingDateRange;@@ -52977,6 +53001,10 @@ export namespace Schemas {* @minLength 1*/search?: string;+ /**+ * When true, the search query also matches attribute values (not just keys), so a value such as a trace_id finds the key holding it.+ */+ search_values?: boolean;};export type EnvironmentsTracingSpansAttributesRetrieveAttributeType = typeof EnvironmentsTracingSpansAttributesRetrieveAttributeType[keyof typeof EnvironmentsTracingSpansAttributesRetrieveAttributeType];@@ -59895,6 +59923,10 @@ export namespace Schemas {* @minLength 1*/search?: string;+ /**+ * When true, the search query also matches attribute values (not just keys), so a value such as a trace_id finds the key holding it.+ */+ search_values?: boolean;};export type TracingSpansAttributesRetrieveAttributeType = typeof TracingSpansAttributesRetrieveAttributeType[keyof typeof TracingSpansAttributesRetrieveAttributeType];diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.tsindex 07c78c088c23..b6982fc581ac 100644--- a/services/mcp/src/generated/tracing/api.ts+++ b/services/mcp/src/generated/tracing/api.ts@@ -234,6 +234,8 @@ export const tracingSpansAttributesRetrieveQueryLimitMax = 100export const tracingSpansAttributesRetrieveQueryOffsetMin = 0+export const tracingSpansAttributesRetrieveQuerySearchValuesDefault = false+export const TracingSpansAttributesRetrieveQueryParams = /* @__PURE__ */ zod.object({attribute_type: zod.enum(['span_attribute', 'span_resource_attribute'])@@ -253,6 +255,12 @@ export const TracingSpansAttributesRetrieveQueryParams = /* @__PURE__ */ zod.obj.optional().describe('Pagination offset (default: 0).'),search: zod.string().min(1).optional().describe('Search filter for attribute names.'),+ search_values: zod+ .boolean()+ .default(tracingSpansAttributesRetrieveQuerySearchValuesDefault)+ .describe(+ 'When true, the search query also matches attribute values (not just keys), so a value such as a trace_id finds the key holding it.'+ ),})export const TracingSpansCountCreateParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/tools/generated/tracing.ts b/services/mcp/src/tools/generated/tracing.tsindex 3ccc6cdcd04e..99a6b6dd4623 100644--- a/services/mcp/src/tools/generated/tracing.ts+++ b/services/mcp/src/tools/generated/tracing.ts@@ -66,12 +66,12 @@ const apmAttributeValuesList = (): ToolBase<typeof ApmAttributeValuesListSchema,const ApmAttributesListSchema = TracingSpansAttributesRetrieveQueryParams-const apmAttributesList = (): ToolBase<typeof ApmAttributesListSchema, unknown> => ({+const apmAttributesList = (): ToolBase<typeof ApmAttributesListSchema, Schemas._TracingAttributesResponse> => ({name: 'apm-attributes-list',schema: ApmAttributesListSchema,handler: async (context: Context, params: z.infer<typeof ApmAttributesListSchema>) => {const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<unknown>({+ const result = await context.api.request<Schemas._TracingAttributesResponse>({method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/attributes/`,query: {@@ -79,6 +79,7 @@ const apmAttributesList = (): ToolBase<typeof ApmAttributesListSchema, unknown>limit: params.limit,offset: params.offset,search: params.search,+ search_values: params.search_values,},})const filtered = pickResponseFields(result, ['results', 'count']) as typeof resultdiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attributes-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attributes-list.jsonindex b634838ae08c..f71dd9fb3440 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attributes-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attributes-list.json@@ -21,6 +21,11 @@"description": "Search filter for attribute names.","minLength": 1,"type": "string"+ },+ "search_values": {+ "default": false,+ "description": "When true, the search query also matches attribute values (not just keys), so a value such as a trace_id finds the key holding it.",+ "type": "boolean"}},"type": "object"