: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(weekly-digest): run activity bodies on worker threads (#104657)
Rafael Audibert609737c99d17
diff --git a/posthog/temporal/tests/weekly_digest/test_activities.py b/posthog/temporal/tests/weekly_digest/test_activities.pyindex 2ef4744469cf..93ff5a588d41 100644--- a/posthog/temporal/tests/weekly_digest/test_activities.py+++ b/posthog/temporal/tests/weekly_digest/test_activities.py@@ -1,21 +1,38 @@import json+import inspect+from collections.abc import Callable, Iteratorfrom datetime import UTC, datetime, timedelta-from uuid import UUID, uuid4+from typing import Any+from uuid import uuid4import pytestfrom posthog.test.base import _create_event, flush_persons_and_events-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import MagicMock, patch-import pytest_asyncio+from django.utils import timezone+import fakeredis+from asgiref.sync import sync_to_async+from temporalio import activity++from posthog.models.messaging import MessagingRecord+from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.organization_notification_lock import OrganizationMemberNotificationLock+from posthog.models.product_intent.product_intent import ProductIntentfrom posthog.models.team import Team+from posthog.models.user import User+from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist+from posthog.session_recordings.session_recording_playlist_api import PLAYLIST_COUNT_REDIS_PREFIXfrom posthog.temporal.weekly_digest.activities import (+ NEW_ERROR_ISSUES_PER_TEAM_LIMIT,+ ActivityCancelled,_cut_team_id_ranges,_query_team_usage_trends,+ _redis_url,_teams_in_range,_usage_trend_metric,- count_organizations,generate_dashboard_lookup,+ generate_error_issue_lookup,generate_event_definition_lookup,generate_experiment_completed_lookup,generate_experiment_launched_lookup,@@ -30,6 +47,7 @@ from posthog.temporal.weekly_digest.activities import (generate_user_notification_lookup,send_weekly_digest_batch,)+from posthog.temporal.weekly_digest.keys import TeamDataKey, UserDataKey, org_digest_key, team_data_key, user_data_keyfrom posthog.temporal.weekly_digest.queries import query_team_ids_for_digest, query_teams_for_digestfrom posthog.temporal.weekly_digest.types import (DEFAULT_PRODUCT_SUGGESTION_TEXT,@@ -42,108 +60,79 @@ from posthog.temporal.weekly_digest.types import (UsageTrends,)-from products.growth.backend.product_push.selection import project_uses_product---class MockRedis:- """Mock Redis client for testing."""-- def __init__(self):- self.data = {}- self.sets = {}- self.ttls = {}-- async def setex(self, key: str, ttl: int, value: str) -> None:- self.data[key] = value- self.ttls[key] = ttl-- async def get(self, key: str) -> str | None:- return self.data.get(key)-- async def mget(self, keys: list[str]) -> list[str | None]:- return [self.data.get(key) for key in keys]-- async def sadd(self, key: str, *values) -> None:- if key not in self.sets:- self.sets[key] = set()- self.sets[key].update(values)-- async def smembers(self, key: str) -> set:- return self.sets.get(key, set())-- async def expire(self, key: str, ttl: int) -> None:- self.ttls[key] = ttl-- async def __aenter__(self):- return self-- async def __aexit__(self, exc_type, exc_val, exc_tb):- pass---class MockAsyncQuerySet:- """Mock Django async queryset for testing."""+from products.dashboards.backend.models.dashboard import Dashboard+from products.error_tracking.backend.facade.testing import create_issue+from products.event_definitions.backend.models.event_definition import EventDefinition+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.growth.backend.models import ProductPushCampaign+from products.surveys.backend.models import Survey+from products.warehouse_sources.backend.facade.models import ExternalDataSource- def __init__(self, items):- self.items = items+DJANGO_REDIS_URL = "redis://django-cache.example.com:6379"- def filter(self, id__gte: int, id__lt: int):- return MockAsyncQuerySet([item for item in self.items if id__gte <= item.id < id__lt])- def __getitem__(self, key):- """Support slicing operations."""- if isinstance(key, slice):- return MockAsyncQuerySet(self.items[key])- return self.items[key]+def run_sync(activity_fn: Callable[..., Any], *args: Any) -> Any:+ # Activities are `@asyncify` wrappers around a sync body. Calling the body directly keeps the+ # test on the fast transactional database, which a thread-hopping coroutine could not see.+ return inspect.unwrap(activity_fn)(*args)- def __aiter__(self):- """Support async iteration."""- return self-- async def __anext__(self):- """Async iterator implementation."""- if not hasattr(self, "_iter"):- self._iter = iter(self.items)- try:- return next(self._iter)- except StopIteration:- delattr(self, "_iter")- raise StopAsyncIteration+class FakeRedisServers:+ def __init__(self, common: CommonInput) -> None:+ self._servers = {+ _redis_url(common): fakeredis.FakeServer(),+ common.django_redis_url: fakeredis.FakeServer(),+ }+ self.digest = fakeredis.FakeRedis(server=self._servers[_redis_url(common)], decode_responses=True)+ self.django_cache = fakeredis.FakeRedis(server=self._servers[common.django_redis_url])-def mock_redis():- """Fixture providing a mock Redis instance."""- return MockRedis()+ def from_url(self, url: str, **kwargs: Any) -> fakeredis.FakeRedis:+ return fakeredis.FakeRedis(server=self._servers[url], decode_responses="decode_responses=true" in url)@pytest.fixture-def common_input():- """Fixture providing common input parameters."""+def common_input() -> CommonInput:return CommonInput(redis_ttl=3600 * 24 * 3,- redis_host="localhost",+ redis_host="digest-redis.example.com",redis_port=6379,batch_size=10,- django_redis_url="redis://localhost:6379",+ django_redis_url=DJANGO_REDIS_URL,)@pytest.fixture-def digest():- """Fixture providing a test digest."""- period_end = datetime.now(UTC)- period_start = period_end - timedelta(days=7)- return Digest(key="test-digest", period_start=period_start, period_end=period_end)+def redis_servers(common_input: CommonInput) -> Iterator[FakeRedisServers]:+ servers = FakeRedisServers(common_input)+ with patch("posthog.temporal.weekly_digest.activities.redis.Redis.from_url", side_effect=servers.from_url):+ yield servers-@pytest_asyncio.fixture(autouse=True)-async def mock_heartbeater():- """Auto-fixture to mock Heartbeater for all tests."""- with patch("posthog.temporal.weekly_digest.activities.Heartbeater"):+def digest() -> Digest:+ # Rows created during the test carry `auto_now_add` timestamps, so the window ends after now.+ period_end = datetime.now(UTC) + timedelta(hours=1)+ return Digest(key="test-digest", period_start=period_end - timedelta(days=7), period_end=period_end)++[email protected](autouse=True)+def mock_heartbeater() -> Iterator[None]:+ # HeartbeaterSync reads the activity context, which the sync bodies do not have under test.+ with patch("posthog.temporal.weekly_digest.activities.HeartbeaterSync"):yield+def batch_input(team: Team, digest: Digest, common: CommonInput) -> GenerateDigestDataBatchInput:+ return GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=team.id, end=team.id + 1), digest=digest, common=common+ )+++def create_user(organization: Organization, email: str, **fields: Any) -> User:+ return User.objects.create_and_join(organization, email, None, **fields)++@pytest.mark.django_dbdef test_team_id_ranges_page_every_digest_team_exactly_once(organization, digest):for i in range(5):@@ -169,808 +158,419 @@ def test_team_id_ranges_page_every_digest_team_exactly_once(organization, digestassert paged == expected-async def test_count_organizations():- """Test counting organizations for digest."""- mock_queryset = AsyncMock()- mock_queryset.acount = AsyncMock(return_value=15)+def _make_dashboards(team: Team, other_team: Team, digest: Digest) -> list[str]:+ Dashboard.objects.create(team=team, name="New dashboard")+ Dashboard.objects.create(team=team, name="Generated Dashboard: onboarding")+ Dashboard.objects.create(team=other_team, name="Other team's dashboard")+ old = Dashboard.objects.create(team=team, name="Old dashboard")+ Dashboard.objects.filter(id=old.id).update(created_at=digest.period_start - timedelta(days=1))+ return ["New dashboard"]- with patch("posthog.temporal.weekly_digest.activities.query_orgs_for_digest", return_value=mock_queryset):- result = await count_organizations()- assert result == 15- mock_queryset.acount.assert_called_once()+def _make_event_definitions(team: Team, other_team: Team, digest: Digest) -> list[str]:+ EventDefinition.objects.create(team=team, name="new_event", created_at=timezone.now())+ EventDefinition.objects.create(team=other_team, name="other_event", created_at=timezone.now())+ EventDefinition.objects.create(team=team, name="old_event", created_at=digest.period_start - timedelta(days=1))+ return ["new_event"]-async def test_generate_dashboard_lookup(mock_redis, common_input, digest):- """Test generating dashboard lookup with mock Redis."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+def _make_experiment(team: Team, name: str, **fields: Any) -> Experiment:+ flag = FeatureFlag.objects.create(+ team=team, key=f"flag-{uuid4().hex[:8]}", name=f"Feature Flag for Experiment {name}")+ return Experiment.objects.create(team=team, feature_flag=flag, name=name, **fields)- # Mock teams- mock_team_1 = MagicMock()- mock_team_1.id = 1- mock_team_2 = MagicMock()- mock_team_2.id = 2-- # Mock dashboards- mock_dashboards = [- {"team_id": 1, "name": "Dashboard 1", "id": 101},- {"team_id": 1, "name": "Dashboard 2", "id": 102},- ]-- mock_team_queryset = MockAsyncQuerySet([mock_team_1, mock_team_2])- mock_dashboard_queryset = MagicMock()- async def mock_queryset_to_list(qs):- if qs == mock_dashboard_queryset:- return mock_dashboards- return []+def _make_experiments_launched(team: Team, other_team: Team, digest: Digest) -> list[str]:+ in_window = digest.period_end - timedelta(days=1)+ _make_experiment(team, "Launched", start_date=in_window)+ _make_experiment(team, "Launched and completed", start_date=in_window, end_date=in_window)+ _make_experiment(team, "Launched earlier", start_date=digest.period_start - timedelta(days=1))+ _make_experiment(other_team, "Other team's launch", start_date=in_window)+ return ["Launched"]- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch(- "posthog.temporal.weekly_digest.activities.query_new_dashboards", return_value=mock_dashboard_queryset- ):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_dashboard_lookup(input_data)- # Verify data was stored in Redis- assert f"{digest.key}-dashboards-1" in mock_redis.data- assert mock_redis.ttls[f"{digest.key}-dashboards-1"] == common_input.redis_ttl+def _make_experiments_completed(team: Team, other_team: Team, digest: Digest) -> list[str]:+ in_window = digest.period_end - timedelta(days=1)+ _make_experiment(team, "Completed", start_date=digest.period_start - timedelta(days=30), end_date=in_window)+ _make_experiment(team, "Still running", start_date=in_window)+ _make_experiment(other_team, "Other team's completion", start_date=in_window, end_date=in_window)+ return ["Completed"]-async def test_generate_event_definition_lookup(mock_redis, common_input, digest):- """Test generating event definition lookup with mock Redis."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+def _make_external_data_source(team: Team, source_type: str, **fields: Any) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=team,+ source_id=str(uuid4()),+ connection_id=str(uuid4()),+ status="Completed",+ source_type=source_type,+ **fields,)- mock_team = MagicMock()- mock_team.id = 1-- mock_events = [- {"team_id": 1, "name": "pageview", "id": str(uuid4())},- {"team_id": 1, "name": "click", "id": str(uuid4())},- ]-- mock_team_queryset = MockAsyncQuerySet([mock_team])-- mock_event_queryset = MagicMock()-- async def mock_queryset_to_list(qs):- if qs == mock_event_queryset:- return mock_events- return []-- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch(- "posthog.temporal.weekly_digest.activities.query_new_event_definitions", return_value=mock_event_queryset- ):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_event_definition_lookup(input_data)- assert f"{digest.key}-event-definitions-1" in mock_redis.data+def _make_external_data_sources(team: Team, other_team: Team, digest: Digest) -> list[str]:+ _make_external_data_source(team, "Stripe")+ _make_external_data_source(team, "Hubspot", deleted=True)+ _make_external_data_source(other_team, "Zendesk")+ old = _make_external_data_source(team, "Postgres")+ ExternalDataSource.objects.filter(id=old.id).update(created_at=digest.period_start - timedelta(days=1))+ return ["Stripe"]-async def test_generate_experiment_launched_lookup(mock_redis, common_input, digest):- """Test generating experiment launched lookup with mock Redis."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+def _make_feature_flags(team: Team, other_team: Team, digest: Digest) -> list[str]:+ FeatureFlag.objects.create(team=team, key="new-flag", name="New flag")+ FeatureFlag.objects.create(team=team, key="exp-flag", name="Feature Flag for Experiment checkout")+ FeatureFlag.objects.create(team=team, key="survey-flag", name="Targeting flag for survey NPS")+ FeatureFlag.objects.create(team=other_team, key="other-flag", name="Other team's flag")+ FeatureFlag.objects.create(+ team=team, key="old-flag", name="Old flag", created_at=digest.period_start - timedelta(days=1))+ return ["New flag"]- mock_team = MagicMock()- mock_team.id = 1-- mock_experiments = [- {"team_id": 1, "name": "Experiment A", "id": 1, "start_date": datetime.now(UTC)},- {"team_id": 1, "name": "Experiment B", "id": 2, "start_date": datetime.now(UTC)},- ]-- mock_team_queryset = MockAsyncQuerySet([mock_team])-- mock_experiment_queryset = MagicMock()-- async def mock_queryset_to_list(qs):- if qs == mock_experiment_queryset:- return mock_experiments- return []- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch(- "posthog.temporal.weekly_digest.activities.query_experiments_launched",- return_value=mock_experiment_queryset,- ):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_experiment_launched_lookup(input_data)-- assert f"{digest.key}-experiments-launched-1" in mock_redis.data---async def test_generate_experiment_completed_lookup(mock_redis, common_input, digest):- """Test generating experiment completed lookup with mock Redis."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+def _make_survey(team: Team, name: str, **fields: Any) -> Survey:+ return Survey.objects.create(+ team=team, name=name, type="popover", questions=[{"type": "open", "id": "q1", "question": "Why?"}], **fields)- mock_team = MagicMock()- mock_team.id = 1- mock_experiments = [- {- "team_id": 1,- "name": "Completed Experiment",- "id": 1,- "start_date": datetime.now(UTC) - timedelta(days=14),- "end_date": datetime.now(UTC) - timedelta(days=1),- }- ]-- mock_team_queryset = MockAsyncQuerySet([mock_team])-- mock_experiment_queryset = MagicMock()-- async def mock_queryset_to_list(qs):- if qs == mock_experiment_queryset:- return mock_experiments- return []-- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch(- "posthog.temporal.weekly_digest.activities.query_experiments_completed",- return_value=mock_experiment_queryset,- ):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_experiment_completed_lookup(input_data)-- assert f"{digest.key}-experiments-completed-1" in mock_redis.data---async def test_generate_external_data_source_lookup(mock_redis, common_input, digest):- """Test generating external data source lookup with mock Redis."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input- )-- mock_team = MagicMock()- mock_team.id = 1+def _make_surveys(team: Team, other_team: Team, digest: Digest) -> list[str]:+ in_window = digest.period_end - timedelta(days=1)+ _make_survey(team, "Launched survey", start_date=in_window)+ _make_survey(team, "Draft survey")+ _make_survey(team, "Old survey", start_date=digest.period_start - timedelta(days=1))+ _make_survey(other_team, "Other team's survey", start_date=in_window)+ return ["Launched survey"]- mock_sources = [{"team_id": 1, "source_type": "stripe", "id": str(uuid4())}]-- mock_team_queryset = MockAsyncQuerySet([mock_team])-- mock_source_queryset = MagicMock()-- async def mock_queryset_to_list(qs):- if qs == mock_source_queryset:- return mock_sources- return []-- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch(- "posthog.temporal.weekly_digest.activities.query_new_external_data_sources",- return_value=mock_source_queryset,- ):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_external_data_source_lookup(input_data)-- assert f"{digest.key}-external-data-sources-1" in mock_redis.data---async def test_generate_feature_flag_lookup(mock_redis, common_input, digest):- """Test generating feature flag lookup with mock Redis."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input- )-- mock_team = MagicMock()- mock_team.id = 1-- mock_flags = [- {"team_id": 1, "name": "New Feature", "id": 1, "key": "new-feature"},- {"team_id": 1, "name": "Beta Feature", "id": 2, "key": "beta-feature"},- ]- mock_team_queryset = MockAsyncQuerySet([mock_team])+def _make_error_issues(team: Team, other_team: Team, digest: Digest) -> list[str]:+ # One more than the cap, oldest first, so the cap must keep the newest ones.+ for index in range(NEW_ERROR_ISSUES_PER_TEAM_LIMIT + 1):+ create_issue(+ team_id=team.id, name=f"issue {index}", created_at=digest.period_start + timedelta(hours=index + 1)+ )+ create_issue(team_id=other_team.id, name="other team's issue", created_at=digest.period_end - timedelta(hours=1))+ create_issue(team_id=team.id, name="old issue", created_at=digest.period_start - timedelta(days=1))+ return [f"issue {index}" for index in range(1, NEW_ERROR_ISSUES_PER_TEAM_LIMIT + 1)]- mock_flag_queryset = MagicMock()- async def mock_queryset_to_list(qs):- if qs == mock_flag_queryset:- return mock_flags- return []+ "activity_fn,key_kind,payload_field,make_rows",+ [+ (generate_dashboard_lookup, TeamDataKey.DASHBOARDS, "name", _make_dashboards),+ (generate_event_definition_lookup, TeamDataKey.EVENT_DEFINITIONS, "name", _make_event_definitions),+ (generate_experiment_launched_lookup, TeamDataKey.EXPERIMENTS_LAUNCHED, "name", _make_experiments_launched),+ (generate_experiment_completed_lookup, TeamDataKey.EXPERIMENTS_COMPLETED, "name", _make_experiments_completed),+ (+ generate_external_data_source_lookup,+ TeamDataKey.EXTERNAL_DATA_SOURCES,+ "source_type",+ _make_external_data_sources,+ ),+ (generate_feature_flag_lookup, TeamDataKey.FEATURE_FLAGS, "name", _make_feature_flags),+ (generate_survey_lookup, TeamDataKey.SURVEYS_LAUNCHED, "name", _make_surveys),+ (generate_error_issue_lookup, TeamDataKey.ERROR_ISSUES, "name", _make_error_issues),+ ],+)+def test_generic_lookup_stores_only_this_teams_rows_from_the_window(+ activity_fn, key_kind, payload_field, make_rows, organization, team, redis_servers, common_input, digest+):+ other_team = Team.objects.create(organization=organization, name="other team")+ expected = make_rows(team, other_team, digest)- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch(- "posthog.temporal.weekly_digest.activities.query_new_feature_flags", return_value=mock_flag_queryset- ):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_feature_flag_lookup(input_data)+ run_sync(activity_fn, batch_input(team, digest, common_input))- assert f"{digest.key}-feature-flags-1" in mock_redis.data+ key = team_data_key(digest.key, key_kind, team.id)+ stored = json.loads(redis_servers.digest.get(key))+ assert sorted(row[payload_field] for row in stored) == sorted(expected)+ assert 0 < redis_servers.digest.ttl(key) <= common_input.redis_ttl+ assert redis_servers.digest.get(team_data_key(digest.key, key_kind, other_team.id)) is None-async def test_generate_survey_lookup(mock_redis, common_input, digest):- """Test generating survey lookup with mock Redis."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+def test_generate_filter_lookup_orders_filters_by_cached_recording_count(team, redis_servers, common_input, digest):+ quiet = SessionRecordingPlaylist.objects.create(team=team, name="Quiet filter", type="filters")+ busy = SessionRecordingPlaylist.objects.create(team=team, name="Busy filter", type="filters")+ SessionRecordingPlaylist.objects.create(team=team, name="A collection", type="collection")+ SessionRecordingPlaylist.objects.create(team=team, name="Deleted filter", type="filters", deleted=True)+ SessionRecordingPlaylist.objects.create(team=team, name="", derived_name="(Untitled)", type="filters")+ redis_servers.django_cache.set(+ f"{PLAYLIST_COUNT_REDIS_PREFIX}{busy.short_id}",+ json.dumps(+ {+ "session_ids": ["s1", "s2", "s3"],+ "has_more": True,+ "previous_ids": None,+ "refreshed_at": timezone.now().isoformat(),+ "error_count": 0,+ "errored_at": None,+ }+ ),)+ redis_servers.django_cache.set(f"{PLAYLIST_COUNT_REDIS_PREFIX}{quiet.short_id}", "not json")- mock_team = MagicMock()- mock_team.id = 1+ run_sync(generate_filter_lookup, batch_input(team, digest, common_input))- mock_surveys = [- {- "team_id": 1,- "name": "Customer Satisfaction",- "id": str(uuid4()),- "description": "How satisfied are you?",- "start_date": datetime.now(UTC),- }+ stored = json.loads(redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.SAVED_FILTERS, team.id)))+ assert [(f["name"], f["recording_count"], f["more_available"]) for f in stored] == [+ ("Busy filter", 3, True),+ ("Quiet filter", 0, False),]- mock_team_queryset = MockAsyncQuerySet([mock_team])- mock_survey_queryset = MagicMock()+def test_generate_recording_lookup_stores_the_count_for_each_team(team, redis_servers, common_input, digest):+ with patch("posthog.temporal.weekly_digest.activities.sync_execute", return_value=[(10,)]) as sync_execute:+ run_sync(generate_recording_lookup, batch_input(team, digest, common_input))- async def mock_queryset_to_list(qs):- if qs == mock_survey_queryset:- return mock_surveys- return []+ assert sync_execute.call_args.args[1]["team_id"] == team.id+ stored = json.loads(redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.EXPIRING_RECORDINGS, team.id)))+ assert stored == {"recording_count": 10}- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch(- "posthog.temporal.weekly_digest.activities.query_surveys_launched", return_value=mock_survey_queryset- ):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_survey_lookup(input_data)- assert f"{digest.key}-surveys-launched-1" in mock_redis.data+def _make_team(organization: Organization, name: str) -> Team:+ return Team.objects.create(organization=organization, name=name)-async def test_generate_filter_lookup(mock_redis, common_input, digest):- """Test generating filter lookup with mock Redis and playlist counts."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+def test_generate_user_notification_lookup_respects_settings_and_organization_locks(+ organization, team, redis_servers, common_input, digest+):+ muted_team = _make_team(organization, "muted for one user")+ everyone = create_user(organization, "[email protected]")+ muted_one = create_user(+ organization,+ "[email protected]",+ partial_notification_settings={"project_weekly_digest_disabled": {str(muted_team.id): True}},)-- mock_team = MagicMock()- mock_team.id = 1-- mock_filters = [- {"name": "High Value Users", "short_id": "abc123", "view_count": 5},- {"name": "Error Tracking", "short_id": "def456", "view_count": 3},- ]-- # Mock playlist count data- mock_django_redis = MockRedis()- await mock_django_redis.setex(- "posthog:1:playlist:abc123:count",- 3600,- '{"session_ids": ["session1", "session2"], "has_more": false, "previous_ids": null, "refreshed_at": "2024-01-01T00:00:00Z", "error_count": 0, "errored_at": null}',+ muted_all = create_user(+ organization, "[email protected]", partial_notification_settings={"all_weekly_digest_disabled": True})- await mock_django_redis.setex(- "posthog:1:playlist:def456:count",- 3600,- '{"session_ids": ["session3"], "has_more": true, "previous_ids": null, "refreshed_at": "2024-01-01T00:00:00Z", "error_count": 0, "errored_at": null}',+ locked = create_user(organization, "[email protected]")+ OrganizationMemberNotificationLock.objects.create(+ organization=organization,+ organization_membership=OrganizationMembership.objects.get(user=locked, organization=organization),+ setting="project_weekly_digest_disabled",+ scope_id=str(team.id),+ locked_value=True,)+ create_user(organization, "[email protected]", is_active=False)- mock_team_queryset = MockAsyncQuerySet([mock_team])-- mock_filter_queryset = MagicMock()-- async def mock_queryset_to_list(qs):- if qs == mock_filter_queryset:- return mock_filters- return []-- def mock_redis_from_url(url):- if "django" in url.lower() or url == common_input.django_redis_url:- return mock_django_redis- return mock_redis-- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch("posthog.temporal.weekly_digest.activities.query_saved_filters", return_value=mock_filter_queryset):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", side_effect=mock_redis_from_url):- await generate_filter_lookup(input_data)-- assert f"{digest.key}-saved-filters-1" in mock_redis.data---async def test_generate_recording_lookup(mock_redis, common_input, digest):- """Test generating recording lookup with mock Redis and ClickHouse."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ run_sync(+ generate_user_notification_lookup,+ GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=team.id, end=muted_team.id + 1), digest=digest, common=common_input+ ),)- mock_team = MagicMock()- mock_team.id = 1-- mock_ch_response = AsyncMock()- mock_ch_response.content.read = AsyncMock(- return_value=b'{"meta": [], "data": [{"recording_count": 10}], "statistics": {}, "rows": 1}'- )- mock_ch_response.__aenter__ = AsyncMock(return_value=mock_ch_response)- mock_ch_response.__aexit__ = AsyncMock(return_value=None)+ def notify_teams(user: User) -> set[int]:+ key = user_data_key(digest.key, UserDataKey.NOTIFY_TEAMS, user.id)+ return {int(team_id) for team_id in redis_servers.digest.smembers(key)}- mock_team_queryset = MockAsyncQuerySet([mock_team])-- mock_ch_client = AsyncMock()- mock_ch_client.aget_query = MagicMock(return_value=mock_ch_response)- mock_ch_client.__aenter__ = AsyncMock(return_value=mock_ch_client)- mock_ch_client.__aexit__ = AsyncMock(return_value=None)-- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch("posthog.temporal.weekly_digest.activities.get_ch_client", return_value=mock_ch_client):- with patch("posthog.temporal.weekly_digest.activities.database_sync_to_async") as mock_sync:- mock_sync.return_value = AsyncMock(return_value=30)- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_recording_lookup(input_data)-- assert f"{digest.key}-expiring-recordings-1" in mock_redis.data+ assert notify_teams(everyone) == {team.id, muted_team.id}+ assert notify_teams(muted_one) == {team.id}+ assert notify_teams(muted_all) == set()+ assert notify_teams(locked) == {muted_team.id}+ assert set(redis_servers.digest.keys(f"{digest.key}-{UserDataKey.NOTIFY_TEAMS}-*")) == {+ user_data_key(digest.key, UserDataKey.NOTIFY_TEAMS, user.id) for user in [everyone, muted_one, locked]+ }[email protected]_db(transaction=True)@pytest.mark.asyncio-async def test_generate_user_notification_lookup(mock_redis, common_input, digest):- """Test generating user notification lookup with mock Redis."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input- )-- mock_team = MagicMock()- mock_team.id = 1-- mock_user_1 = MagicMock()- mock_user_1.id = 100-- mock_user_2 = MagicMock()- mock_user_2.id = 101-- # Create a sync function that database_sync_to_async will wrap- def sync_all_users_with_access():- return [mock_user_1, mock_user_2]-- mock_team.all_users_with_access = sync_all_users_with_access-- mock_team_queryset = MockAsyncQuerySet([mock_team])-- # Create an async generator function- async def async_user_generator():- for user in [mock_user_1, mock_user_2]:- yield user-- # Create a coroutine that returns the async generator- async def async_wrapper():- return async_user_generator()-- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch("posthog.temporal.weekly_digest.activities.should_send_notification", return_value=True):- with patch("posthog.temporal.weekly_digest.activities.database_sync_to_async") as mock_sync:- # database_sync_to_async(fn)() should return an awaitable that yields an async generator- mock_sync.return_value = async_wrapper- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_user_notification_lookup(input_data)-- # Verify user notification sets were created- assert f"{digest.key}-user-notify-100" in mock_redis.sets- assert f"{digest.key}-user-notify-101" in mock_redis.sets- assert 1 in mock_redis.sets[f"{digest.key}-user-notify-100"]- assert 1 in mock_redis.sets[f"{digest.key}-user-notify-101"]+async def test_generate_user_notification_lookup_activity_runs_the_settings_check_off_the_event_loop(+ activity_environment, organization, team, redis_servers, common_input, digest+):+ # The activity runs on the event loop the way the worker calls it. `should_send_notification`+ # queries Postgres, which Django refuses from a coroutine, so a body that stays on the loop+ # skips every team and writes no notification set at all.+ user = await sync_to_async(create_user)(organization, "[email protected]")+ await activity_environment.run(generate_user_notification_lookup, batch_input(team, digest, common_input))-async def test_generate_organization_digest_batch(mock_redis, common_input, digest):- """Test generating organization digest batch with mock Redis."""- batch = (0, 1)- input_data = GenerateOrganizationDigestInput(batch=batch, digest=digest, common=common_input)-- mock_org = MagicMock()- mock_org.id = UUID("12345678-1234-1234-1234-123456789abc")- mock_org.name = "Test Organization"- mock_org.created_at = datetime.now(UTC)-- mock_team = MagicMock()- mock_team.id = 1- mock_team.name = "Test Team"-- # Pre-populate Redis with team digest data- await mock_redis.setex(f"{digest.key}-dashboards-1", 3600, "[]")- await mock_redis.setex(f"{digest.key}-event-definitions-1", 3600, "[]")- await mock_redis.setex(f"{digest.key}-experiments-launched-1", 3600, "[]")- await mock_redis.setex(f"{digest.key}-experiments-completed-1", 3600, "[]")- await mock_redis.setex(f"{digest.key}-external-data-sources-1", 3600, "[]")- await mock_redis.setex(f"{digest.key}-feature-flags-1", 3600, "[]")- await mock_redis.setex(f"{digest.key}-saved-filters-1", 3600, "[]")- await mock_redis.setex(f"{digest.key}-expiring-recordings-1", 3600, '{"recording_count": 0}')- await mock_redis.setex(f"{digest.key}-surveys-launched-1", 3600, "[]")-- mock_org_queryset = MockAsyncQuerySet([mock_org])- mock_team_queryset = MockAsyncQuerySet([mock_team])-- with patch("posthog.temporal.weekly_digest.activities.query_orgs_for_digest", return_value=mock_org_queryset):- with patch("posthog.temporal.weekly_digest.activities.query_org_teams", return_value=mock_team_queryset):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_organization_digest_batch(input_data)-- # Verify organization digest was created- assert f"{digest.key}-{mock_org.id}" in mock_redis.data+ assert redis_servers.digest.smembers(user_data_key(digest.key, UserDataKey.NOTIFY_TEAMS, user.id)) == {str(team.id)}-async def test_send_weekly_digest_batch(mock_redis, common_input, digest):- """Test sending weekly digest batch with mock Redis and PostHog client."""- batch = (0, 1)- input_data = SendWeeklyDigestBatchInput(- batch=batch, dry_run=False, allow_already_sent=False, digest=digest, common=common_input[email protected]("project_already_uses_product", [False, True])+def test_generate_product_suggestion_lookup_targets_opted_in_users_of_projects_without_the_product(+ project_already_uses_product, organization, team, redis_servers, common_input, digest+):+ ProductPushCampaign.objects.create(+ organization=organization,+ product_key="session_replay",+ status=ProductPushCampaign.Status.ACTIVE,+ started_at=timezone.now() - timedelta(days=1),+ reason_text="Give replay a go",)+ opted_in = create_user(organization, "[email protected]")+ create_user(organization, "[email protected]", allow_sidebar_suggestions=False)+ if project_already_uses_product:+ ProductIntent.objects.create(team=team, product_type="session_replay", activated_at=timezone.now())- mock_org = MagicMock()- mock_org.id = UUID("12345678-1234-1234-1234-123456789abc")- mock_org.name = "Test Organization"-- mock_member = MagicMock()- mock_user = MagicMock()- mock_user.id = 100- mock_user.distinct_id = "user-100"- mock_user.email = "[email protected]"- mock_member.user = mock_user-- # Pre-populate Redis with organization digest- org_digest_json = """{- "id": "12345678-1234-1234-1234-123456789abc",- "name": "Test Organization",- "created_at": "2024-01-01T00:00:00Z",- "team_digests": [- {- "id": 1,- "name": "Test Team",- "dashboards": [{"name": "Test Dashboard", "id": 1}],- "event_definitions": [],- "experiments_launched": [- {"name": "Experiment A", "id": 1, "start_date": "2024-01-01T00:00:00Z"},- {"name": "Experiment B", "id": 2, "start_date": "2024-01-01T00:00:00Z"}- ],- "experiments_completed": [],- "external_data_sources": [- {"source_type": "stripe", "id": "12345678-1234-1234-1234-123456789abc"}- ],- "feature_flags": [],- "filters": [],- "expiring_recordings": {"recording_count": 0},- "surveys_launched": []- }- ]- }"""- await mock_redis.setex(f"{digest.key}-{mock_org.id}", 3600, org_digest_json)-- # Add user notification- await mock_redis.sadd(f"{digest.key}-user-notify-100", "1")-- mock_org_queryset = MockAsyncQuerySet([mock_org])- mock_member_queryset = MockAsyncQuerySet([mock_member])-- mock_ph_client = MagicMock()- mock_ph_client.capture = MagicMock()+ run_sync(generate_product_suggestion_lookup, batch_input(team, digest, common_input))- mock_messaging_record = MagicMock()- mock_messaging_record.sent_at = None+ suggestion_keys = redis_servers.digest.keys(f"{digest.key}-{UserDataKey.PRODUCT_SUGGESTION}-*")+ if project_already_uses_product:+ assert suggestion_keys == []+ return- mock_messaging_objects = MagicMock()- mock_messaging_objects.aget_or_create = AsyncMock(return_value=(mock_messaging_record, True))- mock_messaging_objects.abulk_update = AsyncMock()+ assert suggestion_keys == [user_data_key(digest.key, UserDataKey.PRODUCT_SUGGESTION, opted_in.id)]+ stored = json.loads(redis_servers.digest.get(suggestion_keys[0]))+ assert stored == {"team_id": team.id, "product_path": "Session replay", "reason_text": "Give replay a go"}- with patch("posthog.temporal.weekly_digest.activities.query_orgs_for_digest", return_value=mock_org_queryset):- with patch("posthog.temporal.weekly_digest.activities.query_org_members", return_value=mock_member_queryset):- with patch("posthog.temporal.weekly_digest.activities.get_ph_client", return_value=mock_ph_client):- with patch("posthog.temporal.weekly_digest.activities.MessagingRecord.objects", mock_messaging_objects):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await send_weekly_digest_batch(input_data)- # Verify PostHog client was called- mock_ph_client.capture.assert_called_once()-- # Verify messaging record was updated- mock_messaging_objects.abulk_update.assert_called_once()---async def test_send_weekly_digest_batch_dry_run(mock_redis, common_input, digest):- """Test sending weekly digest batch in dry run mode."""- batch = (0, 1)- input_data = SendWeeklyDigestBatchInput(- batch=batch, dry_run=True, allow_already_sent=False, digest=digest, common=common_input+def test_generate_organization_digest_batch_defaults_missing_team_data(+ organization, team, redis_servers, common_input, digest+):+ silent_team = _make_team(organization, "silent team")+ Team.objects.create(organization=organization, name="demo team", is_demo=True)+ redis_servers.digest.set(+ team_data_key(digest.key, TeamDataKey.DASHBOARDS, team.id), json.dumps([{"name": "Dashboard", "id": 1}]))-- mock_org = MagicMock()- mock_org.id = UUID("12345678-1234-1234-1234-123456789abc")- mock_org.name = "Test Organization"-- mock_member = MagicMock()- mock_user = MagicMock()- mock_user.id = 100- mock_user.distinct_id = "user-100"- mock_user.email = "[email protected]"- mock_member.user = mock_user-- # Pre-populate Redis with organization digest- org_digest_json = """{- "id": "12345678-1234-1234-1234-123456789abc",- "name": "Test Organization",- "created_at": "2024-01-01T00:00:00Z",- "team_digests": [- {- "id": 1,- "name": "Test Team",- "dashboards": [{"name": "Test Dashboard", "id": 1}],- "event_definitions": [],- "experiments_launched": [- {"name": "Experiment A", "id": 1, "start_date": "2024-01-01T00:00:00Z"},- {"name": "Experiment B", "id": 2, "start_date": "2024-01-01T00:00:00Z"}- ],- "experiments_completed": [],- "external_data_sources": [- {"source_type": "stripe", "id": "12345678-1234-1234-1234-123456789abc"}- ],- "feature_flags": [],- "filters": [],- "expiring_recordings": {"recording_count": 0},- "surveys_launched": []- }- ]- }"""- await mock_redis.setex(f"{digest.key}-{mock_org.id}", 3600, org_digest_json)-- # Add user notification- await mock_redis.sadd(f"{digest.key}-user-notify-100", "1")-- mock_org_queryset = MockAsyncQuerySet([mock_org])- mock_member_queryset = MockAsyncQuerySet([mock_member])-- mock_ph_client = MagicMock()- mock_ph_client.capture = MagicMock()-- mock_messaging_record = MagicMock()- mock_messaging_record.sent_at = None-- mock_messaging_objects = MagicMock()- mock_messaging_objects.aget_or_create = AsyncMock(return_value=(mock_messaging_record, True))-- with patch("posthog.temporal.weekly_digest.activities.query_orgs_for_digest", return_value=mock_org_queryset):- with patch("posthog.temporal.weekly_digest.activities.query_org_members", return_value=mock_member_queryset):- with patch("posthog.temporal.weekly_digest.activities.get_ph_client", return_value=mock_ph_client):- with patch("posthog.temporal.weekly_digest.activities.MessagingRecord.objects", mock_messaging_objects):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await send_weekly_digest_batch(input_data)-- # In dry run mode, PostHog client should not be called- mock_ph_client.capture.assert_not_called()---async def test_generate_product_suggestion_lookup(mock_redis, common_input, digest):- """Test that an org's active product push campaign becomes one suggestion per opted-in user."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ redis_servers.digest.set(+ team_data_key(digest.key, TeamDataKey.EXPIRING_RECORDINGS, team.id), json.dumps({"recording_count": 7}))+ organization_index = list(Organization.objects.order_by("id").values_list("id", flat=True)).index(organization.id)- organization_id = UUID("12345678-1234-1234-1234-123456789abc")- mock_team = MagicMock()- mock_team.id = 1- mock_team.project_id = 1- mock_team.organization_id = organization_id-- mock_user = MagicMock()- mock_user.id = 100- mock_user.allow_sidebar_suggestions = True-- # Opted out of suggestions, so the campaign must not reach them.- mock_opted_out_user = MagicMock()- mock_opted_out_user.id = 101- mock_opted_out_user.allow_sidebar_suggestions = False-- campaigns = [{"product_key": "session_replay", "reason_text": "Give replay a go"}]-- mock_team_queryset = MockAsyncQuerySet([mock_team])-- async def async_user_generator():- for user in [mock_user, mock_opted_out_user]:- yield user-- async def users_wrapper():- return async_user_generator()-- async def project_uses_product_wrapper(*args, **kwargs):- return False+ run_sync(+ generate_organization_digest_batch,+ GenerateOrganizationDigestInput(+ batch=(organization_index, organization_index + 1), digest=digest, common=common_input+ ),+ )- def fake_database_sync_to_async(fn):- # The activity wraps two different sync callables; dispatch on which one.- if fn is project_uses_product:- return project_uses_product_wrapper- return users_wrapper+ stored = json.loads(redis_servers.digest.get(org_digest_key(digest.key, organization.id)))+ assert stored["name"] == organization.name+ assert [td["id"] for td in stored["team_digests"]] == sorted([team.id, silent_team.id])+ by_team = {td["id"]: td for td in stored["team_digests"]}+ assert by_team[team.id]["dashboards"] == [{"name": "Dashboard", "id": 1}]+ assert by_team[team.id]["expiring_recordings"] == {"recording_count": 7}+ assert by_team[silent_team.id]["dashboards"] == []+ assert by_team[silent_team.id]["expiring_recordings"] == {"recording_count": 0}+ assert by_team[silent_team.id]["usage_trends"] == {"metrics": []}- async def mock_queryset_to_list(qs):- return campaigns- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch("posthog.temporal.weekly_digest.activities.query_org_product_push_campaigns"):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch(- "posthog.temporal.weekly_digest.activities.database_sync_to_async",- side_effect=fake_database_sync_to_async,- ):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_product_suggestion_lookup(input_data)+def _org_digest_json(organization: Organization, team: Team) -> str:+ return json.dumps(+ {+ "id": str(organization.id),+ "name": organization.name,+ "created_at": "2024-01-01T00:00:00Z",+ "team_digests": [+ {+ "id": team.id,+ "name": team.name,+ "dashboards": [{"name": "Test Dashboard", "id": 1}],+ "event_definitions": [],+ "experiments_launched": [+ {"name": "Experiment A", "id": 1, "start_date": "2024-01-01T00:00:00Z"},+ {"name": "Experiment B", "id": 2, "start_date": "2024-01-01T00:00:00Z"},+ ],+ "experiments_completed": [],+ "external_data_sources": [{"source_type": "stripe", "id": str(uuid4())}],+ "feature_flags": [],+ "filters": [],+ "expiring_recordings": {"recording_count": 0},+ "surveys_launched": [],+ }+ ],+ }+ )- assert f"{digest.key}-product-suggestion-101" not in mock_redis.data- stored_data = json.loads(mock_redis.data[f"{digest.key}-product-suggestion-100"])- assert stored_data["team_id"] == mock_team.id- assert stored_data["product_path"] == "Session replay"- assert stored_data["reason_text"] == "Give replay a go"+def _send_input(+ organization: Organization, digest: Digest, common: CommonInput, dry_run: bool+) -> SendWeeklyDigestBatchInput:+ organization_index = list(Organization.objects.order_by("id").values_list("id", flat=True)).index(organization.id)+ return SendWeeklyDigestBatchInput(+ batch=(organization_index, organization_index + 1),+ dry_run=dry_run,+ allow_already_sent=False,+ digest=digest,+ common=common,+ )-async def test_generate_product_suggestion_lookup_skips_projects_already_using_the_product(- mock_redis, common_input, digest+ "dry_run,already_sent,expected_captures",+ [+ (False, False, 1),+ (True, False, 0),+ (False, True, 0),+ ],+)+def test_send_weekly_digest_batch_emails_subscribed_members_once(+ dry_run, already_sent, expected_captures, organization, team, redis_servers, common_input, digest):- """Test that a project already using the pushed product isn't nudged about it."""- input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ subscribed = create_user(organization, "[email protected]")+ create_user(organization, "[email protected]")+ redis_servers.digest.set(org_digest_key(digest.key, organization.id), _org_digest_json(organization, team))+ redis_servers.digest.sadd(user_data_key(digest.key, UserDataKey.NOTIFY_TEAMS, subscribed.id), team.id)+ redis_servers.digest.set(+ user_data_key(digest.key, UserDataKey.PRODUCT_SUGGESTION, subscribed.id),+ json.dumps({"team_id": team.id, "product_path": "Error tracking", "reason_text": None}),)+ if already_sent:+ record, _ = MessagingRecord.objects.get_or_create(raw_email=f"org_{organization.id}", campaign_key=digest.key)+ record.sent_at = timezone.now()+ record.save()+ ph_client = MagicMock()++ with patch("posthog.temporal.weekly_digest.activities.get_ph_client", return_value=ph_client):+ run_sync(send_weekly_digest_batch, _send_input(organization, digest, common_input, dry_run=dry_run))++ assert ph_client.capture.call_count == expected_captures+ record = MessagingRecord.objects.get(campaign_key=digest.key)+ # A dry run must not stamp the record, or the real run that follows would skip the organization.+ assert (record.sent_at is not None) is (not dry_run)+ if expected_captures == 0:+ return++ capture = ph_client.capture.call_args.kwargs+ assert capture["distinct_id"] == subscribed.distinct_id+ assert capture["event"] == "transactional email"+ assert capture["groups"]["organization"] == str(organization.id)+ (team_payload,) = capture["properties"]["teams"]+ assert team_payload["team_id"] == team.id+ assert team_payload["report"]["new_product_suggestion"] == {+ "product_path": "Error tracking",+ "reason_text": DEFAULT_PRODUCT_SUGGESTION_TEXT,+ }++[email protected](name="send-weekly-digest-batch-body", no_thread_cancel_exception=True)+def send_weekly_digest_batch_body(input: SendWeeklyDigestBatchInput) -> None:+ # Runs the sync body under a test activity context. Without the thread cancel exception, cancelling+ # only sets the cancellation event, which is all a worker thread behind `@asyncify` receives.+ inspect.unwrap(send_weekly_digest_batch)(input)- mock_team = MagicMock()- mock_team.id = 1- mock_team.project_id = 1- mock_team.organization_id = UUID("12345678-1234-1234-1234-123456789abc")-- mock_user = MagicMock()- mock_user.id = 100- mock_user.allow_sidebar_suggestions = True-- async def async_user_generator():- yield mock_user-- async def users_wrapper():- return async_user_generator()-- async def project_uses_product_wrapper(*args, **kwargs):- return True-- def fake_database_sync_to_async(fn):- if fn is project_uses_product:- return project_uses_product_wrapper- return users_wrapper- async def mock_queryset_to_list(qs):- return [{"product_key": "session_replay", "reason_text": None}]-- with patch(- "posthog.temporal.weekly_digest.activities.query_teams_for_digest",- return_value=MockAsyncQuerySet([mock_team]),+def test_send_weekly_digest_batch_stops_sending_once_the_activity_is_cancelled(+ activity_environment, organization, team, redis_servers, common_input, digest+):+ members = [create_user(organization, f"member-{index}@example.com") for index in range(3)]+ redis_servers.digest.set(org_digest_key(digest.key, organization.id), _org_digest_json(organization, team))+ for member in members:+ redis_servers.digest.sadd(user_data_key(digest.key, UserDataKey.NOTIFY_TEAMS, member.id), team.id)+ ph_client = MagicMock()+ ph_client.capture.side_effect = lambda **_: activity_environment.cancel()++ with (+ patch("posthog.temporal.weekly_digest.activities.get_ph_client", return_value=ph_client),+ pytest.raises(ActivityCancelled),):- with patch("posthog.temporal.weekly_digest.activities.query_org_product_push_campaigns"):- with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch(- "posthog.temporal.weekly_digest.activities.database_sync_to_async",- side_effect=fake_database_sync_to_async,- ):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- await generate_product_suggestion_lookup(input_data)-- assert mock_redis.data == {}---async def test_send_weekly_digest_batch_with_product_suggestion(mock_redis, common_input, digest):- """Test sending weekly digest batch includes single product suggestion in payload."""- batch = (0, 1)- input_data = SendWeeklyDigestBatchInput(- batch=batch, dry_run=True, allow_already_sent=False, digest=digest, common=common_input- )-- mock_org = MagicMock()- mock_org.id = UUID("12345678-1234-1234-1234-123456789abc")- mock_org.name = "Test Organization"-- mock_member = MagicMock()- mock_user = MagicMock()- mock_user.id = 100- mock_user.distinct_id = "user-100"- mock_user.email = "[email protected]"- mock_member.user = mock_user-- # Pre-populate Redis with organization digest- org_digest_json = """{- "id": "12345678-1234-1234-1234-123456789abc",- "name": "Test Organization",- "created_at": "2024-01-01T00:00:00Z",- "team_digests": [- {- "id": 1,- "name": "Test Team",- "dashboards": [{"name": "Test Dashboard", "id": 1}],- "event_definitions": [],- "experiments_launched": [- {"name": "Experiment A", "id": 1, "start_date": "2024-01-01T00:00:00Z"},- {"name": "Experiment B", "id": 2, "start_date": "2024-01-01T00:00:00Z"}- ],- "experiments_completed": [],- "external_data_sources": [- {"source_type": "stripe", "id": "12345678-1234-1234-1234-123456789abc"}- ],- "feature_flags": [],- "filters": [],- "expiring_recordings": {"recording_count": 0},- "surveys_launched": []- }- ]- }"""- await mock_redis.setex(f"{digest.key}-{mock_org.id}", 3600, org_digest_json)-- # Add user notification- await mock_redis.sadd(f"{digest.key}-user-notify-100", "1")+ activity_environment.run(+ send_weekly_digest_batch_body, _send_input(organization, digest, common_input, dry_run=False)+ )- # Add single product suggestion for user 100 (team_id matches the team in the digest)- suggestion_json = '{"team_id": 1, "product_path": "Error tracking", "reason_text": null}'- await mock_redis.setex(f"{digest.key}-product-suggestion-100", 3600, suggestion_json)-- mock_org_queryset = MockAsyncQuerySet([mock_org])- mock_member_queryset = MockAsyncQuerySet([mock_member])-- mock_ph_client = MagicMock()- mock_ph_client.capture = MagicMock()-- mock_messaging_record = MagicMock()- mock_messaging_record.sent_at = None-- mock_messaging_objects = MagicMock()- mock_messaging_objects.aget_or_create = AsyncMock(return_value=(mock_messaging_record, True))-- captured_payload = {}-- # Capture the logged payload in dry run mode- with patch("posthog.temporal.weekly_digest.activities.query_orgs_for_digest", return_value=mock_org_queryset):- with patch("posthog.temporal.weekly_digest.activities.query_org_members", return_value=mock_member_queryset):- with patch("posthog.temporal.weekly_digest.activities.get_ph_client", return_value=mock_ph_client):- with patch("posthog.temporal.weekly_digest.activities.MessagingRecord.objects", mock_messaging_objects):- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- with patch("posthog.temporal.weekly_digest.activities.LOGGER") as mock_logger:- mock_bound_logger = MagicMock()- mock_logger.bind.return_value = mock_bound_logger-- def capture_info(*args, **kwargs):- if "digest" in kwargs:- captured_payload.update(kwargs["digest"])-- mock_bound_logger.info = capture_info- await send_weekly_digest_batch(input_data)-- # Verify single product suggestion was included in the team's report- assert "teams" in captured_payload- teams = captured_payload["teams"]- assert len(teams) == 1- team_report = teams[0]["report"]- assert "new_product_suggestion" in team_report- suggestion = team_report["new_product_suggestion"]- assert suggestion["product_path"] == "Error tracking"- assert suggestion["reason_text"] == DEFAULT_PRODUCT_SUGGESTION_TEXT+ assert ph_client.capture.call_count == 1+ assert MessagingRecord.objects.get(campaign_key=digest.key).sent_at is not None@pytest.mark.parametrize(@@ -1033,7 +633,7 @@ def test_query_team_usage_trends_windows_persons_and_test_accounts(team):assert (users.label, users.current, users.previous) == ("Active users", 2, 1)@pytest.mark.parametrize("side_effects,should_raise",[@@ -1043,22 +643,21 @@ def test_query_team_usage_trends_windows_persons_and_test_accounts(team):([Exception("boom"), UsageTrends(metrics=[])], False),],)-async def test_generate_usage_trends_lookup_raises_only_when_every_team_fails(- side_effects, should_raise, mock_redis, common_input, digest+def test_generate_usage_trends_lookup_raises_only_when_every_team_fails(+ side_effects, should_raise, organization, team, redis_servers, common_input, digest):+ second_team = _make_team(organization, "second team")input_data = GenerateDigestDataBatchInput(- team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ team_id_range=TeamIdRange(start=team.id, end=second_team.id + 1), digest=digest, common=common_input)- team_1, team_2 = MagicMock(), MagicMock()- team_1.id, team_2.id = 1, 2- mock_team_queryset = MockAsyncQuerySet([team_1, team_2])-- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch("posthog.temporal.weekly_digest.activities.database_sync_to_async") as mock_sync:- mock_sync.return_value = AsyncMock(side_effect=side_effects)- with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):- if should_raise:- with pytest.raises(RuntimeError):- await generate_usage_trends_lookup(input_data)- else:- await generate_usage_trends_lookup(input_data)++ with patch("posthog.temporal.weekly_digest.activities._query_team_usage_trends", side_effect=side_effects):+ if should_raise:+ with pytest.raises(RuntimeError):+ run_sync(generate_usage_trends_lookup, input_data)+ else:+ run_sync(generate_usage_trends_lookup, input_data)+ assert (+ redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.USAGE_TRENDS, second_team.id))+ is not None+ )diff --git a/posthog/temporal/weekly_digest/README.md b/posthog/temporal/weekly_digest/README.mdindex 8ee01cfd87b3..a2cab2505c91 100644--- a/posthog/temporal/weekly_digest/README.md+++ b/posthog/temporal/weekly_digest/README.md@@ -10,6 +10,10 @@ The digest is generated and sent via two Temporal workflows:2. **SendWeeklyDigestWorkflow** - Reads from Redis and sends personalized emailsTeam-level generation keeps at most 100 activities pending per workflow to stay below Temporal's pending-activity limit.+Activities are sync bodies wrapped in `@asyncify`, so each one runs on its own worker thread with its own database connection.+Django's async ORM and `database_sync_to_async` default to one shared thread per process, which serializes every database call across all concurrent activities.+Cancelling an activity cancels only the coroutine that awaits the thread, so the send loop checks the cancellation event before each organization and recipient.+A body that runs on the event loop also trips Django's async-unsafe guard as soon as a helper such as `should_send_notification` queries the database.Every team range and report generator must finish before organization aggregation starts.A Temporal patch marker preserves the activity scheduling behavior when replaying older histories.diff --git a/posthog/temporal/weekly_digest/activities.py b/posthog/temporal/weekly_digest/activities.pyindex ae6f72bc1fa8..db79f887f3c0 100644--- a/posthog/temporal/weekly_digest/activities.py+++ b/posthog/temporal/weekly_digest/activities.py@@ -1,16 +1,15 @@from collections.abc import Callablefrom datetime import UTC, datetime-from typing import Optional-from uuid import uuid4from django.conf import settingsfrom django.db.models import QuerySetfrom django.utils import timezone-import redis.asyncio as redis+import redisfrom posthoganalytics import Posthogfrom pydantic import ValidationErrorfrom structlog.contextvars import bind_contextvars+from structlog.typing import FilteringBoundLoggerfrom temporalio import activityfrom posthog.schema import HogQLFilters@@ -18,18 +17,20 @@ from posthog.schema import HogQLFiltersfrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_query+from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.connection import Workload+from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.models.messaging import MessagingRecord+from posthog.models.organization_notification_lock import notification_locks_for_usersfrom posthog.models.team import Teamfrom posthog.ph_client import get_client as get_ph_clientfrom posthog.session_recordings.queries.session_replay_events import SessionReplayEventsfrom posthog.session_recordings.session_recording_playlist_api import PLAYLIST_COUNT_REDIS_PREFIX-from posthog.sync import database_sync_to_asyncfrom posthog.tasks.email import NotificationSetting, should_send_notificationfrom posthog.tasks.email_utils import compute_week_over_week_change-from posthog.temporal.common.clickhouse import get_client as get_ch_client-from posthog.temporal.common.heartbeat import Heartbeater+from posthog.temporal.common.heartbeat_sync import HeartbeaterSyncfrom posthog.temporal.common.logger import get_write_only_logger+from posthog.temporal.common.utils import asyncifyfrom posthog.temporal.weekly_digest.keys import TeamDataKey, UserDataKey, org_digest_key, team_data_key, user_data_keyfrom posthog.temporal.weekly_digest.queries import (query_experiments_completed,@@ -47,10 +48,8 @@ from posthog.temporal.weekly_digest.queries import (query_surveys_launched,query_team_ids_for_digest,query_teams_for_digest,- queryset_to_list,)from posthog.temporal.weekly_digest.types import (- ClickHouseResponse,CommonInput,DashboardList,DigestProductSuggestion,@@ -77,15 +76,36 @@ from posthog.temporal.weekly_digest.types import (from products.growth.backend.product_push.selection import project_uses_product, resolve_product_path+# Every activity below is a sync body behind `@asyncify`, which runs it on the worker's thread pool.+# Django's async ORM and `database_sync_to_async` both default to `thread_sensitive=True`, which+# funnels every database call from every concurrent activity in the process through one shared+# thread. Sync bodies on the pool give each activity its own thread and database connection, and+# keep Django's async-unsafe guard from tripping on helpers such as `should_send_notification`.++LOGGER = get_write_only_logger()+def _redis_url(common: CommonInput) -> str:return f"redis://{common.redis_host}:{common.redis_port}?decode_responses=true"-async def _load_playlist_counts_from_django_cache(r: redis.Redis, filters: FilterList) -> list[PlaylistCount | None]:- resp: list[str | None] = await r.mget(- [f"{PLAYLIST_COUNT_REDIS_PREFIX}{_filter.short_id}" for _filter in filters.root]+def _digest_redis(common: CommonInput) -> redis.Redis:+ return redis.Redis.from_url(_redis_url(common))+++def _bind_batch_logger(input: GenerateDigestDataBatchInput) -> FilteringBoundLogger:+ bind_contextvars(+ digest_key=input.digest.key,+ period_start=input.digest.period_start,+ period_end=input.digest.period_end,+ team_id_start=input.team_id_range.start,+ team_id_end=input.team_id_range.end,)+ return LOGGER.bind()+++def _load_playlist_counts_from_django_cache(r: redis.Redis, filters: FilterList) -> list[PlaylistCount | None]:+ resp: list[bytes | None] = r.mget([f"{PLAYLIST_COUNT_REDIS_PREFIX}{_filter.short_id}" for _filter in filters.root])playlist_counts: list[PlaylistCount | None] = []@@ -103,9 +123,6 @@ async def _load_playlist_counts_from_django_cache(r: redis.Redis, filters: Filtereturn playlist_counts-LOGGER = get_write_only_logger()--def _teams_in_range(input: GenerateDigestDataBatchInput, *, with_organization: bool = False) -> QuerySet:# An id predicate lets Postgres seek to the first row of the batch on the primary key.# LIMIT/OFFSET made it build and discard every row before the batch instead.@@ -114,243 +131,241 @@ def _teams_in_range(input: GenerateDigestDataBatchInput, *, with_organization: b)-async def generate_digest_data_lookup(+def generate_digest_data_lookup(input: GenerateDigestDataBatchInput,key_kind: TeamDataKey,query_func: Callable[[datetime, datetime], QuerySet],resource_type: DigestResourceType,per_team_limit: int | None = None,) -> None:- async with Heartbeater():- bind_contextvars(- digest_key=input.digest.key,- period_start=input.digest.period_start,- period_end=input.digest.period_end,- team_id_start=input.team_id_range.start,- team_id_end=input.team_id_range.end,- )- logger = LOGGER.bind()- logger.info("Generating digest data batch", key_kind=key_kind)+ logger = _bind_batch_logger(input)+ logger.info("Generating digest data batch", key_kind=key_kind)- resource_count = 0- team_count = 0+ resource_count = 0+ team_count = 0- async with redis.from_url(_redis_url(input.common)) as r:- db_query: QuerySet = query_func(input.digest.period_start, input.digest.period_end)+ with _digest_redis(input.common) as r:+ db_query: QuerySet = query_func(input.digest.period_start, input.digest.period_end)- async for team in _teams_in_range(input):- try:- team_query = db_query.filter(team_id=team.id)- if per_team_limit is not None:- team_query = team_query[:per_team_limit]- digest_data = resource_type(await queryset_to_list(team_query))-- key = team_data_key(input.digest.key, key_kind, team.id)- await r.setex(key, input.common.redis_ttl, digest_data.model_dump_json())+ for team in _teams_in_range(input):+ try:+ team_query = db_query.filter(team_id=team.id)+ if per_team_limit is not None:+ team_query = team_query[:per_team_limit]+ digest_data = resource_type(list(team_query))- team_count += 1- resource_count += len(digest_data.root)- except Exception as e:- logger.warning(- f"Failed to generate digest data for team {team.id}, skipping...", error=str(e), team_id=team.id- )- continue+ key = team_data_key(input.digest.key, key_kind, team.id)+ r.setex(key, input.common.redis_ttl, digest_data.model_dump_json())- logger.info(- "Finished generating digest data batch",- key_kind=key_kind,- resource_count=resource_count,- team_count=team_count,- )+ team_count += 1+ resource_count += len(digest_data.root)+ except Exception as e:+ logger.warning(+ f"Failed to generate digest data for team {team.id}, skipping...", error=str(e), team_id=team.id+ )+ continue++ logger.info(+ "Finished generating digest data batch",+ key_kind=key_kind,+ resource_count=resource_count,+ team_count=team_count,+ )@activity.defn(name="generate-dashboard-lookup")-async def generate_dashboard_lookup(input: GenerateDigestDataBatchInput) -> None:- return await generate_digest_data_lookup(- input,- key_kind=TeamDataKey.DASHBOARDS,- query_func=query_new_dashboards,- resource_type=DashboardList,- )+@asyncify+def generate_dashboard_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ generate_digest_data_lookup(+ input,+ key_kind=TeamDataKey.DASHBOARDS,+ query_func=query_new_dashboards,+ resource_type=DashboardList,+ )@activity.defn(name="generate-event-definition-lookup")-async def generate_event_definition_lookup(input: GenerateDigestDataBatchInput) -> None:- return await generate_digest_data_lookup(- input,- key_kind=TeamDataKey.EVENT_DEFINITIONS,- query_func=query_new_event_definitions,- resource_type=EventDefinitionList,- )+@asyncify+def generate_event_definition_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ generate_digest_data_lookup(+ input,+ key_kind=TeamDataKey.EVENT_DEFINITIONS,+ query_func=query_new_event_definitions,+ resource_type=EventDefinitionList,+ )@activity.defn(name="generate-experiment-completed-lookup")-async def generate_experiment_completed_lookup(input: GenerateDigestDataBatchInput) -> None:- await generate_digest_data_lookup(- input,- key_kind=TeamDataKey.EXPERIMENTS_COMPLETED,- query_func=query_experiments_completed,- resource_type=ExperimentList,- )+@asyncify+def generate_experiment_completed_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ generate_digest_data_lookup(+ input,+ key_kind=TeamDataKey.EXPERIMENTS_COMPLETED,+ query_func=query_experiments_completed,+ resource_type=ExperimentList,+ )@activity.defn(name="generate-experiment-launched-lookup")-async def generate_experiment_launched_lookup(input: GenerateDigestDataBatchInput) -> None:- return await generate_digest_data_lookup(- input,- key_kind=TeamDataKey.EXPERIMENTS_LAUNCHED,- query_func=query_experiments_launched,- resource_type=ExperimentList,- )+@asyncify+def generate_experiment_launched_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ generate_digest_data_lookup(+ input,+ key_kind=TeamDataKey.EXPERIMENTS_LAUNCHED,+ query_func=query_experiments_launched,+ resource_type=ExperimentList,+ )@activity.defn(name="generate-external-data-source-lookup")-async def generate_external_data_source_lookup(input: GenerateDigestDataBatchInput) -> None:- return await generate_digest_data_lookup(- input,- key_kind=TeamDataKey.EXTERNAL_DATA_SOURCES,- query_func=query_new_external_data_sources,- resource_type=ExternalDataSourceList,- )+@asyncify+def generate_external_data_source_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ generate_digest_data_lookup(+ input,+ key_kind=TeamDataKey.EXTERNAL_DATA_SOURCES,+ query_func=query_new_external_data_sources,+ resource_type=ExternalDataSourceList,+ )@activity.defn(name="generate-feature-flag-lookup")-async def generate_feature_flag_lookup(input: GenerateDigestDataBatchInput) -> None:- return await generate_digest_data_lookup(- input,- key_kind=TeamDataKey.FEATURE_FLAGS,- query_func=query_new_feature_flags,- resource_type=FeatureFlagList,- )+@asyncify+def generate_feature_flag_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ generate_digest_data_lookup(+ input,+ key_kind=TeamDataKey.FEATURE_FLAGS,+ query_func=query_new_feature_flags,+ resource_type=FeatureFlagList,+ )@activity.defn(name="generate-survey-lookup")-async def generate_survey_lookup(input: GenerateDigestDataBatchInput) -> None:- return await generate_digest_data_lookup(- input,- key_kind=TeamDataKey.SURVEYS_LAUNCHED,- query_func=query_surveys_launched,- resource_type=SurveyList,- )+@asyncify+def generate_survey_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ generate_digest_data_lookup(+ input,+ key_kind=TeamDataKey.SURVEYS_LAUNCHED,+ query_func=query_surveys_launched,+ resource_type=SurveyList,+ )[email protected](name="generate-filter-lookup")-async def generate_filter_lookup(input: GenerateDigestDataBatchInput) -> None:- async with Heartbeater():- bind_contextvars(- digest_key=input.digest.key,- period_start=input.digest.period_start,- period_end=input.digest.period_end,- team_id_start=input.team_id_range.start,- team_id_end=input.team_id_range.end,- )- logger = LOGGER.bind()- logger.info(f"Generating Replay filter batch")+def _generate_filter_lookup(input: GenerateDigestDataBatchInput) -> None:+ logger = _bind_batch_logger(input)+ logger.info("Generating Replay filter batch")- filter_count = 0- team_count = 0+ filter_count = 0+ team_count = 0- if input.common.django_redis_url is None:- logger.error(f"Unable to generate Replay filter batch, missing URL for Django Redis...")- return+ if input.common.django_redis_url is None:+ logger.error("Unable to generate Replay filter batch, missing URL for Django Redis...")+ return- async with (- redis.from_url(_redis_url(input.common)) as r,- redis.from_url(input.common.django_redis_url) as django_cache,- ):- query_filters: QuerySet = query_saved_filters(input.digest.period_start, input.digest.period_end)+ with (+ _digest_redis(input.common) as r,+ redis.Redis.from_url(input.common.django_redis_url) as django_cache,+ ):+ query_filters: QuerySet = query_saved_filters(input.digest.period_start, input.digest.period_end)- async for team in _teams_in_range(input):- try:- filters = FilterList(await queryset_to_list(query_filters.filter(team_id=team.id)))- playlist_counts = await _load_playlist_counts_from_django_cache(django_cache, filters)+ for team in _teams_in_range(input):+ try:+ filters = FilterList(list(query_filters.filter(team_id=team.id)))+ playlist_counts = _load_playlist_counts_from_django_cache(django_cache, filters)- for filter, playlist_count in zip(filters.root, playlist_counts):- if playlist_count is not None:- filter.recording_count = len(playlist_count.session_ids)- filter.more_available = playlist_count.has_more+ for filter, playlist_count in zip(filters.root, playlist_counts):+ if playlist_count is not None:+ filter.recording_count = len(playlist_count.session_ids)+ filter.more_available = playlist_count.has_more- ordered_filters = filters.order_by_recording_count()+ ordered_filters = filters.order_by_recording_count()- key = team_data_key(input.digest.key, TeamDataKey.SAVED_FILTERS, team.id)- await r.setex(key, input.common.redis_ttl, ordered_filters.model_dump_json())+ key = team_data_key(input.digest.key, TeamDataKey.SAVED_FILTERS, team.id)+ r.setex(key, input.common.redis_ttl, ordered_filters.model_dump_json())- team_count += 1- filter_count += len(ordered_filters.root)- except Exception as e:- logger.warning(- f"Failed to generate Replay filters for team {team.id}, skipping...",- error=str(e),- team_id=team.id,- )- continue+ team_count += 1+ filter_count += len(ordered_filters.root)+ except Exception as e:+ logger.warning(+ f"Failed to generate Replay filters for team {team.id}, skipping...",+ error=str(e),+ team_id=team.id,+ )+ continue++ logger.info(+ "Finished generating Replay filter batch",+ filter_count=filter_count,+ team_count=team_count,+ )- logger.info(- f"Finished generating Replay filter batch",- filter_count=filter_count,- team_count=team_count,- )+[email protected](name="generate-filter-lookup")+@asyncify+def generate_filter_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ _generate_filter_lookup(input)TTL_THRESHOLD = 10 # days[email protected](name="generate-recording-lookup")-async def generate_recording_lookup(input: GenerateDigestDataBatchInput) -> None:- async with Heartbeater():- bind_contextvars(- digest_key=input.digest.key,- period_start=input.digest.period_start,- period_end=input.digest.period_end,- team_id_start=input.team_id_range.start,- team_id_end=input.team_id_range.end,- )- logger = LOGGER.bind()- logger.info(f"Generating Replay recording count batch")+def _generate_recording_lookup(input: GenerateDigestDataBatchInput) -> None:+ logger = _bind_batch_logger(input)+ logger.info("Generating Replay recording count batch")- recording_count = 0- team_count = 0+ recording_count = 0+ team_count = 0- async with redis.from_url(_redis_url(input.common)) as r, get_ch_client() as ch_client:- ch_query: str = SessionReplayEvents.count_soon_to_expire_sessions_query(format="JSON")+ ch_query: str = SessionReplayEvents.count_soon_to_expire_sessions_query()- async for team in _teams_in_range(input):- try:- parameters = {+ with _digest_redis(input.common) as r:+ for team in _teams_in_range(input):+ try:+ tag_queries(product=Product.INTERNAL, feature=Feature.DIGEST, team_id=team.id)+ rows = sync_execute(+ ch_query,+ {"team_id": team.id,"python_now": datetime.now(UTC),"ttl_threshold": TTL_THRESHOLD,- }+ },+ workload=Workload.OFFLINE,+ team_id=team.id,+ )+ expiring_recordings = RecordingCount(recording_count=int(rows[0][0]) if rows else 0)- raw_response: bytes = b""- async with ch_client.aget_query(- query=ch_query,- query_parameters=parameters,- query_id=str(uuid4()),- ) as ch_response:- raw_response = await ch_response.content.read()+ key = team_data_key(input.digest.key, TeamDataKey.EXPIRING_RECORDINGS, team.id)+ r.setex(key, input.common.redis_ttl, expiring_recordings.model_dump_json())- response = ClickHouseResponse.model_validate_json(raw_response)- expiring_recordings = RecordingCount.model_validate(response.data[0])-- key = team_data_key(input.digest.key, TeamDataKey.EXPIRING_RECORDINGS, team.id)- await r.setex(key, input.common.redis_ttl, expiring_recordings.model_dump_json())+ team_count += 1+ recording_count += expiring_recordings.recording_count+ except Exception as e:+ logger.warning(+ f"Failed to generate Replay recording count for team {team.id}, skipping...",+ error=str(e),+ team_id=team.id,+ )+ continue++ logger.info(+ "Finished generating Replay recording count batch",+ recording_count=recording_count,+ team_count=team_count,+ )- team_count += 1- recording_count += expiring_recordings.recording_count- except Exception as e:- logger.warning(- f"Failed to generate Replay recording count for team {team.id}, skipping...",- error=str(e),- team_id=team.id,- )- continue- logger.info(- f"Finished generating Replay recording count batch",- recording_count=recording_count,- team_count=team_count,- )[email protected](name="generate-recording-lookup")+@asyncify+def generate_recording_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ _generate_recording_lookup(input)# Issue names come from exception ingestion, so a noisy (or malicious) client can create@@ -360,16 +375,18 @@ NEW_ERROR_ISSUES_PER_TEAM_LIMIT = 5@activity.defn(name="generate-error-issue-lookup")-async def generate_error_issue_lookup(input: GenerateDigestDataBatchInput) -> None:+@asyncify+def generate_error_issue_lookup(input: GenerateDigestDataBatchInput) -> None:# New error-tracking issues follow the standard "created within window" lookup,# exactly like dashboards / feature flags.- return await generate_digest_data_lookup(- input,- key_kind=TeamDataKey.ERROR_ISSUES,- query_func=query_new_error_issues,- resource_type=ErrorIssueList,- per_team_limit=NEW_ERROR_ISSUES_PER_TEAM_LIMIT,- )+ with HeartbeaterSync(logger=LOGGER):+ generate_digest_data_lookup(+ input,+ key_kind=TeamDataKey.ERROR_ISSUES,+ query_func=query_new_error_issues,+ resource_type=ErrorIssueList,+ per_team_limit=NEW_ERROR_ISSUES_PER_TEAM_LIMIT,+ )# Weekly usage snapshot per team. Written in HogQL so it inherits the team's test-account@@ -405,10 +422,7 @@ def _usage_trend_metric(label: str, current: int, previous: int) -> UsageTrendMedef _query_team_usage_trends(team_id: int, period_start: datetime, period_end: datetime) -> UsageTrends | None:- """Run the per-team usage snapshot on the offline cluster. Returns None for inactive teams.-- Synchronous (HogQL execution is sync); callers wrap it with ``database_sync_to_async``.- """+ """Run the per-team usage snapshot on the offline cluster. Returns None for inactive teams."""team = Team.objects.get(pk=team_id)window = period_end - period_startresponse = execute_hogql_query(@@ -442,176 +456,186 @@ def _query_team_usage_trends(team_id: int, period_start: datetime, period_end: d)[email protected](name="generate-usage-trends-lookup")-async def generate_usage_trends_lookup(input: GenerateDigestDataBatchInput) -> None:- async with Heartbeater():- bind_contextvars(- digest_key=input.digest.key,- period_start=input.digest.period_start,- period_end=input.digest.period_end,- team_id_start=input.team_id_range.start,- team_id_end=input.team_id_range.end,- )- logger = LOGGER.bind()- logger.info("Generating usage trends batch")+def _generate_usage_trends_lookup(input: GenerateDigestDataBatchInput) -> None:+ logger = _bind_batch_logger(input)+ logger.info("Generating usage trends batch")- team_count = 0- attempted = 0- error_count = 0+ team_count = 0+ attempted = 0+ error_count = 0- async with redis.from_url(_redis_url(input.common)) as r:- async for team in _teams_in_range(input):- attempted += 1- try:- usage_trends = await database_sync_to_async(_query_team_usage_trends)(- team.id, input.digest.period_start, input.digest.period_end- )- except Exception as e:- error_count += 1- logger.warning(- f"Failed to generate usage trends for team {team.id}, skipping...",- error=str(e),- team_id=team.id,- )- continue+ with _digest_redis(input.common) as r:+ for team in _teams_in_range(input):+ attempted += 1+ try:+ usage_trends = _query_team_usage_trends(team.id, input.digest.period_start, input.digest.period_end)+ except Exception as e:+ error_count += 1+ logger.warning(+ f"Failed to generate usage trends for team {team.id}, skipping...",+ error=str(e),+ team_id=team.id,+ )+ continue- if usage_trends is None:- continue+ if usage_trends is None:+ continue- key = team_data_key(input.digest.key, TeamDataKey.USAGE_TRENDS, team.id)- await r.setex(key, input.common.redis_ttl, usage_trends.model_dump_json())- team_count += 1+ key = team_data_key(input.digest.key, TeamDataKey.USAGE_TRENDS, team.id)+ r.setex(key, input.common.redis_ttl, usage_trends.model_dump_json())+ team_count += 1- # A malformed query (or an offline-cluster outage) fails for every team, which would- # otherwise look identical to "no active teams" and silently ship an empty section for- # the whole batch. Surface it so the activity retries and then fails the run loudly.- if attempted > 0 and error_count == attempted:- raise RuntimeError(f"Usage trends query failed for all {attempted} teams in batch")+ # A malformed query (or an offline-cluster outage) fails for every team, which would+ # otherwise look identical to "no active teams" and silently ship an empty section for+ # the whole batch. Surface it so the activity retries and then fails the run loudly.+ if attempted > 0 and error_count == attempted:+ raise RuntimeError(f"Usage trends query failed for all {attempted} teams in batch")- logger.info("Finished generating usage trends batch", team_count=team_count, error_count=error_count)+ logger.info("Finished generating usage trends batch", team_count=team_count, error_count=error_count)[email protected](name="generate-user-notification-lookup")-async def generate_user_notification_lookup(input: GenerateDigestDataBatchInput) -> None:- async with Heartbeater():- bind_contextvars(- digest_key=input.digest.key, team_id_start=input.team_id_range.start, team_id_end=input.team_id_range.end- )- logger = LOGGER.bind()- logger.info("Generating team access and notification settings batch")[email protected](name="generate-usage-trends-lookup")+@asyncify+def generate_usage_trends_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ _generate_usage_trends_lookup(input)- team_count = 0- user_count = 0- async with redis.from_url(_redis_url(input.common)) as r:- async for team in _teams_in_range(input, with_organization=True):- try:- async for user in await database_sync_to_async(team.all_users_with_access)():- if should_send_notification(user, NotificationSetting.WEEKLY_PROJECT_DIGEST.value, team.id):- key = user_data_key(input.digest.key, UserDataKey.NOTIFY_TEAMS, user.id)- await r.sadd(key, team.id)- await r.expire(key, input.common.redis_ttl)+def _generate_user_notification_lookup(input: GenerateDigestDataBatchInput) -> None:+ bind_contextvars(+ digest_key=input.digest.key, team_id_start=input.team_id_range.start, team_id_end=input.team_id_range.end+ )+ logger = LOGGER.bind()+ logger.info("Generating team access and notification settings batch")- user_count += 1- team_count += 1- except Exception as e:- logger.warning(- f"Failed to generate access and notification settings for team {team.id}, skipping...",- error=str(e),- team_id=team.id,- )- continue+ team_count = 0+ user_count = 0- logger.info(- "Finished generating team access and notification settings batch",- user_count=user_count,- team_count=team_count,- )+ with _digest_redis(input.common) as r:+ for team in _teams_in_range(input, with_organization=True):+ try:+ users = list(team.all_users_with_access())+ # One lookup for the whole team instead of one per user inside should_send_notification.+ locks_by_user = notification_locks_for_users(+ [user.id for user in users], organization_id=team.organization_id+ )+ for user in users:+ if should_send_notification(+ user,+ NotificationSetting.WEEKLY_PROJECT_DIGEST.value,+ team.id,+ locks=locks_by_user.get(user.id, {}),+ ):+ key = user_data_key(input.digest.key, UserDataKey.NOTIFY_TEAMS, user.id)+ r.sadd(key, team.id)+ r.expire(key, input.common.redis_ttl)+ user_count += 1+ team_count += 1+ except Exception as e:+ logger.warning(+ f"Failed to generate access and notification settings for team {team.id}, skipping...",+ error=str(e),+ team_id=team.id,+ )+ continue++ logger.info(+ "Finished generating team access and notification settings batch",+ user_count=user_count,+ team_count=team_count,+ )[email protected](name="generate-product-suggestion-lookup")-async def generate_product_suggestion_lookup(input: GenerateDigestDataBatchInput) -> None:- async with Heartbeater():- bind_contextvars(- digest_key=input.digest.key,- period_start=input.digest.period_start,- period_end=input.digest.period_end,- team_id_start=input.team_id_range.start,- team_id_end=input.team_id_range.end,- )- logger = LOGGER.bind()- logger.info("Generating product suggestions batch")-- team_count = 0- user_count = 0- suggestion_count = 0- users_with_suggestion: set[int] = set()- # Campaigns are org-scoped but this batch walks teams, so cache per org.- campaigns_by_org: dict[str, list[dict]] = {}-- async with redis.from_url(_redis_url(input.common)) as r:- async for team in _teams_in_range(input, with_organization=True):- try:- organization_id = str(team.organization_id)- if organization_id not in campaigns_by_org:- campaigns_by_org[organization_id] = await queryset_to_list(- query_org_product_push_campaigns(organization_id, input.digest.period_end)- )- campaigns = campaigns_by_org[organization_id]- if not campaigns:- team_count += 1- continue- campaign = campaigns[0]- product_path = resolve_product_path(campaign["product_key"])- # The push is org-wide, but a project that already uses the product- # shouldn't be nudged about it - same rule the nav card applies.- if product_path is None or await database_sync_to_async(project_uses_product)(- team.project_id, campaign["product_key"], organization_id- ):- team_count += 1- continue[email protected](name="generate-user-notification-lookup")+@asyncify+def generate_user_notification_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ _generate_user_notification_lookup(input)- async for user in await database_sync_to_async(team.all_users_with_access)():- # Only store one suggestion per user (first one found)- if user.id in users_with_suggestion:- continue- user_count += 1+def _generate_product_suggestion_lookup(input: GenerateDigestDataBatchInput) -> None:+ logger = _bind_batch_logger(input)+ logger.info("Generating product suggestions batch")- if user.allow_sidebar_suggestions is False:- continue+ team_count = 0+ user_count = 0+ suggestion_count = 0+ users_with_suggestion: set[int] = set()+ # Campaigns are org-scoped but this batch walks teams, so cache per org.+ campaigns_by_org: dict[str, list[dict]] = {}- suggestion = DigestProductSuggestion(- team_id=team.id,- product_path=product_path,- reason_text=campaign["reason_text"],- )- key = user_data_key(input.digest.key, UserDataKey.PRODUCT_SUGGESTION, user.id)- await r.setex(key, input.common.redis_ttl, suggestion.model_dump_json())- users_with_suggestion.add(user.id)- suggestion_count += 1+ with _digest_redis(input.common) as r:+ for team in _teams_in_range(input, with_organization=True):+ try:+ organization_id = str(team.organization_id)+ if organization_id not in campaigns_by_org:+ campaigns_by_org[organization_id] = list(+ query_org_product_push_campaigns(organization_id, input.digest.period_end)+ )+ campaigns = campaigns_by_org[organization_id]+ if not campaigns:team_count += 1- except Exception as e:- logger.warning(- f"Failed to generate product suggestions for team {team.id}, skipping...",- error=str(e),+ continue++ campaign = campaigns[0]+ product_path = resolve_product_path(campaign["product_key"])+ # The push is org-wide, but a project that already uses the product+ # shouldn't be nudged about it - same rule the nav card applies.+ if product_path is None or project_uses_product(+ team.project_id, campaign["product_key"], organization_id+ ):+ team_count += 1+ continue++ for user in team.all_users_with_access():+ # Only store one suggestion per user (first one found)+ if user.id in users_with_suggestion:+ continue++ user_count += 1++ if user.allow_sidebar_suggestions is False:+ continue++ suggestion = DigestProductSuggestion(team_id=team.id,+ product_path=product_path,+ reason_text=campaign["reason_text"],)- continue+ key = user_data_key(input.digest.key, UserDataKey.PRODUCT_SUGGESTION, user.id)+ r.setex(key, input.common.redis_ttl, suggestion.model_dump_json())+ users_with_suggestion.add(user.id)+ suggestion_count += 1+ team_count += 1+ except Exception as e:+ logger.warning(+ f"Failed to generate product suggestions for team {team.id}, skipping...",+ error=str(e),+ team_id=team.id,+ )+ continue++ logger.info(+ "Finished generating product suggestions batch",+ user_count=user_count,+ team_count=team_count,+ suggestion_count=suggestion_count,+ )- logger.info(- "Finished generating product suggestions batch",- user_count=user_count,- team_count=team_count,- suggestion_count=suggestion_count,- )+[email protected](name="generate-product-suggestion-lookup")+@asyncify+def generate_product_suggestion_lookup(input: GenerateDigestDataBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ _generate_product_suggestion_lookup(input)@activity.defn(name="count-organizations")-async def count_organizations() -> int:- async with Heartbeater():- return await query_orgs_for_digest().acount()+@asyncify+def count_organizations() -> int:+ with HeartbeaterSync(logger=LOGGER):+ return query_orgs_for_digest().count()def _cut_team_id_ranges(team_ids: list[int], batch_size: int) -> list[TeamIdRange]:@@ -626,143 +650,159 @@ def _cut_team_id_ranges(team_ids: list[int], batch_size: int) -> list[TeamIdRang@activity.defn(name="list-team-id-ranges")-async def list_team_id_ranges(input: CommonInput) -> list[TeamIdRange]:+@asyncify+def list_team_id_ranges(input: CommonInput) -> list[TeamIdRange]:"""One index scan of the team ids replaces a LIMIT/OFFSET scan per batch per generator."""- async with Heartbeater():- return _cut_team_id_ranges(await queryset_to_list(query_team_ids_for_digest()), input.batch_size)-+ with HeartbeaterSync(logger=LOGGER):+ return _cut_team_id_ranges(list(query_team_ids_for_digest()), input.batch_size)[email protected](name="generate-organization-digest-batch")-async def generate_organization_digest_batch(input: GenerateOrganizationDigestInput) -> None:- async with Heartbeater():- bind_contextvars(digest_key=input.digest.key, batch_start=input.batch[0], batch_end=input.batch[1])- logger = LOGGER.bind()- logger.info("Generating organization-level digest batch")- organization_count = 0- team_count = 0-- async with redis.from_url(_redis_url(input.common)) as r:- batch_start, batch_end = input.batch- async for organization in query_orgs_for_digest()[batch_start:batch_end]:- try:- team_digests: list[TeamDigest] = []-- async for team in query_org_teams(organization):- results: list[str | None] = await r.mget(- [- team_data_key(input.digest.key, TeamDataKey.DASHBOARDS, team.id),- team_data_key(input.digest.key, TeamDataKey.EVENT_DEFINITIONS, team.id),- team_data_key(input.digest.key, TeamDataKey.EXPERIMENTS_LAUNCHED, team.id),- team_data_key(input.digest.key, TeamDataKey.EXPERIMENTS_COMPLETED, team.id),- team_data_key(input.digest.key, TeamDataKey.EXTERNAL_DATA_SOURCES, team.id),- team_data_key(input.digest.key, TeamDataKey.FEATURE_FLAGS, team.id),- team_data_key(input.digest.key, TeamDataKey.SAVED_FILTERS, team.id),- team_data_key(input.digest.key, TeamDataKey.EXPIRING_RECORDINGS, team.id),- team_data_key(input.digest.key, TeamDataKey.SURVEYS_LAUNCHED, team.id),- team_data_key(input.digest.key, TeamDataKey.USAGE_TRENDS, team.id),- team_data_key(input.digest.key, TeamDataKey.ERROR_ISSUES, team.id),- ]- )+def _generate_organization_digest_batch(input: GenerateOrganizationDigestInput) -> None:+ bind_contextvars(digest_key=input.digest.key, batch_start=input.batch[0], batch_end=input.batch[1])+ logger = LOGGER.bind()+ logger.info("Generating organization-level digest batch")- defaults = [- DashboardList(root=[]),- EventDefinitionList(root=[]),- ExperimentList(root=[]),- ExperimentList(root=[]),- ExternalDataSourceList(root=[]),- FeatureFlagList(root=[]),- FilterList(root=[]),- RecordingCount(recording_count=0),- SurveyList(root=[]),- UsageTrends(),- ErrorIssueList(root=[]),- ]+ organization_count = 0+ team_count = 0- digest_data = [- default if result is None else default.__class__.model_validate_json(result)- for default, result in zip(defaults, results)+ with _digest_redis(input.common) as r:+ batch_start, batch_end = input.batch+ for organization in query_orgs_for_digest()[batch_start:batch_end]:+ try:+ team_digests: list[TeamDigest] = []++ for team in query_org_teams(organization):+ results: list[str | None] = r.mget(+ [+ team_data_key(input.digest.key, TeamDataKey.DASHBOARDS, team.id),+ team_data_key(input.digest.key, TeamDataKey.EVENT_DEFINITIONS, team.id),+ team_data_key(input.digest.key, TeamDataKey.EXPERIMENTS_LAUNCHED, team.id),+ team_data_key(input.digest.key, TeamDataKey.EXPERIMENTS_COMPLETED, team.id),+ team_data_key(input.digest.key, TeamDataKey.EXTERNAL_DATA_SOURCES, team.id),+ team_data_key(input.digest.key, TeamDataKey.FEATURE_FLAGS, team.id),+ team_data_key(input.digest.key, TeamDataKey.SAVED_FILTERS, team.id),+ team_data_key(input.digest.key, TeamDataKey.EXPIRING_RECORDINGS, team.id),+ team_data_key(input.digest.key, TeamDataKey.SURVEYS_LAUNCHED, team.id),+ team_data_key(input.digest.key, TeamDataKey.USAGE_TRENDS, team.id),+ team_data_key(input.digest.key, TeamDataKey.ERROR_ISSUES, team.id),]+ )- team_digests.append(- TeamDigest(- id=team.id,- name=team.name,- dashboards=digest_data[0],- event_definitions=digest_data[1],- experiments_launched=digest_data[2],- experiments_completed=digest_data[3],- external_data_sources=digest_data[4],- feature_flags=digest_data[5],- filters=digest_data[6],- expiring_recordings=digest_data[7],- surveys_launched=digest_data[8],- usage_trends=digest_data[9],- error_issues=digest_data[10],- )+ defaults = [+ DashboardList(root=[]),+ EventDefinitionList(root=[]),+ ExperimentList(root=[]),+ ExperimentList(root=[]),+ ExternalDataSourceList(root=[]),+ FeatureFlagList(root=[]),+ FilterList(root=[]),+ RecordingCount(recording_count=0),+ SurveyList(root=[]),+ UsageTrends(),+ ErrorIssueList(root=[]),+ ]++ digest_data = [+ default if result is None else default.__class__.model_validate_json(result)+ for default, result in zip(defaults, results)+ ]++ team_digests.append(+ TeamDigest(+ id=team.id,+ name=team.name,+ dashboards=digest_data[0],+ event_definitions=digest_data[1],+ experiments_launched=digest_data[2],+ experiments_completed=digest_data[3],+ external_data_sources=digest_data[4],+ feature_flags=digest_data[5],+ filters=digest_data[6],+ expiring_recordings=digest_data[7],+ surveys_launched=digest_data[8],+ usage_trends=digest_data[9],+ error_issues=digest_data[10],)- team_count += 1-- org_digest = OrganizationDigest(- id=organization.id,- name=organization.name,- created_at=organization.created_at,- team_digests=team_digests,)+ team_count += 1- key = org_digest_key(input.digest.key, organization.id)- await r.setex(key, input.common.redis_ttl, org_digest.model_dump_json())+ org_digest = OrganizationDigest(+ id=organization.id,+ name=organization.name,+ created_at=organization.created_at,+ team_digests=team_digests,+ )++ key = org_digest_key(input.digest.key, organization.id)+ r.setex(key, input.common.redis_ttl, org_digest.model_dump_json())++ organization_count += 1+ except Exception as e:+ logger.warning(+ f"Failed to generate organization-level digest for organization {organization.id}, skipping...",+ error=str(e),+ org_id=organization.id,+ )+ continue++ logger.info(+ "Finished generating organization-level digest batch",+ organization_count=organization_count,+ team_count=team_count,+ )- organization_count += 1- except Exception as e:- logger.warning(- f"Failed to generate organization-level digest for organization {organization.id}, skipping...",- error=str(e),- org_id=organization.id,- )- continue- logger.info(- "Finished generating organization-level digest batch",- organization_count=organization_count,- team_count=team_count,- )[email protected](name="generate-organization-digest-batch")+@asyncify+def generate_organization_digest_batch(input: GenerateOrganizationDigestInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ _generate_organization_digest_batch(input)RECORD_BATCH_SIZE = 100DIGEST_ITEM_COUNT_THRESHOLD = 4[email protected](name="send-weekly-digest-batch")-async def send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:- async with Heartbeater():- bind_contextvars(digest_key=input.digest.key, batch_start=input.batch[0], batch_end=input.batch[1])- logger = LOGGER.bind()- logger.info("Sending weekly digest batch")+# A BaseException, so that the per-organization `except Exception` handler cannot swallow it.+class ActivityCancelled(BaseException):+ pass+++def _raise_if_cancelled() -> None:+ if activity.in_activity() and activity.is_cancelled():+ raise ActivityCancelled+- sent_digest_count = 0- empty_org_digest_count = 0- empty_user_digest_count = 0+def _send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:+ bind_contextvars(digest_key=input.digest.key, batch_start=input.batch[0], batch_end=input.batch[1])+ logger = LOGGER.bind()+ logger.info("Sending weekly digest batch")- # Only US deployment forwards email events to customer.io- ph_client: Posthog = get_ph_client(region="US", sync_mode=True)+ sent_digest_count = 0+ empty_org_digest_count = 0+ empty_user_digest_count = 0- if not ph_client and not input.dry_run:- logger.error("Failed to set up Posthog client")- return+ # Only US deployment forwards email events to customer.io+ ph_client: Posthog = get_ph_client(region="US", sync_mode=True)- messaging_record_batch: list[MessagingRecord] = []+ if not ph_client and not input.dry_run:+ logger.error("Failed to set up Posthog client")+ return- async with redis.from_url(_redis_url(input.common)) as r:+ messaging_record_batch: list[MessagingRecord] = []++ try:+ with _digest_redis(input.common) as r:batch_start, batch_end = input.batch- async for organization in query_orgs_for_digest()[batch_start:batch_end]:+ for organization in query_orgs_for_digest()[batch_start:batch_end]:+ _raise_if_cancelled()partial = Falsetry:- raw_digest: Optional[str] = await r.get(org_digest_key(input.digest.key, organization.id))+ raw_digest: str | None = r.get(org_digest_key(input.digest.key, organization.id))if not raw_digest:logger.warning(- f"Missing digest data for organization, skipping...", organization_id=organization.id+ "Missing digest data for organization, skipping...", organization_id=organization.id)continue@@ -775,28 +815,26 @@ async def send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:empty_org_digest_count += 1continue- messaging_record, created = await MessagingRecord.objects.aget_or_create(+ messaging_record, created = MessagingRecord.objects.get_or_create(raw_email=f"org_{organization.id}", campaign_key=input.digest.key)if not created and messaging_record.sent_at and not input.allow_already_sent:logger.info(- f"Digest already sent for organization, skipping...", organization_id=organization.id+ "Digest already sent for organization, skipping...", organization_id=organization.id)continue- async for member in query_org_members(organization):+ for member in query_org_members(organization):+ _raise_if_cancelled()user = member.useruser_notify_teams: set[int] = set(- map(- int,- await r.smembers(user_data_key(input.digest.key, UserDataKey.NOTIFY_TEAMS, user.id)),- )+ map(int, r.smembers(user_data_key(input.digest.key, UserDataKey.NOTIFY_TEAMS, user.id))))# Load user-specific contextproduct_suggestion: DigestProductSuggestion | None = None- raw_suggestion: str | None = await r.get(+ raw_suggestion: str | None = r.get(user_data_key(input.digest.key, UserDataKey.PRODUCT_SUGGESTION, user.id))if raw_suggestion:@@ -854,15 +892,24 @@ async def send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:messaging_record_batch.append(messaging_record)if len(messaging_record_batch) >= RECORD_BATCH_SIZE:- await MessagingRecord.objects.abulk_update(messaging_record_batch, ["sent_at"])+ MessagingRecord.objects.bulk_update(messaging_record_batch, ["sent_at"])messaging_record_batch = []+ finally:+ # Sync mode sends each capture before `capture` returns, so a record in the batch belongs to an+ # organization that reached PostHog. Saving it on cancellation too keeps the retry from resending it.+ if messaging_record_batch:+ MessagingRecord.objects.bulk_update(messaging_record_batch, ["sent_at"])++ logger.info(+ "Finished sending weekly digest batch",+ sent_digest_count=sent_digest_count,+ empty_org_digest_count=empty_org_digest_count,+ empty_user_digest_count=empty_user_digest_count,+ )- if len(messaging_record_batch) > 0:- await MessagingRecord.objects.abulk_update(messaging_record_batch, ["sent_at"])- logger.info(- "Finished sending weekly digest batch",- sent_digest_count=sent_digest_count,- empty_org_digest_count=empty_org_digest_count,- empty_user_digest_count=empty_user_digest_count,- )[email protected](name="send-weekly-digest-batch")+@asyncify+def send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:+ with HeartbeaterSync(logger=LOGGER):+ _send_weekly_digest_batch(input)diff --git a/posthog/temporal/weekly_digest/queries.py b/posthog/temporal/weekly_digest/queries.pyindex bc0355de90e5..720402dd664d 100644--- a/posthog/temporal/weekly_digest/queries.py+++ b/posthog/temporal/weekly_digest/queries.py@@ -7,7 +7,6 @@ from posthog.models import Organizationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist-from posthog.sync import database_sync_to_asyncfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.error_tracking.backend.facade.api import query_new_error_issues as query_new_error_issues@@ -169,8 +168,3 @@ def query_org_product_push_campaigns(organization_id: str, period_end: datetime).order_by("-started_at").values("product_key", "reason_text"))---@database_sync_to_async-def queryset_to_list(qs: QuerySet):- return list(qs)diff --git a/posthog/temporal/weekly_digest/types.py b/posthog/temporal/weekly_digest/types.pyindex a3f0d9dc21e1..3cf3395b42a1 100644--- a/posthog/temporal/weekly_digest/types.py+++ b/posthog/temporal/weekly_digest/types.py@@ -373,10 +373,3 @@ class PlaylistCount(BaseModel):refreshed_at: datetimeerror_count: interrored_at: Optional[datetime]---class ClickHouseResponse(BaseModel):- meta: list- data: list- statistics: dict- rows: int