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(tracing): facet rail polish — value search, virtualized lists, error states (#70376)

Jon McCallumb107bf507e12
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index b75906f36866..77f6f56fec53 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -47111,6 +47111,10 @@
"description": "Drop filters targeting the breakdown key itself (including `serviceNames` for a `service_name` breakdown) so a facet's value list stays complete while one of its values is selected.",
"type": "boolean"
},
+ "facetSearch": {
+ "description": "Type-ahead filter over the breakdown field's own values (case-insensitive substring match). Lets a facet's value search reach past the row limit.",
+ "type": "string"
+ },
"filterGroup": {
"$ref": "#/definitions/PropertyGroupFilter"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 80abc85b700c..2bf9a18b1325 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3869,6 +3869,11 @@ export interface TraceSpansAttributeBreakdownQuery extends DataNode<TraceSpansAt
* breakdown) so a facet's value list stays complete while one of its values is selected.
*/
excludeBreakdownFilter?: boolean
+ /**
+ * Type-ahead filter over the breakdown field's own values (case-insensitive substring match).
+ * Lets a facet's value search reach past the row limit.
+ */
+ facetSearch?: string
}
export interface TraceSpansAttributeBreakdownQueryResponse extends AnalyticsQueryResponseBase {
diff --git a/posthog/schema.py b/posthog/schema.py
index 9018cba6f05e..bb1c32848138 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -24824,6 +24824,13 @@ class TraceSpansAttributeBreakdownQuery(BaseModel):
" while one of its values is selected."
),
)
+ facetSearch: str | None = Field(
+ default=None,
+ description=(
+ "Type-ahead filter over the breakdown field's own values (case-insensitive"
+ " substring match). Lets a facet's value search reach past the row limit."
+ ),
+ )
filterGroup: PropertyGroupFilter | None = None
kind: Literal["TraceSpansAttributeBreakdownQuery"] = "TraceSpansAttributeBreakdownQuery"
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
diff --git a/products/tracing/backend/attribute_breakdown_query_runner.py b/products/tracing/backend/attribute_breakdown_query_runner.py
index f5d3c1804707..5717872a33f8 100644
--- a/products/tracing/backend/attribute_breakdown_query_runner.py
+++ b/products/tracing/backend/attribute_breakdown_query_runner.py
@@ -14,7 +14,7 @@ from posthog.schema import (
)
from posthog.hogql import ast
-from posthog.hogql.parser import parse_select
+from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
@@ -36,6 +36,12 @@ _ORDER_COLUMNS: dict[TraceSpanBreakdownOrderBy, str] = {
FACET_COLUMNS: frozenset[str] = frozenset({"service_name", "status_code"})
+def _ilike_pattern(search: str) -> str:
+ # Escape ILIKE wildcards so a search for "%" matches a literal percent sign, not every row.
+ escaped = search.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+ return f"%{escaped}%"
+
+
class TraceSpansAttributeBreakdownQueryRunner(
_SpanAggregationMixin, AnalyticsQueryRunner[TraceSpansAttributeBreakdownQueryResponse]
):
@@ -98,6 +104,24 @@ class TraceSpansAttributeBreakdownQueryRunner(
breakdown_field = ast.Field(chain=["attributes", f"{self.query.breakdownKey}__str"])
order_column = _ORDER_COLUMNS[self.query.orderBy or TraceSpanBreakdownOrderBy.COUNT]
+ where: ast.Expr = self._where_without_date_range()
+ facet_search = (self.query.facetSearch or "").strip()
+ if facet_search:
+ # Type-ahead over the facet's own values — filter pre-group so the top-N limit applies
+ # to matching values, letting the search reach past the default row window.
+ where = ast.And(
+ exprs=[
+ where,
+ parse_expr(
+ "{breakdown_field} ILIKE {pattern}",
+ placeholders={
+ "breakdown_field": breakdown_field,
+ "pattern": ast.Constant(value=_ilike_pattern(facet_search)),
+ },
+ ),
+ ]
+ )
+
query = parse_select(
"""
SELECT
@@ -121,7 +145,7 @@ class TraceSpansAttributeBreakdownQueryRunner(
""",
placeholders={
"breakdown_field": breakdown_field,
- "where": self._where_without_date_range(),
+ "where": where,
"limit": ast.Constant(value=_ROW_LIMIT),
**query_date_range.to_placeholders(),
},
@@ -150,6 +174,7 @@ def run_attribute_breakdown_query(
filter_group: PropertyGroupFilter | None = None,
service_names: list[str] | None = None,
exclude_breakdown_filter: bool = False,
+ facet_search: str | None = None,
) -> TraceSpansAttributeBreakdownQueryResponse | CachedTraceSpansAttributeBreakdownQueryResponse:
"""Facade-friendly entry point for running an attribute breakdown query."""
query = TraceSpansAttributeBreakdownQuery(
@@ -161,6 +186,7 @@ def run_attribute_breakdown_query(
filterGroup=filter_group,
serviceNames=service_names,
excludeBreakdownFilter=exclude_breakdown_filter,
+ facetSearch=facet_search,
)
runner = TraceSpansAttributeBreakdownQueryRunner(query, team)
response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
diff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.py
index a6bc7fc167a5..64a4ac207b87 100644
--- a/products/tracing/backend/facade/api.py
+++ b/products/tracing/backend/facade/api.py
@@ -89,6 +89,7 @@ def run_attribute_breakdown_query(
filter_group: PropertyGroupFilter | None = None,
service_names: list[str] | None = None,
exclude_breakdown_filter: bool = False,
+ facet_search: str | None = None,
) -> TraceSpansAttributeBreakdownQueryResponse | CachedTraceSpansAttributeBreakdownQueryResponse:
"""Run a span breakdown grouped by one attribute's value within a filtered span set."""
return _run_attribute_breakdown_query(
@@ -101,6 +102,7 @@ def run_attribute_breakdown_query(
filter_group=filter_group,
service_names=service_names,
exclude_breakdown_filter=exclude_breakdown_filter,
+ facet_search=facet_search,
)
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 728c13bd7511..6cea0a837b8f 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -377,6 +377,12 @@ class _TracingAttributeBreakdownQueryBodySerializer(serializers.Serializer):
default=False,
help_text="Drop filters targeting the breakdown key itself (including serviceNames for a service_name breakdown), so a facet's value list stays complete while one of its values is selected.",
)
+ facetSearch = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Type-ahead filter over the breakdown field's own values (case-insensitive substring match). "
+ "An empty string means no filter. Lets a facet's value search reach past the row limit.",
+ )
orderBy = serializers.ChoiceField(
choices=["count", "error_count"],
required=False,
@@ -1114,6 +1120,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
filter_group=filter_group,
service_names=query_data.get("serviceNames", None),
exclude_breakdown_filter=bool(query_data.get("excludeBreakdownFilter")),
+ facet_search=query_data.get("facetSearch") or None,
)
return Response(
diff --git a/products/tracing/backend/tests/test_attribute_breakdown.py b/products/tracing/backend/tests/test_attribute_breakdown.py
index 0ee8c971708e..10229633c26f 100644
--- a/products/tracing/backend/tests/test_attribute_breakdown.py
+++ b/products/tracing/backend/tests/test_attribute_breakdown.py
@@ -217,3 +217,17 @@ class TestTraceSpansAttributeBreakdown(_TraceSpansTestBase):
)
by_value = {row["value"]: row["count"] for row in rows}
self.assertEqual(by_value["api2.amplitude.com"], 5)
+
+ @parameterized.expand(
+ [
+ ("case_insensitive_substring", "span_attribute", "server.address", "AMPLITUDE", {"api2.amplitude.com"}),
+ # ILIKE wildcards in the search must match literally: unescaped, "api_" would match
+ # both addresses via the any-one-char wildcard.
+ ("wildcards_match_literally", "span_attribute", "server.address", "api_", set()),
+ ("span_column", "span", "service_name", "cd", {"cdp"}),
+ ("resource_attribute", "span_resource_attribute", "k8s.pod.name", "pod-b", {"pod-b"}),
+ ]
+ )
+ def test_facet_search_filters_values(self, _name, breakdown_type, breakdown_key, search, expected_values):
+ rows = self._breakdown(breakdownKey=breakdown_key, breakdownType=breakdown_type, facetSearch=search)
+ self.assertEqual({row["value"] for row in rows}, expected_values)
diff --git a/products/tracing/frontend/components/FacetRail/Facet.tsx b/products/tracing/frontend/components/FacetRail/Facet.tsx
index 9b15a8d0d0f7..eb33bb2fe76b 100644
--- a/products/tracing/frontend/components/FacetRail/Facet.tsx
+++ b/products/tracing/frontend/components/FacetRail/Facet.tsx
@@ -1,11 +1,16 @@
+import { CSSProperties, useMemo } from 'react'
+import { List } from 'react-window'
+
import { IconChevronDown, IconChevronRight } from '@posthog/icons'
-import { LemonButton, LemonCheckbox } from '@posthog/lemon-ui'
+import { LemonButton, LemonCheckbox, LemonInput } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { FacetOption } from './facets'
+const ROW_HEIGHT = 33
+
interface FacetProps {
title: string
options: FacetOption[]
@@ -13,10 +18,18 @@ interface FacetProps {
onToggle: (value: string) => void
loading?: boolean
emptyLabel?: string
+ /** When provided, renders a search box above the values (state owned by the caller). */
+ searchValue?: string
+ onSearchChange?: (value: string) => void
+ searchPlaceholder?: string
collapsed?: boolean
onToggleCollapsed?: () => void
+ /** When set, values render in a fixed-height virtualized list capped at this many pixels. */
+ maxHeight?: number
/** For fixed facets: render zero-count values dimmed, and disabled unless already selected. */
dimZeroCounts?: boolean
+ /** The facet's latest fetch failed — show an inline error instead of pretending the list is fresh (suppresses emptyLabel). */
+ error?: boolean
}
/**
@@ -39,12 +52,22 @@ export function Facet({
onToggle,
loading = false,
emptyLabel = 'No values',
+ searchValue,
+ onSearchChange,
+ searchPlaceholder = 'Search…',
collapsed = false,
onToggleCollapsed,
+ maxHeight,
dimZeroCounts = false,
+ error = false,
}: FacetProps): JSX.Element {
const slug = slugify(title)
+ const rowProps = useMemo<FacetValueRowProps>(
+ () => ({ options, selected, slug, onToggle, dimZeroCounts }),
+ [options, selected, slug, onToggle, dimZeroCounts]
+ )
+
return (
<div className="mb-3">
<button
@@ -57,31 +80,101 @@ export function Facet({
{collapsed ? <IconChevronRight /> : <IconChevronDown />}
<span>{title}</span>
</button>
+ {!collapsed && onSearchChange && (
+ <div className="px-1 pb-1">
+ <LemonInput
+ type="search"
+ size="small"
+ fullWidth
+ placeholder={searchPlaceholder}
+ value={searchValue ?? ''}
+ onChange={onSearchChange}
+ />
+ </div>
+ )}
+ {/* A failed fetch shows inline (options may be stale-but-usable below) rather than blanking the facet. */}
+ {!collapsed && error && !loading && (
+ <div className="px-1 pb-1 text-xs text-danger" data-attr={`tracing-facet-${slug}-error`}>
+ Couldn't load values
+ </div>
+ )}
{!collapsed &&
(loading && options.length === 0 ? (
<div className="px-1 text-xs text-muted">Loading…</div>
) : options.length === 0 ? (
- <div className="px-1 text-xs text-muted">{emptyLabel}</div>
+ // The error line above already explains the missing values — don't add "No values".
+ !error && <div className="px-1 text-xs text-muted">{emptyLabel}</div>
) : (
- // Dim the list while a refetch is in flight so there's feedback that results
- // are updating, rather than the list silently changing.
- <div className={cn('space-y-px', loading && 'opacity-60 transition-opacity')}>
- {options.map((option) => (
- <FacetValueButton
- key={option.value}
- option={option}
- selected={selected.includes(option.value)}
- slug={slug}
- onToggle={onToggle}
- dimZeroCounts={dimZeroCounts}
+ // Dim the list while a refetch is in flight (e.g. typing in search) so there's
+ // feedback that results are updating, rather than the list silently changing.
+ <div className={cn(loading && 'opacity-60 transition-opacity')}>
+ {maxHeight ? (
+ <List<FacetValueRowProps>
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: '100%', height: Math.min(options.length * ROW_HEIGHT, maxHeight) }}
+ rowCount={options.length}
+ rowHeight={ROW_HEIGHT}
+ overscanCount={5}
+ rowComponent={FacetValueRow}
+ rowProps={rowProps}
/>
- ))}
+ ) : (
+ <div className="space-y-px">
+ {options.map((option) => (
+ <FacetValueButton
+ key={option.value}
+ option={option}
+ selected={selected.includes(option.value)}
+ slug={slug}
+ onToggle={onToggle}
+ dimZeroCounts={dimZeroCounts}
+ />
+ ))}
+ </div>
+ )}
</div>
))}
</div>
)
}
+interface FacetValueRowProps {
+ options: FacetOption[]
+ selected: string[]
+ slug: string
+ onToggle: (value: string) => void
+ dimZeroCounts: boolean
+}
+
+function FacetValueRow({
+ ariaAttributes,
+ index,
+ style,
+ options,
+ selected,
+ slug,
+ onToggle,
+ dimZeroCounts,
+}: {
+ ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }
+ index: number
+ style: CSSProperties
+} & FacetValueRowProps): JSX.Element {
+ const option = options[index]
+ return (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={style} {...ariaAttributes}>
+ <FacetValueButton
+ option={option}
+ selected={selected.includes(option.value)}
+ slug={slug}
+ onToggle={onToggle}
+ dimZeroCounts={dimZeroCounts}
+ />
+ </div>
+ )
+}
+
function FacetValueButton({
option,
selected,
@@ -110,7 +203,10 @@ function FacetValueButton({
data-attr={`tracing-facet-${slug}-${slugify(option.value)}`}
>
<span className="flex items-center gap-2 min-w-0 w-full">
- <span className="truncate flex-1">{option.label}</span>
+ {/* Native title so a truncated value is still readable without popover cost per virtualized row. */}
+ <span className="truncate flex-1" title={option.label}>
+ {option.label}
+ </span>
{option.count != null && (
<span className="shrink-0 text-muted tabular-nums">{humanFriendlyLargeNumber(option.count)}</span>
)}
diff --git a/products/tracing/frontend/components/FacetRail/FacetRail.tsx b/products/tracing/frontend/components/FacetRail/FacetRail.tsx
index b3e3c4dce030..3e8aac8e890b 100644
--- a/products/tracing/frontend/components/FacetRail/FacetRail.tsx
+++ b/products/tracing/frontend/components/FacetRail/FacetRail.tsx
@@ -28,7 +28,8 @@ export function FacetRail(): JSX.Element {
const railRef = useRef<HTMLDivElement>(null)
const { setFacetRailCollapsed } = useActions(tracingConfigLogic)
const { serviceNames, filters } = useValues(tracingFiltersLogic)
- const { facetValues, facetValuesLoading, visibleFacets } = useValues(facetCountsLogic)
+ const { facetValues, loadingFacetKeys, erroredFacetKeys, facetSearch, visibleFacets } = useValues(facetCountsLogic)
+ const { setFacetSearch } = useActions(facetCountsLogic)
const { collapsedFacets, facetNameSearch } = useValues(facetRailLogic)
const { toggleFacetValue, toggleFacetCollapsed, setFacetNameSearch } = useActions(facetRailLogic)
@@ -65,6 +66,8 @@ export function FacetRail(): JSX.Element {
label: row.value,
count: row.count,
}))
+ const loading = loadingFacetKeys.includes(facet.key)
+ const error = erroredFacetKeys.includes(facet.key)
const onToggle = (value: string): void => toggleFacetValue(source, value)
const onToggleCollapsed = (): void => toggleFacetCollapsed(facet.key)
const collapsed = collapsedFacets.includes(facet.key)
@@ -83,27 +86,34 @@ export function FacetRail(): JSX.Element {
options={options}
selected={selected}
onToggle={onToggle}
- loading={facetValuesLoading}
+ loading={loading}
collapsed={collapsed}
onToggleCollapsed={onToggleCollapsed}
dimZeroCounts
+ error={error}
/>
)
}
// Dynamic facet: values + counts come straight from the cross-filtered endpoint (zeros never
// appear), with any selected-but-absent values injected so they stay visible and toggleable.
+ const search = facet.searchable ? facetSearch[facet.key] : undefined
return (
<Facet
key={facet.key}
title={facet.title}
- options={mergeSelectedIntoOptions(fetched, selected)}
+ options={mergeSelectedIntoOptions(fetched, selected, search)}
selected={selected}
onToggle={onToggle}
- loading={facetValuesLoading}
+ loading={loading}
emptyLabel={facet.emptyLabel}
+ searchValue={facet.searchable ? (search ?? '') : undefined}
+ onSearchChange={facet.searchable ? (value) => setFacetSearch(facet.key, value) : undefined}
+ searchPlaceholder={facet.searchPlaceholder}
collapsed={collapsed}
onToggleCollapsed={onToggleCollapsed}
+ maxHeight={facet.maxHeight}
+ error={error}
/>
)
}
@@ -116,7 +126,9 @@ export function FacetRail(): JSX.Element {
ref={railRef}
className="relative flex flex-col shrink-0 border rounded bg-surface-primary overflow-hidden"
// eslint-disable-next-line react/forbid-dom-props
- style={{ width: desiredSize ?? DEFAULT_WIDTH_PX, minWidth: 'min-content', maxWidth: '40%' }}
+ // The width is the user's alone: a fixed min (not min-content) so a long facet value
+ // can never force the rail wider — values truncate to fit instead.
+ style={{ width: desiredSize ?? DEFAULT_WIDTH_PX, minWidth: COLLAPSE_THRESHOLD_PX, maxWidth: '40%' }}
data-attr="tracing-facet-rail"
>
<div className="px-2 py-1 border-b">
diff --git a/products/tracing/frontend/components/FacetRail/facetCountsLogic.test.ts b/products/tracing/frontend/components/FacetRail/facetCountsLogic.test.ts
new file mode 100644
index 000000000000..40a63ecc5aff
--- /dev/null
+++ b/products/tracing/frontend/components/FacetRail/facetCountsLogic.test.ts
@@ -0,0 +1,120 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ tracingSpansAttributeBreakdownCreate,
+ tracingSpansAttributesRetrieve,
+} from 'products/tracing/frontend/generated/api'
+import type { _TracingAttributeBreakdownRowApi } from 'products/tracing/frontend/generated/api.schemas'
+
+import { facetCountsLogic } from './facetCountsLogic'
+
+jest.mock('products/tracing/frontend/generated/api', () => ({
+ __esModule: true,
+ tracingSpansAttributeBreakdownCreate: jest.fn(),
+ tracingSpansAttributesRetrieve: jest.fn(),
+}))
+
+const mockBreakdown = tracingSpansAttributeBreakdownCreate as jest.MockedFunction<
+ typeof tracingSpansAttributeBreakdownCreate
+>
+const mockAttributes = tracingSpansAttributesRetrieve as jest.MockedFunction<typeof tracingSpansAttributesRetrieve>
+
+const ID = 'test-viewer'
+
+function row(value: string, count: number): _TracingAttributeBreakdownRowApi {
+ return { value, count, error_count: 0, p50_duration_nano: 0, p95_duration_nano: 0 }
+}
+
+describe('facetCountsLogic', () => {
+ let logic: ReturnType<typeof facetCountsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.clearAllMocks()
+ // No resource-attribute keys present, so only the column facets (service, status) are visible.
+ mockAttributes.mockResolvedValue({ results: [], count: 0 })
+ mockBreakdown.mockResolvedValue({ results: [row('api', 10)], compare: null })
+ logic = facetCountsLogic({ id: ID })
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('a facet search refetches only that facet, passing facetSearch to the endpoint', async () => {
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])
+ mockBreakdown.mockClear()
+
+ logic.actions.setFacetSearch('service', 'kaf')
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesForKey', 'loadFacetValuesForKeySuccess'])
+
+ expect(mockBreakdown).toHaveBeenCalledTimes(1)
+ expect(mockBreakdown).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ query: expect.objectContaining({ breakdownKey: 'service_name', facetSearch: 'kaf' }),
+ })
+ )
+ })
+
+ it('a failed facet is marked errored without wiping the others, and recovers on the next fetch', async () => {
+ // One broken breakdown must show per-facet (erroredFacetKeys), not blank the whole rail.
+ mockBreakdown.mockImplementation((_, request) =>
+ request.query.breakdownKey === 'status_code'
+ ? Promise.reject(new Error('breakdown failed'))
+ : Promise.resolve({ results: [row('api', 10)], compare: null })
+ )
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])
+
+ expect(logic.values.erroredFacetKeys).toEqual(['status'])
+ expect(logic.values.facetValues['service']).toEqual([row('api', 10)])
+ expect(logic.values.facetValues['status']).toBeUndefined()
+
+ mockBreakdown.mockResolvedValue({ results: [row('2', 3)], compare: null })
+ logic.actions.loadFacetValues(null)
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])
+
+ expect(logic.values.erroredFacetKeys).toEqual([])
+ expect(logic.values.facetValues['status']).toEqual([row('2', 3)])
+ })
+
+ it('a full reload that raced a facet search does not overwrite the narrowed results', async () => {
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])
+
+ // The reload's service request (no facetSearch) hangs until released; the search request
+ // (facetSearch set) and every other facet resolve immediately.
+ let releaseStaleReload: (rows: _TracingAttributeBreakdownRowApi[]) => void = () => {}
+ let staleReloadRequested: () => void = () => {}
+ const staleReloadIssued = new Promise<void>((resolve) => (staleReloadRequested = resolve))
+ mockBreakdown.mockImplementation((_, request) => {
+ if (request.query.breakdownKey === 'service_name' && !request.query.facetSearch) {
+ staleReloadRequested()
+ return new Promise((resolve) => {
+ releaseStaleReload = (rows) => resolve({ results: rows, compare: null })
+ })
+ }
+ if (request.query.facetSearch === 'kaf') {
+ return Promise.resolve({ results: [row('kafka-consumer', 2)], compare: null })
+ }
+ return Promise.resolve({ results: [row('api', 10)], compare: null })
+ })
+
+ logic.actions.loadFacetValues(null)
+ await staleReloadIssued
+
+ logic.actions.setFacetSearch('service', 'kaf')
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesForKeySuccess'])
+ expect(logic.values.facetValues['service']).toEqual([row('kafka-consumer', 2)])
+
+ releaseStaleReload([row('api', 10), row('worker', 5)])
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])
+
+ expect(logic.values.facetValues['service']).toEqual([row('kafka-consumer', 2)])
+ expect(logic.values.erroredFacetKeys).toEqual([])
+ })
+})
diff --git a/products/tracing/frontend/components/FacetRail/facetCountsLogic.ts b/products/tracing/frontend/components/FacetRail/facetCountsLogic.ts
index e938fd73431c..bd3c61a74381 100644
--- a/products/tracing/frontend/components/FacetRail/facetCountsLogic.ts
+++ b/products/tracing/frontend/components/FacetRail/facetCountsLogic.ts
@@ -1,4 +1,4 @@
-import { connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
@@ -39,7 +39,9 @@ export interface BreakdownScope {
* Per-facet values + counts, cross-filtered server-side: each facet's results reflect every active
* filter except its own selection (excludeBreakdownFilter drops the facet's own column, serviceNames,
* or attribute filter). Values come back ordered by count descending. The rail is config-driven, so
- * this fetches one attribute-breakdown request per facet in FACETS, keyed by facet.key.
+ * this fetches one attribute-breakdown request per facet in FACETS, keyed by facet.key. A per-facet
+ * type-ahead search re-fetches only that facet (its CH group-by is a full scan, so we don't refetch
+ * the others on every keystroke).
*/
export const facetCountsLogic = kea<facetCountsLogicType>([
props({ id: TRACING_SCENE_VIEWER_ID } as FacetCountsLogicProps),
@@ -55,7 +57,51 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
],
})),
+ actions({
+ setFacetSearch: (facetKey: string, search: string) => ({ facetKey, search }),
+ // Dispatched by the loaders after each allSettled batch: `attempted` facets leave the error
+ // set (they got a fresh verdict), `failed` ones (re-)enter it.
+ setFacetFetchErrors: (attempted: string[], failed: string[]) => ({ attempted, failed }),
+ }),
+
reducers({
+ facetSearch: [
+ {} as Record<string, string>,
+ {
+ setFacetSearch: (state, { facetKey, search }) => ({ ...state, [facetKey]: search }),
+ },
+ ],
+ // Facets whose latest fetch failed — drives the per-facet inline error state, so one broken
+ // breakdown shows in place instead of blanking the rail.
+ erroredFacetKeys: [
+ [] as string[],
+ {
+ setFacetFetchErrors: (state, { attempted, failed }) => [
+ ...state.filter((key) => !attempted.includes(key)),
+ ...failed,
+ ],
+ },
+ ],
+ // Facets being refreshed by a filter-change reload. Single-flight (its own breakpoint), so the
+ // whole set clears together on settle. null arg = all facets.
+ loadingReloadKeys: [
+ [] as string[],
+ {
+ loadFacetValues: (_, facetKeys: string[] | null) => facetKeys ?? FACETS.map((f) => f.key),
+ loadFacetValuesSuccess: () => [],
+ loadFacetValuesFailure: () => [],
+ },
+ ],
+ // The single facet whose type-ahead search is in flight. Single-flight across facets (the per-key
+ // loader shares one breakpoint), so a new search supersedes the previous one rather than stacking.
+ loadingSearchKey: [
+ null as string | null,
+ {
+ loadFacetValuesForKey: (_, facetKey: string) => facetKey,
+ loadFacetValuesForKeySuccess: () => null,
+ loadFacetValuesForKeyFailure: () => null,
+ },
+ ],
// Latches true once the presence probe settles (success or failure). Until then the value
// fetch is deferred, so column facets aren't fetched on mount and then re-fetched once
// presence resolves and the resource-attribute facets become visible.
@@ -68,7 +114,7 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
],
}),
- loaders(({ values }) => {
+ loaders(({ actions, values }) => {
const fetchFacet = async (facet: FacetConfig): Promise<_TracingAttributeBreakdownRowApi[]> => {
if (!values.currentTeamId) {
return []
@@ -94,6 +140,7 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
excludeBreakdownFilter: true,
dateRange: values.utcDateRange,
serviceNames: values.serviceNames ?? [],
+ facetSearch: values.facetSearch[facet.key] || undefined,
filterGroup,
},
})
@@ -102,18 +149,34 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
// Fetch each facet independently and merge into the existing record. allSettled (not all) so
// one facet's failed request leaves the others' counts intact instead of wiping the batch.
+ // Failures are recorded per facet for the inline error state.
const mergeFetched = async (
facets: FacetConfig[]
): Promise<Record<string, _TracingAttributeBreakdownRowApi[]>> => {
+ // The search term each request is about to carry. A full reload and a per-facet search
+ // have independent breakpoints, so a reload issued before the user typed can settle
+ // after the narrowed search response — merging it would put unsearched rows under a
+ // still-filled search box. Dropping stale-term rows leaves the fresher response's in place.
+ const searchAtRequest = Object.fromEntries(facets.map((f) => [f.key, values.facetSearch[f.key] ?? '']))
const settled = await Promise.allSettled(
facets.map(async (facet) => [facet.key, await fetchFacet(facet)] as const)
)
- const fetched = settled
+ const fulfilled = settled
.filter(
(s): s is PromiseFulfilledResult<readonly [string, _TracingAttributeBreakdownRowApi[]]> =>
s.status === 'fulfilled'
)
.map((s) => s.value)
+ // Error state keys off fulfillment: a stale-term fetch still succeeded, it just doesn't merge.
+ const fulfilledKeys = new Set(fulfilled.map(([key]) => key))
+ const attemptedKeys = facets.map((f) => f.key)
+ // Fires before the final breakpoint, so a superseded batch can record error state — the
+ // winning batch immediately overwrites it, since every batch reports all attempted keys.
+ actions.setFacetFetchErrors(
+ attemptedKeys,
+ attemptedKeys.filter((key) => !fulfilledKeys.has(key))
+ )
+ const fetched = fulfilled.filter(([key]) => (values.facetSearch[key] ?? '') === searchAtRequest[key])
return { ...values.facetValues, ...Object.fromEntries(fetched) }
}
@@ -131,6 +194,15 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
breakpoint()
return result
},
+ // A single facet's type-ahead search. Separate action so its breakpoint is independent:
+ // typing in one facet's search must not cancel a still-debouncing full reload.
+ loadFacetValuesForKey: async (facetKey: string, breakpoint) => {
+ await breakpoint(300)
+ const facet = FACETS.find((f) => f.key === facetKey)
+ const result = facet ? await mergeFetched([facet]) : values.facetValues
+ breakpoint()
+ return result
+ },
},
],
presentResourceKeys: [
@@ -160,6 +232,17 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
(presentResourceKeys): FacetConfig[] =>
FACETS.filter((f) => f.source.type === 'column' || presentResourceKeys.includes(f.source.key)),
],
+ // Per-facet loading state. A filter-change reload and a per-facet search have independent
+ // breakpoints and can overlap, so union both sources — otherwise whichever settles first would
+ // clear the other's spinners. Keeping them as separate single-flight reducers means neither can
+ // leak a stuck spinner: each clears wholesale on its own settle.
+ loadingFacetKeys: [
+ (s) => [s.loadingReloadKeys, s.loadingSearchKey],
+ (loadingReloadKeys: string[], loadingSearchKey: string | null): string[] =>
+ loadingSearchKey && !loadingReloadKeys.includes(loadingSearchKey)
+ ? [...loadingReloadKeys, loadingSearchKey]
+ : loadingReloadKeys,
+ ],
// The subset of filter state the breakdown queries actually depend on, built from the stable
// leaf values — not the `filters` roll-up, which also carries presentation state (viewMode,
// orderBy, compareMode, overlay windows) and gets a new identity whenever any of it changes.
@@ -175,6 +258,9 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
}),
listeners(({ actions }) => ({
+ // A facet's search changed — refetch only that facet, via its own action so it doesn't
+ // cancel a still-debouncing full reload (independent breakpoint).
+ setFacetSearch: ({ facetKey }) => actions.loadFacetValuesForKey(facetKey),
// Presence settled — drive the first full fetch now that visibleFacets is known. On failure
// we still fetch so the column facets (Service/Status) load even if the probe errored.
loadPresentResourceKeysSuccess: () => actions.loadFacetValues(null),
diff --git a/products/tracing/frontend/components/FacetRail/facets.test.ts b/products/tracing/frontend/components/FacetRail/facets.test.ts
index d59fbb443389..4cd37708db12 100644
--- a/products/tracing/frontend/components/FacetRail/facets.test.ts
+++ b/products/tracing/frontend/components/FacetRail/facets.test.ts
@@ -1,6 +1,15 @@
import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
-import { FilterGroupFacetSource, facetFilterValues, mergeSelectedIntoOptions, toggleFacetFilter } from './facets'
+import {
+ FacetSource,
+ FilterGroupFacetSource,
+ facetFilterValues,
+ facetSelectedValues,
+ mergeSelectedIntoOptions,
+ toggleFacetFilter,
+} from './facets'
+
+const SERVICE_SOURCE: FacetSource = { type: 'column', column: 'service_name' }
const STATUS_SOURCE: FilterGroupFacetSource = { type: 'column', column: 'status_code' }
const POD_SOURCE: FilterGroupFacetSource = { type: 'resourceAttribute', key: 'k8s.pod.name' }
@@ -84,6 +93,14 @@ describe('facets', () => {
})
})
+ describe('facetSelectedValues', () => {
+ it('drops empty service names from external state so they cannot inject a blank row', () => {
+ // The service facet reads the dedicated serviceNames field, not the filterGroup — a URL or
+ // saved view carrying serviceNames: [''] must not surface a blank selected service row.
+ expect(facetSelectedValues(undefined, ['api', ''], SERVICE_SOURCE)).toEqual(['api'])
+ })
+ })
+
describe('mergeSelectedIntoOptions', () => {
it('prepends a selected value absent from the fetched list with a zero count', () => {
const fetched = [{ value: 'api', label: 'api', count: 5 }]
@@ -106,4 +123,20 @@ describe('facets', () => {
expect(mergeSelectedIntoOptions(fetched, ['api'])).toEqual(fetched)
})
})
+
+ describe('mergeSelectedIntoOptions', () => {
+ const fetched = [{ value: 'api', label: 'api', count: 10 }]
+
+ // Injected selected-but-absent rows must honor an active type-ahead search — otherwise a
+ // selected value the server just filtered out reappears pinned at 0, contradicting the list.
+ it.each<[string, string | undefined, string[]]>([
+ ['no search injects every missing selected value', undefined, ['worker-1']],
+ ['a matching search keeps the injected value (case-insensitive)', 'WORK', ['worker-1']],
+ ['a non-matching search drops the injected value', 'kafka', []],
+ ])('%s', (_, search, expectedInjected) => {
+ const options = mergeSelectedIntoOptions(fetched, ['api', 'worker-1'], search)
+ expect(options.filter((o) => o.count === 0).map((o) => o.value)).toEqual(expectedInjected)
+ expect(options).toEqual(expect.arrayContaining(fetched))
+ })
+ })
})
diff --git a/products/tracing/frontend/components/FacetRail/facets.ts b/products/tracing/frontend/components/FacetRail/facets.ts
index b7311ccfcaf2..c28b192c142c 100644
--- a/products/tracing/frontend/components/FacetRail/facets.ts
+++ b/products/tracing/frontend/components/FacetRail/facets.ts
@@ -60,6 +60,8 @@ export interface FacetConfig {
searchable?: boolean
searchPlaceholder?: string
emptyLabel?: string
+ /** Max pixel height before the value list virtualizes and scrolls. */
+ maxHeight?: number
}
interface SpanFacetFilter {
@@ -117,7 +119,8 @@ export function facetSelectedValues(
): string[] {
if (source.type === 'column') {
if (source.column === 'service_name') {
- return serviceNames ?? []
+ // Empty strings from external state (URL, saved view) would select a value with no visible row.
+ return (serviceNames ?? []).filter((v) => v !== '')
}
return facetFilterValues(group, { type: 'column', column: source.column })
}
@@ -170,6 +173,7 @@ const SERVICE_FACET: FacetConfig = {
searchable: true,
searchPlaceholder: 'Search services…',
emptyLabel: 'No services',
+ maxHeight: 300,
}
const STATUS_FACET: FacetConfig = {
@@ -193,6 +197,7 @@ function resourceAttributeFacet(key: string, slug: string, title: string, group:
searchable: true,
searchPlaceholder: `Search ${title.toLowerCase()}…`,
emptyLabel: `No ${title.toLowerCase()} values`,
+ maxHeight: 300,
}
}
@@ -241,15 +246,17 @@ export function filterFacetsByName(facets: FacetConfig[], query: string): FacetC
* Ensure every selected value of a dynamic facet renders even when absent from the fetched list —
* a filter from a URL or saved view can reference a value with no matches in the current scope
* (or one below the top-N cutoff), and without a visible row it can't be seen or toggled off.
- * Missing values are prepended with a zero count.
+ * Missing values are prepended with a zero count. An active type-ahead search still applies to
+ * injected rows, matching the server-side substring semantics of the fetched ones.
*/
-export function mergeSelectedIntoOptions(fetched: FacetOption[], selected: string[]): FacetOption[] {
+export function mergeSelectedIntoOptions(fetched: FacetOption[], selected: string[], search?: string): FacetOption[] {
+ const needle = (search ?? '').trim().toLowerCase()
const seen = new Set(fetched.map((option) => option.value))
// Dedupe as we go: a URL or saved view can carry the same value twice, and two rows sharing a
// value would collide on their React key and toggle target.
const missing: FacetOption[] = []
for (const value of selected) {
- if (seen.has(value)) {
+ if (seen.has(value) || (needle && !value.toLowerCase().includes(needle))) {
continue
}
seen.add(value)
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index d3596abc0e43..c77d3e403292 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -136,6 +136,8 @@ export interface _TracingAttributeBreakdownQueryBodyApi {
breakdownType: SpanPropertyTypeEnumApi
/** Drop filters targeting the breakdown key itself (including serviceNames for a service_name breakdown), so a facet's value list stays complete while one of its values is selected. */
excludeBreakdownFilter?: boolean
+ /** Type-ahead filter over the breakdown field's own values (case-insensitive substring match). An empty string means no filter. Lets a facet's value search reach past the row limit. */
+ facetSearch?: string
/** Order rows by span count or error count, descending. Defaults to count.
*
* * `count` - count
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index c3aa23b3e9d4..9bae2ea66ebb 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -125,6 +125,12 @@ export const TracingSpansAttributeBreakdownCreateBody = /* @__PURE__ */ zod.obje
.describe(
"Drop filters targeting the breakdown key itself (including serviceNames for a service_name breakdown), so a facet's value list stays complete while one of its values is selected."
),
+ facetSearch: zod
+ .string()
+ .optional()
+ .describe(
+ "Type-ahead filter over the breakdown field's own values (case-insensitive substring match). An empty string means no filter. Lets a facet's value search reach past the row limit."
+ ),
orderBy: zod
.enum(['count', 'error_count'])
.describe('\* `count` - count\n\* `error_count` - error_count')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a5df1fe393a7..39f524540fe9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29910,6 +29910,8 @@ export namespace Schemas {
dateRange: DateRange;
/** Drop filters targeting the breakdown key itself (including `serviceNames` for a `service_name` breakdown) so a facet's value list stays complete while one of its values is selected. */
excludeBreakdownFilter?: boolean | null;
+ /** Type-ahead filter over the breakdown field's own values (case-insensitive substring match). Lets a facet's value search reach past the row limit. */
+ facetSearch?: string | null;
filterGroup?: PropertyGroupFilter | null;
kind?: 'TraceSpansAttributeBreakdownQuery';
/** Modifiers used when performing the query */
@@ -62227,6 +62229,8 @@ export namespace Schemas {
breakdownType: SpanPropertyTypeEnum;
/** Drop filters targeting the breakdown key itself (including serviceNames for a service_name breakdown), so a facet's value list stays complete while one of its values is selected. */
excludeBreakdownFilter?: boolean;
+ /** Type-ahead filter over the breakdown field's own values (case-insensitive substring match). An empty string means no filter. Lets a facet's value search reach past the row limit. */
+ facetSearch?: string;
/** Order rows by span count or error count, descending. Defaults to count.
*
* * `count` - count
diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.ts
index 4c6209504c6d..08827c0ad513 100644
--- a/services/mcp/src/generated/tracing/api.ts
+++ b/services/mcp/src/generated/tracing/api.ts
@@ -140,6 +140,12 @@ export const TracingSpansAttributeBreakdownCreateBody = /* @__PURE__ */ zod.obje
.describe(
"Drop filters targeting the breakdown key itself (including serviceNames for a service_name breakdown), so a facet's value list stays complete while one of its values is selected."
),
+ facetSearch: zod
+ .string()
+ .optional()
+ .describe(
+ "Type-ahead filter over the breakdown field's own values (case-insensitive substring match). An empty string means no filter. Lets a facet's value search reach past the row limit."
+ ),
orderBy: zod
.enum(['count', 'error_count'])
.describe('* `count` - count\n* `error_count` - error_count')
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-breakdown.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-breakdown.json
index 31e56d1ec014..3f8bfe12f0f2 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-breakdown.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-breakdown.json
@@ -68,6 +68,10 @@
"description": "Drop filters targeting the breakdown key itself (including serviceNames for a service_name breakdown), so a facet's value list stays complete while one of its values is selected.",
"type": "boolean"
},
+ "facetSearch": {
+ "description": "Type-ahead filter over the breakdown field's own values (case-insensitive substring match). An empty string means no filter. Lets a facet's value search reach past the row limit.",
+ "type": "string"
+ },
"filterGroup": {
"default": [],
"description": "Property filters scoping the spans the breakdown runs over (e.g. only error spans).",