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.

perf(metrics): read the name picker from metric_series (#87077)

Frank Hamandba38cffb7039
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index dd75b2ae5db5..a5f7d077b7f5 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -36,7 +36,7 @@ from products.metrics.backend.metric_attributes_query_runner import (
MetricAttributeValuesQueryRunner,
)
from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunner
-from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner
+from products.metrics.backend.metric_names_query_runner import cached_metric_names
from products.metrics.backend.metric_query_runner import MetricQueryRunner
# MetricQueryRunner still speaks the legacy aggregation strings; this shrinks
@@ -222,9 +222,10 @@ def list_metric_names(
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.
+
+ The unsearched list is cached per team for a minute; searches are not.
"""
- runner = MetricNamesQueryRunner(team=team, search=search, limit=limit)
- return runner.run()
+ return cached_metric_names(team=team, search=search, limit=limit)
def list_metric_attribute_keys(
diff --git a/products/metrics/backend/metric_attributes_query_runner.py b/products/metrics/backend/metric_attributes_query_runner.py
index 609ebaf0cc54..ba52cf45b568 100644
--- a/products/metrics/backend/metric_attributes_query_runner.py
+++ b/products/metrics/backend/metric_attributes_query_runner.py
@@ -19,6 +19,8 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
from posthog.models import Team
+from products.metrics.backend.search import ilike_pattern
+
# The OTel service name is a first-class column on `metric_attributes` (extracted
# at ingest), never an attribute row — both spellings resolve to it, mirroring
# `metric_query_runner.attribute_field`.
@@ -41,12 +43,6 @@ _QUERY_SETTINGS = HogQLGlobalSettings(
)
-def _ilike_pattern(search: str) -> str:
- """Escape ILIKE metacharacters so a literal '%'/'_' in the search doesn't wildcard."""
- escaped = search.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
- return f"%{escaped}%"
-
-
def _resolve_window(date_from: dt.datetime | None, date_to: dt.datetime | None) -> tuple[dt.datetime, dt.datetime]:
resolved_to = date_to or dt.datetime.now(dt.UTC)
resolved_from = date_from or (resolved_to - _DEFAULT_LOOKBACK)
@@ -99,7 +95,7 @@ class MetricAttributeKeysQueryRunner:
placeholders={
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
- "search_pattern": ast.Constant(value=_ilike_pattern(self.search)),
+ "search_pattern": ast.Constant(value=ilike_pattern(self.search)),
"exact": ast.Constant(value=self.search),
"limit": ast.Constant(value=self.limit),
},
@@ -203,7 +199,7 @@ class MetricAttributeValuesQueryRunner:
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
"key": ast.Constant(value=self.key),
- "search_pattern": ast.Constant(value=_ilike_pattern(self.search)),
+ "search_pattern": ast.Constant(value=ilike_pattern(self.search)),
"exact": ast.Constant(value=self.search),
"limit": ast.Constant(value=self.limit),
}
diff --git a/products/metrics/backend/metric_names_query_runner.py b/products/metrics/backend/metric_names_query_runner.py
index f3f10ce5e093..d283877a083a 100644
--- a/products/metrics/backend/metric_names_query_runner.py
+++ b/products/metrics/backend/metric_names_query_runner.py
@@ -1,10 +1,18 @@
"""Distinct metric names for a team's picker UI.
-Queries `posthog.metrics` directly rather than `metric_attributes`: `metric_name`
-is a top-level column on the source table with a `set(100)` skip index
-(`idx_metric_name_set`) purpose-built for this lookup. Materialising it into
-the attributes table would require a new MV with negligible upside given the
-cardinality (10s — low 100s of distinct names per team).
+Reads `metric_series` (one row per metric + label-set) rather than the raw
+`metrics` datapoint table. Both are fed from the same Kafka Avro stream, so
+they carry the same names, but the series table is two orders of magnitude
+smaller for the same window — on a busy team, ~3.6M rows against ~800M. It also
+sorts by `(team_id, metric_name, series_fingerprint)`, so `metric_name` is the
+leading key once `team_id` is pinned, where `metrics1` buries it behind
+`time_bucket` and `service_name`.
+
+No FINAL. ReplacingMergeTree duplicates share `(team_id, metric_name,
+series_fingerprint)`, and `max(last_seen)` picks the row FINAL would keep, since
+`last_seen` is the engine's version column. `metric_type` is an input to the
+fingerprint (see `rust/capture-logs/src/metric_record.rs`), so every duplicate
+of one fingerprint agrees on it and `any()` cannot return a stale type.
Surfaces `metric_type` alongside the name so the viewer can hint at the
type-appropriate default aggregation (gauge -> avg, counter/sum -> sum, etc.)
@@ -14,13 +22,34 @@ without a second round-trip.
import datetime as dt
from typing import Any
+from django.core.cache import cache
+
from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.database.schema.metrics import HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
from posthog.models import Team
+from products.metrics.backend.search import ilike_pattern
+
+# Autocomplete tolerates partial results, so reads break at the budget instead
+# of erroring the way the chart queries do. Mirrors MetricAttributeKeysQueryRunner.
+_QUERY_SETTINGS = HogQLGlobalSettings(
+ max_bytes_to_read=HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES,
+ read_overflow_mode="break",
+)
+
+# `metric_series` drops rows 90 days past `last_seen`; `metrics1` has no TTL.
+# A lookback beyond this would quietly return fewer names than the raw table has.
+SERIES_RETENTION = dt.timedelta(days=90)
+
+# Short enough that a new metric shows up while someone is still wiring it up,
+# long enough to absorb the burst of mounts a team generates in a working session.
+METRIC_NAMES_CACHE_TTL = 60
+
class MetricNamesQueryRunner:
def __init__(
@@ -41,42 +70,91 @@ class MetricNamesQueryRunner:
self.limit = limit
self.lookback = lookback
- def run(self) -> list[dict[str, Any]]:
- # ILIKE on metric_name uses the bloom filter side of the skip index;
- # any() on metric_type collapses to the single canonical type per
- # name (a metric name shouldn't change type — if it does, we get the
- # most-recent answer ClickHouse picks, which is fine for a picker).
- query = parse_select(
- """
- SELECT
- metric_name AS name,
- any(metric_type) AS metric_type,
- max(timestamp) AS last_seen
- FROM posthog.metrics
- WHERE timestamp > now() - {lookback}
- AND metric_name ILIKE {search_pattern}
- GROUP BY metric_name
- ORDER BY
- lower(metric_name) = lower({exact}) DESC,
- last_seen DESC
- LIMIT {limit}
- """,
- placeholders={
- "lookback": ast.Call(
- name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))]
- ),
- "search_pattern": ast.Constant(value=f"%{self.search}%"),
- "exact": ast.Constant(value=self.search),
- "limit": ast.Constant(value=self.limit),
- },
- )
+ def _build_query(self) -> ast.SelectQuery:
+ # The alias is `last_seen_at`, not `last_seen`: HogQL registers select
+ # aliases before it resolves WHERE and prefers an alias over a table
+ # column, so `max(last_seen) AS last_seen` would put an aggregate in the
+ # WHERE clause.
+ lookback = ast.Call(name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))])
+
+ if not self.search:
+ # With no search the ILIKE ('%%') and the exact-match sort key are
+ # both no-ops. They're dropped rather than passed as neutral
+ # constants: ClickHouse reads a bare integer in ORDER BY positionally.
+ query = parse_select(
+ """
+ SELECT
+ metric_name AS name,
+ any(metric_type) AS metric_type,
+ max(last_seen) AS last_seen_at
+ FROM posthog.metric_series
+ WHERE last_seen > now() - {lookback}
+ GROUP BY metric_name
+ ORDER BY last_seen_at DESC
+ LIMIT {limit}
+ """,
+ placeholders={"lookback": lookback, "limit": ast.Constant(value=self.limit)},
+ )
+ else:
+ query = parse_select(
+ """
+ SELECT
+ metric_name AS name,
+ any(metric_type) AS metric_type,
+ max(last_seen) AS last_seen_at
+ FROM posthog.metric_series
+ WHERE last_seen > now() - {lookback}
+ AND metric_name ILIKE {search_pattern}
+ GROUP BY metric_name
+ ORDER BY
+ lower(metric_name) = lower({exact}) DESC,
+ last_seen_at DESC
+ LIMIT {limit}
+ """,
+ placeholders={
+ "lookback": lookback,
+ "search_pattern": ast.Constant(value=ilike_pattern(self.search)),
+ "exact": ast.Constant(value=self.search),
+ "limit": ast.Constant(value=self.limit),
+ },
+ )
+
assert isinstance(query, ast.SelectQuery)
+ return query
+ def run(self) -> list[dict[str, Any]]:
response = execute_hogql_query(
query_type="MetricNamesQuery",
- query=query,
+ query=self._build_query(),
team=self.team,
workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now
+ settings=_QUERY_SETTINGS,
)
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]]:
+ """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.
+
+ 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)
+ if runner.search:
+ return runner.run()
+
+ cache_key = f"metrics:{team.id}:metric_names:v1:{limit}"
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached
+
+ names = runner.run()
+ if names:
+ cache.set(cache_key, names, METRIC_NAMES_CACHE_TTL)
+ return names
diff --git a/products/metrics/backend/search.py b/products/metrics/backend/search.py
new file mode 100644
index 000000000000..0152c615a2ca
--- /dev/null
+++ b/products/metrics/backend/search.py
@@ -0,0 +1,7 @@
+"""Shared search helpers for the metrics autocomplete endpoints."""
+
+
+def ilike_pattern(search: str) -> str:
+ """Escape ILIKE metacharacters so a literal '%'/'_' in the search doesn't wildcard."""
+ escaped = search.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+ return f"%{escaped}%"
diff --git a/products/metrics/backend/tests/_seeder.py b/products/metrics/backend/tests/_seeder.py
index 79e79173adba..8baa91310f4b 100644
--- a/products/metrics/backend/tests/_seeder.py
+++ b/products/metrics/backend/tests/_seeder.py
@@ -43,6 +43,47 @@ def _attribute_map_str_with_type_tags(labels: Mapping[str, str]) -> dict[str, st
return {f"{key}__str": value for key, value in labels.items()}
+def truncate_metrics_tables() -> None:
+ """Clear every table the seeders write, so leftovers can't leak between tests."""
+ for table in ("metrics1", "metric_series1", "metric_samples1"):
+ sync_execute(f"TRUNCATE TABLE IF EXISTS {table}")
+
+
+def _insert_series_row(
+ *,
+ team_id: int,
+ metric_name: str,
+ fingerprint: int,
+ metric_type: str,
+ unit: str,
+ aggregation_temporality: str,
+ is_monotonic: bool,
+ service_name: str,
+ resource_attributes: Mapping[str, str],
+ attributes: Mapping[str, str],
+ last_seen: dt.datetime,
+) -> None:
+ """Insert the `metric_series1` row for one (metric, label-set).
+
+ `attributes` goes in untagged — the `__str` suffixes are a `metrics1`
+ storage detail, and the ingest MV writes the series map without them.
+ """
+ series_row = {
+ "team_id": team_id,
+ "metric_name": metric_name,
+ "series_fingerprint": fingerprint,
+ "metric_type": metric_type,
+ "unit": unit,
+ "aggregation_temporality": aggregation_temporality,
+ "is_monotonic": is_monotonic,
+ "service_name": service_name,
+ "resource_attributes": dict(resource_attributes),
+ "attributes": dict(attributes),
+ "last_seen": last_seen.strftime("%Y-%m-%d %H:%M:%S.%f"),
+ }
+ sync_execute("INSERT INTO metric_series1 FORMAT JSONEachRow " + json.dumps(series_row))
+
+
def seed_metric(
*,
team_id: int,
@@ -58,7 +99,12 @@ def seed_metric(
histogram_counts: list[int] | None = None,
unit: str = "",
) -> None:
- """Insert one row per `(timestamp, value)` point into `metrics1`.
+ """Insert one row per `(timestamp, value)` point into `metrics1`, plus the
+ matching `metric_series1` row.
+
+ Production fans one Kafka row into both tables, so the seeder does too —
+ anything reading `metric_series` (the name picker) sees what the raw table
+ sees.
Every point in one call is a sample of the *same* series, since the series
identity (`service_name`, `metric_type`, both attribute maps) is fixed per
@@ -73,8 +119,10 @@ def seed_metric(
Histogram inputs (`histogram_bounds`, `histogram_counts`) are passed
through verbatim; only relevant when `metric_type='histogram'`.
"""
- attributes_map_str = _attribute_map_str_with_type_tags(labels or {})
+ labels = dict(labels or {})
+ attributes_map_str = _attribute_map_str_with_type_tags(labels)
resource_attributes = dict(resource_labels or {})
+ points = list(points)
rows: list[dict[str, Any]] = []
for timestamp, value in points:
@@ -110,6 +158,20 @@ def seed_metric(
payload = "\n".join(json.dumps(row) for row in rows)
sync_execute(f"INSERT INTO metrics1 FORMAT JSONEachRow {payload}")
+ _insert_series_row(
+ team_id=team_id,
+ metric_name=metric_name,
+ fingerprint=_series_fingerprint(metric_name, service_name, resource_attributes, labels),
+ metric_type=metric_type,
+ unit=unit,
+ aggregation_temporality=aggregation_temporality,
+ is_monotonic=is_monotonic,
+ service_name=service_name,
+ resource_attributes=resource_attributes,
+ attributes=labels,
+ last_seen=max(ts for ts, _ in points),
+ )
+
def seed_metric_event(
*,
@@ -159,19 +221,18 @@ def seed_metric_event(
}
for timestamp, value in points
]
- series_row = {
- "team_id": team_id,
- "metric_name": metric_name,
- "series_fingerprint": fingerprint,
- "metric_type": metric_type,
- "unit": unit,
- "aggregation_temporality": aggregation_temporality,
- "is_monotonic": is_monotonic,
- "service_name": service_name,
- "resource_attributes": resource_attributes,
- "attributes": attributes,
- "last_seen": max(ts for ts, _ in points).strftime("%Y-%m-%d %H:%M:%S.%f"),
- }
-
sync_execute("INSERT INTO metric_samples1 FORMAT JSONEachRow " + "\n".join(json.dumps(r) for r in sample_rows))
- sync_execute("INSERT INTO metric_series1 FORMAT JSONEachRow " + json.dumps(series_row))
+
+ _insert_series_row(
+ team_id=team_id,
+ metric_name=metric_name,
+ fingerprint=fingerprint,
+ metric_type=metric_type,
+ unit=unit,
+ aggregation_temporality=aggregation_temporality,
+ is_monotonic=is_monotonic,
+ service_name=service_name,
+ resource_attributes=resource_attributes,
+ attributes=attributes,
+ last_seen=max(ts for ts, _ in points),
+ )
diff --git a/products/metrics/backend/tests/test_anomaly.py b/products/metrics/backend/tests/test_anomaly.py
index 374b3985b291..910e3cac4ca8 100644
--- a/products/metrics/backend/tests/test_anomaly.py
+++ b/products/metrics/backend/tests/test_anomaly.py
@@ -7,10 +7,8 @@ from django.utils import timezone
from rest_framework import status
-from posthog.clickhouse.client import sync_execute
-
from products.metrics.backend.facade.api import characterize_metric_anomaly
-from products.metrics.backend.tests._seeder import seed_metric
+from products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables
class TestCharacterizeAnomaly(ClickhouseTestMixin, APIBaseTest):
@@ -18,7 +16,7 @@ class TestCharacterizeAnomaly(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
# 20-minute window: minutes 0-9 baseline (steady ~10), minutes 10-19
# anomaly (jumps to ~100 from minute 12).
self.start = (timezone.now() - dt.timedelta(hours=1)).replace(second=0, microsecond=0)
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 45527ea58d15..2d7ba8e18532 100644
--- a/products/metrics/backend/tests/test_metric_names_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_names_query_runner.py
@@ -1,15 +1,16 @@
import datetime as dt
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import patch
+from django.core.cache import cache
from django.utils import timezone
+from parameterized import parameterized
from rest_framework import status
-from posthog.clickhouse.client import sync_execute
-
-from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner
-from products.metrics.backend.tests._seeder import seed_metric
+from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner, cached_metric_names
+from products.metrics.backend.tests._seeder import seed_metric, seed_metric_event, truncate_metrics_tables
def _seed_point(
@@ -28,7 +29,8 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
+ cache.clear()
def test_rejects_out_of_range_limit(self):
with self.assertRaises(ValueError):
@@ -53,12 +55,15 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):
timestamp=anchor,
metric_type="histogram",
)
- _seed_point(
+ # A distinct label-set, so this is a second series under the same name —
+ # otherwise the two seeds collapse to one series row and the GROUP BY
+ # never has to do anything.
+ seed_metric(
team_id=self.team.id,
metric_name="http.server.duration",
- value=2.0,
- timestamp=anchor,
+ points=[(anchor, 2.0)],
metric_type="histogram",
+ labels={"route": "/checkout"},
)
_seed_point(
team_id=self.team.id,
@@ -78,14 +83,52 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(by_name["http.server.duration"], "histogram")
self.assertEqual(by_name["queue.depth"], "gauge")
- def test_search_filters_by_substring(self):
+ @parameterized.expand(
+ [
+ ("substring", "server", ["http.server.duration"]),
+ # '_' and '%' are ILIKE wildcards. Prometheus names are full of
+ # underscores, so an unescaped search matches far too much.
+ ("underscore_is_literal", "a_b", ["a_b"]),
+ ("percent_is_literal", "c%d", ["c%d"]),
+ ]
+ )
+ def test_search_filters_by_substring(self, _name: str, search: str, expected: list[str]):
+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)
+ for metric_name in ("http.server.duration", "queue.depth", "a_b", "axb", "c%d", "cxxd"):
+ _seed_point(team_id=self.team.id, metric_name=metric_name, value=1.0, timestamp=anchor)
+
+ runner = MetricNamesQueryRunner(team=self.team, search=search)
+ self.assertEqual([row["name"] for row in runner.run()], expected)
+
+ def test_reads_series_written_without_a_raw_datapoint_row(self):
+ # seed_metric_event writes metric_series1 + metric_samples1 and no metrics1
+ # row, so this is the one test that fails if the runner goes back to
+ # aggregating posthog.metrics. Seeding twice lands two unmerged
+ # ReplacingMergeTree parts for one fingerprint, which must still collapse
+ # to a single picker row without FINAL.
anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)
- _seed_point(team_id=self.team.id, metric_name="http.server.duration", value=1.0, timestamp=anchor)
- _seed_point(team_id=self.team.id, metric_name="queue.depth", value=12.0, timestamp=anchor)
+ for offset in (10, 1):
+ seed_metric_event(
+ team_id=self.team.id,
+ metric_name="queue.depth",
+ points=[(anchor - dt.timedelta(minutes=offset), 3.0)],
+ metric_type="gauge",
+ )
- runner = MetricNamesQueryRunner(team=self.team, search="server")
- results = runner.run()
- self.assertEqual([row["name"] for row in results], ["http.server.duration"])
+ runner = MetricNamesQueryRunner(team=self.team)
+ self.assertEqual(runner.run(), [{"name": "queue.depth", "metric_type": "gauge"}])
+
+ def test_cache_covers_the_unsearched_list_only(self):
+ with patch.object(MetricNamesQueryRunner, "run") as run:
+ run.return_value = [{"name": "m1", "metric_type": "gauge"}]
+ self.assertEqual(cached_metric_names(self.team), run.return_value)
+ self.assertEqual(cached_metric_names(self.team), run.return_value)
+ self.assertEqual(run.call_count, 1)
+
+ # A search must never be answered from the unsearched list's cache.
+ run.return_value = [{"name": "m2", "metric_type": "sum"}]
+ self.assertEqual(cached_metric_names(self.team, search="m2"), run.return_value)
+ self.assertEqual(run.call_count, 2)
def test_exact_match_floats_to_top(self):
anchor = timezone.now().replace(microsecond=0)
@@ -130,7 +173,8 @@ class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
+ cache.clear()
def test_values_requires_authentication(self):
self.client.logout()
diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsx
index d631af187409..1f673c32d80a 100644
--- a/products/metrics/frontend/MetricsScene.tsx
+++ b/products/metrics/frontend/MetricsScene.tsx
@@ -12,6 +12,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { metricNamePickerLogic } from './components/metricNamePickerLogic'
import { MetricsFundamentals } from './components/MetricsFundamentals'
import { MetricsSetupPrompt } from './components/MetricsSetupPrompt'
import { MetricsSqlEditor } from './components/MetricsSqlEditor'
@@ -65,6 +66,9 @@ const MetricsSceneContent = (): JSX.Element => {
// Scene-level so tab switches in both directions are captured; keeps the viewer
// and samples logics (its connect targets) mounted across tab flips as a side effect.
useMountedLogic(metricsUsageTrackingLogic)
+ // Prime the metric-name list here rather than inside MetricsViewer, so the fetch
+ // races the has_metrics check instead of waiting on the setup prompt to resolve.
+ useMountedLogic(metricNamePickerLogic)
return (
<>
diff --git a/products/metrics/frontend/components/metricNamePickerLogic.ts b/products/metrics/frontend/components/metricNamePickerLogic.ts
index 1dd1ccf5fba2..316ce52735bd 100644
--- a/products/metrics/frontend/components/metricNamePickerLogic.ts
+++ b/products/metrics/frontend/components/metricNamePickerLogic.ts
@@ -19,7 +19,9 @@ export interface metricNamePickerLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricNamePickerLogicActions {
- loadItems: (_: any) => any
+ loadItems: ({ debounce }: { debounce: boolean }) => {
+ debounce: boolean
+ }
loadItemsFailure: (
error: string,
errorObject?: any
@@ -29,10 +31,14 @@ export interface metricNamePickerLogicActions {
}
loadItemsSuccess: (
items: _MetricNameApi[],
- payload?: any
+ payload?: {
+ debounce: boolean
+ }
) => {
items: _MetricNameApi[]
- payload?: any
+ payload?: {
+ debounce: boolean
+ }
}
setSearch: (search: string) => {
search: string
@@ -56,13 +62,16 @@ export const metricNamePickerLogic = kea<metricNamePickerLogicType>([
items: [
[] as MetricNameItem[],
{
- loadItems: async (_, breakpoint) => {
+ loadItems: async ({ debounce }: { debounce: boolean }, breakpoint) => {
if (!canViewMetrics()) {
return []
}
- // Debounce — match the 300ms cadence used in the viewer logic so
- // both fetches feel cohesive.
- await breakpoint(300)
+ // 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) {
+ await breakpoint(300)
+ }
const response = await metricsValuesRetrieve(String(values.currentTeamId), {
value: values.search,
limit: 100,
@@ -75,14 +84,14 @@ export const metricNamePickerLogic = kea<metricNamePickerLogicType>([
})),
listeners(({ actions }) => ({
setSearch: () => {
- actions.loadItems({})
+ actions.loadItems({ debounce: true })
},
})),
afterMount(({ actions }) => {
// Prime the list so the dropdown isn't empty on first open. Mirrors
// serviceFilterLogic's afterMount in logs.
if (canViewMetrics()) {
- actions.loadItems({})
+ actions.loadItems({ debounce: false })
}
}),
])
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
index dd98c8cfb416..7ee4b5d9128c 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -319,7 +319,7 @@ describe('metricsViewerLogic', () => {
jest.mocked(metricsValuesRetrieve).mockClear()
await expectLogic(metricNamePickerLogic, () => {
- metricNamePickerLogic.actions.loadItems({})
+ metricNamePickerLogic.actions.loadItems({ debounce: true })
}).toDispatchActions(['loadItemsSuccess'])
logic.actions.setMetricName('queue_depth')
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 47a3aaf9f351..506ff17d430d 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -198,10 +198,16 @@ export interface metricsViewerLogicValues {
export interface metricsViewerLogicActions {
loadItemsSuccess: (
items: _MetricNameApi[],
- payload?: any
+ payload?:
+ | {
+ debounce: boolean
+ }
+ | undefined
) => {
items: _MetricNameApi[]
- payload?: any
+ payload?: {
+ debounce: boolean
+ }
} // metricNamePickerLogic
addToDashboard: () => {
value: true