: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
perf(metrics): filter metric names locally and load them in one query (#113908)
Frank Hamand7989ebac64a5
diff --git a/posthog/hogql/database/schema/metrics.py b/posthog/hogql/database/schema/metrics.pyindex 8062d9772a78..924f3d3093fa 100644--- a/posthog/hogql/database/schema/metrics.py+++ b/posthog/hogql/database/schema/metrics.py@@ -227,6 +227,16 @@ class MetricNamesTable(Table):"service_name": StringDatabaseField(name="service_name", nullable=False, description="Name of the service that emitted the metric."),+ "metric_types": StringArrayDatabaseField(+ name="metric_types",+ nullable=False,+ description="Every OTel metric type (gauge, sum, histogram, summary, exponential_histogram) the service sent the name as in that hour. Empty on rows written before types were recorded.",+ ),+ "metric_type": StringDatabaseField(+ name="metric_type",+ nullable=False,+ description="The first entry of `metric_types`, or empty. A name sent as more than one type in the hour has only one of them here, so filter on `metric_types` to find every type.",+ ),}def to_printed_clickhouse(self, context):diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex f49789cfea54..bdfb0317e763 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -398,15 +398,8 @@ def list_metric_picker_names(limit: int = 100,services: Sequence[str] = (),) -> list[dict[str, Any]]:- """List current metric names for the viewer picker without sparklines or caching."""- rows = MetricNamesQueryRunner(- team=team,- search=search,- limit=limit,- services=services,- include_sparklines=False,- ).run()- return [{"name": row["name"], "metric_type": row["metric_type"]} for row in rows]+ """List current metric names and types for the viewer picker, without sparklines or caching."""+ return MetricNamesQueryRunner(team=team, search=search, limit=limit, services=services).run_picker()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.pyindex 2bc9b160d6fc..809e65a18c11 100644--- a/products/metrics/backend/metric_names_query_runner.py+++ b/products/metrics/backend/metric_names_query_runner.py@@ -13,6 +13,7 @@ from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.database.schema.metrics import HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIESfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_query+from posthog.hogql.visitor import clone_exprfrom posthog.clickhouse.client.connection import Workloadfrom posthog.models import Team@@ -90,14 +91,16 @@ class MetricNamesQueryRunner:right=ast.Tuple(exprs=[ast.Constant(value=service) for service in self.services]),)- def _build_query(self) -> ast.SelectQuery:+ def _names_query(self) -> ast.SelectQuery:if not self.search:# A separate query, because ClickHouse reads a constant sort key as a column position.query = parse_select("""SELECT- metric_name AS name,- uniqExact(service_name) AS matching_services+ metric_name,+ uniqExact(service_name) AS matching_services,+ -- Rows written before the names table had a type read ''.+ anyIf(metric_type, metric_type != '') AS name_metric_typeFROM posthog.metric_namesWHERE time_bucket >= {lookback_start}GROUP BY metric_name@@ -112,8 +115,10 @@ class MetricNamesQueryRunner:query = parse_select("""SELECT- metric_name AS name,- uniqExact(service_name) AS matching_services+ metric_name,+ uniqExact(service_name) AS matching_services,+ -- Rows written before the names table had a type read ''.+ anyIf(metric_type, metric_type != '') AS name_metric_typeFROM posthog.metric_namesWHERE time_bucket >= {lookback_start}AND metric_name ILIKE {search_pattern}@@ -152,31 +157,61 @@ class MetricNamesQueryRunner:query.where = ast.And(exprs=[query.where, self._services_expr()])return query- def _details_query(self, names: Sequence[str]) -> ast.SelectQuery:+ def _build_query(self) -> ast.SelectQuery:+ # One round trip: the names pick the page, and the series join adds type, unit and last seen.+ names_query = self._names_query()# Not aliased `last_seen`: HogQL would resolve the WHERE's `last_seen` to the aggregate.query = parse_select("""SELECT- metric_name AS name,- any(metric_type) AS metric_type,- any(unit) AS unit,- max(last_seen) AS last_seen_at- FROM posthog.metric_series- WHERE last_seen >= {lookback_start}- AND metric_name IN {names}- GROUP BY metric_name+ names.metric_name AS name,+ details.metric_type AS metric_type,+ details.unit AS unit,+ if(details.matched = 1, details.last_seen_at, NULL) AS last_seen_at+ FROM {names} AS names+ LEFT JOIN (+ SELECT+ metric_name AS series_metric_name,+ -- An unmatched row reads 0 here, even for a metric named ''.+ 1 AS matched,+ any(metric_type) AS metric_type,+ any(unit) AS unit,+ max(last_seen) AS last_seen_at+ FROM posthog.metric_series+ WHERE last_seen >= {lookback_start}+ AND metric_name IN (SELECT metric_name FROM {page_names})+ GROUP BY metric_name+ ) AS details ON details.series_metric_name = names.metric_name""",placeholders={+ "names": names_query,+ "page_names": clone_expr(names_query),"lookback_start": self._lookback_start(),- "names": ast.Tuple(exprs=[ast.Constant(value=name) for name in names]),},)assert isinstance(query, ast.SelectQuery)- assert query.where is not Noneif self.services:- query.where = ast.And(exprs=[query.where, self._services_expr()])+ assert query.select_from is not None and query.select_from.next_join is not None+ details = query.select_from.next_join.table+ assert isinstance(details, ast.SelectQuery) and details.where is not None+ details.where = ast.And(exprs=[details.where, self._services_expr()])+ # A join does not keep the page order, so the outer query sorts by the same keys.+ query.order_by = [clone_expr(order) for order in names_query.order_by or []]+ # Without its own LIMIT, the outer query gets the HogQL default and cuts a larger page.+ query.limit = clone_expr(names_query.limit) if names_query.limit else Nonereturn query+ def run_picker(self) -> list[dict[str, str]]:+ """Names and types only. Reads `metric_names` alone, which is much smaller than `metric_series`."""+ response = execute_hogql_query(+ query_type="MetricNamesQuery",+ query=self._names_query(),+ team=self.team,+ workload=Workload.LOGS,+ settings=_SPARKLINE_QUERY_SETTINGS if self.names else _QUERY_SETTINGS,+ )+ return [{"name": name, "metric_type": metric_type} for name, _services, metric_type in response.results]+def run(self) -> list[dict[str, Any]]:settings = _SPARKLINE_QUERY_SETTINGS if self.names else _QUERY_SETTINGSresponse = execute_hogql_query(@@ -186,33 +221,22 @@ class MetricNamesQueryRunner:workload=Workload.LOGS,settings=settings,)- names = [row[0] for row in response.results]- if not names:+ if not response.results:return []- details_response = execute_hogql_query(- query_type="MetricNamesDetailsQuery",- query=self._details_query(names),- team=self.team,- workload=Workload.LOGS,- settings=settings,- )- details = {row[0]: row[1:] for row in details_response.results}+ names = [row[0] for row in response.results]sparklines = self._sparklines(names) if self.include_sparklines else {}- rows = []- for name in names:- metric_type, unit, last_seen = details.get(name, ("", "", None))- rows.append(- {- "name": name,- "metric_type": metric_type,- "unit": unit,- "last_seen": _isoformat(last_seen),- "sparkline": sparklines.get(name, []),- }- )- return rows+ return [+ {+ "name": name,+ "metric_type": metric_type or "",+ "unit": unit or "",+ "last_seen": _isoformat(last_seen),+ "sparkline": sparklines.get(name, []),+ }+ for name, metric_type, unit, last_seen in response.results+ ]def _sparklines(self, names: Sequence[str]) -> dict[str, list[float]]:if not names:@@ -253,6 +277,9 @@ class MetricNamesQueryRunner:},)assert isinstance(query, ast.SelectQuery)+ # One row per name and bucket. Without an explicit LIMIT, the HogQL default cuts the batch after a few names.+ # The extra bucket covers a point on the window's end.+ query.limit = ast.Constant(value=len(names) * (SPARKLINE_MAX_POINTS + 1))response = execute_hogql_query(query_type="MetricNamesSparklineQuery",diff --git a/products/metrics/backend/tests/test_metric_names_query_runner.py b/products/metrics/backend/tests/test_metric_names_query_runner.pyindex a310d0f55432..aaa3f1e1ecb8 100644--- a/products/metrics/backend/tests/test_metric_names_query_runner.py+++ b/products/metrics/backend/tests/test_metric_names_query_runner.py@@ -9,6 +9,10 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client import sync_execute+from products.metrics.backend.facade.api import list_metric_picker_namesfrom products.metrics.backend.facade.contracts import MAX_SPARKLINE_BATCH_SIZEfrom products.metrics.backend.metric_names_query_runner import (@@ -158,11 +162,11 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(run.call_count, 4)def test_picker_names_do_not_cache(self):- with patch.object(MetricNamesQueryRunner, "run") as run:- run.return_value = [{"name": "m1", "metric_type": "gauge"}]- self.assertEqual(list_metric_picker_names(team=self.team), run.return_value)- self.assertEqual(list_metric_picker_names(team=self.team), run.return_value)- self.assertEqual(run.call_count, 2)+ with patch.object(MetricNamesQueryRunner, "run_picker") as run_picker:+ run_picker.return_value = [{"name": "m1", "metric_type": "gauge"}]+ self.assertEqual(list_metric_picker_names(team=self.team), run_picker.return_value)+ self.assertEqual(list_metric_picker_names(team=self.team), run_picker.return_value)+ self.assertEqual(run_picker.call_count, 2)def test_exact_match_floats_to_top(self):anchor = timezone.now().replace(microsecond=0)@@ -312,9 +316,14 @@ class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)_seed_point(team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor)- response = self.client.get(f"/api/projects/{self.team.id}/metrics/names/")+ with patch(+ "products.metrics.backend.metric_names_query_runner.execute_hogql_query", wraps=execute_hogql_query+ ) as execute:+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/names/")self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json(), {"results": [{"name": "m1", "metric_type": "gauge"}]})+ self.assertEqual(execute.call_count, 1)+ self.assertNotIn("metric_series", str(execute.call_args.kwargs["query"]))def test_values_search_param(self):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)@@ -442,6 +451,26 @@ class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertGreater(len(sparkline), 1)self.assertLess(sparkline[0], sparkline[-1])+ def test_catalog_page_is_not_cut_at_the_default_query_limit(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ for i in range(101):+ _seed_point(team_id=self.team.id, metric_name=f"m{i:03d}", value=1.0, timestamp=anchor)++ rows = MetricNamesQueryRunner(team=self.team, limit=150, include_sparklines=False).run()++ self.assertEqual(len(rows), 101)++ def test_every_name_in_a_batch_gets_a_sparkline(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(hours=6)+ names = [f"busy.{i:02d}" for i in range(MAX_SPARKLINE_BATCH_SIZE)]+ for name in names:+ points = [(anchor + dt.timedelta(minutes=15 * i + 1), float(i)) for i in range(24)]+ seed_metric_event(team_id=self.team.id, metric_name=name, points=points, metric_type="gauge")++ rows = MetricNamesQueryRunner(team=self.team, names=names).run()++ self.assertEqual({row["name"]: len(row["sparkline"]) > 1 for row in rows}, dict.fromkeys(names, True))+def test_sparkline_is_bounded(self):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=120)points = [(anchor + dt.timedelta(minutes=i), float(i % 7)) for i in range(120)]@@ -531,11 +560,20 @@ class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):_seed_point(team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor)with patch("products.metrics.backend.metric_names_query_runner.execute_hogql_query") as execute:- execute.side_effect = [- MagicMock(results=[("m1", 1)]),- MagicMock(results=[("m1", "gauge", "", timezone.now())]),- ]+ execute.return_value = MagicMock(results=[("m1", "gauge", "", timezone.now())])rows = MetricNamesQueryRunner(team=self.team, include_sparklines=False).run()- self.assertEqual(execute.call_count, 2)+ self.assertEqual(execute.call_count, 1)self.assertEqual(rows[0]["sparkline"], [])++ def test_name_without_a_series_row_keeps_empty_details(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ _seed_point(team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor)+ sync_execute("TRUNCATE TABLE IF EXISTS metrics4_series")++ rows = MetricNamesQueryRunner(team=self.team, include_sparklines=False).run()++ self.assertEqual(+ [(row["name"], row["metric_type"], row["unit"], row["last_seen"]) for row in rows],+ [("m1", "", "", None)],+ )diff --git a/products/metrics/frontend/components/MetricNameFilter.tsx b/products/metrics/frontend/components/MetricNameFilter.tsxindex 0ba4d63c3096..46df1fe93aef 100644--- a/products/metrics/frontend/components/MetricNameFilter.tsx+++ b/products/metrics/frontend/components/MetricNameFilter.tsx@@ -3,7 +3,7 @@ import { CSSProperties, useCallback, useMemo } from 'react'import { List } from 'react-window'import { IconChevronDown } from '@posthog/icons'-import { LemonButton, LemonDropdown, LemonInput } from '@posthog/lemon-ui'+import { LemonButton, LemonDropdown, LemonInput, Spinner } from '@posthog/lemon-ui'import { metricNamePickerLogic } from './metricNamePickerLogic'@@ -88,14 +88,9 @@ function MetricNameFilterInner({disabled?: booleandisabledReason?: string | null}): JSX.Element {- const { items: pickerItems, itemsLoading, search } = useValues(metricNamePickerLogic)- const { setSearch } = useActions(metricNamePickerLogic)-- // The list holds one entry per name and type, and the type is not shown.- const items = useMemo(- () => pickerItems.filter((item, index) => pickerItems.findIndex((other) => other.name === item.name) === index),- [pickerItems]- )+ const { items, filteredItems, fullItemsLoading, searchedItemsLoading, scopeLoading, search } =+ useValues(metricNamePickerLogic)+ const { setSearch, openPicker } = useActions(metricNamePickerLogic)const onPick = useCallback((name: string) => {@@ -106,18 +101,22 @@ function MetricNameFilterInner({[value, onChange])- const rowProps = useMemo<OptionRowData>(() => ({ items, selected: value, onPick }), [items, value, onPick])+ const rowProps = useMemo<OptionRowData>(+ () => ({ items: filteredItems, selected: value, onPick }),+ [filteredItems, value, onPick]+ )const listHeight = useMemo(() => {- const height = items.length * ROW_HEIGHT+ const height = filteredItems.length * ROW_HEIGHTreturn Math.min(height, MAX_DROPDOWN_HEIGHT)- }, [items.length])+ }, [filteredItems.length])const triggerLabel = value || placeholderreturn (<LemonDropdowncloseOnClickInside+ onVisibilityChange={(visible) => visible && openPicker()}overlay={<div className="space-y-px p-1"><div className="px-1 pb-1">@@ -128,19 +127,26 @@ function MetricNameFilterInner({fullWidthvalue={search}onChange={(val) => setSearch(val)}+ suffix={+ searchedItemsLoading && search && filteredItems.length > 0 ? (+ <Spinner textColored />+ ) : null+ }autoFocus/></div>- {itemsLoading && items.length === 0 ? (- <div className="p-2 text-muted text-center text-xs">Loading metrics…</div>- ) : items.length === 0 ? (+ {(fullItemsLoading || searchedItemsLoading) && filteredItems.length === 0 ? (+ <div className="p-2 text-muted text-center text-xs">+ {search && !scopeLoading ? 'Searching…' : 'Loading metrics…'}+ </div>+ ) : filteredItems.length === 0 ? (<div className="p-2 text-muted text-center text-xs">{search ? 'No metrics match this search.' : 'No metrics ingested in the last 24 hours.'}</div>) : (<List<OptionRowData>style={{ width: DROPDOWN_WIDTH, height: listHeight }}- rowCount={items.length}+ rowCount={filteredItems.length}rowHeight={ROW_HEIGHT}overscanCount={5}rowComponent={MetricOptionRow}@@ -155,7 +161,7 @@ function MetricNameFilterInner({type="secondary"size="small"sideIcon={<IconChevronDown />}- loading={itemsLoading && !value}+ loading={fullItemsLoading && !value && (items.length === 0 || scopeLoading)}disabled={disabled}disabledReason={disabledReason}>diff --git a/products/metrics/frontend/components/metricNamePickerLogic.test.ts b/products/metrics/frontend/components/metricNamePickerLogic.test.tsnew file mode 100644index 000000000000..55e137e7eaf2--- /dev/null+++ b/products/metrics/frontend/components/metricNamePickerLogic.test.ts@@ -0,0 +1,354 @@+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'++import { metricsNamesRetrieve } from '../generated/api'+import { METRIC_NAMES_LIMIT, filterMetricNames, metricNamePickerLogic } from './metricNamePickerLogic'++jest.mock('../generated/api', () => ({+ ...jest.requireActual('../generated/api'),+ metricsNamesRetrieve: jest.fn(),+}))++const deferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void; reject: (error: Error) => void } => {+ let resolve!: (value: T) => void+ let reject!: (error: Error) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+}+const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))+const fullPage = Array.from({ length: METRIC_NAMES_LIMIT }, (_, i) => ({ name: `m${i}`, metric_type: 'gauge' }))++const ITEMS = [+ { name: 'server.http', metric_type: 'sum' },+ { name: 'http.requests', metric_type: 'sum' },+ { name: 'queue.depth', metric_type: 'gauge' },+ { name: 'http', metric_type: 'gauge' },+]++describe('metricNamePickerLogic', () => {+ let logic: ReturnType<typeof metricNamePickerLogic.build>++ beforeEach(() => {+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: {+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,+ [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,+ },+ } as AppContext+ initKeaTests()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.METRICS]: true })+ jest.mocked(metricsNamesRetrieve).mockReset()+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: ITEMS } as any)+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('loads the full list on mount', async () => {+ logic = metricNamePickerLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadItemsSuccess']).toMatchValues({+ items: ITEMS,+ itemsComplete: true,+ })+ expect(metricsNamesRetrieve).toHaveBeenCalledTimes(1)+ expect(metricsNamesRetrieve).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ value: '', limit: METRIC_NAMES_LIMIT })+ )+ })++ it('filters a complete list locally without a request', async () => {+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])+ jest.mocked(metricsNamesRetrieve).mockClear()++ logic.actions.setSearch('HTTP')++ expect(logic.values.filteredItems).toEqual([ITEMS[3], ITEMS[1], ITEMS[0]])+ await expectLogic(logic).toFinishAllListeners()+ expect(metricsNamesRetrieve).not.toHaveBeenCalled()+ })++ it('searches the server when a complete list has no local match', async () => {+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess']).toMatchValues({ itemsComplete: true })++ jest.mocked(metricsNamesRetrieve).mockResolvedValueOnce({ results: [{ name: 'checkout.orders' }] } as any)+ await expectLogic(logic, () => {+ logic.actions.setSearch('checkout')+ }).toDispatchActions(['searchItemsSuccess'])++ expect(logic.values.filteredItems).toEqual([{ name: 'checkout.orders' }])+ })++ it('reloads an empty list when the picker opens', async () => {+ jest.mocked(metricsNamesRetrieve).mockResolvedValueOnce({ results: [] } as any)+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess']).toMatchValues({ items: [] })++ await expectLogic(logic, () => {+ logic.actions.openPicker()+ })+ .toDispatchActions(['loadItemsSuccess'])+ .toMatchValues({ items: ITEMS })+ expect(metricsNamesRetrieve).toHaveBeenCalledTimes(2)+ })++ it.each([+ ['a fresh list', 0, 1],+ ['a list older than a minute', 61_000, 2],+ ])('opening the picker over %s sends %i request(s)', async (_case, ageMs, requests) => {+ const now = Date.now()+ const clock = jest.spyOn(Date, 'now').mockReturnValue(now)+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])++ clock.mockReturnValue(now + ageMs)+ logic.actions.openPicker()+ await expectLogic(logic).toFinishAllListeners()++ expect(metricsNamesRetrieve).toHaveBeenCalledTimes(requests)+ clock.mockRestore()+ })++ it('ignores a failed load that a newer scope change replaced', async () => {+ const replacedLoad = deferred<any>()+ const currentLoad = deferred<any>()+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])+ jest.mocked(metricsNamesRetrieve)+ .mockReturnValueOnce(replacedLoad.promise)+ .mockReturnValueOnce(currentLoad.promise)++ logic.actions.setServices(['a'])+ logic.actions.setServices(['b'])+ replacedLoad.reject(new Error('timeout'))+ await wait(0)++ expect(logic.values.scopeLoading).toBe(true)+ currentLoad.resolve({ results: [ITEMS[2]] })+ await expectLogic(logic)+ .toDispatchActions(['loadItemsSuccess'])+ .toMatchValues({ filteredItems: [ITEMS[2]] })+ })++ it('keeps the first load running when an early search finishes', async () => {+ const firstLoad = deferred<any>()+ jest.mocked(metricsNamesRetrieve)+ .mockReturnValueOnce(firstLoad.promise)+ .mockResolvedValueOnce({ results: [] } as any)+ logic = metricNamePickerLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.setSearch('zzz')+ }).toDispatchActions(['searchItemsSuccess'])++ expect(logic.values.fullItemsLoading).toBe(true)+ firstLoad.resolve({ results: ITEMS })+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess']).toMatchValues({ items: ITEMS })+ })++ it('does not send a search that was cleared during the debounce', async () => {+ jest.mocked(metricsNamesRetrieve).mockResolvedValueOnce({ results: fullPage } as any)+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])+ jest.mocked(metricsNamesRetrieve).mockClear()++ logic.actions.setSearch('zzz')+ logic.actions.setSearch('')+ await expectLogic(logic).toFinishAllListeners()++ expect(metricsNamesRetrieve).not.toHaveBeenCalled()+ expect(logic.values.searchedItemsLoading).toBe(false)+ })++ it('searches in the background and adds new names when the list is partial', async () => {+ jest.mocked(metricsNamesRetrieve).mockResolvedValueOnce({ results: fullPage } as any)+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess']).toMatchValues({ itemsComplete: false })++ jest.mocked(metricsNamesRetrieve).mockResolvedValueOnce({+ results: [{ name: 'm1', metric_type: 'gauge' }, ITEMS[2]],+ } as any)+ await expectLogic(logic, () => {+ logic.actions.setSearch('m1')+ })+ .toMatchValues({ searchedItemsLoading: true })+ .toDispatchActions(['searchItemsSuccess'])+ .toMatchValues({ searchedItemsLoading: false })++ expect(metricsNamesRetrieve).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({ value: 'm1' })+ )+ expect(logic.values.items).toHaveLength(METRIC_NAMES_LIMIT + 1)+ expect(logic.values.items[METRIC_NAMES_LIMIT]).toEqual(ITEMS[2])+ })++ it('reloads the full list when the service scope changes', async () => {+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])++ jest.mocked(metricsNamesRetrieve).mockResolvedValueOnce({ results: [ITEMS[2]] } as any)+ await expectLogic(logic, () => {+ logic.actions.setServices(['api'])+ })+ .toMatchValues({ filteredItems: [], items: ITEMS })+ .toDispatchActions(['loadItemsSuccess'])+ .toMatchValues({ filteredItems: [ITEMS[2]], items: [ITEMS[2]] })+ expect(metricsNamesRetrieve).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({ value: '', service: 'api' })+ )+ })++ it('drops names an old-scope search found once the new scope loads', async () => {+ jest.mocked(metricsNamesRetrieve)+ .mockResolvedValueOnce({ results: fullPage } as any)+ .mockResolvedValueOnce({ results: [{ name: 'old.scope.metric' }] } as any)+ .mockResolvedValueOnce({ results: [ITEMS[2]] } as any)+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])+ await expectLogic(logic, () => {+ logic.actions.setSearch('old')+ }).toDispatchActions(['searchItemsSuccess'])+ logic.actions.setSearch('')++ await expectLogic(logic, () => {+ logic.actions.setServices(['api'])+ }).toDispatchActions(['loadItemsSuccess'])++ expect(logic.values.items).toEqual([ITEMS[2]])+ })++ it('drops old-scope names when a new-scope search finishes before the new list', async () => {+ const newScopeLoad = deferred<any>()+ jest.mocked(metricsNamesRetrieve)+ .mockResolvedValueOnce({ results: fullPage } as any)+ .mockResolvedValueOnce({ results: [{ name: 'old.scope.metric' }] } as any)+ .mockReturnValueOnce(newScopeLoad.promise)+ .mockResolvedValueOnce({ results: [] } as any)+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])+ await expectLogic(logic, () => {+ logic.actions.setSearch('old')+ }).toDispatchActions(['searchItemsSuccess'])++ logic.actions.setServices(['api'])+ await expectLogic(logic, () => {+ logic.actions.setSearch('queue')+ }).toDispatchActions(['searchItemsSuccess'])+ newScopeLoad.resolve({ results: [ITEMS[2]] })+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess']).toFinishAllListeners()++ expect(logic.values.items.map((item) => item.name)).not.toContain('old.scope.metric')+ })++ it('takes a searched name from the newest search reply', async () => {+ jest.mocked(metricsNamesRetrieve)+ .mockResolvedValueOnce({ results: fullPage } as any)+ .mockResolvedValueOnce({ results: [{ name: 'shared.x', metric_type: 'sum' }] } as any)+ .mockResolvedValueOnce({ results: [{ name: 'shared.x', metric_type: 'histogram' }] } as any)+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])++ await expectLogic(logic, () => {+ logic.actions.setSearch('shared')+ }).toDispatchActions(['searchItemsSuccess'])+ await expectLogic(logic, () => {+ logic.actions.setSearch('shared.')+ }).toDispatchActions(['searchItemsSuccess'])++ expect(logic.values.items.find((item) => item.name === 'shared.x')?.metric_type).toBe('histogram')+ })++ it('keeps names a search found in the current scope when the list reloads', async () => {+ jest.mocked(metricsNamesRetrieve)+ .mockResolvedValueOnce({ results: fullPage } as any)+ .mockResolvedValueOnce({ results: [{ name: 'found.by.search' }] } as any)+ .mockResolvedValueOnce({ results: fullPage } as any)+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])+ await expectLogic(logic, () => {+ logic.actions.setSearch('found')+ }).toDispatchActions(['searchItemsSuccess'])+ logic.actions.setSearch('')++ await expectLogic(logic, () => {+ logic.actions.loadItems()+ }).toDispatchActions(['loadItemsSuccess'])++ expect(logic.values.items.map((item) => item.name)).toContain('found.by.search')+ })++ it('shows the old list again when the new scope fails to load', async () => {+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])++ jest.mocked(metricsNamesRetrieve).mockRejectedValueOnce(new Error('timeout'))+ await expectLogic(logic, () => {+ logic.actions.setServices(['api'])+ }).toDispatchActions(['loadItemsFailure'])++ expect(logic.values.filteredItems).toEqual(ITEMS)+ })++ it('drops a search that finishes after the service scope changes', async () => {+ const oldScopeSearch = deferred<any>()+ jest.mocked(metricsNamesRetrieve)+ .mockResolvedValueOnce({ results: fullPage } as any)+ .mockReturnValueOnce(oldScopeSearch.promise)+ .mockResolvedValueOnce({ results: [ITEMS[2]] } as any)+ logic = metricNamePickerLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadItemsSuccess'])++ logic.actions.setSearch('old')+ await wait(350)+ logic.actions.setServices(['api'])+ oldScopeSearch.resolve({ results: [{ name: 'old.scope.metric' }] })++ await expectLogic(logic).toDispatchActions(['loadItemsSuccess']).toFinishAllListeners()+ expect(logic.values.items.map((item) => item.name)).not.toContain('old.scope.metric')+ })+})++describe('filterMetricNames', () => {+ it('ranks exact, then prefix, then suffix, then the server order', () => {+ expect(filterMetricNames(ITEMS, ' Http ').map((item) => item.name)).toEqual([+ 'http',+ 'http.requests',+ 'server.http',+ ])+ })++ it('returns every item for an empty search', () => {+ expect(filterMetricNames(ITEMS, '')).toBe(ITEMS)+ })+})diff --git a/products/metrics/frontend/components/metricNamePickerLogic.ts b/products/metrics/frontend/components/metricNamePickerLogic.tsindex 48159674bd84..004e0f76169f 100644--- a/products/metrics/frontend/components/metricNamePickerLogic.ts+++ b/products/metrics/frontend/components/metricNamePickerLogic.ts@@ -1,4 +1,5 @@-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'+import type { BreakPointFunction } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { FEATURE_FLAGS } from 'lib/constants'@@ -11,21 +12,56 @@ import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'export type MetricNameItem = _MetricPickerNameApi+// The API maximum. Most teams have fewer names, so one load holds the whole list+// and search filters it locally without a request.+export const METRIC_NAMES_LIMIT = 1000+const SEARCH_LIMIT = 100+// Opening the picker reloads a list older than this, so names that started reporting since show up.+const STALE_AFTER_MS = 60_000++/** Same rank as the backend search: exact, then prefix, then suffix, then server order. */+export function filterMetricNames(items: MetricNameItem[], search: string): MetricNameItem[] {+ const needle = search.trim().toLowerCase()+ if (!needle) {+ return items+ }+ const rank = (name: string): number =>+ name === needle ? 0 : name.startsWith(needle) ? 1 : name.endsWith(needle) ? 2 : 3+ return items+ .map((item) => ({ item, name: item.name.toLowerCase() }))+ .filter(({ name }) => name.includes(needle))+ .sort((a, b) => rank(a.name) - rank(b.name))+ .map(({ item }) => item)+}++function mergeMetricNames(items: MetricNameItem[], incoming: MetricNameItem[]): MetricNameItem[] {+ const known = new Set(items.map((item) => item.name))+ const added = incoming.filter((item) => !known.has(item.name))+ return added.length ? [...items, ...added] : items+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface metricNamePickerLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogiccurrentTeamId: number | null // teamLogic+ filteredItems: MetricNameItem[]+ fullItems: MetricNameItem[]+ fullItemsLoading: booleanitems: MetricNameItem[]- itemsLoading: boolean+ itemsComplete: boolean+ scopeLoading: booleansearch: string+ searchedItems: MetricNameItem[]+ searchedItemsLoading: booleanservices: string[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface metricNamePickerLogicActions {- loadItems: ({ debounce }: { debounce: boolean }) => {- debounce: boolean+ dropSearchedItems: (names: string[]) => {+ names: string[]}+ loadItems: (_: void) => voidloadItemsFailure: (error: string,errorObject?: any@@ -34,19 +70,33 @@ export interface metricNamePickerLogicActions {errorObject?: any}loadItemsSuccess: (- items: _MetricPickerNameApi[],- payload?: {- debounce: boolean- }+ fullItems: _MetricPickerNameApi[],+ payload?: void) => {- items: _MetricPickerNameApi[]- payload?: {- debounce: boolean- }+ fullItems: _MetricPickerNameApi[]+ payload?: void+ }+ openPicker: () => {+ value: true}primeItems: () => {value: true}+ searchItems: (_: void) => void+ searchItemsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ searchItemsSuccess: (+ searchedItems: _MetricPickerNameApi[],+ payload?: void+ ) => {+ searchedItems: _MetricPickerNameApi[]+ payload?: void+ }setSearch: (search: string) => {search: string}@@ -55,7 +105,20 @@ export interface metricNamePickerLogicActions {}}-export type metricNamePickerLogicType = MakeLogicType<metricNamePickerLogicValues, metricNamePickerLogicActions>+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricNamePickerLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ items: (fullItems: _MetricPickerNameApi[], searchedItems: _MetricPickerNameApi[]) => MetricNameItem[]+ filteredItems: (items: _MetricPickerNameApi[], search: string, scopeLoading: boolean) => MetricNameItem[]+ }+}++export type metricNamePickerLogicType = MakeLogicType<+ metricNamePickerLogicValues,+ metricNamePickerLogicActions,+ Record<string, any>,+ metricNamePickerLogicMeta+>export const metricNamePickerLogic = kea<metricNamePickerLogicType>([path(['products', 'metrics', 'frontend', 'components', 'metricNamePickerLogic']),@@ -66,6 +129,8 @@ export const metricNamePickerLogic = kea<metricNamePickerLogicType>([// Loads the list once per mount. The scene gate calls it again after the feature preview is on,// because the scene logic mounts this logic before the gate renders.primeItems: true,+ openPicker: true,+ dropSearchedItems: (names: string[]) => ({ names }),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.@@ -74,49 +139,143 @@ export const metricNamePickerLogic = kea<metricNamePickerLogicType>([reducers({search: ['' as string, { setSearch: (_, { search }) => search }],services: [[] as string[], { setServices: (_, { services }) => services }],- }),- loaders(({ values }) => ({- items: [- [] as MetricNameItem[],+ // True when the full load fit under the limit: then local filtering sees+ // every name in the scope, and a search with local matches needs no request.+ itemsComplete: [+ false,{- loadItems: async ({ debounce }: { debounce: boolean }, breakpoint) => {- if (!canViewMetrics()) {- return []- }- // Keystrokes only — matches the 300ms cadence used in the viewer- // logic. The afterMount prime blocks first paint, so debouncing it- // is dead time on every scene load.- if (debounce) {+ setServices: () => false,+ loadItemsSuccess: (_, { fullItems }) => fullItems.length < METRIC_NAMES_LIMIT,+ },+ ],+ }),+ loaders(({ values, cache }) => {+ const fetchNames = async (+ search: string,+ limit: number,+ breakpoint: BreakPointFunction+ ): Promise<{ results: MetricNameItem[] }> => {+ try {+ return await metricsNamesRetrieve(String(values.currentTeamId), {+ value: search,+ limit,+ // 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(',') } : {}),+ })+ } finally {+ // Also on a failure: a request a newer call replaced must not end that call's loading state.+ breakpoint()+ }+ }+ return {+ // The full list for the current scope.+ fullItems: [+ [] as MetricNameItem[],+ {+ loadItems: async (_: void, breakpoint) => {+ if (!canViewMetrics()) {+ return []+ }+ const response = await fetchNames('', METRIC_NAMES_LIMIT, breakpoint)+ return response.results+ },+ },+ ],+ // Names a server search found past the full list. Kept apart from the full list, so a+ // search never ends the full load's loading state or replaces its names.+ searchedItems: [+ [] as MetricNameItem[],+ {+ // Runs on every search change, so a newer call cancels a pending one even when it sends nothing.+ searchItems: async (_: void, breakpoint) => {+ const search = values.search.trim()+ if (!canViewMetrics() || !search || (values.itemsComplete && values.filteredItems.length > 0)) {+ return values.searchedItems+ }+ // Keystrokes only — matches the 300ms cadence used in the viewer logic.await breakpoint(300)- }- const response = await metricsNamesRetrieve(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+ const services = values.services+ const response = await fetchNames(search, SEARCH_LIMIT, breakpoint)+ // A scope change while this ran cleared the list; old-scope names must not join it.+ if (services !== values.services) {+ return values.searchedItems+ }+ // Per name: a later search can find old-scope names again in the new scope.+ cache.searchScopes ??= new Map<string, string[]>()+ for (const item of response.results) {+ cache.searchScopes.set(item.name, services)+ }+ // The newest reply replaces older entries, so a name keeps its type in the current scope.+ const replied = new Set(response.results.map((item) => item.name))+ return mergeMetricNames(+ values.searchedItems.filter((item) => !replied.has(item.name)),+ response.results+ )+ },},+ ],+ }+ }),+ reducers({+ searchedItems: {+ dropSearchedItems: (state, { names }) => {+ const dropped = new Set(names)+ return state.filter((item) => !dropped.has(item.name))},+ },+ // The old scope's names stay in `items` until the new list arrives, so the viewer can still+ // read the type of a name picked as the scope changes. The dropdown hides them meanwhile.+ scopeLoading: [+ false,+ { setServices: () => true, loadItemsSuccess: () => false, loadItemsFailure: () => false },],- })),- listeners(({ actions, cache }) => ({+ }),+ selectors({+ items: [+ (s) => [s.fullItems, s.searchedItems],+ (fullItems: MetricNameItem[], searchedItems: MetricNameItem[]): MetricNameItem[] =>+ mergeMetricNames(fullItems, searchedItems),+ ],+ filteredItems: [+ (s) => [s.items, s.search, s.scopeLoading],+ (items: MetricNameItem[], search: string, scopeLoading: boolean): MetricNameItem[] =>+ scopeLoading ? [] : filterMetricNames(items, search),+ ],+ }),+ listeners(({ actions, values, cache }) => ({primeItems: () => {if (cache.primed || !canViewMetrics()) {return}cache.primed = true- actions.loadItems({ debounce: false })+ actions.loadItems()+ },+ openPicker: () => {+ const stale = !cache.loadedAt || Date.now() - cache.loadedAt > STALE_AFTER_MS+ if (cache.primed && !values.fullItemsLoading && (stale || values.fullItems.length === 0)) {+ actions.loadItems()+ }},setSearch: () => {- actions.loadItems({ debounce: true })+ actions.searchItems()},// Not debounced: the scope changes on a click, not a keystroke.setServices: () => {- actions.loadItems({ debounce: false })+ actions.loadItems()+ },+ loadItemsSuccess: () => {+ cache.loadedAt = Date.now()+ const stale = values.searchedItems+ .map((item) => item.name)+ .filter((name) => cache.searchScopes?.get(name) !== values.services)+ if (stale.length) {+ actions.dropSearchedItems(stale)+ }+ if (values.search.trim()) {+ actions.searchItems()+ }},})),afterMount(({ actions, values }) => {diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex ce6f78902784..755f8aaaa6cb 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -512,6 +512,16 @@ describe('metricsViewerLogic', () => {expect(logic.values.metricsQueryNode?.clauses[0].metricType).toBe('gauge')})+ it.each([+ ['from the full list', 'request_duration'],+ ['from a server search', 'checkout_latency'],+ ])('keeps the type of a metric picked %s while the service scope reloads', (_source, metricName) => {+ metricNamePickerLogic.actions.searchItemsSuccess([{ name: 'checkout_latency', metric_type: 'histogram' }])+ metricNamePickerLogic.actions.setServices(['web'])+ logic.actions.setMetricName(metricName)+ expect(logic.values.selectedMetricType).toBe('histogram')+ })+it('backfills the metric type when the picker loads after the metric was set', () => {metricNamePickerLogic.actions.loadItemsSuccess([])logic.actions.setMetricName('queue_depth')@@ -902,7 +912,7 @@ describe('metricsViewerLogic', () => {jest.mocked(metricsNamesRetrieve).mockClear()await expectLogic(metricNamePickerLogic, () => {- metricNamePickerLogic.actions.loadItems({ debounce: true })+ metricNamePickerLogic.actions.loadItems()}).toDispatchActions(['loadItemsSuccess'])logic.actions.setMetricName('queue_depth')diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex 722cedebe5ba..6a021b2fa331 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -527,17 +527,18 @@ export interface metricsViewerLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface metricsViewerLogicActions {loadItemsSuccess: (- items: _MetricPickerNameApi[],- payload?:- | {- debounce: boolean- }- | undefined+ fullItems: _MetricPickerNameApi[],+ payload?: void | undefined) => {- items: _MetricPickerNameApi[]- payload?: {- debounce: boolean- }+ fullItems: _MetricPickerNameApi[]+ payload?: void | undefined+ } // metricNamePickerLogic+ searchItemsSuccess: (+ searchedItems: _MetricPickerNameApi[],+ payload?: void | undefined+ ) => {+ payload?: void | undefined+ searchedItems: _MetricPickerNameApi[]} // metricNamePickerLogicsetServices: (services: string[]) => {services: string[]@@ -859,7 +860,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([metricNamePickerLogic,['items', 'services as pickerServices'],],- actions: [metricNamePickerLogic, ['loadItemsSuccess', 'setServices']],+ actions: [metricNamePickerLogic, ['loadItemsSuccess', 'searchItemsSuccess', 'setServices']],})),actions({// The single-clause setters target the active clause, so everything that@@ -1283,6 +1284,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([}},loadItemsSuccess: backfillClauseTypes,+ searchItemsSuccess: backfillClauseTypes,// A URL restore replaces every clause at once and never ran the pick-time// latch, so it needs the same backfill against whatever the picker has.setClauses: () => {