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: Pass compare down for web analytics weekly digset (#61904)

Jordan Mryyana0fc36799660
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr
index 5baa5600e7e2..6a0d25618362 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr
@@ -125,60 +125,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestExperimentMeanMetric.test_conversion_window_extends_to_last_exposure_1_precomputed
- '''
- WITH exposures AS
- (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
- if(ifNull(greater(uniqExact(t.variant), 1), 0), '$multiple', argMin(t.variant, toTimeZone(t.first_exposure_time, 'UTC'))) AS variant,
- min(toTimeZone(t.first_exposure_time, 'UTC')) AS first_exposure_time,
- max(toTimeZone(t.last_exposure_time, 'UTC')) AS last_exposure_time,
- argMin(t.exposure_event_uuid, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_event_uuid,
- argMin(t.exposure_session_id, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_session_id
- FROM experiment_exposures_preaggregated AS t
- WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC'))))
- GROUP BY entity_id),
- metric_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- toTimeZone(events.timestamp, 'UTC') AS timestamp,
- coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) AS value
- FROM events
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC')), toIntervalSecond(86400))), equals(events.event, 'purchase'))),
- entity_metrics AS
- (SELECT exposures.entity_id AS entity_id,
- exposures.variant AS variant,
- sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS value
- FROM exposures
- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), exposures.first_exposure_time), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(exposures.last_exposure_time, toIntervalSecond(86400)))))
- GROUP BY exposures.entity_id,
- exposures.variant)
- SELECT entity_metrics.variant AS variant,
- count(entity_metrics.entity_id) AS num_users,
- sum(entity_metrics.value) AS total_sum,
- sum(power(entity_metrics.value, 2)) AS total_sum_of_squares
- FROM entity_metrics
- GROUP BY entity_metrics.variant
- LIMIT 50000 SETTINGS join_algorithm='grace_hash',
- grace_hash_join_initial_buckets=2,
- load_balancing='in_order',
- readonly=2,
- max_execution_time=600,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=39728447488,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestExperimentMeanMetric.test_count_distinct_property_values_via_hogql_0_direct
'''
WITH exposures AS
diff --git a/products/web_analytics/backend/test/test_weekly_digest.py b/products/web_analytics/backend/test/test_weekly_digest.py
index 5e001a87a3a8..3ac0b7b8f6f6 100644
--- a/products/web_analytics/backend/test/test_weekly_digest.py
+++ b/products/web_analytics/backend/test/test_weekly_digest.py
@@ -183,6 +183,37 @@ class TestGetTopPages(ClickhouseTestMixin, APIBaseTest):
assert "change" in result[0]
assert result[0]["change"] is None
+ def test_includes_week_over_week_change(self):
+ with freeze_time(QUERY_TIMESTAMP):
+ _create_person(team_id=self.team.pk, distinct_ids=["prev_user"])
+ _create_pageview(
+ self.team,
+ distinct_id="prev_user",
+ session_id=str(uuid7("2025-01-18")),
+ url="https://example.com/pricing",
+ timestamp="2025-01-18",
+ )
+ for i in range(3):
+ distinct_id = f"curr_user_{i}"
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
+ _create_pageview(
+ self.team,
+ distinct_id=distinct_id,
+ session_id=str(uuid7("2025-01-25")),
+ url="https://example.com/pricing",
+ timestamp="2025-01-25",
+ )
+ flush_persons_and_events()
+
+ result = get_top_pages(self.team)
+
+ assert len(result) == 1
+ assert result[0]["visitors"] == 3
+ change = result[0]["change"]
+ assert change is not None
+ assert change["direction"] == "Up"
+ assert change["text"].startswith("Up")
+
def test_respects_limit(self):
with freeze_time(QUERY_TIMESTAMP):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
@@ -230,6 +261,39 @@ class TestGetTopSources(ClickhouseTestMixin, APIBaseTest):
assert "change" in result[0]
assert result[0]["change"] is None
+ def test_includes_week_over_week_change(self):
+ with freeze_time(QUERY_TIMESTAMP):
+ _create_person(team_id=self.team.pk, distinct_ids=["prev_user"])
+ _create_pageview(
+ self.team,
+ distinct_id="prev_user",
+ session_id=str(uuid7("2025-01-18")),
+ referring_domain="google.com",
+ url="https://example.com/",
+ timestamp="2025-01-18",
+ )
+ for i in range(3):
+ distinct_id = f"curr_user_{i}"
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
+ _create_pageview(
+ self.team,
+ distinct_id=distinct_id,
+ session_id=str(uuid7("2025-01-25")),
+ referring_domain="google.com",
+ url="https://example.com/",
+ timestamp="2025-01-25",
+ )
+ flush_persons_and_events()
+
+ result = get_top_sources(self.team)
+
+ google = next(r for r in result if r["name"] == "google.com")
+ assert google["visitors"] == 3
+ change = google["change"]
+ assert change is not None
+ assert change["direction"] == "Up"
+ assert change["text"].startswith("Up")
+
def test_filters_out_empty_sources(self):
with freeze_time(QUERY_TIMESTAMP):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
diff --git a/products/web_analytics/backend/weekly_digest.py b/products/web_analytics/backend/weekly_digest.py
index 0ca764ef9e7a..d5367e954f5f 100644
--- a/products/web_analytics/backend/weekly_digest.py
+++ b/products/web_analytics/backend/weekly_digest.py
@@ -118,13 +118,14 @@ def _format_duration(seconds: float | None) -> str:
return f"{minutes}m {secs}s"
-def get_top_pages(team: Team, limit: int = 5, days: int = 7) -> list[dict]:
+def get_top_pages(team: Team, limit: int = 5, days: int = 7, compare: bool = True) -> list[dict]:
tag_queries(product=ProductKey.WEB_ANALYTICS, team_id=team.pk, name="weekly_digest:top_pages")
try:
query = WebStatsTableQuery(
breakdownBy=WebStatsBreakdown.PAGE,
dateRange=DateRange(date_from=f"-{days}d"),
+ compareFilter=CompareFilter(compare=compare),
limit=limit,
orderBy=[WebAnalyticsOrderByFields.VISITORS, WebAnalyticsOrderByDirection.DESC],
filterTestAccounts=True,
@@ -150,13 +151,14 @@ def get_top_pages(team: Team, limit: int = 5, days: int = 7) -> list[dict]:
return []
-def get_top_sources(team: Team, limit: int = 5, days: int = 7) -> list[dict]:
+def get_top_sources(team: Team, limit: int = 5, days: int = 7, compare: bool = True) -> list[dict]:
tag_queries(product=ProductKey.WEB_ANALYTICS, team_id=team.pk, name="weekly_digest:top_sources")
try:
query = WebStatsTableQuery(
breakdownBy=WebStatsBreakdown.INITIAL_REFERRING_DOMAIN,
dateRange=DateRange(date_from=f"-{days}d"),
+ compareFilter=CompareFilter(compare=compare),
limit=limit,
orderBy=[WebAnalyticsOrderByFields.VISITORS, WebAnalyticsOrderByDirection.DESC],
filterTestAccounts=True,
@@ -218,8 +220,8 @@ def get_goals_for_team(team: Team, limit: int = 5, days: int = 7, compare: bool
def build_team_digest(team: Team, days: int = 7, compare: bool = True) -> dict:
overview = get_overview_for_team(team, days=days, compare=compare)
- top_pages = get_top_pages(team, days=days)
- top_sources = get_top_sources(team, days=days)
+ top_pages = get_top_pages(team, days=days, compare=compare)
+ top_sources = get_top_sources(team, days=days, compare=compare)
goals = get_goals_for_team(team, days=days, compare=compare)
return {