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(logs,tracing): let users pin custom facets to the facet rail (#88059)

Jimmy Zhub5c631db9617
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 874bde332dc5..4fdd3aa89bfc 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -1160,6 +1160,7 @@ rules:
|PersistedFolder
|Reminder
|SessionRecordingViewed
+ |UserFacetSettings
|UserHomeSettings
|UserProductList
|UserScenePersonalisation
@@ -1233,6 +1234,7 @@ rules:
|PersistedFolder
|Reminder
|SessionRecordingViewed
+ |UserFacetSettings
|UserHomeSettings
|UserProductList
|UserScenePersonalisation
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 942f53736959..fb44b5e13c11 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -284,6 +284,7 @@ export const FEATURE_FLAGS = {
CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS_TRACK_RULES: 'customer-analytics-track-rules', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_PROFILE_CONFIG_BUTTON: 'customer-profile-config-button', // owner: @arthurdedeus #team-customer-analytics
+ CUSTOM_FACET_PINNING: 'custom-facet-pinning', // owner: #team-logs — gates pinning custom facets to the logs/tracing facet rails
DASHBOARD_AI_PROMPT_COMPOSER: 'dashboard-ai-prompt-composer', // owner: @mattp #team-analytics-platform multivariate=control,copy,composer
DASHBOARD_AUTO_PREVIEW_LIMIT: 'dashboard-auto-preview-limit', // owner: @pauldambra #team-product-analytics
DASHBOARD_CUSTOMIZATION: 'dashboard-customization', // owner: @MattPua #team-analytics-platform
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 9011178a3cf3..4bf5e0fe7706 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -62,6 +62,7 @@ from . import (
team,
uploaded_media,
user,
+ user_facet_settings,
user_home_settings,
web_vitals,
webauthn,
@@ -373,6 +374,11 @@ router.register(
user_home_settings.UserHomeSettingsViewSet,
"user_home_settings",
)
+router.register(
+ r"user_facet_settings",
+ user_facet_settings.UserFacetSettingsViewSet,
+ "user_facet_settings",
+)
router.register(r"personal_api_keys", personal_api_key.PersonalAPIKeyViewSet, "personal_api_keys")
router.register(r"cli-auth", cli_auth.CLIAuthViewSet, "cli_auth")
router.register(r"instance_status", instance_status.InstanceStatusViewSet, "instance_status")
diff --git a/posthog/api/test/test_user_facet_settings.py b/posthog/api/test/test_user_facet_settings.py
new file mode 100644
index 000000000000..7448da7b152b
--- /dev/null
+++ b/posthog/api/test/test_user_facet_settings.py
@@ -0,0 +1,56 @@
+from posthog.test.base import APIBaseTest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.user_facet_settings import UserFacetSettingsEntrySerializer
+from posthog.models import UserFacetSettings
+from posthog.models.scoping import team_scope
+
+
+class TestUserFacetSettingsEntrySerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("missing_key", {"source_type": "attribute"}, "key"),
+ ("missing_source_type", {"key": "http.status_code"}, "source_type"),
+ ("invalid_source_type", {"key": "http.status_code", "source_type": "column"}, "source_type"),
+ ]
+ )
+ def test_rejects_invalid_entries(self, _name, data, invalid_field):
+ serializer = UserFacetSettingsEntrySerializer(data=data)
+ self.assertFalse(serializer.is_valid())
+ self.assertIn(invalid_field, serializer.errors)
+
+
+class TestUserFacetSettingsAPI(APIBaseTest):
+ def test_missing_product_query_param_returns_400(self):
+ response = self.client.get("/api/user_facet_settings/@me/")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_retrieve_defaults_to_empty_list(self):
+ response = self.client.get("/api/user_facet_settings/@me/?product=logs")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"custom_facets": []})
+
+ def test_update_is_scoped_per_product(self):
+ payload = {"custom_facets": [{"key": "http.status_code", "source_type": "attribute"}]}
+
+ response = self.client.patch(
+ "/api/user_facet_settings/@me/?product=tracing",
+ payload,
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"custom_facets": payload["custom_facets"]})
+
+ # A different product for the same user/team stays untouched — the real regression risk
+ # here is the product filter being dropped from the underlying update_or_create.
+ logs_response = self.client.get("/api/user_facet_settings/@me/?product=logs")
+ self.assertEqual(logs_response.json(), {"custom_facets": []})
+
+ with team_scope(self.team.id, canonical=True):
+ stored = UserFacetSettings.objects.get(user=self.user, team=self.team, product="tracing")
+ self.assertEqual(stored.custom_facets, payload["custom_facets"])
diff --git a/posthog/api/user_facet_settings.py b/posthog/api/user_facet_settings.py
new file mode 100644
index 000000000000..0f298f21be97
--- /dev/null
+++ b/posthog/api/user_facet_settings.py
@@ -0,0 +1,150 @@
+from typing import Any, cast
+
+from django.db.models import QuerySet
+
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view
+from rest_framework import exceptions, serializers, viewsets
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.models import User, UserFacetSettings
+from posthog.models.scoping import team_scope
+from posthog.permissions import APIScopePermission
+from posthog.rate_limit import UserAuthenticationThrottle
+
+
+class UserFacetSettingsEntrySerializer(serializers.Serializer):
+ key = serializers.CharField(
+ help_text=(
+ "The log or span attribute key this facet is based on — for example `http.status_code` or `k8s.pod.name`."
+ )
+ )
+ source_type = serializers.ChoiceField(
+ choices=["attribute", "resourceAttribute"],
+ help_text=(
+ "Where the key lives: `attribute` for a plain log/span attribute, `resourceAttribute` for an "
+ "OpenTelemetry resource attribute."
+ ),
+ )
+
+
+class UserFacetSettingsSerializer(serializers.Serializer):
+ custom_facets = UserFacetSettingsEntrySerializer(
+ many=True,
+ help_text=(
+ "Ordered list of custom facets the user has pinned for this product, within the current team. "
+ "Send the full list to replace the existing set."
+ ),
+ )
+
+
+PRODUCT_PARAMETER = OpenApiParameter(
+ name="product",
+ type=str,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ enum=UserFacetSettings.Product.values,
+ description="Which product's custom facets to read or update.",
+)
+
+
+@extend_schema(extensions={"x-product": "platform_features"})
+@extend_schema_view(
+ retrieve=extend_schema(
+ description=(
+ "Get the authenticated user's custom facets for a product, within the current team. Pass `@me` as the UUID."
+ ),
+ parameters=[PRODUCT_PARAMETER],
+ responses={200: UserFacetSettingsSerializer},
+ ),
+ partial_update=extend_schema(
+ description=(
+ "Replace the authenticated user's custom facets for a product, within the current team. "
+ "Pass `@me` as the UUID."
+ ),
+ parameters=[PRODUCT_PARAMETER],
+ request=UserFacetSettingsSerializer,
+ responses={200: UserFacetSettingsSerializer},
+ ),
+)
+class UserFacetSettingsViewSet(viewsets.GenericViewSet):
+ scope_object = "user"
+ serializer_class = UserFacetSettingsSerializer
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ throttle_classes = [UserAuthenticationThrottle]
+ queryset = User.objects.filter(is_active=True)
+ lookup_field = "uuid"
+
+ def get_object(self) -> User:
+ lookup_value = self.kwargs[self.lookup_field]
+ request_user = cast(User, self.request.user)
+
+ if lookup_value == "@me":
+ self.check_object_permissions(self.request, request_user)
+ return request_user
+
+ if not request_user.is_staff:
+ raise exceptions.PermissionDenied(
+ "As a non-staff user you're only allowed to access the `@me` user instance."
+ )
+
+ return super().get_object()
+
+ def get_queryset(self) -> QuerySet[User]:
+ queryset = super().get_queryset()
+ if not self.request.user.is_staff:
+ queryset = queryset.filter(id=self.request.user.id)
+ return queryset
+
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ instance = self.get_object()
+ product = self._get_product()
+ team_id = self._get_team_id(instance)
+
+ # Read-only: most users never pin a facet, so a missing row reads as an empty list
+ # instead of creating one per user/team/product on every rail mount.
+ with team_scope(team_id):
+ custom_facets = (
+ UserFacetSettings.objects.filter(user=instance, team_id=team_id, product=product)
+ .values_list("custom_facets", flat=True)
+ .first()
+ )
+ return Response({"custom_facets": custom_facets or []})
+
+ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ instance = self.get_object()
+ product = self._get_product()
+ team_id = self._get_team_id(instance)
+
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ with team_scope(team_id):
+ settings, _ = UserFacetSettings.objects.update_or_create(
+ user=instance,
+ team_id=team_id,
+ product=product,
+ defaults={"custom_facets": serializer.validated_data["custom_facets"]},
+ )
+
+ return Response({"custom_facets": settings.custom_facets})
+
+ def _get_product(self) -> str:
+ product = self.request.query_params.get("product")
+ if product not in UserFacetSettings.Product.values:
+ raise serializers.ValidationError(
+ f"`product` query parameter is required and must be one of: "
+ f"{', '.join(UserFacetSettings.Product.values)}."
+ )
+ return product
+
+ def _get_team_id(self, instance: User) -> int:
+ # The id column on the user row is enough — dereferencing `current_team` would fetch the
+ # whole (wide) Team row on every request.
+ team_id = instance.current_team_id
+ if not team_id:
+ raise serializers.ValidationError("Current team is required to manage custom facets.")
+ return team_id
diff --git a/posthog/migrations/1321_add_user_facet_settings.py b/posthog/migrations/1321_add_user_facet_settings.py
new file mode 100644
index 000000000000..9273957b2d1a
--- /dev/null
+++ b/posthog/migrations/1321_add_user_facet_settings.py
@@ -0,0 +1,65 @@
+# Generated by Django 5.2.17 on 2026-08-19 12:09
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1320_remove_oauth_scope_trgm"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="UserFacetSettings",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "product",
+ models.CharField(
+ choices=[("logs", "Logs"), ("tracing", "Tracing")],
+ max_length=32,
+ ),
+ ),
+ ("custom_facets", models.JSONField(blank=True, default=list)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ db_index=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="facet_settings",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team", "user", "product"),
+ name="posthog_unique_user_facet_settings",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index b16fcf150e55..fe3447b0c2be 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1320_remove_oauth_scope_trgm
+1321_add_user_facet_settings
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index a21dbbe9ac73..1556d7c793b8 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -75,6 +75,7 @@ from .repo_routing_rule import RepoRoutingRule
from .user_repo_preference import UserRepoPreference
from .user_scene_personalisation import UserScenePersonalisation
from .user_home_settings import UserHomeSettings
+from .user_facet_settings import UserFacetSettings
from .oauth import (
CIMDVerificationToken,
OAuthAccessToken,
@@ -174,6 +175,7 @@ __all__ = [
"UserRepoPreference",
"UserScenePersonalisation",
"UserHomeSettings",
+ "UserFacetSettings",
"UserManager",
"UserGroup",
"UserGroupMembership",
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 62f8d5c074b1..141be69fd52c 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -794,6 +794,9 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"totp_devices",
"static_devices",
"recovery_devices",
+ # Reads through UserFacetSettings' own fail-closed TeamScopedManager, which has no
+ # ambient team scope at signal-handling time (same reason Loop excludes triggers/fires).
+ "facet_settings",
],
"AlertConfiguration": [
"last_checked_at",
diff --git a/posthog/models/user_facet_settings.py b/posthog/models/user_facet_settings.py
new file mode 100644
index 000000000000..293a405adc8f
--- /dev/null
+++ b/posthog/models/user_facet_settings.py
@@ -0,0 +1,32 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDTModel
+
+
+class UserFacetSettings(UUIDTModel, TeamScopedRootMixin):
+ """Stores a user's custom facets (pinned log/span attributes) for a product within a team."""
+
+ class Product(models.TextChoices):
+ LOGS = "logs"
+ TRACING = "tracing"
+
+ user = models.ForeignKey(
+ "User",
+ on_delete=models.CASCADE,
+ related_name="facet_settings",
+ db_constraint=False,
+ )
+ # No standalone index: the (team, user, product) unique constraint already leads on team_id.
+ team = models.ForeignKey("Team", on_delete=models.CASCADE, db_constraint=False, db_index=False)
+ product = models.CharField(max_length=32, choices=Product.choices)
+ custom_facets = models.JSONField(default=list, blank=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "user", "product"],
+ name="posthog_unique_user_facet_settings",
+ )
+ ]
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx
index e9362f621ea1..c2e2db92aad0 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx
@@ -1,7 +1,7 @@
import { CSSProperties, useMemo } from 'react'
import { List } from 'react-window'
-import { IconChevronDown, IconChevronRight, IconMinusSmall } from '@posthog/icons'
+import { IconChevronDown, IconChevronRight, IconMinusSmall, IconX } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonInput } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
@@ -37,6 +37,10 @@ interface FacetProps {
maxHeight?: number
/** For fixed facets: render zero-count values dimmed, and disabled unless already selected. */
dimZeroCounts?: boolean
+ /** When set, renders a remove control in the header — for user-added custom facets only. */
+ onRemove?: () => void
+ /** Disables the remove control (with this explanation) while a custom-facet update is in flight. */
+ removeDisabledReason?: string
}
/** A single rail facet: a collapsible field title and its selectable values (multi-select = OR), each with a count. */
@@ -55,6 +59,8 @@ export function Facet({
onToggleCollapsed,
maxHeight,
dimZeroCounts = false,
+ onRemove,
+ removeDisabledReason,
}: FacetProps): JSX.Element {
const slug = title.toLowerCase().replace(/\s+/g, '-')
@@ -65,16 +71,28 @@ export function Facet({
return (
<div className="mb-3">
- <button
- type="button"
- onClick={onToggleCollapsed}
- disabled={!onToggleCollapsed}
- className="flex items-center gap-1 w-full px-1 mb-1 text-[10px] font-semibold uppercase tracking-wide text-secondary hover:text-default"
- data-attr={`logs-facet-${slug}-header`}
- >
- {collapsed ? <IconChevronRight /> : <IconChevronDown />}
- <span>{title}</span>
- </button>
+ <div className="flex items-center gap-1 w-full px-1 mb-1">
+ <button
+ type="button"
+ onClick={onToggleCollapsed}
+ disabled={!onToggleCollapsed}
+ className="flex items-center gap-1 flex-1 min-w-0 text-[10px] font-semibold uppercase tracking-wide text-secondary hover:text-default"
+ data-attr={`logs-facet-${slug}-header`}
+ >
+ {collapsed ? <IconChevronRight /> : <IconChevronDown />}
+ <span className="truncate">{title}</span>
+ </button>
+ {onRemove && (
+ <LemonButton
+ size="small"
+ icon={<IconX />}
+ onClick={onRemove}
+ disabledReason={removeDisabledReason}
+ tooltip="Remove custom facet"
+ data-attr={`logs-facet-${slug}-remove`}
+ />
+ )}
+ </div>
{!collapsed && onSearchChange && (
<div className="px-1 pb-1">
<LemonInput
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
index 7b3983a11274..2530cdfff84a 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
@@ -1,13 +1,17 @@
import { useActions, useValues } from 'kea'
import { useCallback, useMemo, useRef } from 'react'
+import { IconPlus } from '@posthog/icons'
import { LemonInput } from '@posthog/lemon-ui'
import { Resizer } from 'lib/components/Resizer/Resizer'
import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { TaxonomicStringPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
+import { customFacetsLogic } from './customFacetsLogic'
import { facetPresenceLogic } from './facetPresenceLogic'
import { facetRailLogic } from './facetRailLogic'
import { facetsByGroup, filterFacetsByName } from './facets'
@@ -15,6 +19,7 @@ import { RailFacet } from './RailFacet'
const DEFAULT_WIDTH_PX = 240
const COLLAPSE_THRESHOLD_PX = 120
+const ADD_FACET_GROUP_TYPES = [TaxonomicFilterGroupType.LogAttributes, TaxonomicFilterGroupType.LogResourceAttributes]
export interface FacetRailProps {
id: string
@@ -27,6 +32,8 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
const { visibleFacets } = useValues(facetPresenceLogic({ id }))
const { facetNameSearch } = useValues(facetRailLogic({ id }))
const { setFacetNameSearch } = useActions(facetRailLogic({ id }))
+ const { addCustomFacet } = useActions(customFacetsLogic)
+ const { customFacetsEnabled, entriesLoading } = useValues(customFacetsLogic)
const onToggleClosed = useCallback(
(shouldBeClosed: boolean) => setFacetRailCollapsed(shouldBeClosed),
@@ -59,7 +66,7 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
style={{ width: desiredSize ?? DEFAULT_WIDTH_PX, minWidth: 'min-content', maxWidth: '40%' }}
data-attr="logs-facet-rail"
>
- <div className="px-2 py-1 border-b">
+ <div className="flex items-center gap-1 px-2 py-1 border-b">
<LemonInput
type="search"
size="small"
@@ -69,6 +76,26 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
onChange={setFacetNameSearch}
data-attr="logs-facet-rail-search"
/>
+ {customFacetsEnabled && (
+ <TaxonomicStringPopover
+ groupType={TaxonomicFilterGroupType.LogAttributes}
+ groupTypes={ADD_FACET_GROUP_TYPES}
+ placeholder={null}
+ size="small"
+ icon={<IconPlus />}
+ tooltip="Add custom facet"
+ disabledReason={entriesLoading ? 'Custom facets are updating' : undefined}
+ data-attr="logs-facet-rail-add"
+ onChange={(value, groupType) =>
+ addCustomFacet(
+ value,
+ groupType === TaxonomicFilterGroupType.LogResourceAttributes
+ ? 'resourceAttribute'
+ : 'attribute'
+ )
+ }
+ />
+ )}
</div>
<div className="flex-1 min-h-0 overflow-y-auto p-2">
{matchingKeys.size === 0 && facetNameSearch.trim() && (
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
index 94034d78adb5..1fc300969193 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
@@ -3,10 +3,11 @@ import { useCallback, useMemo } from 'react'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
+import { customFacetsLogic } from './customFacetsLogic'
import { Facet, FacetOption } from './Facet'
import { facetFilterTarget, facetSelection } from './facetFilters'
import { facetRailLogic } from './facetRailLogic'
-import { FacetConfig, mergeSelectedIntoOptions } from './facets'
+import { FacetConfig, customFacetIdentity, mergeSelectedIntoOptions } from './facets'
import { facetValuesLogic } from './facetValuesLogic'
export interface RailFacetProps {
@@ -27,6 +28,9 @@ export function RailFacet({ id, facet, hidden }: RailFacetProps): JSX.Element |
const { setFacetSearch } = useActions(facetValuesLogic(logicProps))
const { filterGroup } = useValues(logsViewerFiltersLogic({ id }))
const { toggleFacetValue, toggleFacetCollapsed } = useActions(facetRailLogic({ id }))
+ const { removeCustomFacet } = useActions(customFacetsLogic)
+ const { entriesLoading } = useValues(customFacetsLogic)
+ const removeDisabledReason = entriesLoading ? 'Custom facets are updating' : undefined
const { source } = facet
// Everything the value rows are built from is memoized: Facet feeds them to a virtualized list
@@ -63,6 +67,11 @@ export function RailFacet({ id, facet, hidden }: RailFacetProps): JSX.Element |
(): void => toggleFacetCollapsed(facet.key),
[toggleFacetCollapsed, facet.key]
)
+ // Only custom facets carry an identity; curated facets get no remove control.
+ const onRemove = useMemo(() => {
+ const customIdentity = customFacetIdentity(facet)
+ return customIdentity ? (): void => removeCustomFacet(customIdentity.key, customIdentity.sourceType) : undefined
+ }, [facet, removeCustomFacet])
if (hidden) {
return null
@@ -80,6 +89,8 @@ export function RailFacet({ id, facet, hidden }: RailFacetProps): JSX.Element |
collapsed={collapsed}
onToggleCollapsed={onToggleCollapsed}
dimZeroCounts
+ onRemove={onRemove}
+ removeDisabledReason={removeDisabledReason}
/>
)
}
@@ -99,6 +110,8 @@ export function RailFacet({ id, facet, hidden }: RailFacetProps): JSX.Element |
collapsed={collapsed}
onToggleCollapsed={onToggleCollapsed}
maxHeight={facet.maxHeight}
+ onRemove={onRemove}
+ removeDisabledReason={removeDisabledReason}
/>
)
}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.test.ts
new file mode 100644
index 000000000000..bce44fd5e692
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.test.ts
@@ -0,0 +1,154 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ userFacetSettingsPartialUpdate,
+ userFacetSettingsRetrieve,
+} from 'products/platform_features/frontend/generated/api'
+import { UserFacetSettingsEntrySourceTypeEnumApi } from 'products/platform_features/frontend/generated/api.schemas'
+
+import { customFacetsLogic } from './customFacetsLogic'
+
+jest.mock('products/platform_features/frontend/generated/api', () => ({
+ __esModule: true,
+ userFacetSettingsRetrieve: jest.fn(),
+ userFacetSettingsPartialUpdate: jest.fn(),
+}))
+
+const mockRetrieve = userFacetSettingsRetrieve as jest.MockedFunction<typeof userFacetSettingsRetrieve>
+const mockPartialUpdate = userFacetSettingsPartialUpdate as jest.MockedFunction<typeof userFacetSettingsPartialUpdate>
+
+describe('customFacetsLogic', () => {
+ // A singleton logic (no `key`) — each test sets up its mocks, then mounts fresh via `mount()`
+ // below. Mounting inside `beforeEach` would fire `afterMount` before a test's own mock override
+ // took effect, since re-calling the wrapper mid-test returns the same already-mounted instance.
+ let logic: ReturnType<typeof customFacetsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.clearAllMocks()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
+ mockRetrieve.mockResolvedValue({ custom_facets: [] })
+ mockPartialUpdate.mockImplementation(async (_uuid, _params, body) => ({
+ custom_facets: body?.custom_facets ?? [],
+ }))
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ function mount(): ReturnType<typeof customFacetsLogic.build> {
+ logic = customFacetsLogic()
+ logic.mount()
+ return logic
+ }
+
+ it('does not load or expose custom facets when the feature flag is off', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockRetrieve).not.toHaveBeenCalled()
+ expect(logic.values.customFacets).toEqual([])
+ })
+
+ it('loads entries when the flag arrives after mount', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ mount()
+ expect(mockRetrieve).not.toHaveBeenCalled()
+
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
+ await expectLogic(logic).toDispatchActions(['loadEntries', 'loadEntriesSuccess'])
+ })
+
+ it('mutations build on the persisted list when entries have not loaded yet', async () => {
+ // A PATCH replaces the whole server-side list — building it on unloaded local state would
+ // wipe every facet the user pinned elsewhere.
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ mockRetrieve.mockResolvedValue({
+ custom_facets: [
+ { key: 'pinned.elsewhere', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ ],
+ })
+ mount()
+ logic.actions.addCustomFacet('log.iostream', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(mockPartialUpdate).toHaveBeenCalledWith(
+ '@me',
+ { product: 'logs' },
+ {
+ custom_facets: [
+ { key: 'pinned.elsewhere', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ { key: 'log.iostream', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ ],
+ }
+ )
+ })
+
+ it('loads persisted entries on mount and exposes them as facet configs', async () => {
+ mockRetrieve.mockResolvedValue({
+ custom_facets: [{ key: 'log.iostream', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute }],
+ })
+ mount()
+ await expectLogic(logic).toDispatchActions(['loadEntriesSuccess'])
+
+ expect(logic.values.customFacets).toEqual([
+ expect.objectContaining({
+ key: 'custom:attribute:log.iostream',
+ source: { type: 'attribute', key: 'log.iostream' },
+ }),
+ ])
+ })
+
+ it('adding a facet persists the full updated list and updates local state', async () => {
+ mount()
+ logic.actions.addCustomFacet('log.iostream', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(logic.values.entries).toEqual([
+ { key: 'log.iostream', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ ])
+ expect(mockPartialUpdate).toHaveBeenCalledWith(
+ '@me',
+ { product: 'logs' },
+ { custom_facets: [{ key: 'log.iostream', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute }] }
+ )
+ })
+
+ it('adding the same key and sourceType twice does not duplicate or persist again', async () => {
+ mount()
+ logic.actions.addCustomFacet('log.iostream', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+ mockPartialUpdate.mockClear()
+
+ logic.actions.addCustomFacet('log.iostream', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(logic.values.entries).toHaveLength(1)
+ expect(mockPartialUpdate).not.toHaveBeenCalled()
+ })
+
+ it('removing a facet only drops the matching key+sourceType pair', async () => {
+ // The same key can exist as both an attribute and a resource-attribute facet — removing one
+ // must not also remove the other.
+ mount()
+ logic.actions.addCustomFacet('environment', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+ logic.actions.addCustomFacet('environment', 'resourceAttribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ logic.actions.removeCustomFacet('environment', 'attribute')
+ await expectLogic(logic).toDispatchActions(['removeCustomFacetSuccess'])
+
+ expect(logic.values.entries).toEqual([
+ { key: 'environment', source_type: UserFacetSettingsEntrySourceTypeEnumApi.ResourceAttribute },
+ ])
+ })
+})
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.ts
new file mode 100644
index 000000000000..7be2e72e92e7
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.ts
@@ -0,0 +1,223 @@
+import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import {
+ userFacetSettingsPartialUpdate,
+ userFacetSettingsRetrieve,
+} from 'products/platform_features/frontend/generated/api'
+import { UserFacetSettingsEntryApi } from 'products/platform_features/frontend/generated/api.schemas'
+
+import { CustomFacetSourceType, FacetConfig, buildCustomFacet } from './facets'
+
+const PRODUCT = 'logs' as const
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface customFacetsLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ customFacets: FacetConfig[]
+ customFacetsEnabled: boolean
+ entries: UserFacetSettingsEntryApi[]
+ entriesLoaded: boolean
+ entriesLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface customFacetsLogicActions {
+ addCustomFacet: (
+ key: string,
+ sourceType: CustomFacetSourceType
+ ) => {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ addCustomFacetFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ addCustomFacetSuccess: (
+ entries: UserFacetSettingsEntryApi[],
+ payload?: {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ ) => {
+ entries: UserFacetSettingsEntryApi[]
+ payload?: {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ }
+ loadEntries: () => {
+ value: true
+ }
+ loadEntriesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadEntriesSuccess: (
+ entries: UserFacetSettingsEntryApi[],
+ payload?: {
+ value: true
+ }
+ ) => {
+ entries: UserFacetSettingsEntryApi[]
+ payload?: {
+ value: true
+ }
+ }
+ removeCustomFacet: (
+ key: string,
+ sourceType: CustomFacetSourceType
+ ) => {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ removeCustomFacetFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ removeCustomFacetSuccess: (
+ entries: UserFacetSettingsEntryApi[],
+ payload?: {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ ) => {
+ entries: UserFacetSettingsEntryApi[]
+ payload?: {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface customFacetsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ customFacetsEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ customFacets: (entries: UserFacetSettingsEntryApi[], customFacetsEnabled: boolean) => FacetConfig[]
+ }
+}
+
+export type customFacetsLogicType = MakeLogicType<
+ customFacetsLogicValues,
+ customFacetsLogicActions,
+ Record<string, any>,
+ customFacetsLogicMeta
+>
+
+/**
+ * The user's custom facets for logs, persisted server-side (per user, per team) so they follow the
+ * user across devices. A singleton (not keyed by viewer id): the underlying setting is one row per
+ * user/team/product, not one per rail instance.
+ */
+export const customFacetsLogic = kea<customFacetsLogicType>([
+ path(['products', 'logs', 'frontend', 'components', 'LogsViewer', 'FacetRail', 'customFacetsLogic']),
+
+ connect(() => ({ values: [featureFlagLogic, ['featureFlags']] })),
+
+ actions({
+ loadEntries: true,
+ addCustomFacet: (key: string, sourceType: CustomFacetSourceType) => ({ key, sourceType }),
+ removeCustomFacet: (key: string, sourceType: CustomFacetSourceType) => ({ key, sourceType }),
+ }),
+
+ loaders(({ values }) => {
+ // The PATCH replaces the whole server-side list, so a mutation must build on the persisted
+ // entries: local state can be empty when the load failed or never ran, and using it as the
+ // base would wipe the user's saved facets.
+ const baseEntries = async (): Promise<UserFacetSettingsEntryApi[]> =>
+ values.entriesLoaded
+ ? values.entries
+ : (await userFacetSettingsRetrieve('@me', { product: PRODUCT })).custom_facets
+ return {
+ entries: [
+ [] as UserFacetSettingsEntryApi[],
+ {
+ loadEntries: async () => {
+ const response = await userFacetSettingsRetrieve('@me', { product: PRODUCT })
+ return response.custom_facets
+ },
+ addCustomFacet: async ({ key, sourceType }) => {
+ const base = await baseEntries()
+ if (base.some((entry) => entry.key === key && entry.source_type === sourceType)) {
+ return base
+ }
+ const nextEntries = [...base, { key, source_type: sourceType }]
+ await userFacetSettingsPartialUpdate(
+ '@me',
+ { product: PRODUCT },
+ { custom_facets: nextEntries }
+ )
+ return nextEntries
+ },
+ removeCustomFacet: async ({ key, sourceType }) => {
+ const base = await baseEntries()
+ const nextEntries = base.filter(
+ (entry) => !(entry.key === key && entry.source_type === sourceType)
+ )
+ await userFacetSettingsPartialUpdate(
+ '@me',
+ { product: PRODUCT },
+ { custom_facets: nextEntries }
+ )
+ return nextEntries
+ },
+ },
+ ],
+ }
+ }),
+
+ reducers({
+ entriesLoaded: [
+ false,
+ {
+ loadEntriesSuccess: () => true,
+ },
+ ],
+ }),
+
+ selectors({
+ // A primitive, so downstream facet identities only change when the gate actually flips —
+ // the featureFlags object gets a fresh identity on every flag refresh.
+ customFacetsEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.CUSTOM_FACET_PINNING],
+ ],
+ customFacets: [
+ (s) => [s.entries, s.customFacetsEnabled],
+ (entries: UserFacetSettingsEntryApi[], customFacetsEnabled: boolean): FacetConfig[] =>
+ customFacetsEnabled ? entries.map((entry) => buildCustomFacet(entry.key, entry.source_type)) : [],
+ ],
+ }),
+
+ listeners(({ actions, values }) => ({
+ // Flags resolve asynchronously and often land after this logic mounts — without this, a
+ // flagged user's pinned facets would stay unloaded for the whole session.
+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
+ if (values.customFacetsEnabled && !values.entriesLoaded && !values.entriesLoading) {
+ actions.loadEntries()
+ }
+ },
+ })),
+
+ events(({ actions, values }) => ({
+ afterMount: () => {
+ if (values.customFacetsEnabled) {
+ actions.loadEntries()
+ }
+ },
+ })),
+])
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.test.ts
index f313cb0b7437..89a0658d6b98 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.test.ts
@@ -10,6 +10,7 @@ import {
setFacetIncluded,
setFacetSelection,
} from './facetFilters'
+import type { FacetSource } from './facets'
const NAMESPACE: FacetFilterTarget = {
key: 'k8s.namespace.name',
@@ -32,10 +33,10 @@ const innerValues = (group: UniversalFiltersGroup): unknown[] => (group.values[0
describe('facetFilters', () => {
describe('facetFilterTarget', () => {
- it.each<[string, string, FacetFilterTarget]>([
+ it.each<[string, FacetSource, FacetFilterTarget]>([
[
'a column facet stores its selection as a log filter under its logKey',
- 'severity_text',
+ { type: 'column', column: 'severity_text', logKey: 'severity_level' },
{
key: 'severity_level',
type: PropertyFilterType.Log,
@@ -43,14 +44,18 @@ describe('facetFilters', () => {
],
[
'a resource-attribute facet stores its selection under its attribute key',
- 'k8s.namespace.name',
+ { type: 'resourceAttribute', key: 'k8s.namespace.name' },
NAMESPACE,
],
- ])('%s', (_, key, expected) => {
- const source =
- key === 'severity_text'
- ? ({ type: 'column', column: 'severity_text', logKey: 'severity_level' } as const)
- : ({ type: 'resourceAttribute', key } as const)
+ [
+ 'a plain-attribute (custom) facet stores its selection as log_attribute, not log_resource_attribute',
+ { type: 'attribute', key: 'log.iostream' },
+ {
+ key: 'log.iostream',
+ type: PropertyFilterType.LogAttribute,
+ },
+ ],
+ ])('%s', (_, source, expected) => {
expect(facetFilterTarget(source)).toEqual(expected)
})
})
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.ts
index caced86d8142..2e8f9f440bb3 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.ts
@@ -18,8 +18,8 @@ import type { FacetSource } from './facets'
/**
* The property filter a selection is stored under: one type + key pair, holding both polarities. The
- * rail only ever names a `log` column or a `log_resource_attribute`, but the search bar reconciles
- * whatever type the picker produced, so the type stays open.
+ * rail names a `log` column, a `log_resource_attribute`, or (for custom facets) a `log_attribute`,
+ * but the search bar reconciles whatever type the picker produced, so the type stays open.
*/
export interface FacetFilterTarget {
key: string
@@ -95,9 +95,14 @@ export function filterValues(filter: { value?: PropertyFilterValue }): unknown[]
/** The filterGroup property filter a facet's selection is stored in, derived from its source. */
export function facetFilterTarget(source: FacetSource): FacetFilterTarget {
- return source.type === 'column'
- ? { key: source.logKey, type: PropertyFilterType.Log }
- : { key: source.key, type: PropertyFilterType.LogResourceAttribute }
+ switch (source.type) {
+ case 'column':
+ return { key: source.logKey, type: PropertyFilterType.Log }
+ case 'attribute':
+ return { key: source.key, type: PropertyFilterType.LogAttribute }
+ case 'resourceAttribute':
+ return { key: source.key, type: PropertyFilterType.LogResourceAttribute }
+ }
}
/** A facet's selection, read from the exact (include) and is_not (exclude) filters it owns. */
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts
index f4481fbc3a3f..b996a276b030 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts
@@ -4,6 +4,7 @@ import { loaders } from 'kea-loaders'
import { teamLogic } from 'scenes/teamLogic'
import { logsAttributesRetrieve } from '../../../generated/api'
+import { customFacetsLogic } from './customFacetsLogic'
import { FACETS, FacetConfig, resolveFacets } from './facets'
// Broad, filter-independent window for the "which resource attributes does this tenant emit" probe.
@@ -16,9 +17,11 @@ export interface FacetPresenceLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetPresenceLogicValues {
+ customFacets: FacetConfig[] // customFacetsLogic
currentTeamId: number | null // teamLogic
presentResourceKeys: string[]
presentResourceKeysLoading: boolean
+ resolvedFacets: FacetConfig[]
visibleFacets: FacetConfig[]
}
@@ -45,7 +48,8 @@ export interface facetPresenceLogicActions {
export interface facetPresenceLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
- visibleFacets: (presentResourceKeys: string[]) => FacetConfig[]
+ resolvedFacets: (presentResourceKeys: string[]) => FacetConfig[]
+ visibleFacets: (resolvedFacets: FacetConfig[], customFacets: FacetConfig[]) => FacetConfig[]
}
}
@@ -68,7 +72,7 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([
path((key) => ['products', 'logs', 'frontend', 'components', 'LogsViewer', 'FacetRail', 'facetPresenceLogic', key]),
connect(() => ({
- values: [teamLogic, ['currentTeamId']],
+ values: [teamLogic, ['currentTeamId'], customFacetsLogic, ['customFacets']],
})),
loaders(({ values }) => ({
@@ -93,11 +97,22 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([
selectors({
// Column facets always render; resource-attribute facets only when the tenant emits the key (or one
- // of its aliases, which resolution rewrites the facet onto).
- visibleFacets: [
+ // of its aliases, which resolution rewrites the facet onto). Custom facets skip that presence gate
+ // entirely — the user picked them from a live taxonomic list, so they're known to exist already —
+ // and render last, after every curated facet.
+ // Intermediate so curated facet identities stay stable across custom-facet changes — a fresh
+ // alias-resolved FacetConfig would re-render every virtualized value row (see RailFacet).
+ resolvedFacets: [
(s) => [s.presentResourceKeys],
(presentResourceKeys: string[]): FacetConfig[] => resolveFacets(FACETS, presentResourceKeys),
],
+ visibleFacets: [
+ (s) => [s.resolvedFacets, s.customFacets],
+ (resolvedFacets: FacetConfig[], customFacets: FacetConfig[]): FacetConfig[] => [
+ ...resolvedFacets,
+ ...customFacets,
+ ],
+ ],
}),
events(({ actions }) => ({
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts
index 2103611fd49e..3378ee98b710 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts
@@ -6,7 +6,7 @@ import { logsAttributesRetrieve, logsFacetValuesCreate } from 'products/logs/fro
import { logsViewerFiltersLogic } from '../Filters/logsViewerFiltersLogic'
import { facetRailLogic } from './facetRailLogic'
-import { FACETS, FacetConfig } from './facets'
+import { FACETS, FacetConfig, buildCustomFacet } from './facets'
import { facetValuesLogic } from './facetValuesLogic'
jest.mock('products/logs/frontend/generated/api', () => ({
@@ -89,6 +89,26 @@ describe('facetValuesLogic', () => {
)
})
+ // Each source type must route to its own facet* body field — a binary-to-ternary slip (e.g. a
+ // plain attribute silently querying as a resource attribute) would misreport values with no
+ // type error, since _LogsFacetValuesBodyApi accepts any of the three.
+ it.each<[string, FacetConfig, Record<string, string>]>([
+ ['a column facet', SERVICE, { facetField: 'service_name' }],
+ ['a resource-attribute facet', facetConfig('namespace'), { facetResourceAttribute: 'k8s.namespace.name' }],
+ [
+ 'a custom plain-attribute facet',
+ buildCustomFacet('log.iostream', 'attribute'),
+ { facetAttribute: 'log.iostream' },
+ ],
+ ])('%s requests the matching facet* body field', async (_, facet, expectedFields) => {
+ const logic = mountFacet(facet)
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])
+ expect(mockFacetValues).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ query: expect.objectContaining(expectedFields) })
+ )
+ })
+
it('a collapsed facet defers its fetch until it is expanded, then only if the scope moved', async () => {
railLogic.actions.toggleFacetCollapsed(SERVICE.key)
const logic = mountFacet(SERVICE)
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
index 68d4a7327f6b..aa06c31cb22c 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
@@ -175,7 +175,9 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
const target: Partial<_LogsFacetValuesBodyApi> =
source.type === 'column'
? { facetField: source.column }
- : { facetResourceAttribute: source.key }
+ : source.type === 'attribute'
+ ? { facetAttribute: source.key }
+ : { facetResourceAttribute: source.key }
const response = await logsFacetValuesCreate(String(values.currentTeamId), {
query: {
...target,
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
index cb27fc07a6d8..10a452ef87f9 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
@@ -5,6 +5,8 @@ import {
FACETS as CONFIGURED_FACETS,
FacetConfig,
FacetScope,
+ buildCustomFacet,
+ customFacetIdentity,
facetScopeSignature,
filterFacetsByName,
mergeSelectedIntoOptions,
@@ -303,5 +305,26 @@ describe('facets', () => {
it('keeps column facets whatever the tenant emits', () => {
expect(resolveFacets(CONFIGURED_FACETS, []).map((f) => f.key)).toEqual(['level', 'service'])
})
+
+ it('passes a plain-attribute facet through unchanged, regardless of presence', () => {
+ // Custom facets are added by the user picking a real key, not resolved against a curated
+ // alias list — resolveFacets must never drop or rewrite them the way it does resourceAttribute.
+ const attributeFacet = buildCustomFacet('http.status_code', 'attribute')
+ expect(resolveFacets([attributeFacet], [])).toEqual([attributeFacet])
+ })
+ })
+
+ describe('buildCustomFacet / customFacetIdentity', () => {
+ it.each<['attribute' | 'resourceAttribute']>([['attribute'], ['resourceAttribute']])(
+ 'round-trips the key and sourceType through a %s facet',
+ (sourceType) => {
+ const built = buildCustomFacet('http.status_code', sourceType)
+ expect(customFacetIdentity(built)).toEqual({ key: 'http.status_code', sourceType })
+ }
+ )
+
+ it('returns null for a curated facet', () => {
+ expect(customFacetIdentity(CONFIGURED_FACETS[0])).toBeNull()
+ })
})
})
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
index 64693586fc2f..d22bec250a9e 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
@@ -1,9 +1,15 @@
-import { PropertyFilterType, UniversalFiltersGroup } from '~/types'
+import { UniversalFiltersGroup } from '~/types'
import { SEVERITY_BAR_COLORS } from 'products/logs/frontend/components/VirtualizedLogsList/columnDefinitions'
import { FacetOption } from './Facet'
-import { SERVICE_NAME_FILTER, SEVERITY_LEVEL_FILTER, innerFilters, isPropertyLeaf } from './facetFilters'
+import {
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ facetFilterTarget,
+ innerFilters,
+ isPropertyLeaf,
+} from './facetFilters'
/**
* Whether a facet's value set is known ahead of time or discovered from the data.
@@ -26,6 +32,9 @@ export type FacetField = 'severity_text' | 'service_name'
* - `column`: a top-level logs column, filtered through a `log` property filter under `logKey`.
* - `resourceAttribute`: a `resource_attributes` map key (e.g. k8s.namespace.name), filtered through
* a `log_resource_attribute` property filter under `key`.
+ * - `attribute`: a plain (non-resource) log attribute key, filtered through a `log_attribute`
+ * property filter under `key`. Only used by user-added custom facets today — no curated `FACETS`
+ * entry uses it.
*/
export type FacetSource =
| {
@@ -41,6 +50,7 @@ export type FacetSource =
logKey: string
}
| { type: 'resourceAttribute'; key: string; aliasKeys?: string[] }
+ | { type: 'attribute'; key: string }
export interface FacetConfig {
/** Stable id used for collapse state and data-attrs. */
@@ -59,6 +69,8 @@ export interface FacetConfig {
emptyLabel?: string
/** Max pixel height before the value list virtualizes and scrolls. */
maxHeight?: number
+ /** The (key, sourceType) a user-added custom facet was built from; curated facets never set it. */
+ custom?: { key: string; sourceType: CustomFacetSourceType }
}
/** The data key a facet is queried on: its column, or the resource-attribute key resolution picked. */
@@ -88,24 +100,16 @@ export interface FacetScope {
*/
export function facetScopeSignature(facet: FacetConfig, scope: FacetScope): string {
const { source } = facet
- const selfLogKey = source.type === 'column' ? source.logKey : undefined
- const selfResourceKey = source.type === 'resourceAttribute' ? source.key : undefined
+ // The facet's own filter target — the backend strips filters under it wholesale (any operator,
+ // both polarities), so they must not enter the signature.
+ const self = facetFilterTarget(source)
const groupSignature = innerFilters(scope.queryFilterGroup)
.map((entry): unknown[] | null => {
if (!isPropertyLeaf(entry)) {
// Nested groups aren't leaves the backend can strip — carry them whole.
return ['group', JSON.stringify(entry)]
}
- // Any operator: the backend skips a log filter under the facet's own column wholesale.
- if (selfLogKey !== undefined && entry.type === PropertyFilterType.Log && entry.key === selfLogKey) {
- return null
- }
- // Both polarities, any operator.
- if (
- selfResourceKey !== undefined &&
- entry.type === PropertyFilterType.LogResourceAttribute &&
- entry.key === selfResourceKey
- ) {
+ if (entry.type === self.type && entry.key === self.key) {
return null
}
return [entry.type, entry.key, entry.operator, JSON.stringify(entry.value ?? null)]
@@ -116,7 +120,7 @@ export function facetScopeSignature(facet: FacetConfig, scope: FacetScope): stri
// A facet mounted before the team resolved fetches nothing; keeping the id in the signature
// makes it fetch once the team arrives.
scope.currentTeamId ?? null,
- source.type === 'column' ? ['column', source.column] : ['resource', source.key],
+ [source.type, facetSourceKey(facet)],
scope.utcDateRange.date_from ?? null,
scope.utcDateRange.date_to ?? null,
scope.utcDateRange.explicitDate ?? null,
@@ -226,7 +230,7 @@ export function resolveFacets(facets: FacetConfig[], presentResourceKeys: string
const present = new Set(presentResourceKeys)
const resolved: FacetConfig[] = []
for (const facet of facets) {
- if (facet.source.type === 'column') {
+ if (facet.source.type !== 'resourceAttribute') {
resolved.push(facet)
continue
}
@@ -287,3 +291,26 @@ export function facetsByGroup(facets: FacetConfig[]): [string, FacetConfig[]][]
}
return groups
}
+
+/** A custom facet's source kind, as persisted per-user — mirrors the backend's `source_type` choices. */
+export type CustomFacetSourceType = 'attribute' | 'resourceAttribute'
+
+/** Builds a rail-renderable FacetConfig for a user-added custom facet — always dynamic, with a remove control. */
+export function buildCustomFacet(key: string, sourceType: CustomFacetSourceType): FacetConfig {
+ return {
+ key: `custom:${sourceType}:${key}`,
+ title: key,
+ group: 'Custom',
+ kind: 'dynamic',
+ source: sourceType === 'attribute' ? { type: 'attribute', key } : { type: 'resourceAttribute', key },
+ searchable: true,
+ emptyLabel: `No ${key} values`,
+ maxHeight: 300,
+ custom: { key, sourceType },
+ }
+}
+
+/** The (key, sourceType) a custom facet was built from — `null` for a curated facet. */
+export function customFacetIdentity(facet: FacetConfig): { key: string; sourceType: CustomFacetSourceType } | null {
+ return facet.custom ?? null
+}
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index a15a2d538125..aef4382dbb5a 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -949,6 +949,38 @@ export interface CommentSlackThreadApi {
readonly created_by: UserBasicApi | null
}
+/**
+ * * `attribute` - attribute
+ * * `resourceAttribute` - resourceAttribute
+ */
+export type UserFacetSettingsEntrySourceTypeEnumApi =
+ (typeof UserFacetSettingsEntrySourceTypeEnumApi)[keyof typeof UserFacetSettingsEntrySourceTypeEnumApi]
+
+export const UserFacetSettingsEntrySourceTypeEnumApi = {
+ Attribute: 'attribute',
+ ResourceAttribute: 'resourceAttribute',
+} as const
+
+export interface UserFacetSettingsEntryApi {
+ /** The log or span attribute key this facet is based on — for example `http.status_code` or `k8s.pod.name`. */
+ key: string
+ /** Where the key lives: `attribute` for a plain log/span attribute, `resourceAttribute` for an OpenTelemetry resource attribute.
+ *
+ * * `attribute` - attribute
+ * * `resourceAttribute` - resourceAttribute */
+ source_type: UserFacetSettingsEntrySourceTypeEnumApi
+}
+
+export interface UserFacetSettingsApi {
+ /** Ordered list of custom facets the user has pinned for this product, within the current team. Send the full list to replace the existing set. */
+ custom_facets: UserFacetSettingsEntryApi[]
+}
+
+export interface PatchedUserFacetSettingsApi {
+ /** Ordered list of custom facets the user has pinned for this product, within the current team. Send the full list to replace the existing set. */
+ custom_facets?: UserFacetSettingsEntryApi[]
+}
+
export interface PinnedSceneTabApi {
/** Stable identifier for the tab. Generated client-side; safe to omit on create. */
id?: string
@@ -1641,3 +1673,33 @@ export const CommentsListKind = {
Comment: 'comment',
Task: 'task',
} as const
+
+export type UserFacetSettingsRetrieveParams = {
+ /**
+ * Which product's custom facets to read or update.
+ */
+ product: UserFacetSettingsRetrieveProduct
+}
+
+export type UserFacetSettingsRetrieveProduct =
+ (typeof UserFacetSettingsRetrieveProduct)[keyof typeof UserFacetSettingsRetrieveProduct]
+
+export const UserFacetSettingsRetrieveProduct = {
+ Logs: 'logs',
+ Tracing: 'tracing',
+} as const
+
+export type UserFacetSettingsPartialUpdateParams = {
+ /**
+ * Which product's custom facets to read or update.
+ */
+ product: UserFacetSettingsPartialUpdateProduct
+}
+
+export type UserFacetSettingsPartialUpdateProduct =
+ (typeof UserFacetSettingsPartialUpdateProduct)[keyof typeof UserFacetSettingsPartialUpdateProduct]
+
+export const UserFacetSettingsPartialUpdateProduct = {
+ Logs: 'logs',
+ Tracing: 'tracing',
+} as const
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index df291492a227..2b3cb4d10ded 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -46,6 +46,7 @@ import type {
PatchedOrganizationMemberApi,
PatchedPinnedSceneTabsApi,
PatchedRoleApi,
+ PatchedUserFacetSettingsApi,
PersonalApiKeysListParams,
PinnedSceneTabsApi,
RoleApi,
@@ -53,6 +54,9 @@ import type {
RolesListParams,
RolesRoleMembershipsListParams,
SendCommentToSlackApi,
+ UserFacetSettingsApi,
+ UserFacetSettingsPartialUpdateParams,
+ UserFacetSettingsRetrieveParams,
WelcomeResponseApi,
} from './api.schemas'
@@ -1090,6 +1094,69 @@ export const commentsCountRetrieve = async (projectId: string, options?: Request
})
}
+export const getUserFacetSettingsRetrieveUrl = (uuid: string, params: UserFacetSettingsRetrieveParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/user_facet_settings/${uuid}/?${stringifiedParams}`
+ : `/api/user_facet_settings/${uuid}/`
+}
+
+/**
+ * Get the authenticated user's custom facets for a product, within the current team. Pass `@me` as the UUID.
+ */
+export const userFacetSettingsRetrieve = async (
+ uuid: string,
+ params: UserFacetSettingsRetrieveParams,
+ options?: RequestInit
+): Promise<UserFacetSettingsApi> => {
+ return apiMutator<UserFacetSettingsApi>(getUserFacetSettingsRetrieveUrl(uuid, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getUserFacetSettingsPartialUpdateUrl = (uuid: string, params: UserFacetSettingsPartialUpdateParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/user_facet_settings/${uuid}/?${stringifiedParams}`
+ : `/api/user_facet_settings/${uuid}/`
+}
+
+/**
+ * Replace the authenticated user's custom facets for a product, within the current team. Pass `@me` as the UUID.
+ */
+export const userFacetSettingsPartialUpdate = async (
+ uuid: string,
+ params: UserFacetSettingsPartialUpdateParams,
+ patchedUserFacetSettingsApi?: PatchedUserFacetSettingsApi,
+ options?: RequestInit
+): Promise<UserFacetSettingsApi> => {
+ return apiMutator<UserFacetSettingsApi>(getUserFacetSettingsPartialUpdateUrl(uuid, params), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedUserFacetSettingsApi),
+ })
+}
+
export const getUserHomeSettingsRetrieveUrl = (uuid: string) => {
return `/api/user_home_settings/${uuid}/`
}
diff --git a/products/platform_features/frontend/generated/api.zod.ts b/products/platform_features/frontend/generated/api.zod.ts
index 2056b0997596..ee37109ea6f2 100644
--- a/products/platform_features/frontend/generated/api.zod.ts
+++ b/products/platform_features/frontend/generated/api.zod.ts
@@ -449,6 +449,32 @@ export const CommentsSendToSlackCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Replace the authenticated user's custom facets for a product, within the current team. Pass `@me` as the UUID.
+ */
+export const UserFacetSettingsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ custom_facets: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .describe(
+ 'The log or span attribute key this facet is based on — for example `http.status_code` or `k8s.pod.name`.'
+ ),
+ source_type: zod
+ .enum(['attribute', 'resourceAttribute'])
+ .describe('\* `attribute` - attribute\n\* `resourceAttribute` - resourceAttribute')
+ .describe(
+ 'Where the key lives: `attribute` for a plain log\/span attribute, `resourceAttribute` for an OpenTelemetry resource attribute.\n\n\* `attribute` - attribute\n\* `resourceAttribute` - resourceAttribute'
+ ),
+ })
+ )
+ .optional()
+ .describe(
+ 'Ordered list of custom facets the user has pinned for this product, within the current team. Send the full list to replace the existing set.'
+ ),
+})
+
/**
* Update the authenticated user's pinned sidebar tabs and/or homepage for the current team. Pass `@me` as the UUID. Send `tabs` to replace the pinned tab list, `homepage` to set the home destination (any PostHog URL — dashboard, insight, search results, scene). Either field may be omitted to leave it unchanged; sending `homepage: null` or `{}` clears the homepage.
*/
diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yaml
index 1f3c79935deb..f91ee4494d00 100644
--- a/products/platform_features/mcp/tools.yaml
+++ b/products/platform_features/mcp/tools.yaml
@@ -564,6 +564,12 @@ tools:
teams-data-freshness-retrieve:
operation: teams_data_freshness_retrieve
enabled: false
+ user-facet-settings-partial-update:
+ operation: user_facet_settings_partial_update
+ enabled: false
+ user-facet-settings-retrieve:
+ operation: user_facet_settings_retrieve
+ enabled: false
user-home-settings-get:
operation: user_home_settings_retrieve
enabled: true
diff --git a/products/tracing/frontend/components/FacetRail/Facet.tsx b/products/tracing/frontend/components/FacetRail/Facet.tsx
index 54d1d540636b..163cdb9488e0 100644
--- a/products/tracing/frontend/components/FacetRail/Facet.tsx
+++ b/products/tracing/frontend/components/FacetRail/Facet.tsx
@@ -1,7 +1,7 @@
import { CSSProperties, useMemo } from 'react'
import { List } from 'react-window'
-import { IconChevronDown, IconChevronRight, IconMinusSmall } from '@posthog/icons'
+import { IconChevronDown, IconChevronRight, IconMinusSmall, IconX } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonInput } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
@@ -32,6 +32,10 @@ interface FacetProps {
dimZeroCounts?: boolean
/** The facet's latest fetch failed — show an inline error instead of pretending the list is fresh (suppresses emptyLabel). */
error?: boolean
+ /** When set, renders a remove control in the header — for user-added custom facets only. */
+ onRemove?: () => void
+ /** Disables the remove control (with this explanation) while a custom-facet update is in flight. */
+ removeDisabledReason?: string
}
/**
@@ -63,6 +67,8 @@ export function Facet({
maxHeight,
dimZeroCounts = false,
error = false,
+ onRemove,
+ removeDisabledReason,
}: FacetProps): JSX.Element {
const slug = slugify(title)
@@ -73,16 +79,28 @@ export function Facet({
return (
<div className="mb-3">
- <button
- type="button"
- onClick={onToggleCollapsed}
- disabled={!onToggleCollapsed}
- className="flex items-center gap-1 w-full px-1 mb-1 text-[10px] font-semibold uppercase tracking-wide text-secondary hover:text-default"
- data-attr={`tracing-facet-${slug}-header`}
- >
- {collapsed ? <IconChevronRight /> : <IconChevronDown />}
- <span>{title}</span>
- </button>
+ <div className="flex items-center gap-1 w-full px-1 mb-1">
+ <button
+ type="button"
+ onClick={onToggleCollapsed}
+ disabled={!onToggleCollapsed}
+ className="flex items-center gap-1 flex-1 min-w-0 text-[10px] font-semibold uppercase tracking-wide text-secondary hover:text-default"
+ data-attr={`tracing-facet-${slug}-header`}
+ >
+ {collapsed ? <IconChevronRight /> : <IconChevronDown />}
+ <span className="truncate">{title}</span>
+ </button>
+ {onRemove && (
+ <LemonButton
+ size="small"
+ icon={<IconX />}
+ onClick={onRemove}
+ disabledReason={removeDisabledReason}
+ tooltip="Remove custom facet"
+ data-attr={`tracing-facet-${slug}-remove`}
+ />
+ )}
+ </div>
{!collapsed && onSearchChange && (
<div className="px-1 pb-1">
<LemonInput
diff --git a/products/tracing/frontend/components/FacetRail/FacetRail.tsx b/products/tracing/frontend/components/FacetRail/FacetRail.tsx
index f75850ef63d2..dd04dfce57f8 100644
--- a/products/tracing/frontend/components/FacetRail/FacetRail.tsx
+++ b/products/tracing/frontend/components/FacetRail/FacetRail.tsx
@@ -1,17 +1,23 @@
import { useActions, useValues } from 'kea'
import { useCallback, useMemo, useRef } from 'react'
+import { IconPlus } from '@posthog/icons'
import { LemonInput } from '@posthog/lemon-ui'
import { Resizer } from 'lib/components/Resizer/Resizer'
import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { TaxonomicStringPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
import { tracingConfigLogic } from '../../tracingConfigLogic'
+import { customFacetsLogic } from './customFacetsLogic'
import { facetPresenceLogic } from './facetPresenceLogic'
import { facetRailLogic } from './facetRailLogic'
import { facetsByGroup, filterFacetsByName } from './facets'
import { RailFacet } from './RailFacet'
+const ADD_FACET_GROUP_TYPES = [TaxonomicFilterGroupType.SpanAttributes, TaxonomicFilterGroupType.SpanResourceAttributes]
+
const DEFAULT_WIDTH_PX = 240
const COLLAPSE_THRESHOLD_PX = 120
@@ -22,6 +28,8 @@ export function FacetRail(): JSX.Element {
const { visibleFacets } = useValues(facetPresenceLogic)
const { facetNameSearch } = useValues(facetRailLogic)
const { setFacetNameSearch } = useActions(facetRailLogic)
+ const { addCustomFacet } = useActions(customFacetsLogic)
+ const { customFacetsEnabled, entriesLoading } = useValues(customFacetsLogic)
const onToggleClosed = useCallback(
(shouldBeClosed: boolean) => setFacetRailCollapsed(shouldBeClosed),
@@ -56,7 +64,7 @@ export function FacetRail(): JSX.Element {
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">
+ <div className="flex items-center gap-1 px-2 py-1 border-b">
<LemonInput
type="search"
size="small"
@@ -66,6 +74,26 @@ export function FacetRail(): JSX.Element {
onChange={setFacetNameSearch}
data-attr="tracing-facet-rail-search"
/>
+ {customFacetsEnabled && (
+ <TaxonomicStringPopover
+ groupType={TaxonomicFilterGroupType.SpanAttributes}
+ groupTypes={ADD_FACET_GROUP_TYPES}
+ placeholder={null}
+ size="small"
+ icon={<IconPlus />}
+ tooltip="Add custom facet"
+ disabledReason={entriesLoading ? 'Custom facets are updating' : undefined}
+ data-attr="tracing-facet-rail-add"
+ onChange={(value, groupType) =>
+ addCustomFacet(
+ value,
+ groupType === TaxonomicFilterGroupType.SpanResourceAttributes
+ ? 'resourceAttribute'
+ : 'attribute'
+ )
+ }
+ />
+ )}
</div>
<div className="flex-1 min-h-0 overflow-y-auto p-2">
{matchingKeys.size === 0 && facetNameSearch.trim() && (
diff --git a/products/tracing/frontend/components/FacetRail/RailFacet.tsx b/products/tracing/frontend/components/FacetRail/RailFacet.tsx
index 4df42fd8adbc..4448496794cb 100644
--- a/products/tracing/frontend/components/FacetRail/RailFacet.tsx
+++ b/products/tracing/frontend/components/FacetRail/RailFacet.tsx
@@ -3,9 +3,17 @@ import { useMemo } from 'react'
import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from 'products/tracing/frontend/tracingFiltersLogic'
+import { customFacetsLogic } from './customFacetsLogic'
import { Facet } from './Facet'
import { facetRailLogic } from './facetRailLogic'
-import { FacetConfig, FacetOption, facetSelection, facetValueGroup, mergeSelectedIntoOptions } from './facets'
+import {
+ FacetConfig,
+ FacetOption,
+ customFacetIdentity,
+ facetSelection,
+ facetValueGroup,
+ mergeSelectedIntoOptions,
+} from './facets'
import { facetValuesLogic } from './facetValuesLogic'
export interface RailFacetProps {
@@ -28,6 +36,9 @@ export function RailFacet({ facet, id = TRACING_SCENE_VIEWER_ID, hidden }: RailF
const { setFacetSearch } = useActions(facetValuesLogic(logicProps))
const { serviceNames, filters } = useValues(tracingFiltersLogic({ id }))
const { toggleFacetValue, toggleFacetCollapsed } = useActions(facetRailLogic({ id }))
+ const { removeCustomFacet } = useActions(customFacetsLogic)
+ const { entriesLoading } = useValues(customFacetsLogic)
+ const removeDisabledReason = entriesLoading ? 'Custom facets are updating' : undefined
if (hidden) {
return null
@@ -44,6 +55,10 @@ export function RailFacet({ facet, id = TRACING_SCENE_VIEWER_ID, hidden }: RailF
.map((row) => ({ value: row.value, label: row.value, count: row.count }))
const onToggle = (value: string): void => toggleFacetValue(source, value)
const onToggleCollapsed = (): void => toggleFacetCollapsed(facet.key)
+ const customIdentity = customFacetIdentity(facet)
+ const onRemove = customIdentity
+ ? (): void => removeCustomFacet(customIdentity.key, customIdentity.sourceType)
+ : undefined
if (facet.kind === 'fixed') {
// Fixed value set from config, counts overlaid. Missing values render as a dimmed 0.
@@ -64,6 +79,8 @@ export function RailFacet({ facet, id = TRACING_SCENE_VIEWER_ID, hidden }: RailF
onToggleCollapsed={onToggleCollapsed}
dimZeroCounts
error={fetchFailed}
+ onRemove={onRemove}
+ removeDisabledReason={removeDisabledReason}
/>
)
}
@@ -87,6 +104,8 @@ export function RailFacet({ facet, id = TRACING_SCENE_VIEWER_ID, hidden }: RailF
onToggleCollapsed={onToggleCollapsed}
maxHeight={facet.maxHeight}
error={fetchFailed}
+ onRemove={onRemove}
+ removeDisabledReason={removeDisabledReason}
/>
)
}
diff --git a/products/tracing/frontend/components/FacetRail/customFacetsLogic.test.ts b/products/tracing/frontend/components/FacetRail/customFacetsLogic.test.ts
new file mode 100644
index 000000000000..a19db93891d7
--- /dev/null
+++ b/products/tracing/frontend/components/FacetRail/customFacetsLogic.test.ts
@@ -0,0 +1,160 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ userFacetSettingsPartialUpdate,
+ userFacetSettingsRetrieve,
+} from 'products/platform_features/frontend/generated/api'
+import { UserFacetSettingsEntrySourceTypeEnumApi } from 'products/platform_features/frontend/generated/api.schemas'
+
+import { customFacetsLogic } from './customFacetsLogic'
+
+jest.mock('products/platform_features/frontend/generated/api', () => ({
+ __esModule: true,
+ userFacetSettingsRetrieve: jest.fn(),
+ userFacetSettingsPartialUpdate: jest.fn(),
+}))
+
+const mockRetrieve = userFacetSettingsRetrieve as jest.MockedFunction<typeof userFacetSettingsRetrieve>
+const mockPartialUpdate = userFacetSettingsPartialUpdate as jest.MockedFunction<typeof userFacetSettingsPartialUpdate>
+
+describe('customFacetsLogic', () => {
+ // A singleton logic (no `key`) — each test sets up its mocks, then mounts fresh via `mount()`
+ // below. Mounting inside `beforeEach` would fire `afterMount` before a test's own mock override
+ // took effect, since re-calling the wrapper mid-test returns the same already-mounted instance.
+ let logic: ReturnType<typeof customFacetsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.clearAllMocks()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
+ mockRetrieve.mockResolvedValue({ custom_facets: [] })
+ mockPartialUpdate.mockImplementation(async (_uuid, _params, body) => ({
+ custom_facets: body?.custom_facets ?? [],
+ }))
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ function mount(): ReturnType<typeof customFacetsLogic.build> {
+ logic = customFacetsLogic()
+ logic.mount()
+ return logic
+ }
+
+ it('does not load or expose custom facets when the feature flag is off', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockRetrieve).not.toHaveBeenCalled()
+ expect(logic.values.customFacets).toEqual([])
+ })
+
+ it('loads entries when the flag arrives after mount', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ mount()
+ expect(mockRetrieve).not.toHaveBeenCalled()
+
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
+ await expectLogic(logic).toDispatchActions(['loadEntries', 'loadEntriesSuccess'])
+ })
+
+ it('mutations build on the persisted list when entries have not loaded yet', async () => {
+ // A PATCH replaces the whole server-side list — building it on unloaded local state would
+ // wipe every facet the user pinned elsewhere.
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ mockRetrieve.mockResolvedValue({
+ custom_facets: [
+ { key: 'pinned.elsewhere', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ ],
+ })
+ mount()
+ logic.actions.addCustomFacet('http.status_code', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(mockPartialUpdate).toHaveBeenCalledWith(
+ '@me',
+ { product: 'tracing' },
+ {
+ custom_facets: [
+ { key: 'pinned.elsewhere', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ { key: 'http.status_code', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ ],
+ }
+ )
+ })
+
+ it('loads persisted entries on mount and exposes them as facet configs', async () => {
+ mockRetrieve.mockResolvedValue({
+ custom_facets: [
+ { key: 'http.status_code', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ ],
+ })
+ mount()
+ await expectLogic(logic).toDispatchActions(['loadEntriesSuccess'])
+
+ expect(logic.values.customFacets).toEqual([
+ expect.objectContaining({
+ key: 'custom:attribute:http.status_code',
+ source: { type: 'attribute', key: 'http.status_code' },
+ }),
+ ])
+ })
+
+ it('adding a facet persists the full updated list and updates local state', async () => {
+ mount()
+ logic.actions.addCustomFacet('http.status_code', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(logic.values.entries).toEqual([
+ { key: 'http.status_code', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ ])
+ expect(mockPartialUpdate).toHaveBeenCalledWith(
+ '@me',
+ { product: 'tracing' },
+ {
+ custom_facets: [
+ { key: 'http.status_code', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
+ ],
+ }
+ )
+ })
+
+ it('adding the same key and sourceType twice does not duplicate or persist again', async () => {
+ mount()
+ logic.actions.addCustomFacet('http.status_code', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+ mockPartialUpdate.mockClear()
+
+ logic.actions.addCustomFacet('http.status_code', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(logic.values.entries).toHaveLength(1)
+ expect(mockPartialUpdate).not.toHaveBeenCalled()
+ })
+
+ it('removing a facet only drops the matching key+sourceType pair', async () => {
+ // The same key can exist as both an attribute and a resource-attribute facet — removing one
+ // must not also remove the other.
+ mount()
+ logic.actions.addCustomFacet('environment', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+ logic.actions.addCustomFacet('environment', 'resourceAttribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ logic.actions.removeCustomFacet('environment', 'attribute')
+ await expectLogic(logic).toDispatchActions(['removeCustomFacetSuccess'])
+
+ expect(logic.values.entries).toEqual([
+ { key: 'environment', source_type: UserFacetSettingsEntrySourceTypeEnumApi.ResourceAttribute },
+ ])
+ })
+})
diff --git a/products/tracing/frontend/components/FacetRail/customFacetsLogic.ts b/products/tracing/frontend/components/FacetRail/customFacetsLogic.ts
new file mode 100644
index 000000000000..20a95db72d63
--- /dev/null
+++ b/products/tracing/frontend/components/FacetRail/customFacetsLogic.ts
@@ -0,0 +1,223 @@
+import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import {
+ userFacetSettingsPartialUpdate,
+ userFacetSettingsRetrieve,
+} from 'products/platform_features/frontend/generated/api'
+import { UserFacetSettingsEntryApi } from 'products/platform_features/frontend/generated/api.schemas'
+
+import { CustomFacetSourceType, FacetConfig, buildCustomFacet } from './facets'
+
+const PRODUCT = 'tracing' as const
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface customFacetsLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ customFacets: FacetConfig[]
+ customFacetsEnabled: boolean
+ entries: UserFacetSettingsEntryApi[]
+ entriesLoaded: boolean
+ entriesLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface customFacetsLogicActions {
+ addCustomFacet: (
+ key: string,
+ sourceType: CustomFacetSourceType
+ ) => {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ addCustomFacetFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ addCustomFacetSuccess: (
+ entries: UserFacetSettingsEntryApi[],
+ payload?: {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ ) => {
+ entries: UserFacetSettingsEntryApi[]
+ payload?: {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ }
+ loadEntries: () => {
+ value: true
+ }
+ loadEntriesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadEntriesSuccess: (
+ entries: UserFacetSettingsEntryApi[],
+ payload?: {
+ value: true
+ }
+ ) => {
+ entries: UserFacetSettingsEntryApi[]
+ payload?: {
+ value: true
+ }
+ }
+ removeCustomFacet: (
+ key: string,
+ sourceType: CustomFacetSourceType
+ ) => {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ removeCustomFacetFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ removeCustomFacetSuccess: (
+ entries: UserFacetSettingsEntryApi[],
+ payload?: {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ ) => {
+ entries: UserFacetSettingsEntryApi[]
+ payload?: {
+ key: string
+ sourceType: CustomFacetSourceType
+ }
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface customFacetsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ customFacetsEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ customFacets: (entries: UserFacetSettingsEntryApi[], customFacetsEnabled: boolean) => FacetConfig[]
+ }
+}
+
+export type customFacetsLogicType = MakeLogicType<
+ customFacetsLogicValues,
+ customFacetsLogicActions,
+ Record<string, any>,
+ customFacetsLogicMeta
+>
+
+/**
+ * The user's custom facets for tracing, persisted server-side (per user, per team) so they follow
+ * the user across devices. A singleton (not keyed by viewer id): the underlying setting is one row
+ * per user/team/product, not one per rail instance.
+ */
+export const customFacetsLogic = kea<customFacetsLogicType>([
+ path(['products', 'tracing', 'frontend', 'components', 'FacetRail', 'customFacetsLogic']),
+
+ connect(() => ({ values: [featureFlagLogic, ['featureFlags']] })),
+
+ actions({
+ loadEntries: true,
+ addCustomFacet: (key: string, sourceType: CustomFacetSourceType) => ({ key, sourceType }),
+ removeCustomFacet: (key: string, sourceType: CustomFacetSourceType) => ({ key, sourceType }),
+ }),
+
+ loaders(({ values }) => {
+ // The PATCH replaces the whole server-side list, so a mutation must build on the persisted
+ // entries: local state can be empty when the load failed or never ran, and using it as the
+ // base would wipe the user's saved facets.
+ const baseEntries = async (): Promise<UserFacetSettingsEntryApi[]> =>
+ values.entriesLoaded
+ ? values.entries
+ : (await userFacetSettingsRetrieve('@me', { product: PRODUCT })).custom_facets
+ return {
+ entries: [
+ [] as UserFacetSettingsEntryApi[],
+ {
+ loadEntries: async () => {
+ const response = await userFacetSettingsRetrieve('@me', { product: PRODUCT })
+ return response.custom_facets
+ },
+ addCustomFacet: async ({ key, sourceType }) => {
+ const base = await baseEntries()
+ if (base.some((entry) => entry.key === key && entry.source_type === sourceType)) {
+ return base
+ }
+ const nextEntries = [...base, { key, source_type: sourceType }]
+ await userFacetSettingsPartialUpdate(
+ '@me',
+ { product: PRODUCT },
+ { custom_facets: nextEntries }
+ )
+ return nextEntries
+ },
+ removeCustomFacet: async ({ key, sourceType }) => {
+ const base = await baseEntries()
+ const nextEntries = base.filter(
+ (entry) => !(entry.key === key && entry.source_type === sourceType)
+ )
+ await userFacetSettingsPartialUpdate(
+ '@me',
+ { product: PRODUCT },
+ { custom_facets: nextEntries }
+ )
+ return nextEntries
+ },
+ },
+ ],
+ }
+ }),
+
+ reducers({
+ entriesLoaded: [
+ false,
+ {
+ loadEntriesSuccess: () => true,
+ },
+ ],
+ }),
+
+ selectors({
+ // A primitive, so downstream facet identities only change when the gate actually flips —
+ // the featureFlags object gets a fresh identity on every flag refresh.
+ customFacetsEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.CUSTOM_FACET_PINNING],
+ ],
+ customFacets: [
+ (s) => [s.entries, s.customFacetsEnabled],
+ (entries: UserFacetSettingsEntryApi[], customFacetsEnabled: boolean): FacetConfig[] =>
+ customFacetsEnabled ? entries.map((entry) => buildCustomFacet(entry.key, entry.source_type)) : [],
+ ],
+ }),
+
+ listeners(({ actions, values }) => ({
+ // Flags resolve asynchronously and often land after this logic mounts — without this, a
+ // flagged user's pinned facets would stay unloaded for the whole session.
+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
+ if (values.customFacetsEnabled && !values.entriesLoaded && !values.entriesLoading) {
+ actions.loadEntries()
+ }
+ },
+ })),
+
+ events(({ actions, values }) => ({
+ afterMount: () => {
+ if (values.customFacetsEnabled) {
+ actions.loadEntries()
+ }
+ },
+ })),
+])
diff --git a/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts b/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts
index 5af7e604ecc5..2f5909141495 100644
--- a/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts
+++ b/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts
@@ -7,6 +7,7 @@ import { TRACING_SCENE_VIEWER_ID } from 'products/tracing/frontend/tracingFilter
import { tracingSpansAttributesRetrieve } from '../../generated/api'
import { TracingSpansAttributesRetrieveAttributeType } from '../../generated/api.schemas'
+import { customFacetsLogic } from './customFacetsLogic'
import { FACETS, FacetConfig, resolveFacets } from './facets'
export interface FacetPresenceLogicProps {
@@ -15,9 +16,11 @@ export interface FacetPresenceLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetPresenceLogicValues {
+ customFacets: FacetConfig[] // customFacetsLogic
currentTeamId: number | null // teamLogic
presentResourceKeys: string[]
presentResourceKeysLoading: boolean
+ resolvedFacets: FacetConfig[]
visibleFacets: FacetConfig[]
}
@@ -44,7 +47,8 @@ export interface facetPresenceLogicActions {
export interface facetPresenceLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
- visibleFacets: (presentResourceKeys: string[]) => FacetConfig[]
+ resolvedFacets: (presentResourceKeys: string[]) => FacetConfig[]
+ visibleFacets: (resolvedFacets: FacetConfig[], customFacets: FacetConfig[]) => FacetConfig[]
}
}
@@ -67,7 +71,7 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([
path((key) => ['products', 'tracing', 'frontend', 'components', 'FacetRail', 'facetPresenceLogic', key]),
connect(() => ({
- values: [teamLogic, ['currentTeamId']],
+ values: [teamLogic, ['currentTeamId'], customFacetsLogic, ['customFacets']],
})),
loaders(({ values }) => ({
@@ -92,11 +96,22 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([
selectors({
// Column facets always render; resource-attribute facets only when the tenant emits the key (or one
- // of its aliases, which resolution rewrites the facet onto).
- visibleFacets: [
+ // of its aliases, which resolution rewrites the facet onto). Custom facets skip that presence gate
+ // entirely — the user picked them from a live taxonomic list, so they're known to exist already —
+ // and render last, after every curated facet.
+ // Intermediate so curated facet identities stay stable across custom-facet changes — a fresh
+ // alias-resolved FacetConfig would re-render every virtualized value row (see RailFacet).
+ resolvedFacets: [
(s) => [s.presentResourceKeys],
(presentResourceKeys: string[]): FacetConfig[] => resolveFacets(FACETS, presentResourceKeys),
],
+ visibleFacets: [
+ (s) => [s.resolvedFacets, s.customFacets],
+ (resolvedFacets: FacetConfig[], customFacets: FacetConfig[]): FacetConfig[] => [
+ ...resolvedFacets,
+ ...customFacets,
+ ],
+ ],
}),
events(({ actions }) => ({
diff --git a/products/tracing/frontend/components/FacetRail/facetValuesLogic.test.ts b/products/tracing/frontend/components/FacetRail/facetValuesLogic.test.ts
index b2335328eab3..5086bf5670ad 100644
--- a/products/tracing/frontend/components/FacetRail/facetValuesLogic.test.ts
+++ b/products/tracing/frontend/components/FacetRail/facetValuesLogic.test.ts
@@ -5,10 +5,11 @@ import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalF
import { tracingSpansAttributeBreakdownCreate } from 'products/tracing/frontend/generated/api'
import type { _TracingAttributeBreakdownRowApi } from 'products/tracing/frontend/generated/api.schemas'
+import { SpanPropertyTypeEnumApi } from 'products/tracing/frontend/generated/api.schemas'
import { tracingFiltersLogic } from 'products/tracing/frontend/tracingFiltersLogic'
import { facetRailLogic } from './facetRailLogic'
-import { FACETS, FacetConfig } from './facets'
+import { FACETS, FacetConfig, buildCustomFacet } from './facets'
import { facetValuesLogic } from './facetValuesLogic'
jest.mock('products/tracing/frontend/generated/api', () => ({
@@ -112,6 +113,34 @@ describe('facetValuesLogic', () => {
)
})
+ // Each source type must route to its own breakdownType — a binary-to-ternary slip (e.g. a
+ // plain attribute silently querying as a resource attribute) would misreport values with no
+ // type error, since both shapes only differ in this one field.
+ it.each<[string, FacetConfig, string, SpanPropertyTypeEnumApi]>([
+ ['a column facet', SERVICE, 'service_name', SpanPropertyTypeEnumApi.Span],
+ [
+ 'a resource-attribute facet',
+ facetConfig('namespace'),
+ 'k8s.namespace.name',
+ SpanPropertyTypeEnumApi.SpanResourceAttribute,
+ ],
+ [
+ 'a custom plain-attribute facet',
+ buildCustomFacet('http.status_code', 'attribute'),
+ 'http.status_code',
+ SpanPropertyTypeEnumApi.SpanAttribute,
+ ],
+ ])('%s requests the matching breakdownType', async (_, facet, expectedKey, expectedType) => {
+ const logic = mountFacet(facet)
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])
+ expect(mockBreakdown).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ query: expect.objectContaining({ breakdownKey: expectedKey, breakdownType: expectedType }),
+ })
+ )
+ })
+
it('a failed breakdown shows in place and clears on the next fetch', async () => {
// One broken breakdown must show on its own facet, not blank the rail.
mockBreakdown.mockRejectedValueOnce(new Error('breakdown failed'))
diff --git a/products/tracing/frontend/components/FacetRail/facetValuesLogic.ts b/products/tracing/frontend/components/FacetRail/facetValuesLogic.ts
index bf7a46c79da8..7749df8f9664 100644
--- a/products/tracing/frontend/components/FacetRail/facetValuesLogic.ts
+++ b/products/tracing/frontend/components/FacetRail/facetValuesLogic.ts
@@ -193,10 +193,12 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
const target =
source.type === 'column'
? { breakdownKey: source.column, breakdownType: SpanPropertyTypeEnumApi.Span }
- : {
- breakdownKey: source.key,
- breakdownType: SpanPropertyTypeEnumApi.SpanResourceAttribute,
- }
+ : source.type === 'attribute'
+ ? { breakdownKey: source.key, breakdownType: SpanPropertyTypeEnumApi.SpanAttribute }
+ : {
+ breakdownKey: source.key,
+ breakdownType: SpanPropertyTypeEnumApi.SpanResourceAttribute,
+ }
const response = await tracingSpansAttributeBreakdownCreate(String(values.currentTeamId), {
query: {
...target,
diff --git a/products/tracing/frontend/components/FacetRail/facets.test.ts b/products/tracing/frontend/components/FacetRail/facets.test.ts
index 572b8f75beda..4792f080eb9f 100644
--- a/products/tracing/frontend/components/FacetRail/facets.test.ts
+++ b/products/tracing/frontend/components/FacetRail/facets.test.ts
@@ -7,6 +7,8 @@ import {
FacetSelection,
FacetSource,
FilterGroupFacetSource,
+ buildCustomFacet,
+ customFacetIdentity,
cycleFacetFilter,
facetFilterSelection,
facetScopeSignature,
@@ -20,6 +22,7 @@ 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' }
+const HTTP_STATUS_ATTRIBUTE_SOURCE: FilterGroupFacetSource = { type: 'attribute', key: 'http.status_code' }
function groupWith(values: object[]): UniversalFiltersGroup {
return {
@@ -40,6 +43,11 @@ describe('facets', () => {
POD_SOURCE,
PropertyFilterType.SpanResourceAttribute,
],
+ [
+ 'plain-attribute facet writes a span_attribute filter',
+ HTTP_STATUS_ATTRIBUTE_SOURCE,
+ PropertyFilterType.SpanAttribute,
+ ],
])('%s', (_, source, expectedType) => {
const group = cycleFacetFilter(undefined, source, 'a')
const inner = (group.values[0] as UniversalFiltersGroup).values
@@ -358,5 +366,26 @@ describe('facets', () => {
it('keeps column facets whatever the tenant emits', () => {
expect(resolveFacets(FACETS, []).map((f) => f.key)).toEqual(['service', 'status'])
})
+
+ it('passes a plain-attribute facet through unchanged, regardless of presence', () => {
+ // Custom facets are added by the user picking a real key, not resolved against a curated
+ // alias list — resolveFacets must never drop or rewrite them the way it does resourceAttribute.
+ const attributeFacet = buildCustomFacet('http.status_code', 'attribute')
+ expect(resolveFacets([attributeFacet], [])).toEqual([attributeFacet])
+ })
+ })
+
+ describe('buildCustomFacet / customFacetIdentity', () => {
+ it.each<['attribute' | 'resourceAttribute']>([['attribute'], ['resourceAttribute']])(
+ 'round-trips the key and sourceType through a %s facet',
+ (sourceType) => {
+ const facet = buildCustomFacet('http.status_code', sourceType)
+ expect(customFacetIdentity(facet)).toEqual({ key: 'http.status_code', sourceType })
+ }
+ )
+
+ it('returns null for a curated facet', () => {
+ expect(customFacetIdentity(FACETS[0])).toBeNull()
+ })
})
})
diff --git a/products/tracing/frontend/components/FacetRail/facets.ts b/products/tracing/frontend/components/FacetRail/facets.ts
index 80c2fbe015eb..5abad4cdc523 100644
--- a/products/tracing/frontend/components/FacetRail/facets.ts
+++ b/products/tracing/frontend/components/FacetRail/facets.ts
@@ -33,10 +33,13 @@ export type FacetColumn = 'service_name' | 'status_code'
* selection lives in the dedicated `serviceNames` filter field; `status_code`'s in a span property filter.
* - `resourceAttribute`: a `resource_attributes` map key (e.g. k8s.namespace.name), queried with
* breakdownType `span_resource_attribute`. Selection is a span_resource_attribute property filter.
+ * - `attribute`: a plain (non-resource) span attribute key, queried with breakdownType `span_attribute`.
+ * Only used by user-added custom facets today — no curated `FACETS` entry uses it.
*/
export type FacetSource =
| { type: 'column'; column: FacetColumn }
| { type: 'resourceAttribute'; key: string; aliasKeys?: string[] }
+ | { type: 'attribute'; key: string }
/**
* The sources whose selection lives in the filterGroup. `service_name` is deliberately excluded:
@@ -46,6 +49,7 @@ export type FacetSource =
export type FilterGroupFacetSource =
| { type: 'column'; column: Exclude<FacetColumn, 'service_name'> }
| { type: 'resourceAttribute'; key: string; aliasKeys?: string[] }
+ | { type: 'attribute'; key: string }
export interface FacetConfig {
/** Stable id used for collapse state and data-attrs. */
@@ -64,11 +68,13 @@ export interface FacetConfig {
emptyLabel?: string
/** Max pixel height before the value list virtualizes and scrolls. */
maxHeight?: number
+ /** The (key, sourceType) a user-added custom facet was built from; curated facets never set it. */
+ custom?: { key: string; sourceType: CustomFacetSourceType }
}
interface SpanFacetFilter {
key: string
- type: PropertyFilterType.Span | PropertyFilterType.SpanResourceAttribute
+ type: PropertyFilterType.Span | PropertyFilterType.SpanResourceAttribute | PropertyFilterType.SpanAttribute
operator: PropertyOperator
value?: PropertyFilterValue
}
@@ -81,11 +87,18 @@ export function innerFilters(group: UniversalFiltersGroup | undefined): SpanFace
return ((group?.values?.[0] as UniversalFiltersGroup | undefined)?.values ?? []) as SpanFacetFilter[]
}
-/** The property filter home for a facet's selection: span filters for status_code, resource-attribute filters otherwise. */
+/** The property filter home for a facet's selection: span filters for status_code, attribute/resource-attribute filters otherwise. */
function facetFilterType(
- source: FilterGroupFacetSource
-): PropertyFilterType.Span | PropertyFilterType.SpanResourceAttribute {
- return source.type === 'column' ? PropertyFilterType.Span : PropertyFilterType.SpanResourceAttribute
+ source: FacetSource
+): PropertyFilterType.Span | PropertyFilterType.SpanResourceAttribute | PropertyFilterType.SpanAttribute {
+ switch (source.type) {
+ case 'column':
+ return PropertyFilterType.Span
+ case 'attribute':
+ return PropertyFilterType.SpanAttribute
+ case 'resourceAttribute':
+ return PropertyFilterType.SpanResourceAttribute
+ }
}
function facetFilterKey(source: FilterGroupFacetSource): string {
@@ -207,7 +220,7 @@ export function cycleFacetFilter(
return { type: FilterLogicalOperator.And, values: [{ type: FilterLogicalOperator.And, values }] }
}
-/** The data key a facet is broken down by: its column, or the resource-attribute key resolution picked. */
+/** The data key a facet is broken down by: its column, or the attribute/resource-attribute key resolution picked. */
export function facetSourceKey(facet: FacetConfig): string {
return facet.source.type === 'column' ? facet.source.column : facet.source.key
}
@@ -236,7 +249,7 @@ export interface FacetScope {
export function facetScopeSignature(facet: FacetConfig, scope: FacetScope): string {
const { source } = facet
const selfKey = facetSourceKey(facet)
- const selfType = source.type === 'column' ? PropertyFilterType.Span : PropertyFilterType.SpanResourceAttribute
+ const selfType = facetFilterType(source)
// Any operator: the backend drops every filter under the breakdown key, not just the rail's own.
const groupSignature = innerFilters(scope.queryFilterGroup)
.filter((filter) => !(filter.type === selfType && filter.key === selfKey))
@@ -404,7 +417,7 @@ export function resolveFacets(facets: FacetConfig[], presentResourceKeys: string
const present = new Set(presentResourceKeys)
const resolved: FacetConfig[] = []
for (const facet of facets) {
- if (facet.source.type === 'column') {
+ if (facet.source.type !== 'resourceAttribute') {
resolved.push(facet)
continue
}
@@ -468,3 +481,26 @@ export function facetsByGroup(facets: FacetConfig[]): [string, FacetConfig[]][]
}
return groups
}
+
+/** A custom facet's source kind, as persisted per-user — mirrors the backend's `source_type` choices. */
+export type CustomFacetSourceType = 'attribute' | 'resourceAttribute'
+
+/** Builds a rail-renderable FacetConfig for a user-added custom facet — always dynamic, with a remove control. */
+export function buildCustomFacet(key: string, sourceType: CustomFacetSourceType): FacetConfig {
+ return {
+ key: `custom:${sourceType}:${key}`,
+ title: key,
+ group: 'Custom',
+ kind: 'dynamic',
+ source: sourceType === 'attribute' ? { type: 'attribute', key } : { type: 'resourceAttribute', key },
+ searchable: true,
+ emptyLabel: `No ${key} values`,
+ maxHeight: 300,
+ custom: { key, sourceType },
+ }
+}
+
+/** The (key, sourceType) a custom facet was built from — `null` for a curated facet. */
+export function customFacetIdentity(facet: FacetConfig): { key: string; sourceType: CustomFacetSourceType } | null {
+ return facet.custom ?? null
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 50892add4196..bdd099002626 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -66113,6 +66113,33 @@ export namespace Schemas {
readonly requires_credential_review?: boolean;
}
+ /**
+ * * `attribute` - attribute
+ * * `resourceAttribute` - resourceAttribute
+ */
+ export type UserFacetSettingsEntrySourceTypeEnum = typeof UserFacetSettingsEntrySourceTypeEnum[keyof typeof UserFacetSettingsEntrySourceTypeEnum];
+
+
+ export const UserFacetSettingsEntrySourceTypeEnum = {
+ Attribute: 'attribute',
+ ResourceAttribute: 'resourceAttribute',
+ } as const;
+
+ export interface UserFacetSettingsEntry {
+ /** The log or span attribute key this facet is based on — for example `http.status_code` or `k8s.pod.name`. */
+ key: string;
+ /** Where the key lives: `attribute` for a plain log/span attribute, `resourceAttribute` for an OpenTelemetry resource attribute.
+ *
+ * * `attribute` - attribute
+ * * `resourceAttribute` - resourceAttribute */
+ source_type: UserFacetSettingsEntrySourceTypeEnum;
+ }
+
+ export interface PatchedUserFacetSettings {
+ /** Ordered list of custom facets the user has pinned for this product, within the current team. Send the full list to replace the existing set. */
+ custom_facets?: UserFacetSettingsEntry[];
+ }
+
export interface PatchedUserInterview {
readonly id?: string;
readonly created_by?: UserBasic;
@@ -83862,6 +83889,11 @@ export namespace Schemas {
total: number;
}
+ export interface UserFacetSettings {
+ /** Ordered list of custom facets the user has pinned for this product, within the current team. Send the full list to replace the existing set. */
+ custom_facets: UserFacetSettingsEntry[];
+ }
+
export interface UserGitHubLinkStartRequest {
/**
* Optional team/project id (e.g. PostHog Desktop); web UI uses the session's current team.
@@ -97497,6 +97529,36 @@ export namespace Schemas {
offset?: number;
};
+ export type UserFacetSettingsRetrieveParams = {
+ /**
+ * Which product's custom facets to read or update.
+ */
+ product: UserFacetSettingsRetrieveProduct;
+ };
+
+ export type UserFacetSettingsRetrieveProduct = typeof UserFacetSettingsRetrieveProduct[keyof typeof UserFacetSettingsRetrieveProduct];
+
+
+ export const UserFacetSettingsRetrieveProduct = {
+ Logs: 'logs',
+ Tracing: 'tracing',
+ } as const;
+
+ export type UserFacetSettingsPartialUpdateParams = {
+ /**
+ * Which product's custom facets to read or update.
+ */
+ product: UserFacetSettingsPartialUpdateProduct;
+ };
+
+ export type UserFacetSettingsPartialUpdateProduct = typeof UserFacetSettingsPartialUpdateProduct[keyof typeof UserFacetSettingsPartialUpdateProduct];
+
+
+ export const UserFacetSettingsPartialUpdateProduct = {
+ Logs: 'logs',
+ Tracing: 'tracing',
+ } as const;
+
export type UsersListParams = {
email?: string;
is_staff?: boolean;