: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): page teams by id instead of offset (#93073)
posthog[bot]d8b5352be0e3
diff --git a/posthog/temporal/tests/weekly_digest/test_activities.py b/posthog/temporal/tests/weekly_digest/test_activities.pyindex 70644d89e0f1..2ef4744469cf 100644--- a/posthog/temporal/tests/weekly_digest/test_activities.py+++ b/posthog/temporal/tests/weekly_digest/test_activities.py@@ -8,11 +8,13 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest_asyncio+from posthog.models.team import Teamfrom posthog.temporal.weekly_digest.activities import (+ _cut_team_id_ranges,_query_team_usage_trends,+ _teams_in_range,_usage_trend_metric,count_organizations,- count_teams,generate_dashboard_lookup,generate_event_definition_lookup,generate_experiment_completed_lookup,@@ -28,6 +30,7 @@ from posthog.temporal.weekly_digest.activities import (generate_user_notification_lookup,send_weekly_digest_batch,)+from 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,CommonInput,@@ -35,6 +38,7 @@ from posthog.temporal.weekly_digest.types import (GenerateDigestDataBatchInput,GenerateOrganizationDigestInput,SendWeeklyDigestBatchInput,+ TeamIdRange,UsageTrends,)@@ -83,6 +87,9 @@ class MockAsyncQuerySet:def __init__(self, items):self.items = items+ 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):@@ -137,17 +144,29 @@ async def mock_heartbeater():yield-async def test_count_teams():- """Test counting teams for digest."""- mock_queryset = AsyncMock()- mock_queryset.acount = AsyncMock(return_value=42)-- with patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_queryset):- result = await count_teams()+def test_team_id_ranges_page_every_digest_team_exactly_once(organization, digest):+ for i in range(5):+ Team.objects.create(organization=organization, name=f"digest team {i}")+ if i == 2:+ # Sits inside a batch range, so a leak here shows up as an extra paged team.+ Team.objects.create(organization=organization, name="demo team", is_demo=True)++ common = CommonInput(batch_size=2, redis_host="localhost", redis_port=6379)+ expected = list(query_teams_for_digest().values_list("id", flat=True))++ paged: list[int] = []+ for team_id_range in _cut_team_id_ranges(list(query_team_ids_for_digest()), common.batch_size):+ team_ids = [+ team.id+ for team in _teams_in_range(+ GenerateDigestDataBatchInput(team_id_range=team_id_range, digest=digest, common=common)+ )+ ]+ assert len(team_ids) <= common.batch_size+ paged.extend(team_ids)- assert result == 42- mock_queryset.acount.assert_called_once()+ assert paged == expected@pytest.mark.asyncio@@ -166,8 +185,9 @@ async def test_count_organizations():@pytest.mark.asyncioasync def test_generate_dashboard_lookup(mock_redis, common_input, digest):"""Test generating dashboard lookup with mock Redis."""- batch = (0, 2)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )# Mock teamsmock_team_1 = MagicMock()@@ -205,8 +225,9 @@ async def test_generate_dashboard_lookup(mock_redis, common_input, digest):@pytest.mark.asyncioasync def test_generate_event_definition_lookup(mock_redis, common_input, digest):"""Test generating event definition lookup with mock Redis."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -239,8 +260,9 @@ async def test_generate_event_definition_lookup(mock_redis, common_input, digest@pytest.mark.asyncioasync def test_generate_experiment_launched_lookup(mock_redis, common_input, digest):"""Test generating experiment launched lookup with mock Redis."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -274,8 +296,9 @@ async def test_generate_experiment_launched_lookup(mock_redis, common_input, dig@pytest.mark.asyncioasync def test_generate_experiment_completed_lookup(mock_redis, common_input, digest):"""Test generating experiment completed lookup with mock Redis."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -314,8 +337,9 @@ async def test_generate_experiment_completed_lookup(mock_redis, common_input, di@pytest.mark.asyncioasync def test_generate_external_data_source_lookup(mock_redis, common_input, digest):"""Test generating external data source lookup with mock Redis."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -346,8 +370,9 @@ async def test_generate_external_data_source_lookup(mock_redis, common_input, di@pytest.mark.asyncioasync def test_generate_feature_flag_lookup(mock_redis, common_input, digest):"""Test generating feature flag lookup with mock Redis."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -380,8 +405,9 @@ async def test_generate_feature_flag_lookup(mock_redis, common_input, digest):@pytest.mark.asyncioasync def test_generate_survey_lookup(mock_redis, common_input, digest):"""Test generating survey lookup with mock Redis."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -419,8 +445,9 @@ async def test_generate_survey_lookup(mock_redis, common_input, digest):@pytest.mark.asyncioasync def test_generate_filter_lookup(mock_redis, common_input, digest):"""Test generating filter lookup with mock Redis and playlist counts."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -469,8 +496,9 @@ async def test_generate_filter_lookup(mock_redis, common_input, digest):@pytest.mark.asyncioasync def test_generate_recording_lookup(mock_redis, common_input, digest):"""Test generating recording lookup with mock Redis and ClickHouse."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -502,8 +530,9 @@ async def test_generate_recording_lookup(mock_redis, common_input, digest):@pytest.mark.asyncioasync def test_generate_user_notification_lookup(mock_redis, common_input, digest):"""Test generating user notification lookup with mock Redis."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -737,8 +766,9 @@ async def test_send_weekly_digest_batch_dry_run(mock_redis, common_input, digest@pytest.mark.asyncioasync 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."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )organization_id = UUID("12345678-1234-1234-1234-123456789abc")mock_team = MagicMock()@@ -801,8 +831,9 @@ async def test_generate_product_suggestion_lookup_skips_projects_already_using_tmock_redis, common_input, digest):"""Test that a project already using the pushed product isn't nudged about it."""- batch = (0, 1)- input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )mock_team = MagicMock()mock_team.id = 1@@ -1015,7 +1046,9 @@ def test_query_team_usage_trends_windows_persons_and_test_accounts(team):async def test_generate_usage_trends_lookup_raises_only_when_every_team_fails(side_effects, should_raise, mock_redis, common_input, digest):- input_data = GenerateDigestDataBatchInput(batch=(0, 2), digest=digest, common=common_input)+ input_data = GenerateDigestDataBatchInput(+ team_id_range=TeamIdRange(start=1, end=3), digest=digest, common=common_input+ )team_1, team_2 = MagicMock(), MagicMock()team_1.id, team_2.id = 1, 2mock_team_queryset = MockAsyncQuerySet([team_1, team_2])diff --git a/posthog/temporal/tests/weekly_digest/test_workflows.py b/posthog/temporal/tests/weekly_digest/test_workflows.pyindex 5ce491c21bc2..e53be8c13718 100644--- a/posthog/temporal/tests/weekly_digest/test_workflows.py+++ b/posthog/temporal/tests/weekly_digest/test_workflows.py@@ -15,6 +15,7 @@ from posthog.temporal.weekly_digest.types import (GenerateDigestDataInput,SendWeeklyDigestBatchInput,SendWeeklyDigestInput,+ TeamIdRange,WeeklyDigestInput,)from posthog.temporal.weekly_digest.workflows import (@@ -107,7 +108,7 @@ async def test_generate_digest_data_workflow():TEST_BATCH_SIZE = 2activity_calls = {- "count_teams": 0,+ "team_id_ranges": 0,"count_organizations": 0,"dashboard": 0,"event_definition": 0,@@ -125,10 +126,10 @@ async def test_generate_digest_data_workflow():"org_digest": 0,}- @activity.defn(name="count-teams")- async def count_teams_mocked() -> int:- activity_calls["count_teams"] += 1- return TEST_TEAM_COUNT+ @activity.defn(name="list-team-id-ranges")+ async def list_team_id_ranges_mocked(input) -> list[TeamIdRange]:+ activity_calls["team_id_ranges"] += 1+ return [TeamIdRange(start=i, end=i + TEST_BATCH_SIZE) for i in range(1, TEST_TEAM_COUNT + 1, TEST_BATCH_SIZE)]@activity.defn(name="count-organizations")async def count_organizations_mocked() -> int:@@ -198,7 +199,7 @@ async def test_generate_digest_data_workflow():task_queue=task_queue_name,workflows=[GenerateDigestDataWorkflow],activities=[- count_teams_mocked,+ list_team_id_ranges_mocked,count_organizations_mocked,generate_dashboard_lookup_mocked,generate_event_definition_lookup_mocked,@@ -231,7 +232,7 @@ async def test_generate_digest_data_workflow():task_queue=task_queue_name,)- assert activity_calls["count_teams"] == 1+ assert activity_calls["team_id_ranges"] == 1assert activity_calls["count_organizations"] == 1# Calculate expected batches for teamsdiff --git a/posthog/temporal/weekly_digest/README.md b/posthog/temporal/weekly_digest/README.mdindex 359a4692db0b..909bf38d9740 100644--- a/posthog/temporal/weekly_digest/README.md+++ b/posthog/temporal/weekly_digest/README.md@@ -57,7 +57,7 @@ Generated via `user_data_key(digest_key, UserDataKey.*, user_id)`:│ GenerateDigestDataWorkflow │├─────────────────────────────────────────────────────────────────────────────┤│ │-│ 1. Count teams & orgs for batching │+│ 1. Cut teams into id-range batches, count orgs for batching ││ ││ 2. Generate team-level data (parallel per batch): ││ ├── generate_dashboard_lookup │diff --git a/posthog/temporal/weekly_digest/__init__.py b/posthog/temporal/weekly_digest/__init__.pyindex 04126adf55b1..686f783933da 100644--- a/posthog/temporal/weekly_digest/__init__.py+++ b/posthog/temporal/weekly_digest/__init__.py@@ -1,6 +1,5 @@from posthog.temporal.weekly_digest.activities import (count_organizations,- count_teams,generate_dashboard_lookup,generate_error_issue_lookup,generate_event_definition_lookup,@@ -15,6 +14,7 @@ from posthog.temporal.weekly_digest.activities import (generate_survey_lookup,generate_usage_trends_lookup,generate_user_notification_lookup,+ list_team_id_ranges,send_weekly_digest_batch,)from posthog.temporal.weekly_digest.workflows import (@@ -40,7 +40,7 @@ ACTIVITIES = [generate_user_notification_lookup,generate_organization_digest_batch,count_organizations,- count_teams,+ list_team_id_ranges,send_weekly_digest_batch,generate_filter_lookup,generate_recording_lookup,diff --git a/posthog/temporal/weekly_digest/activities.py b/posthog/temporal/weekly_digest/activities.pyindex e1f460757fac..cf17f8f31bfd 100644--- a/posthog/temporal/weekly_digest/activities.py+++ b/posthog/temporal/weekly_digest/activities.py@@ -45,6 +45,7 @@ from posthog.temporal.weekly_digest.queries import (query_orgs_for_digest,query_saved_filters,query_surveys_launched,+ query_team_ids_for_digest,query_teams_for_digest,queryset_to_list,)@@ -68,6 +69,7 @@ from posthog.temporal.weekly_digest.types import (SendWeeklyDigestBatchInput,SurveyList,TeamDigest,+ TeamIdRange,UsageTrendMetric,UsageTrends,UserDigestContext,@@ -104,6 +106,12 @@ async def _load_playlist_counts_from_django_cache(r: redis.Redis, filters: FilteLOGGER = get_write_only_logger()+def _teams_in_range(input: GenerateDigestDataBatchInput) -> 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.+ return query_teams_for_digest().filter(id__gte=input.team_id_range.start, id__lt=input.team_id_range.end)++async def generate_digest_data_lookup(input: GenerateDigestDataBatchInput,key_kind: TeamDataKey,@@ -116,8 +124,8 @@ async def generate_digest_data_lookup(digest_key=input.digest.key,period_start=input.digest.period_start,period_end=input.digest.period_end,- batch_start=input.batch[0],- batch_end=input.batch[1],+ 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)@@ -128,8 +136,7 @@ async def generate_digest_data_lookup(async with redis.from_url(_redis_url(input.common)) as r:db_query: QuerySet = query_func(input.digest.period_start, input.digest.period_end)- batch_start, batch_end = input.batch- async for team in query_teams_for_digest()[batch_start:batch_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:@@ -232,8 +239,8 @@ async def generate_filter_lookup(input: GenerateDigestDataBatchInput) -> None:digest_key=input.digest.key,period_start=input.digest.period_start,period_end=input.digest.period_end,- batch_start=input.batch[0],- batch_end=input.batch[1],+ 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")@@ -251,8 +258,7 @@ async def generate_filter_lookup(input: GenerateDigestDataBatchInput) -> None:):query_filters: QuerySet = query_saved_filters(input.digest.period_start, input.digest.period_end)- batch_start, batch_end = input.batch- async for team in query_teams_for_digest()[batch_start:batch_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)@@ -294,8 +300,8 @@ async def generate_recording_lookup(input: GenerateDigestDataBatchInput) -> Nonedigest_key=input.digest.key,period_start=input.digest.period_start,period_end=input.digest.period_end,- batch_start=input.batch[0],- batch_end=input.batch[1],+ 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")@@ -306,8 +312,7 @@ async def generate_recording_lookup(input: GenerateDigestDataBatchInput) -> Noneasync 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")- batch_start, batch_end = input.batch- async for team in query_teams_for_digest()[batch_start:batch_end]:+ async for team in _teams_in_range(input):try:parameters = {"team_id": team.id,@@ -442,8 +447,8 @@ async def generate_usage_trends_lookup(input: GenerateDigestDataBatchInput) -> Ndigest_key=input.digest.key,period_start=input.digest.period_start,period_end=input.digest.period_end,- batch_start=input.batch[0],- batch_end=input.batch[1],+ 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")@@ -453,8 +458,7 @@ async def generate_usage_trends_lookup(input: GenerateDigestDataBatchInput) -> Nerror_count = 0async with redis.from_url(_redis_url(input.common)) as r:- batch_start, batch_end = input.batch- async for team in query_teams_for_digest()[batch_start:batch_end]:+ async for team in _teams_in_range(input):attempted += 1try:usage_trends = await database_sync_to_async(_query_team_usage_trends)(@@ -488,7 +492,9 @@ async def generate_usage_trends_lookup(input: GenerateDigestDataBatchInput) -> N@activity.defn(name="generate-user-notification-lookup")async def generate_user_notification_lookup(input: GenerateDigestDataBatchInput) -> None:async with Heartbeater():- bind_contextvars(digest_key=input.digest.key, batch_start=input.batch[0], batch_end=input.batch[1])+ 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")@@ -496,8 +502,7 @@ async def generate_user_notification_lookup(input: GenerateDigestDataBatchInput)user_count = 0async with redis.from_url(_redis_url(input.common)) as r:- batch_start, batch_end = input.batch- async for team in query_teams_for_digest()[batch_start:batch_end]:+ async for team in _teams_in_range(input):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):@@ -529,8 +534,8 @@ async def generate_product_suggestion_lookup(input: GenerateDigestDataBatchInputdigest_key=input.digest.key,period_start=input.digest.period_start,period_end=input.digest.period_end,- batch_start=input.batch[0],- batch_end=input.batch[1],+ 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")@@ -543,8 +548,7 @@ async def generate_product_suggestion_lookup(input: GenerateDigestDataBatchInputcampaigns_by_org: dict[str, list[dict]] = {}async with redis.from_url(_redis_url(input.common)) as r:- batch_start, batch_end = input.batch- async for team in query_teams_for_digest()[batch_start:batch_end]:+ async for team in _teams_in_range(input):try:organization_id = str(team.organization_id)if organization_id not in campaigns_by_org:@@ -608,10 +612,22 @@ async def count_organizations() -> int:return await query_orgs_for_digest().acount()[email protected](name="count-teams")-async def count_teams() -> int:+def _cut_team_id_ranges(team_ids: list[int], batch_size: int) -> list[TeamIdRange]:+ """Cut ordered team ids into [start, end) ranges of at most `batch_size` teams each."""+ return [+ TeamIdRange(+ start=team_ids[start],+ end=team_ids[start + batch_size] if start + batch_size < len(team_ids) else team_ids[-1] + 1,+ )+ for start in range(0, len(team_ids), batch_size)+ ]++[email protected](name="list-team-id-ranges")+async 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 await query_teams_for_digest().acount()+ return _cut_team_id_ranges(await queryset_to_list(query_team_ids_for_digest()), input.batch_size)@activity.defn(name="generate-organization-digest-batch")diff --git a/posthog/temporal/weekly_digest/queries.py b/posthog/temporal/weekly_digest/queries.pyindex 84bd27e3015f..3f15a6e6e9bf 100644--- a/posthog/temporal/weekly_digest/queries.py+++ b/posthog/temporal/weekly_digest/queries.py@@ -37,6 +37,10 @@ def query_teams_for_digest() -> QuerySet:)+def query_team_ids_for_digest() -> QuerySet:+ return query_teams_for_digest().values_list("id", flat=True)++def query_orgs_for_digest() -> QuerySet:return Organization.objects.exclude(Q(for_internal_metrics=True)).only("id", "name", "created_at").order_by("id")diff --git a/posthog/temporal/weekly_digest/types.py b/posthog/temporal/weekly_digest/types.pyindex 0bfe21d5d293..a3f0d9dc21e1 100644--- a/posthog/temporal/weekly_digest/types.py+++ b/posthog/temporal/weekly_digest/types.py@@ -41,8 +41,15 @@ class GenerateDigestDataInput(BaseModel):common: CommonInput+class TeamIdRange(BaseModel):+ """A half-open [start, end) range of team ids."""++ start: int+ end: int++class GenerateDigestDataBatchInput(BaseModel):- batch: tuple[int, int]+ team_id_range: TeamIdRangedigest: Digestcommon: CommonInputdiff --git a/posthog/temporal/weekly_digest/workflows.py b/posthog/temporal/weekly_digest/workflows.pyindex d7a87282d4b3..043911eb432b 100644--- a/posthog/temporal/weekly_digest/workflows.py+++ b/posthog/temporal/weekly_digest/workflows.py@@ -10,7 +10,6 @@ from temporalio import common, workflowfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.weekly_digest.activities import (count_organizations,- count_teams,generate_dashboard_lookup,generate_error_issue_lookup,generate_event_definition_lookup,@@ -25,6 +24,7 @@ from posthog.temporal.weekly_digest.activities import (generate_survey_lookup,generate_usage_trends_lookup,generate_user_notification_lookup,+ list_team_id_ranges,send_weekly_digest_batch,)from posthog.temporal.weekly_digest.types import (@@ -109,10 +109,9 @@ class GenerateDigestDataWorkflow(PostHogWorkflow):@workflow.runasync def run(self, input: GenerateDigestDataInput) -> None:- batch_size = input.common.batch_size-- team_count = await workflow.execute_activity(- count_teams,+ team_id_ranges = await workflow.execute_activity(+ list_team_id_ranges,+ input.common,start_to_close_timeout=timedelta(minutes=5),retry_policy=common.RetryPolicy(maximum_attempts=2,@@ -121,8 +120,6 @@ class GenerateDigestDataWorkflow(PostHogWorkflow):heartbeat_timeout=timedelta(minutes=1),)- team_batches = [(i, i + batch_size) for i in range(0, team_count, batch_size)]-generators = [generate_dashboard_lookup,generate_event_definition_lookup,@@ -144,7 +141,7 @@ class GenerateDigestDataWorkflow(PostHogWorkflow):workflow.execute_activity(generator,GenerateDigestDataBatchInput(- batch=batch,+ team_id_range=team_id_range,digest=input.digest,common=input.common,),@@ -155,7 +152,7 @@ class GenerateDigestDataWorkflow(PostHogWorkflow):),heartbeat_timeout=timedelta(minutes=2),)- for batch, generator in itertools.product(team_batches, generators)+ for team_id_range, generator in itertools.product(team_id_ranges, generators)])@@ -169,6 +166,7 @@ class GenerateDigestDataWorkflow(PostHogWorkflow):heartbeat_timeout=timedelta(minutes=1),)+ batch_size = input.common.batch_sizeorg_batches = [(i, i + batch_size) for i in range(0, organization_count, batch_size)]await asyncio.gather(