:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): configurable session and person attribute keys (#91873)
Jimmy Zhu0d4bd1f6dbbb
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex de69d1185605..f63d47e1cd96 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -209,6 +209,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"TeamLogsConfig","TeamMarketingAnalyticsConfig","TeamRevenueAnalyticsConfig",+ "TeamTracingConfig","TeamJsSnippetConfig","TeamProvisioningConfig",# --- User preferences with no IDOR risk (read own data only) ---diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex e6126f598429..6c4e445b9cb8 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -532,6 +532,7 @@ export const FEATURE_FLAGS = {TRACING_METRICS_TAB: 'tracing-metrics-tab', // owner: #team-apm — gates the Metrics tab (metrics correlated via exemplars) in the trace drawerTRACING_OPERATIONS_VIEW: 'tracing-operations-view', // owner: #team-apm — gates the Operations (per-operation aggregate) tab in tracingTRACING_SAVED_VIEWS: 'tracing-saved-views', // owner: #team-apm — gates saved views (saved filter sets) in tracing+ TRACING_SESSION_PERSON_LINKS: 'tracing-session-person-links', // owner: #team-apm — gates span attribute links to session replay and persons, plus the tracing correlation settingsTRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analyticsUI_CUSTOMIZATION: 'ui-customization-enabled', // owner: @fercgomes #team-self-driving, gates sidebar/homepage UI customizationUNIFIED_APM_PRODUCT: 'unified-apm-product', // owner: #team-apm (@jonmcwest, @frankh), gates the shared APM product backing logs, tracing, and metricsdiff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 78122648b861..0ca89b0da5ca 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -143,6 +143,8 @@ import { SurveyDefaultAppearance, SurveyEnableToggle } from './environment/Surveimport { TeamAccessControl } from './environment/TeamAccessControl'import { TeamAuthorizedURLs, TeamBusinessModel, TeamTimezone, TeamVariables } from './environment/TeamSettings'import { ProjectAccountFiltersSetting } from './environment/TestAccountFiltersConfig'+import { TracingDistinctIdAttributeKeys } from './environment/TracingDistinctIdAttributeKeys'+import { TracingSessionIdAttributeKeys } from './environment/TracingSessionIdAttributeKeys'import { UsageMetricsConfig } from './environment/UsageMetricsConfig'import { WebAnalyticsEnablePreAggregatedTables } from './environment/WebAnalyticsAPISetting'import { AIHipaaDisclaimer, getExternalAIProvidersTooltipTitle } from './organization/aiConsentCopy'@@ -1333,6 +1335,47 @@ export const SETTINGS_MAP: SettingSection[] = [},],},+ {+ level: 'environment',+ id: 'environment-tracing',+ title: 'Tracing',+ group: 'Products',+ flag: ['TRACING', 'TRACING_SESSION_PERSON_LINKS'],+ settings: [+ {+ id: 'tracing-distinct-id-attribute-keys',+ title: 'Link to person',+ description: (+ <>+ The span attributes PostHog reads to identify which person a trace belongs to. A span is linked+ when any of these attributes holds one of the person's distinct IDs. Defaults to{' '}+ <code>posthogDistinctId</code>. Add keys only if your pipeline emits the person identifier under+ different attributes.+ </>+ ),+ searchDescription:+ "The span attributes PostHog reads to identify which person a trace belongs to. A span is linked when any of these attributes holds one of the person's distinct IDs. Defaults to posthogDistinctId. Add keys only if your pipeline emits the person identifier under different attributes.",+ component: <TracingDistinctIdAttributeKeys />,+ keywords: ['trace', 'span', 'person', 'distinct', 'attribute', 'pivot', 'profile', 'link'],+ },+ {+ id: 'tracing-session-id-attribute-keys',+ title: 'Link to session',+ description: (+ <>+ The span attributes PostHog reads to identify which session a trace belongs to, checked in order+ with the first match winning, followed by other common session ID attributes. Defaults to{' '}+ <code>sessionId</code>. Add keys only if your pipeline emits the session ID under different+ attributes.+ </>+ ),+ searchDescription:+ 'The span attributes PostHog reads to identify which session a trace belongs to, checked in order with the first match winning, followed by other common session ID attributes. Defaults to sessionId. Add keys only if your pipeline emits the session ID under different attributes.',+ component: <TracingSessionIdAttributeKeys />,+ keywords: ['trace', 'span', 'session', 'replay', 'attribute', 'link'],+ },+ ],+ },{level: 'environment',id: 'environment-web-analytics',diff --git a/frontend/src/scenes/settings/environment/TracingDistinctIdAttributeKeys.tsx b/frontend/src/scenes/settings/environment/TracingDistinctIdAttributeKeys.tsxnew file mode 100644index 000000000000..9020d6e822fd--- /dev/null+++ b/frontend/src/scenes/settings/environment/TracingDistinctIdAttributeKeys.tsx@@ -0,0 +1,67 @@+import { useActions, useValues } from 'kea'+import { useEffect, useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { objectsEqual } from 'lib/utils/objects'++import {+ DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS,+ tracingCorrelationConfigLogic,+} from 'products/tracing/frontend/tracingCorrelationConfigLogic'++export function TracingDistinctIdAttributeKeys(): JSX.Element {+ const { tracingConfig, tracingConfigLoading } = useValues(tracingCorrelationConfigLogic)+ const { updateTracingConfig } = useActions(tracingCorrelationConfigLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ const [value, setValue] = useState<string[]>([])++ useEffect(() => {+ if (tracingConfig) {+ setValue(tracingConfig.tracing_distinct_id_attribute_keys ?? DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS)+ }+ }, [tracingConfig])++ if (!tracingConfig && tracingConfigLoading) {+ return <LemonSkeleton className="w-1/2 h-4" />+ }++ const cleaned = value.map((key) => key.trim()).filter(Boolean)+ const isDirty = !objectsEqual(cleaned, tracingConfig?.tracing_distinct_id_attribute_keys ?? [])+ const isEmpty = cleaned.length === 0++ return (+ <div className="deprecated-space-y-4">+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={value}+ onChange={setValue}+ placeholder={DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS.join(', ')}+ loading={tracingConfigLoading}+ disabled={tracingConfigLoading || !!restrictedReason}+ data-attr="tracing-distinct-id-attribute-keys-select"+ className="max-w-md"+ />+ <LemonButton+ type="primary"+ onClick={() => updateTracingConfig({ tracing_distinct_id_attribute_keys: cleaned })}+ disabledReason={+ restrictedReason ||+ (isEmpty ? 'At least one attribute key is required' : !isDirty ? 'No changes to save' : undefined)+ }+ loading={tracingConfigLoading}+ >+ Save+ </LemonButton>+ </div>+ )+}diff --git a/frontend/src/scenes/settings/environment/TracingSessionIdAttributeKeys.tsx b/frontend/src/scenes/settings/environment/TracingSessionIdAttributeKeys.tsxnew file mode 100644index 000000000000..00150608a8a8--- /dev/null+++ b/frontend/src/scenes/settings/environment/TracingSessionIdAttributeKeys.tsx@@ -0,0 +1,67 @@+import { useActions, useValues } from 'kea'+import { useEffect, useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { objectsEqual } from 'lib/utils/objects'++import {+ DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS,+ tracingCorrelationConfigLogic,+} from 'products/tracing/frontend/tracingCorrelationConfigLogic'++export function TracingSessionIdAttributeKeys(): JSX.Element {+ const { tracingConfig, tracingConfigLoading } = useValues(tracingCorrelationConfigLogic)+ const { updateTracingConfig } = useActions(tracingCorrelationConfigLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ const [value, setValue] = useState<string[]>([])++ useEffect(() => {+ if (tracingConfig) {+ setValue(tracingConfig.tracing_session_id_attribute_keys ?? DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS)+ }+ }, [tracingConfig])++ if (!tracingConfig && tracingConfigLoading) {+ return <LemonSkeleton className="w-1/2 h-4" />+ }++ const cleaned = value.map((key) => key.trim()).filter(Boolean)+ const isDirty = !objectsEqual(cleaned, tracingConfig?.tracing_session_id_attribute_keys ?? [])+ const isEmpty = cleaned.length === 0++ return (+ <div className="deprecated-space-y-4">+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={value}+ onChange={setValue}+ placeholder={DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS.join(', ')}+ loading={tracingConfigLoading}+ disabled={tracingConfigLoading || !!restrictedReason}+ data-attr="tracing-session-id-attribute-keys-select"+ className="max-w-md"+ />+ <LemonButton+ type="primary"+ onClick={() => updateTracingConfig({ tracing_session_id_attribute_keys: cleaned })}+ disabledReason={+ restrictedReason ||+ (isEmpty ? 'At least one attribute key is required' : !isDirty ? 'No changes to save' : undefined)+ }+ loading={tracingConfigLoading}+ >+ Save+ </LemonButton>+ </div>+ )+}diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 83f8817cdc71..70054e30a6ed 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -46,6 +46,7 @@ export type SettingSectionId =| 'environment-secret-api-keys'| 'environment-surveys'| 'environment-task-agents'+ | 'environment-tracing'| 'environment-web-analytics'| 'environment-workflows'| 'environment-danger-zone'@@ -274,6 +275,8 @@ export type SettingId =| 'task-agent-my-preference'| 'task-agent-project-default'| 'theme'+ | 'tracing-distinct-id-attribute-keys'+ | 'tracing-session-id-attribute-keys'| 'user-delete'| 'user-groups'| 'variables'diff --git a/posthog/api/project.py b/posthog/api/project.pyindex ffc82cd92f7b..9d97350eefa3 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -40,6 +40,7 @@ from posthog.api.team import (TeamMarketingAnalyticsConfigSerializer,TeamRevenueAnalyticsConfigSerializer,TeamSerializer,+ TeamTracingConfigSerializer,TeamWorkflowsConfigSerializer,_default_data_color_theme_id,_format_serializer_errors,@@ -47,6 +48,7 @@ from posthog.api.team import (handle_conversations_token_on_update,handle_experiments_config,handle_logs_config,+ handle_tracing_config,report_conversations_settings_changes,team_event_ingestion_restrictions_view,validate_secret_token_generation,@@ -1728,6 +1730,32 @@ class ProjectViewSet(project = self.get_object()return handle_logs_config(request, project.passthrough_team)+ @extend_schema(+ methods=["GET"],+ request=None,+ responses={200: TeamTracingConfigSerializer},+ extensions={"x-product": "tracing"},+ )+ @extend_schema(+ methods=["PATCH"],+ request=TeamTracingConfigSerializer,+ responses={200: TeamTracingConfigSerializer},+ extensions={"x-product": "tracing"},+ )+ @action(+ methods=["GET", "PATCH"],+ detail=True,+ permission_classes=[TeamMemberStrictManagementPermission],+ url_path="tracing_config",+ )+ def tracing_config(self, request: request.Request, id: str, **kwargs) -> response.Response:+ """Manage tracing product configuration for this project's canonical environment.+ Members can read; writing requires project admin, matching the admin-only+ settings UI. Mirrors the env-router action so /api/projects/:id/tracing_config/+ resolves alongside the legacy /api/environments/:id/tracing_config/ alias."""+ project = self.get_object()+ return handle_tracing_config(request, project.passthrough_team)+@action(methods=["GET"], detail=True)def activity(self, request: request.Request, **kwargs):# TODO: This is currently the same as in TeamViewSet - we should rework for the Project scopediff --git a/posthog/api/team.py b/posthog/api/team.pyindex 10eb0b477d01..c9c45b48512d 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -120,6 +120,7 @@ from products.customer_analytics.backend.facade.team_extension import TeamCustomfrom products.feature_flags.backend.models.evaluation_context import EvaluationContext, normalize_context_namefrom products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfigfrom products.logs.backend.models import TeamLogsConfig+from products.tracing.backend.facade.team_extension import TeamTracingConfigfrom products.web_analytics.backend.hogql_queries.custom_bot_definitions import (MAX_CUSTOM_BOT_DEFINITIONS,assert_patterns_compile as assert_custom_bot_patterns_compile,@@ -131,6 +132,14 @@ from products.workflows.backend.models.team_workflows_config import EmailTrackintracer = trace.get_tracer(__name__)+def _validate_unique_attribute_keys(value: list[str]) -> list[str]:+ # The child CharField already trims whitespace and rejects blanks; only+ # cross-item uniqueness needs checking here.+ if len(set(value)) != len(value):+ raise serializers.ValidationError("Attribute keys must be unique.")+ return value++class TeamLogsConfigSerializer(serializers.ModelSerializer):logs_distinct_id_attribute_key = serializers.CharField(read_only=True,@@ -194,21 +203,14 @@ class TeamLogsConfigSerializer(serializers.ModelSerializer):"logs_pattern_message_keys",]- def _validate_unique_keys(self, value: list[str]) -> list[str]:- # The child CharField already trims whitespace and rejects blanks; only- # cross-item uniqueness needs checking here.- if len(set(value)) != len(value):- raise serializers.ValidationError("Attribute keys must be unique.")- return value-def validate_logs_distinct_id_attribute_keys(self, value: list[str]) -> list[str]:- return self._validate_unique_keys(value)+ return _validate_unique_attribute_keys(value)def validate_logs_session_id_attribute_keys(self, value: list[str]) -> list[str]:- return self._validate_unique_keys(value)+ return _validate_unique_attribute_keys(value)def validate_logs_pattern_message_keys(self, value: list[str]) -> list[str]:- return self._validate_unique_keys(value)+ return _validate_unique_attribute_keys(value)def update(self, instance: TeamLogsConfig, validated_data: dict) -> TeamLogsConfig:# Keep the legacy single-key column in sync so pre-plural readers stay coherent.@@ -218,6 +220,66 @@ class TeamLogsConfigSerializer(serializers.ModelSerializer):return super().update(instance, validated_data)+class TeamTracingConfigSerializer(serializers.ModelSerializer):+ tracing_distinct_id_attribute_keys = serializers.ListField(+ # trim_whitespace is the DRF default, but the uniqueness validator below+ # depends on it — spell it out so it can't drift silently.+ child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),+ allow_empty=False,+ max_length=10,+ help_text=(+ "Span or resource attribute keys whose values should match a person's distinct_id — "+ "a span links to a person when any of these attributes holds one of their distinct "+ "IDs. Defaults to ['posthogDistinctId'], the key the posthog-js / "+ "posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if "+ "your pipeline emits the person identifier under different attributes."+ ),+ )+ tracing_session_id_attribute_keys = serializers.ListField(+ # trim_whitespace is the DRF default, but the uniqueness validator below+ # depends on it — spell it out so it can't drift silently.+ child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),+ allow_empty=False,+ max_length=10,+ help_text=(+ "Ordered list of span or resource attribute keys whose values hold the PostHog "+ "session ID. Detection checks keys in order, then falls back to common session ID "+ "attribute conventions; the first key with a value wins. Defaults to ['sessionId'], "+ "the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they "+ "emit. Add keys only if your pipeline emits the session ID under different attributes."+ ),+ )++ class Meta:+ model = TeamTracingConfig+ fields = [+ "tracing_distinct_id_attribute_keys",+ "tracing_session_id_attribute_keys",+ ]++ def validate_tracing_distinct_id_attribute_keys(self, value: list[str]) -> list[str]:+ return _validate_unique_attribute_keys(value)++ def validate_tracing_session_id_attribute_keys(self, value: list[str]) -> list[str]:+ return _validate_unique_attribute_keys(value)+++def handle_tracing_config(request: request.Request, team: Team) -> response.Response:+ """Shared handler for the tracing_config action — exposed under both the team/environment+ and project routers so the canonical /api/projects/ URL resolves alongside the legacy+ /api/environments/ alias. Both endpoints operate on the env-scoped TeamTracingConfig+ keyed by team_id."""+ config = get_or_create_team_extension(team, TeamTracingConfig)++ if request.method == "PATCH":+ serializer = TeamTracingConfigSerializer(config, data=request.data, partial=True)+ serializer.is_valid(raise_exception=True)+ serializer.save()+ return response.Response(serializer.data)++ return response.Response(TeamTracingConfigSerializer(config).data)++def handle_experiments_config(request: request.Request, team: Team) -> response.Response:"""Shared handler for the experiments_config action — exposed under both theteam/environment and project routers so both surfaces stay in parity."""@@ -2509,6 +2571,29 @@ class TeamViewSet(writing requires project admin, matching the admin-only settings UI."""return handle_logs_config(request, self.get_object())+ @extend_schema(+ methods=["GET"],+ request=None,+ responses={200: TeamTracingConfigSerializer},+ extensions={"x-product": "tracing"},+ )+ @extend_schema(+ methods=["PATCH"],+ request=TeamTracingConfigSerializer,+ responses={200: TeamTracingConfigSerializer},+ extensions={"x-product": "tracing"},+ )+ @action(+ methods=["GET", "PATCH"],+ detail=True,+ permission_classes=[TeamMemberStrictManagementPermission],+ url_path="tracing_config",+ )+ def tracing_config(self, request: request.Request, id: str, **kwargs) -> response.Response:+ """Manage tracing product configuration for this environment. Members can read;+ writing requires project admin, matching the admin-only settings UI."""+ return handle_tracing_config(request, self.get_object())+@action(methods=["GET", "PATCH"],detail=True,diff --git a/posthog/api/test/test_team_tracing_config.py b/posthog/api/test/test_team_tracing_config.pynew file mode 100644index 000000000000..61e960026668--- /dev/null+++ b/posthog/api/test/test_team_tracing_config.py@@ -0,0 +1,198 @@+from posthog.test.base import APIBaseTest++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status++from posthog.api.team import TeamTracingConfigSerializer+from posthog.models import OrganizationMembership, Team+from posthog.models.team.extensions import get_or_create_team_extension++from products.tracing.backend.facade.team_extension import (+ DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS,+ DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS,+ TeamTracingConfig,+)++# Both routes resolve to the same handler — /api/projects/ is canonical, /api/environments/+# remains as the back-compat alias. See `handle_tracing_config` in posthog/api/team.py.+URL_PREFIXES = [("projects", "api/projects"), ("environments", "api/environments")]++DEFAULT_CONFIG = {+ "tracing_distinct_id_attribute_keys": DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS,+ "tracing_session_id_attribute_keys": DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS,+}+++class TestTeamTracingConfig(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ def _url(self, prefix: str) -> str:+ return f"/{prefix}/{self.team.id}/tracing_config/"++ @parameterized.expand(URL_PREFIXES)+ def test_get_returns_defaults(self, _name: str, prefix: str):+ response = self.client.get(self._url(prefix))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), DEFAULT_CONFIG)++ @parameterized.expand(URL_PREFIXES)+ def test_patch_updates_distinct_id_keys(self, _name: str, prefix: str):+ response = self.client.patch(+ self._url(prefix),+ {"tracing_distinct_id_attribute_keys": ["user.id", "posthogDistinctId"]},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["tracing_distinct_id_attribute_keys"], ["user.id", "posthogDistinctId"])++ config = get_or_create_team_extension(self.team, TeamTracingConfig)+ self.assertEqual(config.tracing_distinct_id_attribute_keys, ["user.id", "posthogDistinctId"])++ @parameterized.expand(URL_PREFIXES)+ def test_patch_persists_across_requests(self, _name: str, prefix: str):+ self.client.patch(+ self._url(prefix),+ {"tracing_distinct_id_attribute_keys": ["posthog.distinct_id"]},+ format="json",+ )++ response = self.client.get(self._url(prefix))+ self.assertEqual(response.json()["tracing_distinct_id_attribute_keys"], ["posthog.distinct_id"])++ @parameterized.expand(URL_PREFIXES)+ def test_regular_member_can_read_but_not_patch(self, _name: str, prefix: str):+ # Writes are admin-only, matching the admin-gated settings UI; reads stay open+ # to members so the settings page can render for everyone.+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()++ get_response = self.client.get(self._url(prefix))+ self.assertEqual(get_response.status_code, status.HTTP_200_OK)++ patch_response = self.client.patch(+ self._url(prefix),+ {"tracing_distinct_id_attribute_keys": ["user.id"]},+ format="json",+ )+ self.assertEqual(patch_response.status_code, status.HTTP_403_FORBIDDEN)++ @parameterized.expand(URL_PREFIXES)+ def test_config_is_scoped_per_environment(self, _name: str, prefix: str):+ # Each environment under a project must keep its own config. A write on this+ # environment must not leak to a sibling environment that shares its project.+ sibling = Team.objects.create(+ organization=self.organization,+ parent_team=self.team,+ name="sibling-env",+ )++ self.client.patch(+ self._url(prefix),+ {"tracing_distinct_id_attribute_keys": ["user.id"]},+ format="json",+ )++ sibling_response = self.client.get(f"/{prefix}/{sibling.id}/tracing_config/")+ self.assertEqual(sibling_response.json(), DEFAULT_CONFIG)++ def test_project_and_environment_share_same_config(self):+ # Writes via the canonical /api/projects/ URL must be visible via the+ # /api/environments/ alias and vice versa — both routes operate on the+ # same env-scoped TeamTracingConfig keyed by team_id.+ self.client.patch(+ f"/api/projects/{self.team.id}/tracing_config/",+ {"tracing_distinct_id_attribute_keys": ["user.id"]},+ format="json",+ )+ env_response = self.client.get(f"/api/environments/{self.team.id}/tracing_config/")+ self.assertEqual(env_response.json()["tracing_distinct_id_attribute_keys"], ["user.id"])++ def test_patch_updates_session_id_keys_preserving_order(self):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/tracing_config/",+ {"tracing_session_id_attribute_keys": ["session.id", "posthogSessionId"]},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["tracing_session_id_attribute_keys"], ["session.id", "posthogSessionId"])++ config = get_or_create_team_extension(self.team, TeamTracingConfig)+ self.assertEqual(config.tracing_session_id_attribute_keys, ["session.id", "posthogSessionId"])++ def test_partial_patch_leaves_other_field_untouched(self):+ # A naive serializer change could make a PATCH on one field reset the other+ # to its default — the two settings must update independently.+ self.client.patch(+ f"/api/projects/{self.team.id}/tracing_config/",+ {"tracing_session_id_attribute_keys": ["session.id"]},+ format="json",+ )+ self.client.patch(+ f"/api/projects/{self.team.id}/tracing_config/",+ {"tracing_distinct_id_attribute_keys": ["user.id"]},+ format="json",+ )++ response = self.client.get(f"/api/projects/{self.team.id}/tracing_config/")+ self.assertEqual(+ response.json(),+ {+ "tracing_distinct_id_attribute_keys": ["user.id"],+ "tracing_session_id_attribute_keys": ["session.id"],+ },+ )++ @parameterized.expand(+ [+ ("distinct_id", "tracing_distinct_id_attribute_keys"),+ ("session_id", "tracing_session_id_attribute_keys"),+ ]+ )+ def test_patch_rejects_invalid_keys(self, _name: str, field: str):+ # Wiring guard: the endpoint must reject bodies the serializer marks invalid.+ # The full validation matrix lives in TestTeamTracingConfigSerializerValidation.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/tracing_config/",+ {field: []},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+++KEY_LIST_FIELDS = ["tracing_distinct_id_attribute_keys", "tracing_session_id_attribute_keys"]++INVALID_KEY_LISTS = [+ ("empty_list", []),+ ("blank_entry", ["sessionId", ""]),+ ("whitespace_entry", ["sessionId", " "]),+ ("duplicate_keys", ["session.id", "session.id"]),+ ("duplicate_after_trim", ["session.id", " session.id "]),+ ("too_many_keys", [f"key{i}" for i in range(11)]),+ ("key_over_max_length", ["x" * 201]),+]+++class TestTeamTracingConfigSerializerValidation(SimpleTestCase):+ @parameterized.expand(+ [(f"{field}_{name}", field, keys) for field in KEY_LIST_FIELDS for name, keys in INVALID_KEY_LISTS]+ )+ def test_rejects_invalid_keys(self, _name: str, field: str, keys):+ serializer = TeamTracingConfigSerializer(data={field: keys}, partial=True)++ self.assertFalse(serializer.is_valid())+ self.assertIn(field, serializer.errors)++ @parameterized.expand([(field,) for field in KEY_LIST_FIELDS])+ def test_trims_whitespace_from_keys(self, field: str):+ serializer = TeamTracingConfigSerializer(data={field: [" first.key ", "second.key"]}, partial=True)++ self.assertTrue(serializer.is_valid())+ self.assertEqual(serializer.validated_data[field], ["first.key", "second.key"])diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex d6fa5c3e02af..6eb80ca26713 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -60,6 +60,7 @@ actions_that_require_current_team = ["default_evaluation_contexts","evaluation_context_suggestions","logs_config",+ "tracing_config",]diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 52d09bc7f1df..aa413f481f04 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -383,6 +383,7 @@ posthog.Team tasks.SandboxEnvironment.team reverse-accessor(sandboxenvironment_sposthog.Team tasks.Task.team reverse-accessor(task_set) 1posthog.Team tasks.TaskRun.team reverse-accessor(taskrun_set) 1posthog.Team tasks.TaskWorkflowDispatch.team reverse-accessor(taskworkflowdispatch_set) 1+posthog.Team tracing.TeamTracingConfig.team reverse-accessor(teamtracingconfig) 1posthog.Team tracing.TracingView.team reverse-accessor(tracingview_set) 1posthog.Team user_interviews.IntervieweeContext.team reverse-accessor(intervieweecontext_set) 1posthog.Team user_interviews.UserInterview.team reverse-accessor(userinterview_set) 1diff --git a/products/tracing/backend/facade/team_extension.py b/products/tracing/backend/facade/team_extension.pynew file mode 100644index 000000000000..9b8e0e9c88e5--- /dev/null+++ b/products/tracing/backend/facade/team_extension.py@@ -0,0 +1,19 @@+"""Facade re-export for the tracing team-extension model.++Core's ``posthog/api/team.py`` registers/reads this extension by class identity+through ``get_or_create_team_extension``. Re-exporting the model class keeps+that registry coupling at the facade boundary without exposing the internal+models module. Mirrors the customer_analytics precedent.+"""++from products.tracing.backend.models import (+ DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS,+ DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS,+ TeamTracingConfig,+)++__all__ = [+ "DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS",+ "DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS",+ "TeamTracingConfig",+]diff --git a/products/tracing/backend/migrations/0002_teamtracingconfig.py b/products/tracing/backend/migrations/0002_teamtracingconfig.pynew file mode 100644index 000000000000..31f9aa748796--- /dev/null+++ b/products/tracing/backend/migrations/0002_teamtracingconfig.py@@ -0,0 +1,59 @@+# Generated by Django 5.2.17 on 2026-08-31 17:28++import django.db.models.deletion+import django.contrib.postgres.fields+from django.db import migrations, models++from posthog.migration_helpers import AddForeignKeyNotValid++import products.tracing.backend.models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1329_drop_cimd_metadata_url"),+ ("tracing", "0001_initial"),+ ]++ operations = [+ migrations.CreateModel(+ name="TeamTracingConfig",+ fields=[+ (+ "team",+ models.OneToOneField(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ primary_key=True,+ serialize=False,+ to="posthog.team",+ ),+ ),+ (+ "tracing_distinct_id_attribute_keys",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=200),+ db_default=models.Value("{posthogDistinctId}"),+ default=products.tracing.backend.models.default_tracing_distinct_id_attribute_keys,+ size=None,+ ),+ ),+ (+ "tracing_session_id_attribute_keys",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=200),+ db_default=models.Value("{sessionId}"),+ default=products.tracing.backend.models.default_tracing_session_id_attribute_keys,+ size=None,+ ),+ ),+ ],+ ),+ AddForeignKeyNotValid(+ model_name="teamtracingconfig",+ name="teamtracingconfig_team_id_fk",+ column="team_id",+ to_table="posthog_team",+ to_column="id",+ ),+ ]diff --git a/products/tracing/backend/migrations/max_migration.txt b/products/tracing/backend/migrations/max_migration.txtindex cbab66dde92a..2baeba77da03 100644--- a/products/tracing/backend/migrations/max_migration.txt+++ b/products/tracing/backend/migrations/max_migration.txt@@ -1 +1 @@-0001_initial+0002_teamtracingconfigdiff --git a/products/tracing/backend/models.py b/products/tracing/backend/models.pyindex 18b2e771abf7..02146e5e702d 100644--- a/products/tracing/backend/models.py+++ b/products/tracing/backend/models.py@@ -1,11 +1,18 @@"""Django models for tracing."""+import logging++from django.contrib.postgres.fields import ArrayFieldfrom django.db import models+from django.db.models import Valuefrom posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.team.extensions import register_team_extension_signalfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModelfrom posthog.utils import generate_short_id+logger = logging.getLogger(__name__)+# Define your models here# Important:# - Keep models thin, no business logic, use logic.py instead@@ -13,6 +20,59 @@ from posthog.utils import generate_short_id# - Do not use ForeignKeys to models outside this app unless allowed, as you will make implicit dependencies.# - If you make a ForeignKey to a common model, disallow reverse relations with related_name='+'+# Default span/resource attribute keys whose values match a PostHog person's distinct_id.+# Mirrors the logs convention (https://posthog.com/docs/logs/link-session-replay): the+# posthog-js / posthog-react-native SDKs attach `posthogDistinctId` to the OTel signals+# they emit. Customers whose pipeline uses different keys can override via the+# `tracing_config` endpoint.+DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS = ["posthogDistinctId"]+++def default_tracing_distinct_id_attribute_keys() -> list[str]:+ return list(DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS)+++# Default span/resource attribute keys whose values hold the PostHog session ID.+# `sessionId` is the key the posthog-js / posthog-react-native SDKs emit on OTel+# signals. Ordered: detection checks keys in list order and the first match wins.+DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS = ["sessionId"]+++def default_tracing_session_id_attribute_keys() -> list[str]:+ return list(DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS)+++class TeamTracingConfig(models.Model):+ # Plain `models.Model` (not `TeamScopedRootMixin`) — span emission and ingestion are+ # per-environment, and so is this config. Inheriting the root-mixin would rewrite+ # writes to the parent project on save, letting a member of one child environment+ # mutate config that affects sibling environments they may not have access to.+ # Mirrors the `TeamLogsConfig` precedent.+ # db_constraint=False so creating this table takes no lock on the hot posthog_team+ # parent; the real constraint is added lock-free via AddForeignKeyNotValid in the+ # migration, same as TracingView.+ team = models.OneToOneField("posthog.Team", on_delete=models.CASCADE, primary_key=True, db_constraint=False)++ # Span or resource attribute keys whose values match a PostHog person's distinct_id —+ # a span links to a person when any of these attributes holds their distinct ID.+ tracing_distinct_id_attribute_keys = ArrayField(+ models.CharField(max_length=200),+ default=default_tracing_distinct_id_attribute_keys,+ db_default=Value("{posthogDistinctId}"),+ )++ # Ordered list of span or resource attribute keys whose values hold the PostHog+ # session ID. Detection checks keys in order; the first key with a value wins.+ # Used to link spans to session replay.+ tracing_session_id_attribute_keys = ArrayField(+ models.CharField(max_length=200),+ default=default_tracing_session_id_attribute_keys,+ db_default=Value("{sessionId}"),+ )+++register_team_extension_signal(TeamTracingConfig, logger=logger)+class TracingView(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):"""A saved set of tracing filters (date range, services, attribute filters, sort, view mode).diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex 799239c298a5..3fb20bdd881b 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -7,6 +7,36 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+export interface TeamTracingConfigApi {+ /**+ * Span or resource attribute keys whose values should match a person's distinct_id — a span links to a person when any of these attributes holds one of their distinct IDs. Defaults to ['posthogDistinctId'], the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the person identifier under different attributes.+ * @maxItems 10+ * @items.maxLength 200+ */+ tracing_distinct_id_attribute_keys: string[]+ /**+ * Ordered list of span or resource attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'], the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the session ID under different attributes.+ * @maxItems 10+ * @items.maxLength 200+ */+ tracing_session_id_attribute_keys: string[]+}++export interface PatchedTeamTracingConfigApi {+ /**+ * Span or resource attribute keys whose values should match a person's distinct_id — a span links to a person when any of these attributes holds one of their distinct IDs. Defaults to ['posthogDistinctId'], the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the person identifier under different attributes.+ * @maxItems 10+ * @items.maxLength 200+ */+ tracing_distinct_id_attribute_keys?: string[]+ /**+ * Ordered list of span or resource attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'], the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the session ID under different attributes.+ * @maxItems 10+ * @items.maxLength 200+ */+ tracing_session_id_attribute_keys?: string[]+}+export interface _TracingDateRangeApi {/*** Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex 00c744372463..125708d11e63 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -10,7 +10,9 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'*/import type {PaginatedTracingViewListApi,+ PatchedTeamTracingConfigApi,PatchedTracingViewApi,+ TeamTracingConfigApi,TracingSpansAttributesRetrieveParams,TracingSpansServiceNamesRetrieveParams,TracingSpansValuesRetrieveParams,@@ -52,6 +54,92 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getOrganizationsProjectsTracingConfigRetrieveUrl = (organizationId: string, id: number) => {+ return `/api/organizations/${organizationId}/projects/${id}/tracing_config/`+}++/**+ * Manage tracing product configuration for this project's canonical environment.+ * Members can read; writing requires project admin, matching the admin-only+ * settings UI. Mirrors the env-router action so /api/projects/:id/tracing_config/+ * resolves alongside the legacy /api/environments/:id/tracing_config/ alias.+ */+export const organizationsProjectsTracingConfigRetrieve = async (+ organizationId: string,+ id: number,+ options?: RequestInit+): Promise<TeamTracingConfigApi> => {+ return apiMutator<TeamTracingConfigApi>(getOrganizationsProjectsTracingConfigRetrieveUrl(organizationId, id), {+ ...options,+ method: 'GET',+ })+}++export const getOrganizationsProjectsTracingConfigPartialUpdateUrl = (organizationId: string, id: number) => {+ return `/api/organizations/${organizationId}/projects/${id}/tracing_config/`+}++/**+ * Manage tracing product configuration for this project's canonical environment.+ * Members can read; writing requires project admin, matching the admin-only+ * settings UI. Mirrors the env-router action so /api/projects/:id/tracing_config/+ * resolves alongside the legacy /api/environments/:id/tracing_config/ alias.+ */+export const organizationsProjectsTracingConfigPartialUpdate = async (+ organizationId: string,+ id: number,+ patchedTeamTracingConfigApi?: PatchedTeamTracingConfigApi,+ options?: RequestInit+): Promise<TeamTracingConfigApi> => {+ return apiMutator<TeamTracingConfigApi>(getOrganizationsProjectsTracingConfigPartialUpdateUrl(organizationId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedTeamTracingConfigApi),+ })+}++export const getEnvironmentsTracingConfigRetrieveUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/environments/${id}/tracing_config/`+}++/**+ * Manage tracing product configuration for this environment. Members can read;+ * writing requires project admin, matching the admin-only settings UI.+ */+export const environmentsTracingConfigRetrieve = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<TeamTracingConfigApi> => {+ return apiMutator<TeamTracingConfigApi>(getEnvironmentsTracingConfigRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getEnvironmentsTracingConfigPartialUpdateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/environments/${id}/tracing_config/`+}++/**+ * Manage tracing product configuration for this environment. Members can read;+ * writing requires project admin, matching the admin-only settings UI.+ */+export const environmentsTracingConfigPartialUpdate = async (+ projectId: string,+ id: number,+ patchedTeamTracingConfigApi?: PatchedTeamTracingConfigApi,+ options?: RequestInit+): Promise<TeamTracingConfigApi> => {+ return apiMutator<TeamTracingConfigApi>(getEnvironmentsTracingConfigPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedTeamTracingConfigApi),+ })+}+export const getTracingSpansAggregateCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/tracing/spans/aggregate/`}diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex 289a650e44ca..043edb30bff9 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -9,6 +9,70 @@*/import * as zod from 'zod'+/**+ * Manage tracing product configuration for this project's canonical environment.+ * Members can read; writing requires project admin, matching the admin-only+ * settings UI. Mirrors the env-router action so /api/projects/:id/tracing_config/+ * resolves alongside the legacy /api/environments/:id/tracing_config/ alias.+ */+export const organizationsProjectsTracingConfigPartialUpdateBodyTracingDistinctIdAttributeKeysItemMax = 200++export const organizationsProjectsTracingConfigPartialUpdateBodyTracingDistinctIdAttributeKeysMax = 10++export const organizationsProjectsTracingConfigPartialUpdateBodyTracingSessionIdAttributeKeysItemMax = 200++export const organizationsProjectsTracingConfigPartialUpdateBodyTracingSessionIdAttributeKeysMax = 10++export const OrganizationsProjectsTracingConfigPartialUpdateBody = /* @__PURE__ */ zod.object({+ tracing_distinct_id_attribute_keys: zod+ .array(+ zod.string().max(organizationsProjectsTracingConfigPartialUpdateBodyTracingDistinctIdAttributeKeysItemMax)+ )+ .max(organizationsProjectsTracingConfigPartialUpdateBodyTracingDistinctIdAttributeKeysMax)+ .optional()+ .describe(+ "Span or resource attribute keys whose values should match a person's distinct_id — a span links to a person when any of these attributes holds one of their distinct IDs. Defaults to ['posthogDistinctId'], the key the posthog-js \/ posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the person identifier under different attributes."+ ),+ tracing_session_id_attribute_keys: zod+ .array(+ zod.string().max(organizationsProjectsTracingConfigPartialUpdateBodyTracingSessionIdAttributeKeysItemMax)+ )+ .max(organizationsProjectsTracingConfigPartialUpdateBodyTracingSessionIdAttributeKeysMax)+ .optional()+ .describe(+ "Ordered list of span or resource attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'], the key the posthog-js \/ posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the session ID under different attributes."+ ),+})++/**+ * Manage tracing product configuration for this environment. Members can read;+ * writing requires project admin, matching the admin-only settings UI.+ */+export const environmentsTracingConfigPartialUpdateBodyTracingDistinctIdAttributeKeysItemMax = 200++export const environmentsTracingConfigPartialUpdateBodyTracingDistinctIdAttributeKeysMax = 10++export const environmentsTracingConfigPartialUpdateBodyTracingSessionIdAttributeKeysItemMax = 200++export const environmentsTracingConfigPartialUpdateBodyTracingSessionIdAttributeKeysMax = 10++export const EnvironmentsTracingConfigPartialUpdateBody = /* @__PURE__ */ zod.object({+ tracing_distinct_id_attribute_keys: zod+ .array(zod.string().max(environmentsTracingConfigPartialUpdateBodyTracingDistinctIdAttributeKeysItemMax))+ .max(environmentsTracingConfigPartialUpdateBodyTracingDistinctIdAttributeKeysMax)+ .optional()+ .describe(+ "Span or resource attribute keys whose values should match a person's distinct_id — a span links to a person when any of these attributes holds one of their distinct IDs. Defaults to ['posthogDistinctId'], the key the posthog-js \/ posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the person identifier under different attributes."+ ),+ tracing_session_id_attribute_keys: zod+ .array(zod.string().max(environmentsTracingConfigPartialUpdateBodyTracingSessionIdAttributeKeysItemMax))+ .max(environmentsTracingConfigPartialUpdateBodyTracingSessionIdAttributeKeysMax)+ .optional()+ .describe(+ "Ordered list of span or resource attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'], the key the posthog-js \/ posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the session ID under different attributes."+ ),+})+export const tracingSpansAggregateCreateBodyQueryOneCompareFilterOneCompareDefault = falseexport const tracingSpansAggregateCreateBodyQueryOneFilterGroupDefault = []export const tracingSpansAggregateCreateBodyQueryOneLimitMax = 5000diff --git a/products/tracing/frontend/tracingCorrelationConfigLogic.ts b/products/tracing/frontend/tracingCorrelationConfigLogic.tsnew file mode 100644index 000000000000..8d28686efd2e--- /dev/null+++ b/products/tracing/frontend/tracingCorrelationConfigLogic.ts@@ -0,0 +1,117 @@+import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { teamLogic } from 'scenes/teamLogic'++import type { PatchedTeamTracingConfigApi, TeamTracingConfigApi } from 'products/tracing/frontend/generated/api.schemas'++// Mirrors the backend defaults in products/tracing/backend/models.py — the same convention+// the Logs product uses (https://posthog.com/docs/logs/link-session-replay). Used as the+// pre-load fallback before `tracing_config` resolves.+export const DEFAULT_TRACING_DISTINCT_ID_ATTRIBUTE_KEYS = ['posthogDistinctId']++// Mirrors the backend default in products/tracing/backend/models.py. Ordered: session ID+// detection checks keys in list order and the first match wins.+export const DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS = ['sessionId']++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface tracingCorrelationConfigLogicValues {+ currentTeamId: number | null // teamLogic+ configuredDistinctIdKeys: string[] | undefined+ configuredSessionIdKeys: string[] | undefined+ tracingConfig: TeamTracingConfigApi | null+ tracingConfigLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface tracingCorrelationConfigLogicActions {+ loadTracingConfig: () => any+ loadTracingConfigFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTracingConfigSuccess: (+ tracingConfig: TeamTracingConfigApi,+ payload?: any+ ) => {+ tracingConfig: TeamTracingConfigApi+ payload?: any+ }+ updateTracingConfig: (patch: PatchedTeamTracingConfigApi) => PatchedTeamTracingConfigApi+ updateTracingConfigFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ updateTracingConfigSuccess: (+ tracingConfig: TeamTracingConfigApi,+ payload?: PatchedTeamTracingConfigApi+ ) => {+ tracingConfig: TeamTracingConfigApi+ payload?: PatchedTeamTracingConfigApi+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface tracingCorrelationConfigLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ configuredDistinctIdKeys: (tracingConfig: TeamTracingConfigApi | null) => string[] | undefined+ configuredSessionIdKeys: (tracingConfig: TeamTracingConfigApi | null) => string[] | undefined+ }+}++export type tracingCorrelationConfigLogicType = MakeLogicType<+ tracingCorrelationConfigLogicValues,+ tracingCorrelationConfigLogicActions,+ Record<string, any>,+ tracingCorrelationConfigLogicMeta+>++export const tracingCorrelationConfigLogic = kea<tracingCorrelationConfigLogicType>([+ path(['products', 'tracing', 'frontend', 'tracingCorrelationConfigLogic']),+ connect({ values: [teamLogic, ['currentTeamId']] }),+ loaders(({ values }) => ({+ tracingConfig: [+ null as TeamTracingConfigApi | null,+ {+ // The flat /api/projects/:team_id/ route is the canonical per-environment one+ // (same as logsConfigLogic). The generated client only exposes the nested+ // /api/projects/:pid/environments/:id/ variant, whose viewset rejects every+ // request, so these URLs are deliberately hand-built.+ loadTracingConfig: async (): Promise<TeamTracingConfigApi> => {+ // nosemgrep: prefer-codegen-api+ return await api.get(`api/projects/${values.currentTeamId}/tracing_config/`)+ },+ updateTracingConfig: async (patch: PatchedTeamTracingConfigApi): Promise<TeamTracingConfigApi> => {+ // nosemgrep: prefer-codegen-api+ return await api.update(`api/projects/${values.currentTeamId}/tracing_config/`, patch)+ },+ },+ ],+ })),+ selectors({+ // Undefined until tracing_config resolves — distinct-id detection falls back to its+ // built-in convention list (which contains the default) in the meantime.+ configuredDistinctIdKeys: [+ (s) => [s.tracingConfig],+ (tracingConfig: TeamTracingConfigApi | null): string[] | undefined =>+ tracingConfig?.tracing_distinct_id_attribute_keys,+ ],+ // Undefined until tracing_config resolves — session detection falls back to its+ // built-in convention list (which contains the default) in the meantime.+ configuredSessionIdKeys: [+ (s) => [s.tracingConfig],+ (tracingConfig: TeamTracingConfigApi | null): string[] | undefined =>+ tracingConfig?.tracing_session_id_attribute_keys,+ ],+ }),+ afterMount(({ actions }) => {+ actions.loadTracingConfig()+ }),+])diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yamlindex fe701d8eb16d..b82006890089 100644--- a/products/tracing/mcp/tools.yaml+++ b/products/tracing/mcp/tools.yaml@@ -205,6 +205,18 @@ tools:response:include:- results+ environments-tracing-config-partial-update:+ operation: environments_tracing_config_partial_update+ enabled: false+ environments-tracing-config-retrieve:+ operation: environments_tracing_config_retrieve+ enabled: false+ organizations-projects-tracing-config-partial-update:+ operation: organizations_projects_tracing_config_partial_update+ enabled: false+ organizations-projects-tracing-config-retrieve:+ operation: organizations_projects_tracing_config_retrieve+ enabled: falsequery-apm-spans:operation: tracing_spans_query_createenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cee9d3c43929..578b10293f8d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -67765,6 +67765,21 @@ export namespace Schemas {readonly events_retention_enforced?: boolean;}+ export interface PatchedTeamTracingConfig {+ /**+ * Span or resource attribute keys whose values should match a person's distinct_id — a span links to a person when any of these attributes holds one of their distinct IDs. Defaults to ['posthogDistinctId'], the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the person identifier under different attributes.+ * @maxItems 10+ * @items.maxLength 200+ */+ tracing_distinct_id_attribute_keys?: string[];+ /**+ * Ordered list of span or resource attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'], the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the session ID under different attributes.+ * @maxItems 10+ * @items.maxLength 200+ */+ tracing_session_id_attribute_keys?: string[];+ }+/*** Payload for updating a private note on a ticket.*/@@ -85975,6 +85990,21 @@ export namespace Schemas {has_membership_data: boolean;}+ export interface TeamTracingConfig {+ /**+ * Span or resource attribute keys whose values should match a person's distinct_id — a span links to a person when any of these attributes holds one of their distinct IDs. Defaults to ['posthogDistinctId'], the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the person identifier under different attributes.+ * @maxItems 10+ * @items.maxLength 200+ */+ tracing_distinct_id_attribute_keys: string[];+ /**+ * Ordered list of span or resource attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'], the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the session ID under different attributes.+ * @maxItems 10+ * @items.maxLength 200+ */+ tracing_session_id_attribute_keys: string[];+ }+/*** * `none` - none* * `last` - lastdiff --git a/tach.toml b/tach.tomlindex 06b0bbb3ca6f..27c1972a621a 100644--- a/tach.toml+++ b/tach.toml@@ -1175,6 +1175,14 @@ from = ["products.error_tracking",]+[[interfaces]]+expose = [+ "backend\\.facade.*",+]+from = [+ "products.tracing",+]+[[interfaces]]expose = ["backend\\.logic.*",