: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(web-analytics): Fix Web Analytics Digest Cohort / feature flag fetching (#58181)
Jordan Mryyan3ead9276035c
diff --git a/products/web_analytics/backend/temporal/weekly_digest/activities.py b/products/web_analytics/backend/temporal/weekly_digest/activities.pyindex 20b5c205b048..d4704a3aff3e 100644--- a/products/web_analytics/backend/temporal/weekly_digest/activities.py+++ b/products/web_analytics/backend/temporal/weekly_digest/activities.py@@ -78,23 +78,10 @@ def _get_org_id_batches(input: WAWeeklyDigestInput) -> list[list[str]]:)))- all_org_ids = [str(oid) for oid in qs.values_list("id", flat=True)]-- org_ids = [- org_id- for org_id in all_org_ids- if posthoganalytics.feature_enabled(- "web-analytics-weekly-digest",- distinct_id=f"digest-worker-{org_id}",- groups={"organization": org_id},- only_evaluate_locally=True,- send_feature_flag_events=False,- )- ]+ org_ids = [str(oid) for oid in qs.values_list("id", flat=True)]logger.info("wa digest org query complete",- total=len(all_org_ids),- after_flag=len(org_ids),+ count=len(org_ids),active_since_days=input.active_since_days,cutoff=cutoff.isoformat() if cutoff else None,)@@ -192,6 +179,28 @@ def _send_digest_for_user(return DigestOutcome.SENT+def _is_user_targeted_for_digest(user: User, org_id: str) -> bool:+ try:+ return bool(+ posthoganalytics.feature_enabled(+ "web-analytics-weekly-digest",+ distinct_id=str(user.distinct_id),+ groups={"organization": org_id},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception as e:+ logger.warning(+ "wa digest: flag eval failed, treating user as not targeted",+ user_id=str(user.uuid),+ org_id=org_id,+ error=str(e),+ )+ capture_exception(e, {"user_id": str(user.uuid), "org_id": org_id})+ return False++def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> OrgDigestCounts:close_old_connections()@@ -205,17 +214,7 @@ def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> OrgDigestCounreturn countsmemberships = list(OrganizationMembership.objects.prefetch_related("user").filter(organization_id=org.id))- targeted_memberships = [- m- for m in memberships- if posthoganalytics.feature_enabled(- "web-analytics-weekly-digest",- distinct_id=str(m.user.distinct_id),- groups={"organization": str(org.id)},- only_evaluate_locally=True,- send_feature_flag_events=False,- )- ]+ targeted_memberships = [m for m in memberships if _is_user_targeted_for_digest(m.user, str(org.id))]if not targeted_memberships:counts.skipped_reason = "no_targeted_memberships"return countsdiff --git a/products/web_analytics/backend/temporal/weekly_digest/workflows.py b/products/web_analytics/backend/temporal/weekly_digest/workflows.pyindex c5df1feb67c6..9ecb09a5cb6b 100644--- a/products/web_analytics/backend/temporal/weekly_digest/workflows.py+++ b/products/web_analytics/backend/temporal/weekly_digest/workflows.py@@ -44,7 +44,10 @@ class WAWeeklyDigestWorkflow(PostHogWorkflow):return WAWeeklyDigestInput()@workflow.run- async def run(self, input: WAWeeklyDigestInput) -> dict:+ async def run(self, input: WAWeeklyDigestInput | None = None) -> dict:+ if input is None:+ input = WAWeeklyDigestInput()+batches = await workflow.execute_activity(get_org_id_batches,input,@@ -52,42 +55,42 @@ class WAWeeklyDigestWorkflow(PostHogWorkflow):retry_policy=ACTIVITY_RETRY_POLICY,)- if not batches:- workflow.logger.info("No org batches for WA weekly digest")- return {"orgs": 0, "batches": 0}+ totals = DigestBatchResult()+ failed_batches = 0- workflow.logger.info(- "Fanning out WA digest",- batches=len(batches),- orgs=sum(len(b) for b in batches),- )+ if batches:+ workflow.logger.info(+ "Fanning out WA digest",+ batches=len(batches),+ orgs=sum(len(b) for b in batches),+ )- semaphore = asyncio.Semaphore(input.max_concurrent)-- async def _run_batch(batch: list[str]) -> DigestBatchResult:- async with semaphore:- return await workflow.execute_activity(- run_wa_digest_batch,- DigestBatchInput(org_ids=batch, dry_run=input.dry_run),- start_to_close_timeout=timedelta(minutes=30),- heartbeat_timeout=timedelta(minutes=5),- retry_policy=ACTIVITY_RETRY_POLICY,- )-- results = await asyncio.gather(- *[_run_batch(b) for b in batches],- return_exceptions=True,- )+ semaphore = asyncio.Semaphore(input.max_concurrent)++ async def _run_batch(batch: list[str]) -> DigestBatchResult:+ async with semaphore:+ return await workflow.execute_activity(+ run_wa_digest_batch,+ DigestBatchInput(org_ids=batch, dry_run=input.dry_run),+ start_to_close_timeout=timedelta(minutes=30),+ heartbeat_timeout=timedelta(minutes=5),+ retry_policy=ACTIVITY_RETRY_POLICY,+ )++ results = await asyncio.gather(+ *[_run_batch(b) for b in batches],+ return_exceptions=True,+ )- totals = DigestBatchResult()- failed_batches = 0- for batch, r in zip(batches, results):- if isinstance(r, BaseException):- failed_batches += 1- totals += DigestBatchResult(batch_size=len(batch), orgs_failed=len(batch))- workflow.logger.error("WA digest batch failed: %s", str(r))- else:- totals += r+ for batch, r in zip(batches, results):+ if isinstance(r, BaseException):+ failed_batches += 1+ totals += DigestBatchResult(batch_size=len(batch), orgs_failed=len(batch))+ workflow.logger.error("WA digest batch failed: %s", str(r))+ else:+ totals += r+ else:+ workflow.logger.info("No org batches for WA weekly digest")threshold_exceeded = totals.batch_size > 0 and totals.failure_rate > input.failure_thresholddiff --git a/products/web_analytics/backend/test/test_weekly_digest_activities.py b/products/web_analytics/backend/test/test_weekly_digest_activities.pyindex 7f134d519af6..6130715edf37 100644--- a/products/web_analytics/backend/test/test_weekly_digest_activities.py+++ b/products/web_analytics/backend/test/test_weekly_digest_activities.py@@ -15,6 +15,7 @@ from posthog.models.organization import Organizationfrom products.web_analytics.backend.temporal.weekly_digest.activities import (_get_org_id_batches,+ _is_user_targeted_for_digest,_run_wa_digest_batch,_send_digest_for_user,_send_test_digest,@@ -331,11 +332,6 @@ class TestSendTestDigestFullUserMode(_DigestTestBase):class TestGetOrgIdBatches(APIBaseTest):def setUp(self):super().setUp()- self.flag_patcher = patch(- "products.web_analytics.backend.temporal.weekly_digest.activities.posthoganalytics.feature_enabled",- return_value=True,- )- self.flag_patcher.start()self.kill_switch_patcher = patch("products.web_analytics.backend.temporal.weekly_digest.activities.get_kill_switch_level",)@@ -355,7 +351,6 @@ class TestGetOrgIdBatches(APIBaseTest):self.close_conn_patcher.stop()self.email_available_patcher.stop()self.kill_switch_patcher.stop()- self.flag_patcher.stop()super().tearDown()def test_returns_empty_list_when_kill_switch_active(self):@@ -552,3 +547,38 @@ class TestRunWaDigestBatch(APIBaseTest):assert totals.orgs_processed == 1assert totals.emails_sent == 1assert totals.emails_skipped_optout == 1+++class TestIsUserTargetedForDigest(APIBaseTest):+ def test_returns_true_when_flag_evaluates_true(self):+ with patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.posthoganalytics.feature_enabled",+ return_value=True,+ ) as mock_flag:+ assert _is_user_targeted_for_digest(self.user, str(self.organization.id)) is True++ kwargs = mock_flag.call_args.kwargs+ assert kwargs["only_evaluate_locally"] is False+ assert kwargs["groups"] == {"organization": str(self.organization.id)}+ assert kwargs["distinct_id"] == str(self.user.distinct_id)++ def test_returns_false_when_flag_evaluates_false(self):+ with patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.posthoganalytics.feature_enabled",+ return_value=False,+ ):+ assert _is_user_targeted_for_digest(self.user, str(self.organization.id)) is False++ def test_fails_closed_on_flag_service_error(self):+ with patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("decide endpoint timeout"),+ ):+ assert _is_user_targeted_for_digest(self.user, str(self.organization.id)) is False++ def test_returns_false_when_flag_evaluator_returns_none(self):+ with patch(+ "products.web_analytics.backend.temporal.weekly_digest.activities.posthoganalytics.feature_enabled",+ return_value=None,+ ):+ assert _is_user_targeted_for_digest(self.user, str(self.organization.id)) is Falsediff --git a/products/web_analytics/backend/test/test_weekly_digest_workflows.py b/products/web_analytics/backend/test/test_weekly_digest_workflows.pyindex 700a89433074..a6cc5f409d7f 100644--- a/products/web_analytics/backend/test/test_weekly_digest_workflows.py+++ b/products/web_analytics/backend/test/test_weekly_digest_workflows.py@@ -23,7 +23,7 @@ def _empty_batch_result(batch_size: int) -> DigestBatchResult:@pytest.mark.asyncio-async def test_wa_weekly_digest_returns_early_when_no_batches() -> None:+async def test_wa_weekly_digest_skips_batch_fanout_when_no_batches_but_still_pushes_metrics() -> None:@activity.defn(name="wa-digest-get-org-batches")async def _get_batches(input: WAWeeklyDigestInput) -> list[list[str]]:return []@@ -32,9 +32,11 @@ async def test_wa_weekly_digest_returns_early_when_no_batches() -> None:async def _run_batch(input: DigestBatchInput) -> DigestBatchResult:raise AssertionError("should not be called when there are no batches")+ metric_pushes: list[tuple[dict, bool]] = []+@activity.defn(name="wa-digest-push-metrics")async def _push_metrics(totals_dict: dict, success: bool) -> None:- raise AssertionError("should not push metrics when there is no work")+ metric_pushes.append((totals_dict, success))task_queue = str(uuid.uuid4())async with await WorkflowEnvironment.start_time_skipping() as env:@@ -52,7 +54,11 @@ async def test_wa_weekly_digest_returns_early_when_no_batches() -> None:task_queue=task_queue,)- assert result == {"orgs": 0, "batches": 0}+ assert result["orgs"] == 0+ assert result["batches"] == 0+ assert result["emails_sent"] == 0+ assert len(metric_pushes) == 1+ assert metric_pushes[0][1] is True@dataclasses.dataclass