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.

fix(logs): session links from error tracking find nothing for unconfigured teams (#83710)

Anna Garcia07e4b5849e9c
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index d055749ecb8f..8ff71d300f17 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -853,13 +853,13 @@ export const SETTINGS_MAP: SettingSection[] = [
description: (
<>
The log attributes PostHog reads to identify which session a log belongs to, checked in order
- with the first match winning. Defaults to <code>posthogSessionId</code>, the key the JavaScript
- and React Native SDKs auto-attach. Add keys only if your pipeline emits the session ID under
- different attributes.
+ with the first match winning, followed by other common session ID attributes. Defaults to{' '}
+ <code>sessionId</code>, the key the JavaScript and React Native SDKs auto-attach. Add keys only
+ if your pipeline emits the session ID under different attributes.
</>
),
searchDescription:
- 'The log attributes PostHog reads to identify which session a log belongs to, checked in order with the first match winning. Defaults to posthogSessionId, the key the JavaScript and React Native SDKs auto-attach. Add keys only if your pipeline emits the session ID under different attributes.',
+ 'The log attributes PostHog reads to identify which session a log belongs to, checked in order with the first match winning, followed by other common session ID attributes. Defaults to sessionId, the key the JavaScript and React Native SDKs auto-attach. Add keys only if your pipeline emits the session ID under different attributes.',
component: <LogsSessionIdAttributeKeys />,
flag: 'LOGS_SETTINGS',
keywords: ['log', 'session', 'replay', 'attribute', 'link'],
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 8fc16c50174f..a0e3f001a8c6 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -149,10 +149,11 @@ class TeamLogsConfigSerializer(serializers.ModelSerializer):
max_length=10,
help_text=(
"Ordered list of log attribute keys whose values hold the PostHog session ID. "
- "Detection checks keys in order; the first key with a value wins. Defaults to "
- "['posthogSessionId'] — the key the posthog-js / posthog-react-native SDKs "
- "auto-attach. Add keys only if your pipeline emits the session ID under "
- "different attributes."
+ "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 "
+ "convention documented at https://posthog.com/docs/logs/link-session-replay and "
+ "the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only "
+ "if your pipeline emits the session ID under different attributes."
),
)
diff --git a/products/error_tracking/frontend/ErrorTracking.stories.tsx b/products/error_tracking/frontend/ErrorTracking.stories.tsx
index 0d7a834e5ab8..2688594ebfef 100644
--- a/products/error_tracking/frontend/ErrorTracking.stories.tsx
+++ b/products/error_tracking/frontend/ErrorTracking.stories.tsx
@@ -255,7 +255,7 @@ const meta: Meta = {
{
logs_distinct_id_attribute_key: 'posthogDistinctId',
logs_distinct_id_attribute_keys: ['posthogDistinctId'],
- logs_session_id_attribute_keys: ['posthogSessionId'],
+ logs_session_id_attribute_keys: ['sessionId'],
},
],
'/api/environments/:team_id/error_tracking/issues/exists/': [200, { exists: true }],
diff --git a/products/logs/backend/migrations/0022_backfill_logs_session_id_attribute_keys.py b/products/logs/backend/migrations/0022_backfill_logs_session_id_attribute_keys.py
new file mode 100644
index 000000000000..e760f1169c91
--- /dev/null
+++ b/products/logs/backend/migrations/0022_backfill_logs_session_id_attribute_keys.py
@@ -0,0 +1,35 @@
+from django.db import migrations
+
+BATCH_SIZE = 1000
+
+# No SDK emits this key, so a team still carrying it as its stored default resolves nothing
+# wherever detection trusts the configured keys.
+OLD_DEFAULT = ["posthogSessionId"]
+
+# The old key stays first. Some pipelines do emit it, and detection is first-match-wins, so
+# reordering these two would move those teams onto a different attribute.
+NEW_VALUE = ["posthogSessionId", "sessionId"]
+
+
+def backfill_session_id_attribute_keys(apps, schema_editor):
+ TeamLogsConfig = apps.get_model("logs", "TeamLogsConfig")
+ configs = TeamLogsConfig.objects.filter(logs_session_id_attribute_keys=OLD_DEFAULT)
+ batch = []
+ for config in configs.iterator(chunk_size=BATCH_SIZE):
+ config.logs_session_id_attribute_keys = list(NEW_VALUE)
+ batch.append(config)
+ if len(batch) >= BATCH_SIZE:
+ TeamLogsConfig.objects.bulk_update(batch, ["logs_session_id_attribute_keys"])
+ batch = []
+ if batch:
+ TeamLogsConfig.objects.bulk_update(batch, ["logs_session_id_attribute_keys"])
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("logs", "0021_logsalertconfiguration_schedule_restriction"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_session_id_attribute_keys, migrations.RunPython.noop),
+ ]
diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txt
index 9f0c225c1783..1a387b05ab1b 100644
--- a/products/logs/backend/migrations/max_migration.txt
+++ b/products/logs/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0021_logsalertconfiguration_schedule_restriction
+0022_backfill_logs_session_id_attribute_keys
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index eb51c6c2973a..f59666b80890 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -54,12 +54,12 @@ DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS = [
]
-# Default log attribute keys whose values hold the PostHog session ID. `posthogSessionId`
-# is the key the posthog-js / posthog-react-native SDKs auto-attach to every log they
-# emit (see https://posthog.com/docs/logs/link-session-replay). Ordered: detection checks
-# keys in list order and the first match wins. Customers whose pipeline emits the session
-# ID under different keys can override via the `logs_config` endpoint.
-DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS = ["posthogSessionId"]
+# Default log attribute keys whose values hold the PostHog session ID. `sessionId` is what
+# the posthog-js / posthog-react-native SDKs emit and what
+# https://posthog.com/docs/logs/link-session-replay tells backends to send. Ordered:
+# detection checks keys in list order and the first match wins. Customers whose pipeline
+# emits the session ID under different keys can override via the `logs_config` endpoint.
+DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS = ["sessionId"]
def default_logs_session_id_attribute_keys() -> list[str]:
@@ -98,6 +98,8 @@ class TeamLogsConfig(models.Model):
logs_session_id_attribute_keys = ArrayField(
models.CharField(max_length=200),
default=default_logs_session_id_attribute_keys,
+ # Stale relative to the default above; aligning it needs a migration and Django
+ # applies `default` first, so this is never observed.
db_default=Value("{posthogSessionId}"),
)
diff --git a/products/logs/backend/test/test_models.py b/products/logs/backend/test/test_models.py
index ae0cf0943901..17f4cb79d338 100644
--- a/products/logs/backend/test/test_models.py
+++ b/products/logs/backend/test/test_models.py
@@ -13,6 +13,7 @@ from posthog.models.team.extensions import get_or_create_team_extension
from products.logs.backend.models import (
DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY,
+ DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS,
MAX_EVALUATION_PERIODS,
LogsAlertConfiguration,
LogsAlertEvent,
@@ -236,6 +237,11 @@ class TestTeamLogsConfig(BaseTest):
# their person without any team configuration.
assert config.logs_distinct_id_attribute_key == "posthogDistinctId"
assert config.logs_distinct_id_attribute_keys == ["posthogDistinctId"]
+ # The SDKs namespace the distinct ID but leave the session ID bare, so this one is
+ # `sessionId`, not `posthogSessionId`. Asserted literally: an assertion against the
+ # constant alone moves with it and would not catch the key drifting from the SDKs.
+ assert config.logs_session_id_attribute_keys == DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS
+ assert config.logs_session_id_attribute_keys == ["sessionId"]
def test_custom_attribute_keys_persist(self):
config = get_or_create_team_extension(self.team, TeamLogsConfig)
@@ -261,6 +267,44 @@ class TestTeamLogsConfig(BaseTest):
customized.refresh_from_db()
assert customized.logs_distinct_id_attribute_keys == ["user.id"]
+ def test_migration_backfill_appends_the_key_the_sdks_emit(self):
+ # Order matters — see the migration for why the old key stays first.
+ untouched = get_or_create_team_extension(self.team, TeamLogsConfig)
+ untouched.logs_session_id_attribute_keys = ["posthogSessionId"]
+ untouched.save()
+
+ self._run_session_id_backfill()
+
+ untouched.refresh_from_db()
+ assert untouched.logs_session_id_attribute_keys == ["posthogSessionId", "sessionId"]
+
+ def test_migration_backfill_leaves_a_customized_value_alone(self):
+ customized = get_or_create_team_extension(self.team, TeamLogsConfig)
+ customized.logs_session_id_attribute_keys = ["my.session.key"]
+ customized.save()
+
+ self._run_session_id_backfill()
+
+ customized.refresh_from_db()
+ assert customized.logs_session_id_attribute_keys == ["my.session.key"]
+
+ def test_migration_backfill_is_idempotent(self):
+ already_backfilled = get_or_create_team_extension(self.team, TeamLogsConfig)
+ already_backfilled.logs_session_id_attribute_keys = ["posthogSessionId", "sessionId"]
+ already_backfilled.save()
+
+ self._run_session_id_backfill()
+
+ already_backfilled.refresh_from_db()
+ assert already_backfilled.logs_session_id_attribute_keys == ["posthogSessionId", "sessionId"]
+
+ @staticmethod
+ def _run_session_id_backfill():
+ backfill_module = importlib.import_module(
+ "products.logs.backend.migrations.0022_backfill_logs_session_id_attribute_keys"
+ )
+ backfill_module.backfill_session_id_attribute_keys(apps, None)
+
def test_cascade_delete_with_team(self):
get_or_create_team_extension(self.team, TeamLogsConfig)
team_id = self.team.pk
diff --git a/products/logs/frontend/logsConfigLogic.ts b/products/logs/frontend/logsConfigLogic.ts
index b8fe659f94a0..1f79eb2c4cab 100644
--- a/products/logs/frontend/logsConfigLogic.ts
+++ b/products/logs/frontend/logsConfigLogic.ts
@@ -14,7 +14,7 @@ export const DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS = [DEFAULT_LOGS_DISTINCT_ID
// Mirrors the backend default in products/logs/backend/models.py. Ordered: session ID
// detection checks keys in list order and the first match wins.
-export const DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS = ['posthogSessionId']
+export const DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS = ['sessionId']
export interface LogsConfig {
// Legacy single-key alias — always the first entry of logs_distinct_id_attribute_keys.
diff --git a/products/logs/frontend/utils.test.ts b/products/logs/frontend/utils.test.ts
index 72752b2f3373..f9b22909311f 100644
--- a/products/logs/frontend/utils.test.ts
+++ b/products/logs/frontend/utils.test.ts
@@ -1,5 +1,7 @@
import { UniversalFiltersGroup } from '~/types'
+import { DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS } from 'products/logs/frontend/logsConfigLogic'
+
import {
buildLogsSessionFilters,
formatFilterGroupValues,
@@ -164,26 +166,84 @@ describe('logs utils', () => {
})
describe('buildLogsSessionFilters', () => {
+ // Byte-for-byte SESSION_ID_KEYS from utils.tsx. Spelled out rather than imported so a
+ // silent edit to that list shows up here as a failing assertion.
+ const CONVENTION_KEYS = [
+ 'session.id',
+ 'session_id',
+ 'sessionId',
+ 'sessionID',
+ '$session_id',
+ 'posthogSessionId',
+ 'posthogSessionID',
+ 'posthog_session_id',
+ 'posthog.session.id',
+ 'posthog.session_id',
+ ]
+
+ // Keys of the log-attribute filters only. Every key also gets a resource-attribute
+ // twin, asserted separately below.
+ const filterKeys = (configuredKeys?: string[]): string[] => {
+ const innerGroup = buildLogsSessionFilters('sess-1', configuredKeys).filterGroup!
+ .values[0] as UniversalFiltersGroup
+ expect(innerGroup.type).toBe('OR')
+ return (innerGroup.values as { key: string; type: string }[])
+ .filter((filter) => filter.type === 'log_attribute')
+ .map((filter) => filter.key)
+ }
+
it.each([
- ['defaults to the SDK convention key', undefined, ['posthogSessionId']],
- ['uses configured keys in order', ['session.id', 'custom.key'], ['session.id', 'custom.key']],
- ['empty configured list falls back to default', [], ['posthogSessionId']],
- ])('%s', (_, configuredKeys, expectedKeys) => {
- const filters = buildLogsSessionFilters('sess-1', configuredKeys)
+ ['no configured keys', undefined],
+ ['empty configured list', []],
+ ])('%s queries the built-in conventions', (_, configuredKeys) => {
+ expect(filterKeys(configuredKeys)).toEqual(CONVENTION_KEYS)
+ })
+
+ it('puts configured keys first, then the conventions, deduped', () => {
+ // `sessionId` is configured and a convention: it keeps its configured position
+ // and is not repeated.
+ expect(filterKeys(['custom.key', 'sessionId'])).toEqual([
+ 'custom.key',
+ 'sessionId',
+ ...CONVENTION_KEYS.filter((key) => key !== 'sessionId'),
+ ])
+ })
+
+ it('queries the shipped default, which must be one of the conventions', () => {
+ // buildLogsSessionFilters queries the conventions, not the default, so a default
+ // outside this list would go unqueried for a team that never edited it.
+ expect(CONVENTION_KEYS).toEqual(expect.arrayContaining(DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS))
+ })
+
+ it('queries sessionId for a team whose stored config is the old posthogSessionId default', () => {
+ // Every team created before the default changed has `posthogSessionId` materialised.
+ // The conventions union is what keeps their session link resolving SDK logs.
+ expect(filterKeys(['posthogSessionId'])).toContain('sessionId')
+ })
+
+ it('queries each key as both a log attribute and a resource attribute', () => {
+ // A log carrying the session id only under resource_attributes still renders the
+ // session link, so View Logs has to match that map too.
+ const filters = buildLogsSessionFilters('sess-1', ['custom.key'])
const innerGroup = filters.filterGroup!.values[0] as UniversalFiltersGroup
- expect(innerGroup.type).toBe('OR')
- expect(innerGroup.values).toEqual(
- expectedKeys.map((key) => ({
- key,
- value: ['sess-1'],
- operator: 'exact',
- type: 'log_attribute',
- }))
- )
+ expect(innerGroup.values.slice(0, 2)).toEqual([
+ { key: 'custom.key', value: ['sess-1'], operator: 'exact', type: 'log_attribute' },
+ { key: 'custom.key', value: ['sess-1'], operator: 'exact', type: 'log_resource_attribute' },
+ ])
expect(filters.dateRange).toBeUndefined()
})
+ it('pairs every queried key across both maps', () => {
+ const innerGroup = buildLogsSessionFilters('sess-1', ['custom.key']).filterGroup!
+ .values[0] as UniversalFiltersGroup
+ const values = innerGroup.values as { key: string; type: string }[]
+ const keysByType = (type: string): string[] =>
+ values.filter((filter) => filter.type === type).map((filter) => filter.key)
+
+ expect(keysByType('log_resource_attribute')).toEqual(keysByType('log_attribute'))
+ })
+
it('scopes the date range around the timestamp', () => {
const filters = buildLogsSessionFilters('sess-1', undefined, '2026-03-24T12:00:00.000Z')
expect(filters.dateRange).toEqual({
diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsx
index cbda6f9b9a23..1df20909582f 100644
--- a/products/logs/frontend/utils.tsx
+++ b/products/logs/frontend/utils.tsx
@@ -6,7 +6,6 @@ import { capitalizeFirstLetter } from 'lib/utils/strings'
import { AnyPropertyFilter, FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'
import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'
-import { DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS } from 'products/logs/frontend/logsConfigLogic'
export function formatFilterGroupValues(filterGroup: Record<string, any> | undefined): string[] {
const group = filterGroup?.values?.[0]
@@ -83,6 +82,7 @@ const DISTINCT_ID_KEYS = [
'posthog.distinct.id',
'posthog.distinct_id',
]
+// Some pipelines emit `posthogSessionId` even though no SDK does. Removing it breaks them.
const SESSION_ID_KEYS = [
'session.id',
'session_id',
@@ -170,27 +170,41 @@ export function buildDateRangeAround(timestamp: string, windowMinutes: number):
}
// Builds logs viewer filters scoped to one session, for other products surfacing logs
-// (error tracking, session replay). Filters on the team's configured session ID keys
-// (OR across keys, exact match), defaulting to the SDK convention; a timestamp scopes
-// the date range to ±30 minutes so old sessions aren't hidden by the default range.
+// (error tracking, session replay). Filters (OR across keys, exact match) on the team's
+// configured session ID keys plus the SESSION_ID_KEYS conventions, deduped, configured
+// first — the same breadth `getSessionIdWithKey` resolves, so a team whose stored key their
+// pipeline never emits still matches. Literal keys only: an exact filter can't express the
+// dot-suffix variants `matchesKey` allows. A timestamp scopes the date range to ±30 minutes
+// so old sessions aren't hidden by the default range.
export function buildLogsSessionFilters(
sessionId: string,
configuredKeys?: string[],
timestamp?: string
): Partial<LogsViewerFilters> {
- const keys = configuredKeys?.length ? configuredKeys : DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS
+ const keys = Array.from(new Set([...(configuredKeys ?? []), ...SESSION_ID_KEYS]))
const filters: Partial<LogsViewerFilters> = {
filterGroup: {
type: FilterLogicalOperator.And,
values: [
{
type: FilterLogicalOperator.Or,
- values: keys.map((key) => ({
- key,
- value: [sessionId],
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.LogAttribute,
- })),
+ // Each key is queried in both maps, because getSessionIdWithKey renders the
+ // session link off attributes or resource_attributes. Person scoping resolves
+ // distinct ids across both maps for the same reason.
+ values: keys.flatMap((key) => [
+ {
+ key,
+ value: [sessionId],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.LogAttribute,
+ },
+ {
+ key,
+ value: [sessionId],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.LogResourceAttribute,
+ },
+ ]),
},
],
},