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(web-analytics): flag pageviews without a usable session id (#90564)

posthog[bot]52a2323066fa
diff --git a/frontend/src/scenes/health/healthCategories.tsx b/frontend/src/scenes/health/healthCategories.tsx
index 82e731558243..964c71a70bef 100644
--- a/frontend/src/scenes/health/healthCategories.tsx
+++ b/frontend/src/scenes/health/healthCategories.tsx
@@ -28,6 +28,7 @@ export type HealthIssueKind =
| 'partial_proxy'
| 'web_vitals'
| 'path_cleaning_suggestions'
+ | 'missing_session_id'
| 'ingestion_lag'
| 'ingestion_warning'
| 'sdk_outdated'
@@ -131,6 +132,7 @@ const KIND_TO_CATEGORY: Record<HealthIssueKind, HealthIssueCategory> = {
partial_proxy: 'web_analytics',
web_vitals: 'web_analytics',
path_cleaning_suggestions: 'web_analytics',
+ missing_session_id: 'web_analytics',
}
export const KIND_LABELS: Record<HealthIssueKind, string> = {
@@ -142,6 +144,7 @@ export const KIND_LABELS: Record<HealthIssueKind, string> = {
partial_proxy: 'Partial reverse proxy',
web_vitals: 'No web vitals',
path_cleaning_suggestions: 'Path cleaning suggestions',
+ missing_session_id: 'Missing session IDs',
ingestion_lag: 'Ingestion lag',
external_data_failure: 'External data failures',
ingestion_warning: 'Ingestion warning',
diff --git a/frontend/src/scenes/web-analytics/health/healthCheckTypes.ts b/frontend/src/scenes/web-analytics/health/healthCheckTypes.ts
index e06f468c3e87..8368a2af9045 100644
--- a/frontend/src/scenes/web-analytics/health/healthCheckTypes.ts
+++ b/frontend/src/scenes/web-analytics/health/healthCheckTypes.ts
@@ -32,6 +32,7 @@ export enum HealthCheckId {
PAGEVIEW_EVENTS = 'pageview_events',
PAGELEAVE_EVENTS = 'pageleave_events',
SCROLL_DEPTH = 'scroll_depth',
+ MISSING_SESSION_ID = 'missing_session_id',
AUTHORIZED_URLS = 'authorized_urls',
REVERSE_PROXY = 'reverse_proxy',
diff --git a/frontend/src/scenes/web-analytics/health/webAnalyticsHealthLogic.ts b/frontend/src/scenes/web-analytics/health/webAnalyticsHealthLogic.ts
index cf265a0f8442..986f1517a95d 100644
--- a/frontend/src/scenes/web-analytics/health/webAnalyticsHealthLogic.ts
+++ b/frontend/src/scenes/web-analytics/health/webAnalyticsHealthLogic.ts
@@ -91,6 +91,20 @@ const WEB_HEALTH_CHECKS: WebHealthCheckConfig[] = [
failingAction: INSTALL_GUIDE_ACTION,
docsUrl: 'https://posthog.com/docs/web-analytics/scroll-depth',
},
+ {
+ id: HealthCheckId.MISSING_SESSION_ID,
+ kind: 'missing_session_id',
+ category: 'events',
+ title: 'Session IDs',
+ passingDescription: 'Pageviews carry a session ID that web analytics can use.',
+ failingDescription:
+ 'Some pageviews arrive without a session ID that web analytics can use. Web analytics needs a UUIDv7, and leaves out any pageview without one, so your visitor and session counts come in low. This usually means events are sent server-side or through a pipeline that omits the session ID.',
+ failingAction: {
+ label: 'Set up session IDs',
+ to: 'https://posthog.com/docs/data/sessions#custom-session-ids',
+ },
+ docsUrl: 'https://posthog.com/docs/data/sessions#custom-session-ids',
+ },
{
id: HealthCheckId.AUTHORIZED_URLS,
kind: 'authorized_urls',
diff --git a/posthog/temporal/health_checks/registry.py b/posthog/temporal/health_checks/registry.py
index b7365b415d9c..451e54d6d1d0 100644
--- a/posthog/temporal/health_checks/registry.py
+++ b/posthog/temporal/health_checks/registry.py
@@ -16,6 +16,7 @@ HEALTH_CHECK_MODULES = [
"products.data_warehouse.backend.temporal.health_checks.external_data_failure",
"products.web_analytics.backend.temporal.health_checks.no_live_events",
"products.web_analytics.backend.temporal.health_checks.no_pageleave_events",
+ "products.web_analytics.backend.temporal.health_checks.missing_session_id",
"products.growth.backend.temporal.health_checks.sdk_outdated",
"products.cdp.backend.temporal.health_checks.ingestion_warnings",
"products.data_warehouse.backend.temporal.health_checks.materialized_view_failure",
diff --git a/products/web_analytics/backend/temporal/health_checks/missing_session_id.py b/products/web_analytics/backend/temporal/health_checks/missing_session_id.py
new file mode 100644
index 000000000000..38a8bb141ec8
--- /dev/null
+++ b/products/web_analytics/backend/temporal/health_checks/missing_session_id.py
@@ -0,0 +1,147 @@
+from posthog.clickhouse.query_tagging import Product
+from posthog.job_owners import JobOwners
+from posthog.models.health_issue import HealthIssue
+from posthog.temporal.health_checks.detectors import CLICKHOUSE_BATCH_EXECUTION_POLICY
+from posthog.temporal.health_checks.framework import (
+ _SEVERITY_WEIGHT,
+ AlertContent,
+ HealthCheck,
+ Remediation,
+ SignalContent,
+ build_signal_extra,
+)
+from posthog.temporal.health_checks.models import HealthCheckResult
+from posthog.temporal.health_checks.query import execute_clickhouse_health_team_query
+
+MISSING_SESSION_ID_LOOKBACK_DAYS = 30
+
+# The recent window decides when the issue clears. The 30-day share is stable enough to detect a
+# problem, but it keeps matching for almost a month after a fix, because the old events stay in the
+# window. A team must also fail the recent window to stay flagged, so a fix clears the issue about a
+# week later instead.
+MISSING_SESSION_ID_RECENT_DAYS = 7
+
+# A healthy project sits near zero, so the share threshold is far above the noise floor. The volume
+# floor counts unusable pageviews rather than total pageviews: a floor on the total suppresses a
+# low-traffic project whose every pageview is unusable, which is the case this check exists to find.
+MISSING_SESSION_ID_THRESHOLD = 0.05
+MISSING_SESSION_ID_MIN_UNUSABLE = 100
+
+# Web analytics reads sessions through the `$session_id_uuid` materialized column, which is NULL when
+# `$session_id` is absent or is not a UUID. The raw_sessions materialized views then admit UUIDv7
+# alone, and hold the version in the nibble at bit 76 (see posthog/models/raw_sessions/sessions_v2.py).
+# A pageview that fails either test never reaches a session, so web analytics drops it from every
+# visitor and session aggregate.
+UNUSABLE_SESSION_ID = "(`$session_id_uuid` IS NULL OR bitAnd(bitShiftRight(`$session_id_uuid`, 76), 0xF) != 7)"
+
+MISSING_SESSION_ID_SQL = f"""
+SELECT
+ team_id,
+ count() AS total_pageviews,
+ countIf({UNUSABLE_SESSION_ID}) AS unusable_pageviews,
+ countIf(`$session_id_uuid` IS NULL) AS absent_or_not_uuid,
+ countIf(timestamp >= now() - INTERVAL %(recent_days)s DAY) AS recent_pageviews,
+ countIf(timestamp >= now() - INTERVAL %(recent_days)s DAY AND {UNUSABLE_SESSION_ID}) AS recent_unusable_pageviews
+FROM events
+WHERE team_id IN %(team_ids)s
+ AND event = '$pageview'
+ AND timestamp >= now() - INTERVAL %(lookback_days)s DAY
+GROUP BY team_id
+HAVING unusable_pageviews >= %(min_unusable)s
+ AND unusable_pageviews >= total_pageviews * %(threshold)s
+ -- A team with no pageviews in the recent window stays flagged, because 0 >= 0 holds.
+ -- The no_live_events check owns that case.
+ AND recent_unusable_pageviews >= recent_pageviews * %(threshold)s
+"""
+
+
+class MissingSessionIdCheck(HealthCheck):
+ name = "missing_session_id"
+ kind = "missing_session_id"
+ owner = JobOwners.TEAM_WEB_ANALYTICS
+ product = Product.WEB_ANALYTICS
+ policy = CLICKHOUSE_BATCH_EXECUTION_POLICY
+ schedule = "0 6 * * *"
+ active_since_days = 30
+ remediation = Remediation(
+ human=f"""
+ Open the Web analytics health page. Web analytics builds sessions only from a UUIDv7
+ $session_id, and leaves out every $pageview whose $session_id is absent, is not a UUID, or is
+ another UUID version. Those events undercount your visitor and session counts. This usually
+ comes from events sent server-side or through a third-party pipeline. Attach a UUIDv7
+ $session_id to those events. A plain UUIDv4 is not enough. The check also reads the last
+ {MISSING_SESSION_ID_RECENT_DAYS} days, so the warning clears about a week after the fix. See
+ https://posthog.com/docs/data/sessions#custom-session-ids.
+ """,
+ agent=f"""
+ Use `execute-sql` to size the gap: over the last {MISSING_SESSION_ID_RECENT_DAYS} days, count
+ $pageview events and split them by whether properties.$session_id parses as a UUID
+ (toUUIDOrNull) and whether its version nibble is 7
+ (bitAnd(bitShiftRight(toUInt128(toUUIDOrNull(properties.$session_id)), 76), 0xF) = 7). Then fix
+ it in the user's codebase: find where $pageview events are produced outside posthog-js, such as
+ server-side SDK calls or a third-party pipeline, and set a UUIDv7 $session_id on each event. A
+ plain UUIDv4, which crypto.randomUUID() and uuid.uuid4() produce, does not work: web analytics
+ builds sessions only from UUIDv7 ids, so a UUIDv4 leaves the counts low. Use `docs-search` for
+ the custom session id docs. The check needs the last {MISSING_SESSION_ID_RECENT_DAYS} days to
+ look clean, so the warning clears about a week after the fix rather than on the next check run.
+ """,
+ )
+
+ @classmethod
+ def render_alert(cls, issue: HealthIssue) -> AlertContent:
+ return AlertContent(
+ title="Pageviews missing a usable session id",
+ summary=issue.payload.get("reason", "$pageview events arrive without a usable $session_id"),
+ link="/web/health",
+ )
+
+ @classmethod
+ def render_signal(cls, issue: HealthIssue) -> SignalContent | None:
+ title = "Pageviews missing a usable session id"
+ summary = issue.payload.get("reason", "$pageview events arrive without a usable $session_id.")
+ return SignalContent(
+ description=(
+ f"A meaningful share of this project's `$pageview` events arrive without a `$session_id` that "
+ f"web analytics can use, over the last {MISSING_SESSION_ID_LOOKBACK_DAYS} days. Web analytics "
+ "builds sessions only from UUIDv7 ids, and excludes every event whose `$session_id` is absent, "
+ "is not a UUID, or is another UUID version, so visitor and session counts come in under the real "
+ "numbers while the raw events stay queryable in product analytics. This usually means events are "
+ "sent server-side or through a third-party pipeline. Recommend attaching a UUIDv7 `$session_id` "
+ "to those events, since a plain UUIDv4 will not restore the counts."
+ ),
+ weight=_SEVERITY_WEIGHT[issue.severity],
+ extra=build_signal_extra(issue, title=title, summary=summary, link="/web/health"),
+ )
+
+ def detect(self, team_ids: list[int]) -> dict[int, list[HealthCheckResult]]:
+ rows = execute_clickhouse_health_team_query(
+ MISSING_SESSION_ID_SQL,
+ team_ids=team_ids,
+ lookback_days=MISSING_SESSION_ID_LOOKBACK_DAYS,
+ params={
+ "threshold": MISSING_SESSION_ID_THRESHOLD,
+ "min_unusable": MISSING_SESSION_ID_MIN_UNUSABLE,
+ "recent_days": MISSING_SESSION_ID_RECENT_DAYS,
+ },
+ )
+
+ issues: dict[int, list[HealthCheckResult]] = {}
+ for team_id, total_pageviews, unusable_pageviews, absent_or_not_uuid, _recent, _recent_unusable in rows:
+ share = unusable_pageviews / total_pageviews
+ wrong_uuid_version = unusable_pageviews - absent_or_not_uuid
+ issues[team_id] = [
+ HealthCheckResult(
+ severity=HealthIssue.Severity.WARNING,
+ payload={
+ "reason": (
+ f"{share:.1%} of $pageview events ({unusable_pageviews} of {total_pageviews}) "
+ f"carried a $session_id web analytics cannot use in last "
+ f"{MISSING_SESSION_ID_LOOKBACK_DAYS} days "
+ f"({absent_or_not_uuid} absent or not a UUID, {wrong_uuid_version} not a UUIDv7)"
+ )
+ },
+ hash_keys=[],
+ )
+ ]
+
+ return issues
diff --git a/products/web_analytics/backend/test/test_missing_session_id.py b/products/web_analytics/backend/test/test_missing_session_id.py
new file mode 100644
index 000000000000..73a9218cb0ee
--- /dev/null
+++ b/products/web_analytics/backend/test/test_missing_session_id.py
@@ -0,0 +1,105 @@
+import uuid
+import datetime as dt
+
+import pytest
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.models.health_issue import HealthIssue
+from posthog.models.utils import uuid7
+
+from products.web_analytics.backend.temporal.health_checks.missing_session_id import MissingSessionIdCheck
+
+MODULE = "products.web_analytics.backend.temporal.health_checks.missing_session_id"
+
+
+ "mock_rows, expected_teams",
+ [
+ ([], set()),
+ ([(42, 20_000, 6_000, 6_000, 5_000, 1_500)], {42}),
+ ([(1, 50_000, 40_000, 40_000, 10_000, 8_000), (3, 12_000, 800, 500, 3_000, 200)], {1, 3}),
+ ],
+ ids=["all_healthy", "single_team_unusable_session_ids", "multiple_teams_flagged"],
+)
+@patch(f"{MODULE}.execute_clickhouse_health_team_query")
+def test_detect_missing_session_id(mock_query: MagicMock, mock_rows: list, expected_teams: set) -> None:
+ mock_query.return_value = mock_rows
+
+ result = MissingSessionIdCheck().detect([1, 2, 3, 42])
+
+ assert set(result.keys()) == expected_teams
+ for team_id in expected_teams:
+ issues = result[team_id]
+ assert len(issues) == 1
+ assert issues[0].severity == HealthIssue.Severity.WARNING
+ assert "$session_id" in issues[0].payload["reason"]
+
+
+@patch(f"{MODULE}.execute_clickhouse_health_team_query")
+def test_reason_reports_share_and_splits_the_causes(mock_query: MagicMock) -> None:
+ mock_query.return_value = [(7, 20_000, 5_000, 3_000, 5_000, 1_250)]
+
+ reason = MissingSessionIdCheck().detect([7])[7][0].payload["reason"]
+
+ assert "25.0%" in reason
+ assert "3000 absent or not a UUID, 2000 not a UUIDv7" in reason
+
+
+class TestMissingSessionIdQuery(ClickhouseTestMixin, BaseTest):
+ def _create_pageviews(self, session_ids: list[str | None], days_ago: int = 1) -> None:
+ timestamp = dt.datetime.now(dt.UTC) - dt.timedelta(days=days_ago)
+ for index, session_id in enumerate(session_ids):
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=f"user-{index}",
+ timestamp=timestamp,
+ properties={} if session_id is None else {"$session_id": session_id},
+ )
+ flush_persons_and_events()
+
+ def _flagged(self) -> bool:
+ # Small threshold and floor keep the row count down. The production values only decide
+ # sensitivity, while the conditions under test are which events count as unusable, whether the
+ # floor counts unusable events or total events, and whether the recent window clears the issue.
+ with (
+ patch(f"{MODULE}.MISSING_SESSION_ID_THRESHOLD", 0.5),
+ patch(f"{MODULE}.MISSING_SESSION_ID_MIN_UNUSABLE", 2),
+ ):
+ return self.team.id in MissingSessionIdCheck().detect([self.team.id])
+
+ @parameterized.expand(
+ [
+ ("uuidv7_ids_are_usable", [str(uuid7()), str(uuid7())], False),
+ ("no_session_id_property", [None, None], True),
+ ("empty_session_id", ["", ""], True),
+ ("session_id_is_not_a_uuid", ["not-a-uuid", "not-a-uuid"], True),
+ ("uuidv4_ids_never_reach_a_session", [str(uuid.uuid4()), str(uuid.uuid4())], True),
+ ("below_the_unusable_floor", [None], False),
+ ("below_the_share_threshold", [None, None, str(uuid7()), str(uuid7()), str(uuid7())], False),
+ ]
+ )
+ def test_detects_unusable_session_ids(self, _name: str, session_ids: list[str | None], expected: bool) -> None:
+ self._create_pageviews(session_ids)
+
+ self.assertEqual(self._flagged(), expected)
+
+ def test_recent_clean_window_clears_the_issue(self) -> None:
+ self._create_pageviews([None, None, None], days_ago=20)
+ self._create_pageviews([str(uuid7()), str(uuid7()), str(uuid7())], days_ago=1)
+
+ self.assertFalse(self._flagged())
+
+ def test_reason_counts_absent_ids_and_wrong_uuid_versions_apart(self) -> None:
+ self._create_pageviews([None, str(uuid.uuid4()), str(uuid7())])
+
+ with (
+ patch(f"{MODULE}.MISSING_SESSION_ID_THRESHOLD", 0.5),
+ patch(f"{MODULE}.MISSING_SESSION_ID_MIN_UNUSABLE", 2),
+ ):
+ reason = MissingSessionIdCheck().detect([self.team.id])[self.team.id][0].payload["reason"]
+
+ self.assertIn("1 absent or not a UUID, 1 not a UUIDv7", reason)