: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(data-catalog): stop weekly digest alerting on a tiny attempted sample (#108216)
posthog[bot]90c613b1f371
diff --git a/posthog/temporal/common/digest.py b/posthog/temporal/common/digest.pyindex 0d0d6a2c25ac..65d56ba2866b 100644--- a/posthog/temporal/common/digest.py+++ b/posthog/temporal/common/digest.py@@ -50,10 +50,13 @@ class DigestBatchTotals:def total_duration(self) -> float:return self.build_duration + self.send_duration+ @property+ def orgs_attempted(self) -> int:+ return self.orgs_processed + self.orgs_failed+@propertydef failure_rate(self) -> float:- attempted = self.orgs_processed + self.orgs_failed- return self.orgs_failed / attempted if attempted > 0 else 0.0+ return self.orgs_failed / self.orgs_attempted if self.orgs_attempted > 0 else 0.0def __iadd__(self, other: Self) -> Self:for f in dataclasses.fields(self):diff --git a/products/data_catalog/backend/temporal/weekly_digest/activities.py b/products/data_catalog/backend/temporal/weekly_digest/activities.pyindex 98c741d0eccf..dd98c6d6f0b3 100644--- a/products/data_catalog/backend/temporal/weekly_digest/activities.py+++ b/products/data_catalog/backend/temporal/weekly_digest/activities.py@@ -3,7 +3,7 @@ from datetime import datetime, timedeltafrom itertools import batchedfrom django.conf import settings-from django.db import close_old_connections+from django.db import OperationalError, close_old_connectionsfrom django.db.models import Exists, OuterRef, QuerySetfrom django.utils import timezone@@ -284,6 +284,18 @@ def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> OrgDigestCounreturn counts+def _build_and_send_for_org_with_retry(org_id: str, dry_run: bool = False) -> OrgDigestCounts:+ """Retries once when the database drops the connection. The retry starts with+ `close_old_connections`, which replaces the broken connection. The campaign key dedupes+ any email that the first attempt already sent.+ """+ try:+ return _build_and_send_for_org(org_id, dry_run=dry_run)+ except OperationalError as e:+ logger.warning("Data catalog digest hit a database error for org, retrying once", org_id=org_id, error=str(e))+ return _build_and_send_for_org(org_id, dry_run=dry_run)++def _run_digest_batch(input: DigestBatchInput) -> DigestBatchResult:close_old_connections()@@ -291,7 +303,7 @@ def _run_digest_batch(input: DigestBatchInput) -> DigestBatchResult:for org_id in input.org_ids:try:- org_counts = _build_and_send_for_org(org_id, dry_run=input.dry_run)+ org_counts = _build_and_send_for_org_with_retry(org_id, dry_run=input.dry_run)except Exception as e:logger.exception("Data catalog digest failed for org", org_id=org_id, error=str(e))capture_exception(e, {"org_id": org_id})diff --git a/products/data_catalog/backend/temporal/weekly_digest/types.py b/products/data_catalog/backend/temporal/weekly_digest/types.pyindex d31c32b756f2..4638a0e84b25 100644--- a/products/data_catalog/backend/temporal/weekly_digest/types.py+++ b/products/data_catalog/backend/temporal/weekly_digest/types.py@@ -40,6 +40,9 @@ class DataCatalogWeeklyDigestInput:batch_size: int = 25max_concurrent: int = 4failure_threshold: float = 0.2+ # While the rollout flag skips almost every organization, the run attempts only a few. One+ # transient error in so few attempts goes over the rate, so the rate applies only from this count.+ min_attempted_orgs: int = 20active_since_days: int | None = 30org_ids: list[str] | None = None@@ -50,6 +53,9 @@ class DataCatalogWeeklyDigestInput:def publishes_metrics(self) -> bool:return self.org_ids is None and not self.dry_run+ def exceeds_failure_threshold(self, totals: DigestBatchTotals) -> bool:+ return totals.orgs_attempted >= self.min_attempted_orgs and totals.failure_rate > self.failure_threshold+@dataclasses.dataclass(frozen=True)class OrgBatchPageInput:diff --git a/products/data_catalog/backend/temporal/weekly_digest/workflows.py b/products/data_catalog/backend/temporal/weekly_digest/workflows.pyindex 7ce70864e48e..b39bbab611f6 100644--- a/products/data_catalog/backend/temporal/weekly_digest/workflows.py+++ b/products/data_catalog/backend/temporal/weekly_digest/workflows.py@@ -93,7 +93,7 @@ class DataCatalogWeeklyDigestWorkflow(PostHogWorkflow):if batch_count == 0:workflow.logger.info("No org batches for data catalog weekly digest")- threshold_exceeded = totals.batch_size > 0 and totals.failure_rate > input.failure_threshold+ threshold_exceeded = input.exceeds_failure_threshold(totals)if input.publishes_metrics:await workflow.execute_activity(diff --git a/products/data_catalog/backend/tests/test_weekly_digest.py b/products/data_catalog/backend/tests/test_weekly_digest.pyindex d61bb7f32353..4d502f72d162 100644--- a/products/data_catalog/backend/tests/test_weekly_digest.py+++ b/products/data_catalog/backend/tests/test_weekly_digest.py@@ -6,6 +6,7 @@ from unittest import mockfrom unittest.mock import MagicMock, patchfrom django.conf import settings+from django.db import OperationalErrorfrom django.test import SimpleTestCase, override_settingsfrom django.utils import timezone@@ -23,6 +24,7 @@ from products.data_catalog.backend.temporal.schedule import create_data_catalog_from products.data_catalog.backend.temporal.weekly_digest.activities import (_build_and_send_for_org,_get_org_batch_page,+ _run_digest_batch,_send_digest_for_user,)from products.data_catalog.backend.temporal.weekly_digest.email_context import (@@ -34,8 +36,11 @@ from products.data_catalog.backend.temporal.weekly_digest.email_context import ()from products.data_catalog.backend.temporal.weekly_digest.types import (DataCatalogWeeklyDigestInput,+ DigestBatchInput,+ DigestBatchResult,DigestOutcome,OrgBatchPageInput,+ OrgDigestCounts,)from products.data_catalog.backend.temporal.weekly_digest.workflows import DataCatalogWeeklyDigestWorkflow@@ -350,3 +355,40 @@ def test_only_the_full_real_run_publishes_metrics(workflow_input: DataCatalogWeeklyDigestInput, publishes: bool) -> None:assert workflow_input.publishes_metrics is publishes+++ "orgs_processed,orgs_failed,exceeded",+ [+ (0, 2, False),+ (18, 2, False),+ (10, 10, True),+ (0, 25, True),+ ],+)+def test_the_failure_threshold_needs_enough_attempted_orgs(+ orgs_processed: int, orgs_failed: int, exceeded: bool+) -> None:+ totals = DigestBatchResult(orgs_processed=orgs_processed, orgs_failed=orgs_failed, orgs_skipped=75_000)+ assert DataCatalogWeeklyDigestInput().exceeds_failure_threshold(totals) is exceeded+++ "side_effect,orgs_processed,orgs_failed",+ [+ ([OperationalError("connection closed"), OrgDigestCounts(sent=1)], 1, 0),+ ([OperationalError("connection closed"), OperationalError("connection closed")], 0, 1),+ ([ValueError("bug")], 0, 1),+ ],+)+def test_a_dropped_database_connection_is_retried_once(+ side_effect: list, orgs_processed: int, orgs_failed: int+) -> None:+ with (+ patch(f"{_ACTIVITIES}.close_old_connections"),+ patch(f"{_ACTIVITIES}.capture_exception"),+ patch(f"{_ACTIVITIES}._build_and_send_for_org", side_effect=side_effect),+ ):+ totals = _run_digest_batch(DigestBatchInput(org_ids=["org"]))++ assert (totals.orgs_processed, totals.orgs_failed) == (orgs_processed, orgs_failed)