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): opt-in session-start attribution for calendar heatmap unique users (#60126)

Lucas Ricoydb7cb7e48db9
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index f68227379c55..56818ae37e58 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -10281,8 +10281,10 @@
"CalendarHeatmapFilter": {
"additionalProperties": false,
"properties": {
- "dummy": {
- "type": "string"
+ "bucketBySessionStart": {
+ "default": false,
+ "description": "When true and the series math is `dau`/`unique_users`, each user contributes to the (day-of-week, hour) bucket of their session's first event only — matching the web overview session-start attribution. When false (default), the user contributes to every bucket they have any event in. No effect on `total` math (event counts are unchanged either way).",
+ "type": "boolean"
}
},
"type": "object"
@@ -38663,6 +38665,10 @@
"$ref": "#/definitions/BreakdownFilter",
"description": "Breakdown of the events and actions"
},
+ "calendarHeatmapFilter": {
+ "$ref": "#/definitions/CalendarHeatmapFilter",
+ "description": "Properties specific to the calendar heatmap display variant. Only consulted when `trendsFilter.display === ChartDisplayType.CalendarHeatmap`; ignored otherwise."
+ },
"compareFilter": {
"$ref": "#/definitions/CompareFilter",
"description": "Compare to date range"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 168437db16b0..d0723e881314 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1452,8 +1452,14 @@ export type TrendsFilter = {
}
export type CalendarHeatmapFilter = {
- // Reserved for future filter properties
- dummy?: string
+ /**
+ * When true and the series math is `dau`/`unique_users`, each user contributes to the
+ * (day-of-week, hour) bucket of their session's first event only — matching the web overview
+ * session-start attribution. When false (default), the user contributes to every bucket
+ * they have any event in. No effect on `total` math (event counts are unchanged either way).
+ * @default false
+ */
+ bucketBySessionStart?: boolean
}
export const TRENDS_FILTER_PROPERTIES = new Set<keyof TrendsFilter>([
@@ -1525,6 +1531,11 @@ export interface TrendsQuery extends InsightsQueryBase<TrendsQueryResponse> {
series: (AnyEntityNode | GroupNode)[]
/** Properties specific to the trends insight */
trendsFilter?: TrendsFilter
+ /**
+ * Properties specific to the calendar heatmap display variant. Only consulted when
+ * `trendsFilter.display === ChartDisplayType.CalendarHeatmap`; ignored otherwise.
+ */
+ calendarHeatmapFilter?: CalendarHeatmapFilter
/** Breakdown of the events and actions */
breakdownFilter?: BreakdownFilter
/** Compare to date range */
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index 7fa4c0222ff5..f5f69322427d 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -2052,6 +2052,11 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
trendsFilter: {
display: ChartDisplayType.CalendarHeatmap,
},
+ // Web overview attributes session metrics to the session's start hour;
+ // mirror that here so visitor counts line up across the dashboard.
+ calendarHeatmapFilter: {
+ bucketBySessionStart: true,
+ },
},
},
docs: {
diff --git a/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py b/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py
index 3e88671965bc..3f04ec654b0e 100644
--- a/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py
@@ -80,6 +80,70 @@ FROM (
) as query
"""
+# Session-start-attribution variant of `templateUniqueUsers`, opt-in via
+# `CalendarHeatmapFilter.bucketBySessionStart`. Each session contributes exactly once,
+# bucketed by the (day-of-week, hour) of its first event — matching the web overview
+# semantic where a session's metrics are attributed to its start hour. Brought back
+# from the pre-#57296 implementation so web analytics' Active Hours tile lines up with
+# the visitor counts the overview computes for the same window.
+#
+# Scan bounds on `uniqueSessionEvents`:
+# * `notEmpty($session_id)` — `events.$session_id` is a non-nullable String
+# that surfaces as empty when no session id was captured. Without this guard
+# every session-less event collapses into one synthetic session and
+# `any(person_id)` picks a single visitor for the whole group, undercounting
+# projects with partial session capture.
+# * `timestamp >= {session_window_start}` / `timestamp <= {current_period_end}`
+# — the outer `query` CTE filters by `min(timestamp) >= date_from`, but
+# without an inner date bound ClickHouse must read every matching event
+# across all time before that filter is applied. The 24-hour lookback covers
+# sessions that started before `date_from` and extend into the window (the
+# posthog-js cap is 24h, so the only loss is a session continuously open
+# longer than that — vanishingly rare for web traffic).
+templateUniqueUsersBySession = """
+WITH uniqueSessionEvents AS (
+ SELECT
+ person_id,
+ $session_id,
+ timestamp
+ FROM events
+ WHERE and(
+ {event_expr},
+ {all_properties},
+ {test_account_filters},
+ notEmpty($session_id),
+ timestamp >= {session_window_start},
+ timestamp <= {current_period_end}
+ )
+),
+uniqueSessionEventsGrouped AS (
+ SELECT
+ any(person_id) as person_id,
+ $session_id as session_id,
+ min(timestamp) as timestamp
+ FROM uniqueSessionEvents
+ GROUP BY $session_id
+),
+query AS (
+ SELECT
+ uniqMap(map(concatWithSeparator({separator},toString(toDayOfWeek(uniqueSessionEventsGrouped.timestamp)),toString(toHour(uniqueSessionEventsGrouped.timestamp))), uniqueSessionEventsGrouped.person_id)) as hoursAndDays,
+ uniqMap(map(toHour(uniqueSessionEventsGrouped.timestamp), uniqueSessionEventsGrouped.person_id)) as hours,
+ uniqMap(map(toDayOfWeek(uniqueSessionEventsGrouped.timestamp), uniqueSessionEventsGrouped.person_id)) as days,
+ uniq(person_id) as total
+ FROM uniqueSessionEventsGrouped
+ WHERE {current_period}
+)
+SELECT
+ mapKeys(query.hoursAndDays) as hoursAndDaysKeys,
+ mapValues(query.hoursAndDays) as hoursAndDaysValues,
+ mapKeys(query.hours) as hoursKeys,
+ mapValues(query.hours) as hoursValues,
+ mapKeys(query.days) as daysKeys,
+ mapValues(query.days) as daysValues,
+ query.total
+FROM query
+"""
+
templateAllUsers = """
SELECT
mapKeys(query.hoursAndDays) as hoursAndDaysKeys,
@@ -146,17 +210,25 @@ class CalendarHeatmapQueryRunner(AnalyticsQueryRunner[CalendarHeatmapResponse]):
def to_query(self) -> ast.SelectQuery:
# Use the heatmap query logic
- template = templateUniqueUsers if self.query.series[0].math == "dau" else templateAllUsers
- query = parse_select(
- template,
- placeholders={
- "all_properties": self._all_properties(),
- "test_account_filters": self._test_account_filters,
- "current_period": self._current_period_expression(field="timestamp"),
- "event_expr": self.getEventExpr(),
- "separator": ast.Constant(value=SEPARATOR),
- },
+ is_unique_users = self.query.series[0].math == "dau"
+ bucket_by_session = bool(
+ self.query.calendarHeatmapFilter and self.query.calendarHeatmapFilter.bucketBySessionStart
)
+ if is_unique_users:
+ template = templateUniqueUsersBySession if bucket_by_session else templateUniqueUsers
+ else:
+ template = templateAllUsers
+ placeholders: dict[str, ast.Expr] = {
+ "all_properties": self._all_properties(),
+ "test_account_filters": self._test_account_filters,
+ "current_period": self._current_period_expression(field="timestamp"),
+ "event_expr": self.getEventExpr(),
+ "separator": ast.Constant(value=SEPARATOR),
+ }
+ if bucket_by_session:
+ placeholders["session_window_start"] = self._session_window_start_expr()
+ placeholders["current_period_end"] = self.query_date_range.date_to_as_hogql()
+ query = parse_select(template, placeholders=placeholders)
assert isinstance(query, ast.SelectQuery)
return query
@@ -251,6 +323,20 @@ class CalendarHeatmapQueryRunner(AnalyticsQueryRunner[CalendarHeatmapResponse]):
else:
return ast.Call(name="and", args=property_exprs)
+ def _session_window_start_expr(self) -> ast.Expr:
+ # Lookback buffer applied to the inner events scan in
+ # `templateUniqueUsersBySession`. Capped at the posthog-js session limit
+ # so we still catch sessions that opened just before `date_from` and
+ # extend into the window. See the template's leading comment for the
+ # full rationale.
+ return ast.Call(
+ name="minus",
+ args=[
+ self.query_date_range.date_from_as_hogql(),
+ ast.Call(name="toIntervalHour", args=[ast.Constant(value=24)]),
+ ],
+ )
+
def _current_period_expression(self, field="start_timestamp"):
return ast.Call(
name="and",
diff --git a/posthog/hogql_queries/insights/trends/calendar_heatmap_trends_query_runner.py b/posthog/hogql_queries/insights/trends/calendar_heatmap_trends_query_runner.py
index fe8da49ffcf7..89777da38161 100644
--- a/posthog/hogql_queries/insights/trends/calendar_heatmap_trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/calendar_heatmap_trends_query_runner.py
@@ -15,13 +15,16 @@ class CalendarHeatmapTrendsQueryRunner(TrendsQueryRunner):
def _calculate(self):
from posthog.hogql_queries.insights.trends.calendar_heatmap_query_runner import CalendarHeatmapQueryRunner
- # Convert TrendsQuery to CalendarHeatmapQuery
+ # Convert TrendsQuery to CalendarHeatmapQuery. Forward calendarHeatmapFilter as-is
+ # so opt-in flags (e.g. bucketBySessionStart, set by the web analytics Active Hours
+ # tile) flow through without the wrapper needing to know about each one.
calendar_query = CalendarHeatmapQuery(
dateRange=self.query.dateRange,
filterTestAccounts=self.query.filterTestAccounts,
properties=self.query.properties,
series=self.query.series,
conversionGoal=getattr(self.query, "conversionGoal", None),
+ calendarHeatmapFilter=getattr(self.query, "calendarHeatmapFilter", None),
)
# Create and run calendar heatmap query runner
diff --git a/posthog/hogql_queries/insights/trends/test/test_calendar_heatmap_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_calendar_heatmap_query_runner.py
index acbdbacb2e8c..7b23b7f33048 100644
--- a/posthog/hogql_queries/insights/trends/test/test_calendar_heatmap_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/test/test_calendar_heatmap_query_runner.py
@@ -3,7 +3,16 @@ from typing import Optional
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
-from posthog.schema import ActionConversionGoal, CalendarHeatmapQuery, CustomEventConversionGoal, DateRange, EventsNode
+from parameterized import parameterized
+
+from posthog.schema import (
+ ActionConversionGoal,
+ CalendarHeatmapFilter,
+ CalendarHeatmapQuery,
+ CustomEventConversionGoal,
+ DateRange,
+ EventsNode,
+)
from posthog.hogql_queries.insights.trends.calendar_heatmap_query_runner import CalendarHeatmapQueryRunner
from posthog.models.utils import uuid7
@@ -1323,11 +1332,32 @@ class TestCalendarHeatmapQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert (date_to_explicit.hour, date_to_explicit.minute, date_to_explicit.second) == (14, 32, 11)
assert (date_to_explicit - date_from_explicit).total_seconds() == 7 * 24 * 60 * 60
- def test_unique_users_buckets_per_event_not_per_session(self):
- # Regression test: with `dau` math, every (day-of-week, hour) bucket the user touched
- # must report the user — not just the bucket containing the session's first event.
- # All events below share one session_id, so the previous templateUniqueUsers
- # implementation would only count the user in the 23:00 bucket of Saturday.
+ @parameterized.expand(
+ [
+ # Default mode (post-#57296): user contributes to every (day-of-week, hour) bucket they have
+ # an event in. All three cells get the user.
+ (
+ "per_event_bucket_default",
+ None,
+ {(6, 23): 1, (7, 0): 1, (7, 1): 1},
+ ),
+ (
+ "per_event_bucket_explicit_false",
+ CalendarHeatmapFilter(bucketBySessionStart=False),
+ {(6, 23): 1, (7, 0): 1, (7, 1): 1},
+ ),
+ # Session-start mode (restored pre-#57296 behaviour, opt-in): user contributes only to the
+ # bucket of their session's first event — matches web overview's session-start attribution.
+ (
+ "per_session_bucket_when_opted_in",
+ CalendarHeatmapFilter(bucketBySessionStart=True),
+ {(6, 23): 1},
+ ),
+ ]
+ )
+ def test_unique_users_bucket_attribution(
+ self, _name: str, calendar_filter: Optional[CalendarHeatmapFilter], expected: dict[tuple[int, int], int]
+ ) -> None:
shared_session_id = str(uuid7())
timestamps = [
"2023-12-02 23:50:00", # Saturday 23:00
@@ -1351,13 +1381,87 @@ class TestCalendarHeatmapQueryRunner(ClickhouseTestMixin, APIBaseTest):
properties=[],
filterTestAccounts=False,
series=[EventsNode(kind="EventsNode", math="dau")],
+ calendarHeatmapFilter=calendar_filter,
)
response = CalendarHeatmapQueryRunner(team=self.team, query=query).calculate()
results_dict = {(r.row, r.column): r.value for r in response.results.data}
- assert results_dict.get((6, 23)) == 1, f"Expected 1 unique user at Sat 23:00, got {results_dict.get((6, 23))}"
- assert results_dict.get((7, 0)) == 1, f"Expected 1 unique user at Sun 00:00, got {results_dict.get((7, 0))}"
- assert results_dict.get((7, 1)) == 1, f"Expected 1 unique user at Sun 01:00, got {results_dict.get((7, 1))}"
+ for cell, expected_value in expected.items():
+ assert results_dict.get(cell) == expected_value, (
+ f"Expected {expected_value} at {cell}, got {results_dict.get(cell)}"
+ )
+ # Cells outside the expected set must be empty so the modes can't silently overlap.
+ for cell, value in results_dict.items():
+ if cell not in expected:
+ assert value == 0, f"Unexpected non-zero count at {cell}: {value}"
assert response.results.allAggregations == 1, (
f"Expected 1 unique user total, got {response.results.allAggregations}"
)
+
+ def test_session_bucket_does_not_collapse_missing_session_ids(self) -> None:
+ # Two distinct visitors hit a page in the same hour, but neither event
+ # carries a `$session_id`. Without the IS NOT NULL filter inside
+ # `uniqueSessionEvents` they would group into one synthetic session and
+ # `any(person_id)` would pick a single visitor — undercounting the
+ # bucket. The fix drops null-session events entirely so the count
+ # reflects only attributable sessions.
+ _create_person(team_id=self.team.pk, distinct_ids=["userA"], properties={"name": "userA"})
+ _create_person(team_id=self.team.pk, distinct_ids=["userB"], properties={"name": "userB"})
+ for distinct_id in ("userA", "userB"):
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp="2023-12-03 01:30:00",
+ uuid=str(uuid7()),
+ properties={}, # no $session_id
+ )
+
+ query = CalendarHeatmapQuery(
+ dateRange=DateRange(date_from="2023-12-01", date_to="2023-12-04"),
+ properties=[],
+ filterTestAccounts=False,
+ series=[EventsNode(kind="EventsNode", math="dau")],
+ calendarHeatmapFilter=CalendarHeatmapFilter(bucketBySessionStart=True),
+ )
+ response = CalendarHeatmapQueryRunner(team=self.team, query=query).calculate()
+
+ assert response.results.allAggregations == 0
+ assert response.results.data == []
+
+ def test_session_bucket_ignores_pre_lookback_session_start(self) -> None:
+ # A session whose first event is older than the 24h lookback applied to
+ # `uniqueSessionEvents` would, before the bound, scan unbounded history
+ # and surface here. After the bound, the scan misses the pre-window
+ # event and the only remaining timestamps fall inside the requested
+ # range — so the session is attributed to those in-range events instead
+ # of being discarded. This documents the documented trade-off in the
+ # template comment (sessions continuously open > 24h get re-attributed).
+ shared_session_id = str(uuid7())
+ _create_person(team_id=self.team.pk, distinct_ids=["userA"], properties={"name": "userA"})
+ timestamps = [
+ "2023-11-29 12:00:00", # > 24h before date_from
+ "2023-12-03 01:30:00", # inside the requested window
+ ]
+ for ts in timestamps:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="userA",
+ timestamp=ts,
+ uuid=str(uuid7()),
+ properties={"$session_id": shared_session_id},
+ )
+
+ query = CalendarHeatmapQuery(
+ dateRange=DateRange(date_from="2023-12-01", date_to="2023-12-04"),
+ properties=[],
+ filterTestAccounts=False,
+ series=[EventsNode(kind="EventsNode", math="dau")],
+ calendarHeatmapFilter=CalendarHeatmapFilter(bucketBySessionStart=True),
+ )
+ response = CalendarHeatmapQueryRunner(team=self.team, query=query).calculate()
+
+ results_dict = {(r.row, r.column): r.value for r in response.results.data}
+ assert results_dict.get((7, 1)) == 1, f"Expected 1 visitor at (Sun, 01h), got {results_dict}"
+ assert response.results.allAggregations == 1
diff --git a/posthog/schema.py b/posthog/schema.py
index 0405c0998afa..b6e5ca473d6e 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -959,7 +959,16 @@ class CalendarHeatmapFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
- dummy: str | None = None
+ bucketBySessionStart: bool | None = Field(
+ default=False,
+ description=(
+ "When true and the series math is `dau`/`unique_users`, each user"
+ " contributes to the (day-of-week, hour) bucket of their session's first"
+ " event only — matching the web overview session-start attribution. When"
+ " false (default), the user contributes to every bucket they have any event"
+ " in. No effect on `total` math (event counts are unchanged either way)."
+ ),
+ )
class CalendarHeatmapMathType(StrEnum):
@@ -21565,6 +21574,14 @@ class TrendsQuery(BaseModel):
)
aggregation_group_type_index: int | None = Field(default=None, description="Groups aggregation")
breakdownFilter: BreakdownFilter | None = Field(default=None, description="Breakdown of the events and actions")
+ calendarHeatmapFilter: CalendarHeatmapFilter | None = Field(
+ default=None,
+ description=(
+ "Properties specific to the calendar heatmap display variant. Only"
+ " consulted when `trendsFilter.display ==="
+ " ChartDisplayType.CalendarHeatmap`; ignored otherwise."
+ ),
+ )
compareFilter: CompareFilter | None = Field(default=None, description="Compare to date range")
conversionGoal: ActionConversionGoal | CustomEventConversionGoal | None = Field(
default=None,
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 6bb568bda425..e9236d1671fb 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -220,6 +220,11 @@ export interface BreakdownFilterApi {
breakdowns?: BreakdownApi[] | null
}
+export interface CalendarHeatmapFilterApi {
+ /** When true and the series math is `dau`/`unique_users`, each user contributes to the (day-of-week, hour) bucket of their session's first event only — matching the web overview session-start attribution. When false (default), the user contributes to every bucket they have any event in. No effect on `total` math (event counts are unchanged either way). */
+ bucketBySessionStart?: boolean | null
+}
+
export interface CompareFilterApi {
/** Whether to compare the current date range to a previous date range. */
compare?: boolean | null
@@ -1554,6 +1559,8 @@ export interface TrendsQueryApi {
aggregation_group_type_index?: number | null
/** Breakdown of the events and actions */
breakdownFilter?: BreakdownFilterApi | null
+ /** Properties specific to the calendar heatmap display variant. Only consulted when `trendsFilter.display === ChartDisplayType.CalendarHeatmap`; ignored otherwise. */
+ calendarHeatmapFilter?: CalendarHeatmapFilterApi | null
/** Compare to date range */
compareFilter?: CompareFilterApi | null
/** Whether we should be comparing against a specific conversion goal */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 036f2d5d2b17..2591f6eb3c82 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1776,6 +1776,11 @@ export namespace Schemas {
breakdowns?: Breakdown[] | null;
}
+ export interface CalendarHeatmapFilter {
+ /** When true and the series math is `dau`/`unique_users`, each user contributes to the (day-of-week, hour) bucket of their session's first event only — matching the web overview session-start attribution. When false (default), the user contributes to every bucket they have any event in. No effect on `total` math (event counts are unchanged either way). */
+ bucketBySessionStart?: boolean | null;
+ }
+
export interface CompareFilter {
/** Whether to compare the current date range to a previous date range. */
compare?: boolean | null;
@@ -2114,6 +2119,8 @@ export namespace Schemas {
aggregation_group_type_index?: number | null;
/** Breakdown of the events and actions */
breakdownFilter?: BreakdownFilter | null;
+ /** Properties specific to the calendar heatmap display variant. Only consulted when `trendsFilter.display === ChartDisplayType.CalendarHeatmap`; ignored otherwise. */
+ calendarHeatmapFilter?: CalendarHeatmapFilter | null;
/** Compare to date range */
compareFilter?: CompareFilter | null;
/** Whether we should be comparing against a specific conversion goal */
@@ -6771,10 +6778,6 @@ export namespace Schemas {
readonly value: string;
}
- export interface CalendarHeatmapFilter {
- dummy?: string | null;
- }
-
export interface EventsHeatMapColumnAggregationResult {
column: number;
value: number;