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: run team digests and achievements without a user (#110683)

Alex Liderb249734f2d82
diff --git a/posthog/hogql/ACCESS_CONTROL.md b/posthog/hogql/ACCESS_CONTROL.md
index ec9dae499918..6bc08416a890 100644
--- a/posthog/hogql/ACCESS_CONTROL.md
+++ b/posthog/hogql/ACCESS_CONTROL.md
@@ -154,7 +154,7 @@ Without a user, warehouse access control denies every warehouse table and view,
Cache warming runs as the insight's creator, on the assumption that their access is the one most viewers of that insight share.
Warming without access control would more often end in a cache miss.
-3. **Trusted internal job with no user at all:** pass `bypass_warehouse_access_control=True` explicitly. Materialization workflows (`posthog/temporal/data_modeling/`), insight cache warming, and ducklake compilation (`posthog/ducklake/client.py`) use this path. Add a bypass only when the job has no acting user and its output has a separate access boundary.
+3. **Trusted internal job with no user at all:** pass `bypass_warehouse_access_control=True` explicitly. Materialization workflows (`posthog/temporal/data_modeling/`), insight cache warming, ducklake compilation (`posthog/ducklake/client.py`), and the web analytics team digest and team achievements sweep (`products/web_analytics/backend/weekly_digest.py`, `products/web_analytics/backend/achievements/evaluators.py`) use this path. Add a bypass only when the job has no acting user and its output has a separate access boundary.
```python
# Background materialization job: no user exists, so bypass explicitly.
diff --git a/products/web_analytics/backend/achievements/evaluators.py b/products/web_analytics/backend/achievements/evaluators.py
index 414c71ce7b01..38c9b65de054 100644
--- a/products/web_analytics/backend/achievements/evaluators.py
+++ b/products/web_analytics/backend/achievements/evaluators.py
@@ -178,7 +178,13 @@ def evaluate_cumulative_pageviews(ctx: EvalContext, prior: PriorProgress) -> Tra
"test": _test_account_filter_expr(team),
},
)
- response = execute_hogql_query(query=query, team=team, query_type="web_achievements_pageviews")
+ response = execute_hogql_query(
+ query=query,
+ team=team,
+ query_type="web_achievements_pageviews",
+ # The team-scoped sweep has no acting user, and only an aggregate count leaves the query.
+ bypass_warehouse_access_control=True,
+ )
if response.results:
total += int(response.results[0][0] or 0)
return TrackEvaluation(value=total, checkpoint={"counted_through": until.isoformat()})
@@ -310,6 +316,8 @@ def _add_conversion_counts(
query=query,
team=team,
query_type="web_achievements_conversions",
+ # The team-scoped sweep has no acting user, and only per-day counts leave the query.
+ bypass_warehouse_access_control=True,
settings=HogQLGlobalSettings(timeout_overflow_mode="throw", read_overflow_mode="throw"),
)
for row in response.results or []:
diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.py
index 3cd946106e68..cd2628ea9f18 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table.py
@@ -817,6 +817,7 @@ WHERE and(
query=query,
team=self.team,
user=self.user,
+ bypass_warehouse_access_control=self.bypass_warehouse_access_control,
timings=self.timings,
modifiers=modifiers,
)
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py
index 85f3276e47ce..b1fec865cd73 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py
@@ -150,6 +150,15 @@ class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(runner.clickhouse_query_type(), expected_query_type)
+ def test_bypass_run_does_not_share_cache_or_single_flight_with_user_run(self) -> None:
+ query = WebOverviewQuery(dateRange=DateRange(date_from="2023-12-08", date_to="2023-12-15"), properties=[])
+
+ user_run = WebOverviewQueryRunner(team=self.team, query=query)
+ bypass_run = WebOverviewQueryRunner(team=self.team, query=query, bypass_warehouse_access_control=True)
+
+ assert user_run.get_cache_key() != bypass_run.get_cache_key()
+ assert user_run.single_flight_variant() != bypass_run.single_flight_variant()
+
class TestWebAnalyticsBreakdownTagging(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
index 51bdbd7ab34f..6e3c2054101d 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
@@ -3,7 +3,7 @@ from abc import ABC
from datetime import datetime, timedelta
from math import ceil
from time import perf_counter
-from typing import Optional, Union
+from typing import Any, Optional, Union
from zoneinfo import ZoneInfo
from django.conf import settings
@@ -110,6 +110,26 @@ class WebAnalyticsQueryRunner(AnalyticsQueryRunner[WAR], ABC):
# SAMPLE clauses nor scale results.
query: WebQueryNode
query_type: type[WebQueryNode]
+ bypass_warehouse_access_control: bool = False
+
+ def __init__(self, *args: Any, bypass_warehouse_access_control: bool = False, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self.bypass_warehouse_access_control = bypass_warehouse_access_control
+
+ def get_cache_payload(self) -> dict:
+ payload = super().get_cache_payload()
+ # The base fingerprint does not see a warehouse table that a test-account filter reads through a join,
+ # so a bypass run and a user run would share one cache entry. The separate key stops a user who is
+ # denied that table from reading a result that a bypass run computed.
+ if self.bypass_warehouse_access_control:
+ payload["bypass_warehouse_access_control"] = True
+ return payload
+
+ def single_flight_variant(self) -> str:
+ variant = super().single_flight_variant()
+ if self.bypass_warehouse_access_control:
+ return f"{variant}:bypass_warehouse_access_control"
+ return variant
def query_strategy(self) -> str | None:
return None
@@ -326,6 +346,7 @@ WHERE and(
query=count_query,
team=self.team,
user=self.user,
+ bypass_warehouse_access_control=self.bypass_warehouse_access_control,
timings=self.timings,
modifiers=self.modifiers,
limit_context=self.limit_context,
diff --git a/products/web_analytics/backend/hogql_queries/web_goals.py b/products/web_analytics/backend/hogql_queries/web_goals.py
index 7d940ec445c8..95f933a24a88 100644
--- a/products/web_analytics/backend/hogql_queries/web_goals.py
+++ b/products/web_analytics/backend/hogql_queries/web_goals.py
@@ -213,6 +213,7 @@ WHERE {periods_expression}
query=query,
team=self.team,
user=self.user,
+ bypass_warehouse_access_control=self.bypass_warehouse_access_control,
timings=self.timings,
modifiers=self.modifiers,
limit_context=self.limit_context,
diff --git a/products/web_analytics/backend/hogql_queries/web_overview.py b/products/web_analytics/backend/hogql_queries/web_overview.py
index 7e2d5c9bde02..f208f5df3644 100644
--- a/products/web_analytics/backend/hogql_queries/web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview.py
@@ -279,6 +279,7 @@ CROSS JOIN {sessions_agg} AS sessions_agg
query=self.preaggregated_query_builder.get_query(),
team=self.team,
user=self.user,
+ bypass_warehouse_access_control=self.bypass_warehouse_access_control,
timings=self.timings,
modifiers=pre_agg_modifiers,
limit_context=self.limit_context,
@@ -394,6 +395,7 @@ WHERE and(
modifiers=self.modifiers,
limit_context=self.limit_context,
user=self.user,
+ bypass_warehouse_access_control=self.bypass_warehouse_access_control,
)
visitors_response = visitors_runner._calculate()
visitors = next(item for item in visitors_response.results if item.key == "visitors")
@@ -403,6 +405,7 @@ WHERE and(
query=self._conversion_goal_select(),
team=self.team,
user=self.user,
+ bypass_warehouse_access_control=self.bypass_warehouse_access_control,
timings=self.timings,
modifiers=self.modifiers,
limit_context=self.limit_context,
@@ -479,6 +482,7 @@ WHERE and(
query=self.to_query(),
team=self.team,
user=self.user,
+ bypass_warehouse_access_control=self.bypass_warehouse_access_control,
timings=self.timings,
modifiers=execution_modifiers,
limit_context=self.limit_context,
diff --git a/products/web_analytics/backend/temporal/digest_notification/activities.py b/products/web_analytics/backend/temporal/digest_notification/activities.py
index fe672e4440c9..5e8f43686b8b 100644
--- a/products/web_analytics/backend/temporal/digest_notification/activities.py
+++ b/products/web_analytics/backend/temporal/digest_notification/activities.py
@@ -440,7 +440,8 @@ def _send_test_digest_notification(email: str, team_id: int | None = None) -> No
if not membership:
raise PermissionError(f"User {email} is not a member of the organization that owns team {team_id}")
- digest = weekly_digest.build_team_digest(team)
+ # No user runs these queries. `_accessible_team_data` drops the teams that the recipient cannot access.
+ digest = weekly_digest.build_team_digest(team, bypass_warehouse_access_control=True)
accessible = _accessible_team_data(user, team.organization, membership, {team.id: digest})
if not accessible:
raise PermissionError(f"User {email} does not have access to team {team_id}")
@@ -473,8 +474,10 @@ def _send_test_digest_notification(email: str, team_id: int | None = None) -> No
sent_count = 0
for membership in memberships:
org = membership.organization
+ # No user runs these queries. `_accessible_team_data` drops the teams that the recipient cannot access.
team_digest_data = {
- t.id: weekly_digest.build_team_digest(t) for t in Team.objects.filter(organization_id=org.id)
+ t.id: weekly_digest.build_team_digest(t, bypass_warehouse_access_control=True)
+ for t in Team.objects.filter(organization_id=org.id)
}
accessible = _accessible_team_data(user, org, membership, team_digest_data)
if not accessible:
diff --git a/products/web_analytics/backend/temporal/weekly_digest/activities.py b/products/web_analytics/backend/temporal/weekly_digest/activities.py
index cb1dd40c8e17..54d85c900b11 100644
--- a/products/web_analytics/backend/temporal/weekly_digest/activities.py
+++ b/products/web_analytics/backend/temporal/weekly_digest/activities.py
@@ -455,7 +455,8 @@ def _send_test_digest(email: str, team_id: int | None = None) -> None:
user=user,
org=team.organization,
membership=membership,
- team_digest_data={team.id: weekly_digest.build_team_digest(team)},
+ # No user runs these queries. `_send_digest_for_user` drops the teams that the recipient cannot access.
+ team_digest_data={team.id: weekly_digest.build_team_digest(team, bypass_warehouse_access_control=True)},
date_suffix=date_suffix,
test=True,
)
@@ -481,7 +482,10 @@ def _send_test_digest(email: str, team_id: int | None = None) -> None:
org_teams = list(Team.objects.filter(organization_id=org.id))
if not org_teams:
continue
- team_digest_data = {t.id: weekly_digest.build_team_digest(t) for t in org_teams}
+ # No user runs these queries. `_send_digest_for_user` drops the teams that the recipient cannot access.
+ team_digest_data = {
+ t.id: weekly_digest.build_team_digest(t, bypass_warehouse_access_control=True) for t in org_teams
+ }
outcome = _send_digest_for_user(
user=user,
org=org,
diff --git a/products/web_analytics/backend/test/test_achievements_evaluators.py b/products/web_analytics/backend/test/test_achievements_evaluators.py
index 0581f2dd58e2..3215cf8e98ba 100644
--- a/products/web_analytics/backend/test/test_achievements_evaluators.py
+++ b/products/web_analytics/backend/test/test_achievements_evaluators.py
@@ -1,7 +1,8 @@
+from collections.abc import Callable
from datetime import UTC, date, datetime, time, timedelta
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from django.utils import timezone
@@ -13,12 +14,14 @@ from posthog.hogql.query import execute_hogql_query
from posthog.errors import CHQueryErrorTooManyBytes
from posthog.exceptions import ClickHouseEstimatedQueryExecutionTimeTooLong, ClickHouseQueryTimeOut
from posthog.models import Element, Team, User
+from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, filter_through_warehouse_join
from products.actions.backend.models.action import Action
from products.web_analytics.backend.achievements.definitions import STREAK_ARM_DAILY, STREAK_ARM_WEEKLY
from products.web_analytics.backend.achievements.evaluators import (
EvalContext,
PriorProgress,
+ TrackEvaluation,
_action_fingerprints,
_add_conversion_counts,
evaluate_conversions,
@@ -157,6 +160,29 @@ class TestTeamEvaluators(ClickhouseTestMixin, APIBaseTest):
self._pay_action("$autocapture")
self.assertEqual(evaluate_conversions(self._ctx(), EMPTY_PRIOR).value, 1)
+ @parameterized.expand(
+ [
+ ("pageviews", evaluate_cumulative_pageviews, [(7,)], 7),
+ ("conversions", evaluate_conversions, [(date.today(), 4)], 4),
+ ]
+ )
+ @patch(WAREHOUSE_ACCESS_CONTROL_FLAG, new=Mock(return_value=True))
+ def test_team_tracks_read_a_test_account_filter_through_a_warehouse_join(
+ self,
+ _name: str,
+ evaluate: Callable[[EvalContext, PriorProgress], TrackEvaluation],
+ rows: list[tuple[object, ...]],
+ expected: int,
+ ) -> None:
+ self.team.test_account_filters = [filter_through_warehouse_join(self.team)]
+ self.team.save()
+ self._pay_action("$autocapture")
+
+ with patch("posthog.hogql.query.sync_execute", return_value=(rows, [])):
+ evaluation = evaluate(self._ctx(), EMPTY_PRIOR)
+
+ self.assertEqual(evaluation.value, expected)
+
@parameterized.expand(
[
("byte_limit", CHQueryErrorTooManyBytes("read limit", code=307)),
diff --git a/products/web_analytics/backend/test/test_digest_notification_activities.py b/products/web_analytics/backend/test/test_digest_notification_activities.py
index 4e876eafef98..8e4560b40d66 100644
--- a/products/web_analytics/backend/test/test_digest_notification_activities.py
+++ b/products/web_analytics/backend/test/test_digest_notification_activities.py
@@ -72,7 +72,7 @@ class _DigestNotificationTestBase(APIBaseTest):
self.build_digest_patcher = patch(
"products.web_analytics.backend.weekly_digest.build_team_digest",
- side_effect=lambda team: _make_team_digest(team),
+ side_effect=lambda team, **_kwargs: _make_team_digest(team),
)
self.mock_build_digest = self.build_digest_patcher.start()
@@ -144,7 +144,7 @@ class TestBuildAndSendForOrg(_DigestNotificationTestBase):
self.mock_create_notification.assert_not_called()
def test_org_with_no_wa_data_is_skipped(self):
- self.mock_build_digest.side_effect = lambda team: _make_team_digest(team, visitors=0)
+ self.mock_build_digest.side_effect = lambda team, **_kwargs: _make_team_digest(team, visitors=0)
counts = _build_and_send_for_org(str(self.organization.id), flag_key="my-flag")
@@ -154,7 +154,7 @@ class TestBuildAndSendForOrg(_DigestNotificationTestBase):
def test_a_failing_team_is_left_out_and_counted(self):
broken_team = Team.objects.create(organization=self.organization, name="Broken team")
- def build(team):
+ def build(team, **_kwargs):
if team.id == broken_team.id:
raise TimeoutError("Query timed out")
return _make_team_digest(team)
@@ -178,7 +178,7 @@ class TestBuildAndSendForOrg(_DigestNotificationTestBase):
def test_raises_when_the_only_teams_with_data_may_be_the_failed_ones(self):
broken_team = Team.objects.create(organization=self.organization, name="Broken team")
- def build(team):
+ def build(team, **_kwargs):
if team.id == broken_team.id:
raise TimeoutError("Query timed out")
return _make_team_digest(team, visitors=0)
@@ -193,7 +193,7 @@ class TestBuildAndSendForOrg(_DigestNotificationTestBase):
def test_busiest_team_is_selected_when_user_has_multiple(self):
team_b = Team.objects.create(organization=self.organization, name="Team B")
- def digest_by_team(team):
+ def digest_by_team(team, **_kwargs):
visitors = 500 if team.id == team_b.id else 10
return _make_team_digest(team, visitors=visitors)
diff --git a/products/web_analytics/backend/test/test_weekly_digest.py b/products/web_analytics/backend/test/test_weekly_digest.py
index a6849bb73a5f..82b0b4b79f71 100644
--- a/products/web_analytics/backend/test/test_weekly_digest.py
+++ b/products/web_analytics/backend/test/test_weekly_digest.py
@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta
import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from django.test import SimpleTestCase
from django.utils import timezone
@@ -19,8 +19,11 @@ from posthog.schema import (
WebStatsTableQueryResponse,
)
+from posthog.hogql.errors import TableAccessDeniedError
+
from posthog.models import Team
from posthog.models.utils import uuid7
+from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, filter_through_warehouse_join
from products.actions.backend.models.action import Action
from products.web_analytics.backend.hogql_queries.web_goals import NoActionsError
@@ -29,6 +32,7 @@ from products.web_analytics.backend.weekly_digest import (
_format_duration,
auto_select_project_for_user,
build_team_digest,
+ build_team_digests,
get_goals_for_team,
get_overview_for_team,
get_top_pages,
@@ -431,6 +435,23 @@ class TestGetGoalsForTeam(ClickhouseTestMixin, APIBaseTest):
goal = next(g for g in result if g["name"] == "Signed Up")
assert goal["conversions"] >= 1
+ @patch(WAREHOUSE_ACCESS_CONTROL_FLAG, new=Mock(return_value=True))
+ def test_userless_job_reads_an_action_filter_through_a_warehouse_join(self):
+ Action.objects.create(
+ team=self.team,
+ name="Signed Up",
+ steps_json=[{"event": "signed_up", "properties": [filter_through_warehouse_join(self.team)]}],
+ last_calculated_at=timezone.now(),
+ )
+ goal_row = (5, 0, "Signed Up", (3, 0), (2, 0))
+
+ with patch("posthog.hogql.query.sync_execute", return_value=([goal_row], [])):
+ with self.assertRaises(TableAccessDeniedError):
+ get_goals_for_team(self.team)
+ result = get_goals_for_team(self.team, bypass_warehouse_access_control=True)
+
+ assert [(goal["name"], goal["conversions"]) for goal in result] == [("Signed Up", 3)]
+
class TestBuildTeamDigest(ClickhouseTestMixin, APIBaseTest):
def test_returns_all_expected_keys(self):
@@ -500,3 +521,16 @@ class TestBuildTeamDigest(ClickhouseTestMixin, APIBaseTest):
assert result["metadata"]["date_from"].date().isoformat() == "2025-01-21"
assert result["metadata"]["date_to"].date().isoformat() == "2025-01-28"
+
+ @patch(WAREHOUSE_ACCESS_CONTROL_FLAG, new=Mock(return_value=True))
+ def test_scheduled_digest_reads_a_test_account_filter_through_a_warehouse_join(self):
+ self.team.test_account_filters = [filter_through_warehouse_join(self.team)]
+ self.team.save()
+
+ with patch("posthog.hogql.query.sync_execute", return_value=([], [])):
+ with self.assertRaises(TableAccessDeniedError):
+ build_team_digest(self.team)
+ build = build_team_digests([self.team])
+
+ assert list(build.digests) == [self.team.id]
+ assert build.failed_teams == []
diff --git a/products/web_analytics/backend/test/test_weekly_digest_activities.py b/products/web_analytics/backend/test/test_weekly_digest_activities.py
index 833680a79088..468ed9510b5e 100644
--- a/products/web_analytics/backend/test/test_weekly_digest_activities.py
+++ b/products/web_analytics/backend/test/test_weekly_digest_activities.py
@@ -240,7 +240,7 @@ class TestBuildAndSendForOrg(_DigestTestBase):
self.addCleanup(flag_patcher.stop)
build_digest_patcher = patch(
"products.web_analytics.backend.weekly_digest.build_team_digest",
- side_effect=lambda team: _make_team_digest(team),
+ side_effect=lambda team, **_kwargs: _make_team_digest(team),
)
self.mock_build_digest = build_digest_patcher.start()
self.addCleanup(build_digest_patcher.stop)
@@ -248,7 +248,7 @@ class TestBuildAndSendForOrg(_DigestTestBase):
def test_a_failing_team_is_left_out_and_disclosed(self):
broken_team = Team.objects.create(organization=self.organization, name="Broken team")
- def build(team):
+ def build(team, **_kwargs):
if team.id == broken_team.id:
raise TimeoutError("Query timed out")
return _make_team_digest(team)
@@ -279,7 +279,7 @@ class TestSendTestDigestSingleTeamMode(_DigestTestBase):
super().setUp()
self.build_digest_patcher = patch(
"products.web_analytics.backend.weekly_digest.build_team_digest",
- side_effect=lambda team: _make_team_digest(team),
+ side_effect=lambda team, **_kwargs: _make_team_digest(team),
)
self.build_digest_patcher.start()
@@ -330,7 +330,7 @@ class TestSendTestDigestFullUserMode(_DigestTestBase):
super().setUp()
self.build_digest_patcher = patch(
"products.web_analytics.backend.weekly_digest.build_team_digest",
- side_effect=lambda team: _make_team_digest(team),
+ side_effect=lambda team, **_kwargs: _make_team_digest(team),
)
self.build_digest_patcher.start()
@@ -604,7 +604,7 @@ class TestRunWaDigestBatch(APIBaseTest):
),
patch(
"products.web_analytics.backend.weekly_digest.build_team_digest",
- side_effect=lambda team: _make_team_digest(team),
+ side_effect=lambda team, **_kwargs: _make_team_digest(team),
),
patch("products.web_analytics.backend.temporal.weekly_digest.activities.EmailMessage") as mock_email_class,
):
diff --git a/products/web_analytics/backend/weekly_digest.py b/products/web_analytics/backend/weekly_digest.py
index 43ead1096196..e697b0276076 100644
--- a/products/web_analytics/backend/weekly_digest.py
+++ b/products/web_analytics/backend/weekly_digest.py
@@ -92,6 +92,7 @@ def get_overview_for_team(
*,
execution_mode: ExecutionMode = DEFAULT_DIGEST_EXECUTION_MODE,
user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
) -> dict:
tag_queries(product=ProductKey.WEB_ANALYTICS, team_id=team.pk, name="weekly_digest:web_overview")
result = _default_overview()
@@ -102,7 +103,9 @@ def get_overview_for_team(
filterTestAccounts=True,
properties=[],
)
- runner = WebOverviewQueryRunner(team=team, query=query)
+ runner = WebOverviewQueryRunner(
+ team=team, query=query, bypass_warehouse_access_control=bypass_warehouse_access_control
+ )
response = _require_digest_response(runner.run(execution_mode=execution_mode, user=user))
if response.dateFrom and response.dateTo:
# A cached response can come from an earlier day, so keep the period that the numbers cover.
@@ -180,6 +183,7 @@ def _run_stats_table_query(
*,
execution_mode: ExecutionMode,
user: User | None,
+ bypass_warehouse_access_control: bool,
) -> WebStatsTableQueryResponse:
query = WebStatsTableQuery(
breakdownBy=breakdown_by,
@@ -190,7 +194,9 @@ def _run_stats_table_query(
filterTestAccounts=True,
properties=[],
)
- runner = WebStatsTableQueryRunner(team=team, query=query)
+ runner = WebStatsTableQueryRunner(
+ team=team, query=query, bypass_warehouse_access_control=bypass_warehouse_access_control
+ )
return _require_digest_response(runner.run(execution_mode=execution_mode, user=user))
@@ -202,10 +208,18 @@ def get_top_pages(
*,
execution_mode: ExecutionMode = DEFAULT_DIGEST_EXECUTION_MODE,
user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
) -> list[dict]:
tag_queries(product=ProductKey.WEB_ANALYTICS, team_id=team.pk, name="weekly_digest:top_pages")
response = _run_stats_table_query(
- team, WebStatsBreakdown.PAGE, limit, days, compare, execution_mode=execution_mode, user=user
+ team,
+ WebStatsBreakdown.PAGE,
+ limit,
+ days,
+ compare,
+ execution_mode=execution_mode,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
)
return [
@@ -227,10 +241,18 @@ def get_top_sources(
*,
execution_mode: ExecutionMode = DEFAULT_DIGEST_EXECUTION_MODE,
user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
) -> list[dict]:
tag_queries(product=ProductKey.WEB_ANALYTICS, team_id=team.pk, name="weekly_digest:top_sources")
response = _run_stats_table_query(
- team, WebStatsBreakdown.INITIAL_REFERRING_DOMAIN, limit, days, compare, execution_mode=execution_mode, user=user
+ team,
+ WebStatsBreakdown.INITIAL_REFERRING_DOMAIN,
+ limit,
+ days,
+ compare,
+ execution_mode=execution_mode,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
)
return [
@@ -252,6 +274,7 @@ def get_goals_for_team(
*,
execution_mode: ExecutionMode = DEFAULT_DIGEST_EXECUTION_MODE,
user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
) -> list[dict]:
tag_queries(product=ProductKey.WEB_ANALYTICS, team_id=team.pk, name="weekly_digest:goals")
@@ -261,7 +284,9 @@ def get_goals_for_team(
compareFilter=CompareFilter(compare=compare),
properties=[],
)
- runner = WebGoalsQueryRunner(team=team, query=query)
+ runner = WebGoalsQueryRunner(
+ team=team, query=query, bypass_warehouse_access_control=bypass_warehouse_access_control
+ )
response = _require_digest_response(runner.run(execution_mode=execution_mode, user=user))
except NoActionsError:
return []
@@ -348,11 +373,40 @@ def build_team_digest(
*,
execution_mode: ExecutionMode = DEFAULT_DIGEST_EXECUTION_MODE,
user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
) -> dict:
- overview = get_overview_for_team(team, days=days, compare=compare, execution_mode=execution_mode, user=user)
- top_pages = get_top_pages(team, days=days, compare=compare, execution_mode=execution_mode, user=user)
- top_sources = get_top_sources(team, days=days, compare=compare, execution_mode=execution_mode, user=user)
- goals = get_goals_for_team(team, days=days, compare=compare, execution_mode=execution_mode, user=user)
+ overview = get_overview_for_team(
+ team,
+ days=days,
+ compare=compare,
+ execution_mode=execution_mode,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
+ top_pages = get_top_pages(
+ team,
+ days=days,
+ compare=compare,
+ execution_mode=execution_mode,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
+ top_sources = get_top_sources(
+ team,
+ days=days,
+ compare=compare,
+ execution_mode=execution_mode,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
+ goals = get_goals_for_team(
+ team,
+ days=days,
+ compare=compare,
+ execution_mode=execution_mode,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
return {
"team": team,
@@ -376,7 +430,10 @@ def build_team_digests(teams: Iterable[Team]) -> TeamDigestBuild:
failed_teams: list[Team] = []
for team in teams:
try:
- digests[team.id] = build_team_digest(team)
+ # The scheduled digest has no acting user, and it emits team-wide aggregates that recipients
+ # only receive for projects they can access. Without the bypass, a test-account or action
+ # filter that reads a warehouse join fails closed and the team section is lost.
+ digests[team.id] = build_team_digest(team, bypass_warehouse_access_control=True)
except Exception as e:
logger.warning("WA digest could not build a team section", team_id=team.id, error=str(e))
capture_exception(e, {"team_id": team.id})