Skip to content

: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.

feat(metrics): scope the metric picker to the filtered services (#88834)

Daniel Visca0ad77a2e50a5
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index fce7cabb5ac8..a4e79143ad0e 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -218,16 +218,19 @@ def list_metric_names(
team: Team,
search: str = "",
limit: int = 100,
+ services: Sequence[str] = (),
) -> list[dict[str, Any]]:
"""List distinct metric names for the team's picker.
Returns a list of `{"name": str, "metric_type": str}` dicts ordered by
most-recently-seen, with exact-name matches floated to the top.
- Raises `ValueError` for an out-of-range limit.
+ Passing `services` narrows the list to names those services reported.
+ Raises `ValueError` for an out-of-range limit or too many services.
- The unsearched list is cached per team for a minute; searches are not.
+ The unsearched list is cached per team and service scope for a minute;
+ searches are not.
"""
- return cached_metric_names(team=team, search=search, limit=limit)
+ return cached_metric_names(team=team, search=search, limit=limit, services=services)
def get_metrics_overview(*, team: Team, lookback: dt.timedelta | None = None) -> MetricsOverview:
diff --git a/products/metrics/backend/metric_names_query_runner.py b/products/metrics/backend/metric_names_query_runner.py
index d283877a083a..a78c25c2370b 100644
--- a/products/metrics/backend/metric_names_query_runner.py
+++ b/products/metrics/backend/metric_names_query_runner.py
@@ -20,6 +20,8 @@ without a second round-trip.
"""
import datetime as dt
+from collections.abc import Sequence
+from hashlib import sha256
from typing import Any
from django.core.cache import cache
@@ -50,6 +52,10 @@ SERIES_RETENTION = dt.timedelta(days=90)
# long enough to absorb the burst of mounts a team generates in a working session.
METRIC_NAMES_CACHE_TTL = 60
+# Past this the picker is not scoped to anything a person can hold in their head,
+# and the bound keeps one request from building an unbounded IN list.
+MAX_PICKER_SERVICES = 50
+
class MetricNamesQueryRunner:
def __init__(
@@ -59,16 +65,24 @@ class MetricNamesQueryRunner:
search: str = "",
limit: int = 100,
lookback: dt.timedelta = dt.timedelta(days=7),
+ services: Sequence[str] = (),
) -> None:
if limit <= 0 or limit > 1000:
raise ValueError("limit must be in [1, 1000]")
if lookback <= dt.timedelta(0):
raise ValueError("lookback must be positive")
+ if len(services) > MAX_PICKER_SERVICES:
+ raise ValueError(f"at most {MAX_PICKER_SERVICES} services may be selected")
self.team = team
self.search = search.strip()
self.limit = limit
self.lookback = lookback
+ # Sorted and deduped so two callers that picked the same services in a
+ # different order share one cache entry. An empty string is a real
+ # selection: a sender that omits the `service.name` resource attribute
+ # lands in the group the overview labels "unknown".
+ self.services = tuple(sorted(set(services)))
def _build_query(self) -> ast.SelectQuery:
# The alias is `last_seen_at`, not `last_seen`: HogQL registers select
@@ -120,6 +134,26 @@ class MetricNamesQueryRunner:
)
assert isinstance(query, ast.SelectQuery)
+ # Both variants above filter on the lookback, so there is always a WHERE to
+ # extend; the assert is what tells the type checker so.
+ assert query.where is not None
+
+ # Appended to the parsed tree rather than written into both SQL variants
+ # above, so the scoped and unscoped pickers stay one query definition.
+ # `service_name` is the only filterable column with its own skip index
+ # (`idx_service_set`), which is what keeps a type-ahead affordable —
+ # attribute predicates read the label maps and belong in the chart query.
+ if self.services:
+ query.where = ast.And(
+ exprs=[
+ query.where,
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["service_name"]),
+ right=ast.Tuple(exprs=[ast.Constant(value=service) for service in self.services]),
+ ),
+ ]
+ )
return query
def run(self) -> list[dict[str, Any]]:
@@ -134,22 +168,31 @@ class MetricNamesQueryRunner:
return [{"name": row[0], "metric_type": row[1]} for row in response.results]
-def cached_metric_names(team: Team, *, search: str = "", limit: int = 100) -> list[dict[str, Any]]:
+def cached_metric_names(
+ team: Team, *, search: str = "", limit: int = 100, services: Sequence[str] = ()
+) -> list[dict[str, Any]]:
"""Metric names for the picker, with the unsearched list cached per team.
Only the empty-search prime is cached: every viewer mount issues it and the
answer is the same for everyone on the team. Searches are per-keystroke and
per-user, so caching them would fill the cache with single-hit entries.
+ The service scope is part of the key, not a filter over one cached list: the
+ unscoped list is capped at `limit` names, so narrowing it in Python would hide
+ metrics that a scoped query returns.
+
Only non-empty results are cached, matching `team_has_metrics`: a team that
just wired up OTel must not be pinned to an empty picker while the setup
prompt's poll has already let them through.
"""
- runner = MetricNamesQueryRunner(team=team, search=search, limit=limit)
+ runner = MetricNamesQueryRunner(team=team, search=search, limit=limit, services=services)
if runner.search:
return runner.run()
- cache_key = f"metrics:{team.id}:metric_names:v1:{limit}"
+ # `repr` of the sorted tuple, hashed: service names come from user data, so
+ # they can carry spaces and unicode that a memcached key cannot.
+ scope = sha256(repr(runner.services).encode()).hexdigest()[:16] if runner.services else "all"
+ cache_key = f"metrics:{team.id}:metric_names:v2:{limit}:{scope}"
cached = cache.get(cache_key)
if cached is not None:
return cached
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index e35e9f1d4545..ed6fcc6d8ffe 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -405,6 +405,26 @@ class _MetricValuesParamsSerializer(serializers.Serializer):
max_value=1000,
help_text="Max number of names to return. Defaults to 100; maximum 1000.",
)
+ service = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ default=None,
+ max_length=1024,
+ help_text=(
+ "Comma-separated services to narrow the list to, e.g. `service=web,worker`. "
+ "Omit for every service. Send it empty to select only series whose sender "
+ "did not set `service.name`. A service name containing a comma cannot be "
+ "selected."
+ ),
+ )
+
+ def validate_service(self, value: str | None) -> list[str]:
+ # Absent and empty mean different things, which is why the default is None
+ # rather than "": omitting the param leaves the picker unscoped, while
+ # sending it empty scopes to the senders that set no service name.
+ if value is None:
+ return []
+ return [service.strip() for service in value.split(",")]
class _MetricNameSerializer(serializers.Serializer):
@@ -784,7 +804,10 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
try:
results = list_metric_names(
- team=self.team, search=params.validated_data["value"], limit=params.validated_data["limit"]
+ team=self.team,
+ search=params.validated_data["value"],
+ limit=params.validated_data["limit"],
+ services=params.validated_data["service"],
)
except ValueError as exc:
raise ParseError(str(exc))
diff --git a/products/metrics/backend/tests/test_metric_names_query_runner.py b/products/metrics/backend/tests/test_metric_names_query_runner.py
index 2d7ba8e18532..bd6a3084fd73 100644
--- a/products/metrics/backend/tests/test_metric_names_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_names_query_runner.py
@@ -9,7 +9,11 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
-from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner, cached_metric_names
+from products.metrics.backend.metric_names_query_runner import (
+ MAX_PICKER_SERVICES,
+ MetricNamesQueryRunner,
+ cached_metric_names,
+)
from products.metrics.backend.tests._seeder import seed_metric, seed_metric_event, truncate_metrics_tables
@@ -130,6 +134,17 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(cached_metric_names(self.team, search="m2"), run.return_value)
self.assertEqual(run.call_count, 2)
+ # Nor may a service scope: the unscoped list is capped at `limit`, so
+ # serving it to a scoped picker both widens and truncates the answer.
+ run.return_value = [{"name": "m3", "metric_type": "gauge"}]
+ self.assertEqual(cached_metric_names(self.team, services=["web"]), run.return_value)
+ self.assertEqual(run.call_count, 3)
+ # Same scope twice is one query; a different scope is its own entry.
+ self.assertEqual(cached_metric_names(self.team, services=["web"]), run.return_value)
+ self.assertEqual(run.call_count, 3)
+ self.assertEqual(cached_metric_names(self.team, services=["worker"]), run.return_value)
+ self.assertEqual(run.call_count, 4)
+
def test_exact_match_floats_to_top(self):
anchor = timezone.now().replace(microsecond=0)
_seed_point(
@@ -167,6 +182,36 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertIn("recent.metric", names)
self.assertNotIn("old.metric", names)
+ def test_rejects_more_services_than_the_cap(self):
+ with self.assertRaises(ValueError):
+ MetricNamesQueryRunner(team=self.team, services=[f"svc-{i}" for i in range(MAX_PICKER_SERVICES + 1)])
+
+ def _seed_two_services_and_an_unnamed_sender(self) -> None:
+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)
+ for service, metric_name in (("web", "http.duration"), ("worker", "jobs.processed"), ("", "orphan.metric")):
+ seed_metric(
+ team_id=self.team.id,
+ metric_name=metric_name,
+ points=[(anchor, 1.0)],
+ service_name=service,
+ )
+
+ @parameterized.expand(
+ [
+ ("one service", ["web"], {"http.duration"}),
+ ("several services", ["web", "worker"], {"http.duration", "jobs.processed"}),
+ # An empty service name is a real group, not "no filter": a sender that
+ # omits the `service.name` resource attribute lands here.
+ ("the unnamed sender group", [""], {"orphan.metric"}),
+ ("no scope", [], {"http.duration", "jobs.processed", "orphan.metric"}),
+ ]
+ )
+ def test_scopes_names_to_the_selected_services(self, _name: str, services: list[str], expected: set[str]):
+ self._seed_two_services_and_an_unnamed_sender()
+
+ runner = MetricNamesQueryRunner(team=self.team, services=services)
+ self.assertEqual({row["name"] for row in runner.run()}, expected)
+
class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):
CLASS_DATA_LEVEL_SETUP = True
@@ -207,6 +252,30 @@ class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):
names = [row["name"] for row in response.json()["results"]]
self.assertEqual(names, ["http.duration"])
+ @parameterized.expand(
+ [
+ # Omitting the param and sending it empty mean different things, and the
+ # only thing carrying that difference over the wire is the query string.
+ ("omitted", "", {"http.duration", "jobs.processed", "orphan.metric"}),
+ ("one service", "&service=web", {"http.duration"}),
+ ("several services", "&service=web,worker", {"http.duration", "jobs.processed"}),
+ ("empty, the unnamed sender group", "&service=", {"orphan.metric"}),
+ ]
+ )
+ def test_values_service_param(self, _name: str, query: str, expected: set[str]):
+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)
+ for service, metric_name in (("web", "http.duration"), ("worker", "jobs.processed"), ("", "orphan.metric")):
+ seed_metric(
+ team_id=self.team.id,
+ metric_name=metric_name,
+ points=[(anchor, 1.0)],
+ service_name=service,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/values?limit=100{query}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual({row["name"] for row in response.json()["results"]}, expected)
+
def test_values_rejects_invalid_limit(self):
response = self.client.get(f"/api/projects/{self.team.id}/metrics/values?limit=not-a-number")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/products/metrics/frontend/components/metricNamePickerLogic.ts b/products/metrics/frontend/components/metricNamePickerLogic.ts
index 316ce52735bd..6efe617db627 100644
--- a/products/metrics/frontend/components/metricNamePickerLogic.ts
+++ b/products/metrics/frontend/components/metricNamePickerLogic.ts
@@ -15,6 +15,7 @@ export interface metricNamePickerLogicValues {
items: MetricNameItem[]
itemsLoading: boolean
search: string
+ services: string[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -43,6 +44,9 @@ export interface metricNamePickerLogicActions {
setSearch: (search: string) => {
search: string
}
+ setServices: (services: string[]) => {
+ services: string[]
+ }
}
export type metricNamePickerLogicType = MakeLogicType<metricNamePickerLogicValues, metricNamePickerLogicActions>
@@ -54,9 +58,13 @@ export const metricNamePickerLogic = kea<metricNamePickerLogicType>([
})),
actions({
setSearch: (search: string) => ({ search }),
+ // Pushed in by the viewer rather than read from it: the viewer already
+ // reads this logic's `items`, so a connection the other way would cycle.
+ setServices: (services: string[]) => ({ services }),
}),
reducers({
search: ['' as string, { setSearch: (_, { search }) => search }],
+ services: [[] as string[], { setServices: (_, { services }) => services }],
}),
loaders(({ values }) => ({
items: [
@@ -75,6 +83,10 @@ export const metricNamePickerLogic = kea<metricNamePickerLogicType>([
const response = await metricsValuesRetrieve(String(values.currentTeamId), {
value: values.search,
limit: 100,
+ // Joined here rather than passed as an array: the generated
+ // client stringifies params, and an empty array would send
+ // `service=`, which the API reads as the unnamed-sender scope.
+ ...(values.services.length ? { service: values.services.join(',') } : {}),
})
breakpoint()
return response.results
@@ -86,6 +98,10 @@ export const metricNamePickerLogic = kea<metricNamePickerLogicType>([
setSearch: () => {
actions.loadItems({ debounce: true })
},
+ // Not debounced: the scope changes on a click, not a keystroke.
+ setServices: () => {
+ actions.loadItems({ debounce: false })
+ },
})),
afterMount(({ actions }) => {
// Prime the list so the dropdown isn't empty on first open. Mirrors
diff --git a/products/metrics/frontend/components/metricsOverviewLogic.test.ts b/products/metrics/frontend/components/metricsOverviewLogic.test.ts
index 8a4f95f7913b..40db3cc26b01 100644
--- a/products/metrics/frontend/components/metricsOverviewLogic.test.ts
+++ b/products/metrics/frontend/components/metricsOverviewLogic.test.ts
@@ -6,6 +6,7 @@ import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/typ
import { metricsOverviewRetrieve, metricsValuesRetrieve } from '../generated/api'
import type { _MetricsOverviewResponseApi } from '../generated/api.schemas'
import { metricsSceneLogic } from '../metricsSceneLogic'
+import { metricNamePickerLogic } from './metricNamePickerLogic'
import { metricsOverviewLogic } from './metricsOverviewLogic'
import { metricsViewerLogic } from './metricsViewerLogic'
@@ -68,20 +69,26 @@ describe('metricsOverviewLogic', () => {
// the query goes out unfiltered. These assert `queryFilters` — what actually reaches
// the API — including the "unknown" row, whose service_name is empty.
it.each([
- ['a named service', 'api', { key: 'service_name', op: 'eq', value: 'api' }],
- ['the unknown service', '', { key: 'service_name', op: 'regex', value: '^$' }],
- ])('viewService sends a service filter for %s and switches tab', async (_name, serviceName, expected) => {
- logic = metricsOverviewLogic()
- logic.mount()
+ ['a named service', 'api', { key: 'service_name', op: 'eq', value: 'api' }, ['api']],
+ ['the unknown service', '', { key: 'service_name', op: 'regex', value: '^$' }, ['']],
+ ])(
+ 'viewService sends a service filter for %s, scopes the picker, and switches tab',
+ async (_name, serviceName, expected, pickerServices) => {
+ logic = metricsOverviewLogic()
+ logic.mount()
- await expectLogic(logic, () => {
- logic.actions.viewService(serviceName as string)
- }).toDispatchActions([
- metricsViewerLogic.actionTypes.setFilterGroup,
- metricsSceneLogic.actionTypes.setActiveTab,
- ])
+ await expectLogic(logic, () => {
+ logic.actions.viewService(serviceName as string)
+ }).toDispatchActions([
+ metricsViewerLogic.actionTypes.setFilterGroup,
+ metricsSceneLogic.actionTypes.setActiveTab,
+ ])
- expect(metricsSceneLogic.values.activeTab).toBe('viewer')
- expect(metricsViewerLogic.values.queryFilters).toEqual([expected])
- })
+ expect(metricsSceneLogic.values.activeTab).toBe('viewer')
+ expect(metricsViewerLogic.values.queryFilters).toEqual([expected])
+ // The landing promise: the viewer the user arrives at offers only the
+ // metrics that service reports, not every metric in the project.
+ expect(metricNamePickerLogic.values.services).toEqual(pickerServices)
+ }
+ )
})
diff --git a/products/metrics/frontend/components/metricsOverviewLogic.tsx b/products/metrics/frontend/components/metricsOverviewLogic.tsx
index dff021ed4fcc..f865e8107dc1 100644
--- a/products/metrics/frontend/components/metricsOverviewLogic.tsx
+++ b/products/metrics/frontend/components/metricsOverviewLogic.tsx
@@ -9,7 +9,7 @@ import { metricsOverviewRetrieve } from '../generated/api'
import type { _MetricsOverviewResponseApi } from '../generated/api.schemas'
import { canViewMetrics } from '../metricsAccess'
import { metricsSceneLogic } from '../metricsSceneLogic'
-import { metricsViewerLogic } from './metricsViewerLogic'
+import { EMPTY_SERVICE_PATTERN, SERVICE_NAME_KEY, metricsViewerLogic } from './metricsViewerLogic'
// Long enough to keep the landing page cheap, short enough that "receiving
// metrics" flips to a warning within a minute of ingestion stopping.
@@ -64,14 +64,14 @@ const serviceFilterGroup = (serviceName: string): UniversalFiltersGroup => {
// as an anchored regex, which survives the same pipeline.
const matcher = serviceName
? { value: [serviceName], operator: PropertyOperator.Exact }
- : { value: ['^$'], operator: PropertyOperator.Regex }
+ : { value: [EMPTY_SERVICE_PATTERN], operator: PropertyOperator.Regex }
return {
type: FilterLogicalOperator.And,
values: [
{
type: FilterLogicalOperator.And,
- values: [{ type: PropertyFilterType.MetricAttribute, key: 'service_name', ...matcher }],
+ values: [{ type: PropertyFilterType.MetricAttribute, key: SERVICE_NAME_KEY, ...matcher }],
},
],
}
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
index 7ee4b5d9128c..aa58cdb4f1e9 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -281,6 +281,36 @@ describe('metricsViewerLogic', () => {
expect(logic.values.queryFilters).toEqual([expected])
})
+ // Drives the metric picker's scope. Getting this wrong is silent: the picker
+ // reverts to offering every metric while the filter bar still shows a service.
+ it.each([
+ ['one exact service', [{ key: 'service_name', operator: PropertyOperator.Exact, value: ['web'] }], ['web']],
+ [
+ 'several exact services',
+ [{ key: 'service_name', operator: PropertyOperator.Exact, value: ['web', 'worker'] }],
+ ['web', 'worker'],
+ ],
+ ['the unnamed sender group', [{ key: 'service_name', operator: PropertyOperator.Regex, value: ['^$'] }], ['']],
+ ['a non-service chip', [{ key: 'env', operator: PropertyOperator.Exact, value: ['prod'] }], []],
+ [
+ // Two chips are ANDed, which one IN list cannot express.
+ 'two service chips',
+ [
+ { key: 'service_name', operator: PropertyOperator.Exact, value: ['web'] },
+ { key: 'service_name', operator: PropertyOperator.Exact, value: ['worker'] },
+ ],
+ [],
+ ],
+ [
+ 'a service chip that is not a membership test',
+ [{ key: 'service_name', operator: PropertyOperator.IContains, value: ['we'] }],
+ [],
+ ],
+ ])('derives the picker service scope from %s', (_name, propertyFilters, expected) => {
+ logic.actions.setFilterGroup(filterGroupWith(propertyFilters))
+ expect(logic.values.selectedServices).toEqual(expected)
+ })
+
it('skips chips that are still being edited or use unsupported operators', () => {
logic.actions.setFilterGroup(
filterGroupWith([
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 37c4460efb9b..1c683f1dc356 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -133,6 +133,29 @@ const propertyFilterToMetricFilter = (filter: UniversalFilterValue): _MetricFilt
const flattenFilterValues = (group: UniversalFiltersGroup): UniversalFilterValue[] =>
group.values.flatMap((value) => (isUniversalGroupFilterLike(value) ? flattenFilterValues(value) : [value]))
+// Ingestion promotes `service.name` to its own column, so it is the one label the
+// picker can be narrowed by cheaply — see MetricNamesQueryRunner.
+export const SERVICE_NAME_KEY = 'service_name'
+
+// The anchored regex standing in for senders that set no service name: the empty
+// string cannot survive the filter pipeline, which drops empty chip values.
+export const EMPTY_SERVICE_PATTERN = '^$'
+
+/** The services a chip pins the query to, or `[]` when it isn't a membership test. */
+const serviceChipValues = (chip: UniversalFilterValue): string[] => {
+ const operator = 'operator' in chip ? chip.operator : undefined
+ const values = toValueStrings('value' in chip ? chip.value : null)
+ if (operator === PropertyOperator.Exact) {
+ return values
+ }
+ // `toValueStrings` drops the empty string, so the "unknown service" chip only
+ // survives the trip as this regex; anything else narrows in ways an IN cannot.
+ if (operator === PropertyOperator.Regex && values.length === 1 && values[0] === EMPTY_SERVICE_PATTERN) {
+ return ['']
+ }
+ return []
+}
+
export const resolveDate = (value: string | null | undefined): string | null => {
if (!value) {
return null
@@ -150,6 +173,7 @@ export const toKnownMetricType = (metricType: string | undefined): OtelMetricTyp
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsViewerLogicValues {
items: MetricNameItem[] // metricNamePickerLogic
+ pickerServices: string[] // metricNamePickerLogic
currentTeamId: number | null // teamLogic
aggregation: MetricAggregation
anomalyBadge: MetricsAnomalyBadge | null
@@ -183,6 +207,7 @@ export interface metricsViewerLogicValues {
savedInsight: QueryBasedInsightModel | null
savedInsightLoading: boolean
selectedMetricType: OtelMetricTypeEnumApi | null
+ selectedServices: string[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -200,6 +225,9 @@ export interface metricsViewerLogicActions {
debounce: boolean
}
} // metricNamePickerLogic
+ setServices: (services: string[]) => {
+ services: string[]
+ } // metricNamePickerLogic
addToDashboard: () => {
value: true
}
@@ -345,6 +373,7 @@ export interface metricsViewerLogicMeta {
queryFilters: _MetricFilterApi[]
) => MetricsQuery | null
queryFilters: (filterGroup: UniversalFiltersGroup) => _MetricFilterApi[]
+ selectedServices: (filterGroup: UniversalFiltersGroup) => string[]
attributeEndpointFilters: (dateFrom: string | null, dateTo: string | null) => Record<string, string>
chartSeries: (queryResults: _MetricSeriesApi[]) => MetricsChartSeries[]
hasResults: (queryResults: _MetricSeriesApi[]) => boolean
@@ -362,8 +391,8 @@ export type metricsViewerLogicType = MakeLogicType<
export const metricsViewerLogic = kea<metricsViewerLogicType>([
path(['products', 'metrics', 'frontend', 'components', 'metricsViewerLogic']),
connect(() => ({
- values: [teamLogic, ['currentTeamId'], metricNamePickerLogic, ['items']],
- actions: [metricNamePickerLogic, ['loadItemsSuccess']],
+ values: [teamLogic, ['currentTeamId'], metricNamePickerLogic, ['items', 'services as pickerServices']],
+ actions: [metricNamePickerLogic, ['loadItemsSuccess', 'setServices']],
})),
actions({
setMetricName: (metricName: string) => ({ metricName }),
@@ -459,6 +488,15 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
],
}),
listeners(({ actions, values, cache }) => ({
+ // Narrows the metric picker to the filtered services, so it offers only the
+ // metrics they report. `setFilterGroup` is the one action that changes the
+ // chips, and the scope is compared before pushing so editing an unrelated
+ // chip does not refetch the list.
+ setFilterGroup: () => {
+ if (!objectsEqual(values.selectedServices, values.pickerServices)) {
+ actions.setServices(values.selectedServices)
+ }
+ },
setMetricName: ({ metricName }) => {
const metricType = values.items.find((item) => item.name === metricName.trim())?.metric_type
actions.setSelectedMetricType(toKnownMetricType(metricType))
@@ -727,6 +765,22 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
.map(propertyFilterToMetricFilter)
.filter((f): f is _MetricFilterApi => f !== null),
],
+ // Services the metric picker is narrowed to, so it only offers metrics the
+ // filtered services actually report. Empty means "every service".
+ selectedServices: [
+ (s) => [s.filterGroup],
+ (filterGroup: UniversalFiltersGroup): string[] => {
+ const chips = flattenFilterValues(filterGroup).filter(
+ (filter) => 'key' in filter && filter.key === SERVICE_NAME_KEY
+ )
+ // Two service chips are ANDed, which no single IN list expresses, so
+ // the picker stays unscoped rather than guessing at the intersection.
+ if (chips.length !== 1) {
+ return []
+ }
+ return serviceChipValues(chips[0])
+ },
+ ],
// Scopes the filter bar's key/value suggestions to the viewer's window; splatted onto the
// taxonomic endpoints as query params.
attributeEndpointFilters: [
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index da0eb23b3fdd..e00fd6a82003 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -814,6 +814,11 @@ export type MetricsValuesRetrieveParams = {
* @maximum 1000
*/
limit?: number
+ /**
+ * Comma-separated services to narrow the list to, e.g. `service=web,worker`. Omit for every service. Send it empty to select only series whose sender did not set `service.name`. A service name containing a comma cannot be selected.
+ * @maxLength 1024
+ */
+ service?: string
/**
* Substring filter (case-insensitive) applied to metric names.
* @maxLength 255
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a1ec35e17394..a16c7dacd63f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -93790,6 +93790,11 @@ export namespace Schemas {
* @maximum 1000
*/
limit?: number;
+ /**
+ * Comma-separated services to narrow the list to, e.g. `service=web,worker`. Omit for every service. Send it empty to select only series whose sender did not set `service.name`. A service name containing a comma cannot be selected.
+ * @maxLength 1024
+ */
+ service?: string;
/**
* Substring filter (case-insensitive) applied to metric names.
* @maxLength 255
diff --git a/services/mcp/src/generated/metrics/api.ts b/services/mcp/src/generated/metrics/api.ts
index a063a9d3b146..e90e80f41d61 100644
--- a/services/mcp/src/generated/metrics/api.ts
+++ b/services/mcp/src/generated/metrics/api.ts
@@ -397,6 +397,8 @@ export const MetricsValuesRetrieveParams = /* @__PURE__ */ zod.object({
export const metricsValuesRetrieveQueryLimitDefault = 100
export const metricsValuesRetrieveQueryLimitMax = 1000
+export const metricsValuesRetrieveQueryServiceMax = 1024
+
export const metricsValuesRetrieveQueryValueDefault = ``
export const metricsValuesRetrieveQueryValueMax = 255
@@ -407,6 +409,13 @@ export const MetricsValuesRetrieveQueryParams = /* @__PURE__ */ zod.object({
.max(metricsValuesRetrieveQueryLimitMax)
.default(metricsValuesRetrieveQueryLimitDefault)
.describe('Max number of names to return. Defaults to 100; maximum 1000.'),
+ service: zod
+ .string()
+ .max(metricsValuesRetrieveQueryServiceMax)
+ .optional()
+ .describe(
+ 'Comma-separated services to narrow the list to, e.g. `service=web,worker`. Omit for every service. Send it empty to select only series whose sender did not set `service.name`. A service name containing a comma cannot be selected.'
+ ),
value: zod
.string()
.max(metricsValuesRetrieveQueryValueMax)
diff --git a/services/mcp/src/tools/generated/metrics.ts b/services/mcp/src/tools/generated/metrics.ts
index 72403997d411..8488a41cca8f 100644
--- a/services/mcp/src/tools/generated/metrics.ts
+++ b/services/mcp/src/tools/generated/metrics.ts
@@ -45,6 +45,7 @@ const metricNamesList = (): ToolBase<typeof MetricNamesListSchema, Schemas._Metr
path: `/api/projects/${encodeURIComponent(String(projectId))}/metrics/values/`,
query: {
limit: params.limit,
+ service: params.service,
value: params.value,
},
})