: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(error-tracking): stop filing worker drains as auto-merge issues (#97977)
posthog[bot]1e3519d121eb
diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.pyindex ae478d6ab4e8..4f4c8331ead0 100644--- a/posthog/temporal/common/posthog_client.py+++ b/posthog/temporal/common/posthog_client.py@@ -38,6 +38,32 @@ EXPECTED_CONTROL_FLOW_ERROR_TYPES = frozenset()+def is_expected_activity_failure(error: BaseException) -> bool:+ """Whether an activity failure is expected rather than a defect, so it must not reach error tracking.++ Cancellations (worker drain, activity timeout, workflow cancellation), a cooperative worker+ shutdown (raised mid-activity during a deploy, always retried on a fresh worker), our own+ egress-budget backpressure (a deliberate "defer and retry later" signal that our rate limiter+ already records via record_outbound_decision), errors explicitly marked non-reportable+ (expected customer/upstream conditions, e.g. a REST API serving a login page instead of JSON),+ expected-control-flow ApplicationErrors (activity-retry-as-poll probes), and a saturated or+ restarting database that clears on its own.++ The activity interceptor below re-raises these without reporting them. An activity that also+ captures locally must apply the same filter, or a worker drain mints an error tracking issue+ that nobody can action.+ """+ return (+ temporalio.exceptions.is_cancelled_exception(error)+ or isinstance(error, EgressBudgetExhausted | WorkerShuttingDownError | NonReportableError)+ or (+ isinstance(error, temporalio.exceptions.ApplicationError)+ and error.type in EXPECTED_CONTROL_FLOW_ERROR_TYPES+ )+ or is_transient_db_error(error)+ )++def _tag_team_id_on_current_span(input: ExecuteActivityInput | ExecuteWorkflowInput) -> None:"""Tag the active span (the Temporal RunActivity/RunWorkflow span, when OTel tracing isenabled on the worker) with team_id read from the activity/workflow input.@@ -83,35 +109,17 @@ class _PostHogClientActivityInboundInterceptor(ActivityInboundInterceptor):try:return await super().execute_activity(input)except Exception as e:- # Cancellations (worker drain, activity timeout, workflow cancellation), a cooperative- # worker shutdown (raised mid-activity during a deploy, always retried on a fresh- # worker), our own egress-budget backpressure (a deliberate "defer and retry later"- # signal that our rate limiter already records via record_outbound_decision), errors- # explicitly marked non-reportable (expected customer/upstream conditions, e.g. a REST- # API serving a login page instead of JSON), and expected-control-flow ApplicationErrors- # (activity-retry-as-poll probes) are not defects — re-raise without reporting them to- # error tracking.- if (- temporalio.exceptions.is_cancelled_exception(e)- or isinstance(e, EgressBudgetExhausted | WorkerShuttingDownError | NonReportableError)- or (- isinstance(e, temporalio.exceptions.ApplicationError)- and e.type in EXPECTED_CONTROL_FLOW_ERROR_TYPES- )- ):+ if is_expected_activity_failure(e):+ # A pool problem that outlives the retries surfaces as a workflow failure, so a+ # log here is enough. Capturing would mint an issue per module for one condition.+ if is_transient_db_error(e):+ await logger.awarning(+ "Transient database error in activity %s, leaving retry to Temporal",+ activity.info().activity_type,+ exc_info=e,+ )raiseactivity_info = activity.info()- # A saturated connection pool clears on its own and Temporal retries the activity, so- # a burst of them would otherwise mint a fresh error tracking issue per module for a- # condition nobody can action per-activity. Log it instead, and leave the retry to- # Temporal — a pool problem that outlives the retries surfaces as a workflow failure.- if is_transient_db_error(e):- await logger.awarning(- "Transient database error in activity %s, leaving retry to Temporal",- activity_info.activity_type,- exc_info=e,- )- raisecapture_kwargs = {"properties": {# Ambient properties (e.g. warehouse-sources JobContext) first so the explicitdiff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.pyindex 92a853d5152f..0ca449857e3b 100644--- a/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py+++ b/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py@@ -13,6 +13,7 @@ from posthog.event_usage import groupsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Teamfrom posthog.ph_client import ph_background_capture+from posthog.temporal.common.posthog_client import is_expected_activity_failurefrom products.error_tracking.backend.indexed_embedding import EMBEDDING_TABLESfrom products.error_tracking.backend.models import (@@ -299,10 +300,13 @@ def merge_similar_fingerprints(closest_fingerprints=closest_fingerprints,)except Exception as err:- _capture_activity_exception(- err,- inputs,- activity_name=activity_name,- workflow_name=workflow_name,- )+ # A drained worker raises a cancellation straight into this thread, usually while the+ # merge waits on a row lock, so the trace looks like a database fault.+ if not is_expected_activity_failure(err):+ _capture_activity_exception(+ err,+ inputs,+ activity_name=activity_name,+ workflow_name=workflow_name,+ )raisediff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_fingerprint_embedding_result.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_fingerprint_embedding_result.pyindex a580773af535..0a25acaa39d1 100644--- a/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_fingerprint_embedding_result.py+++ b/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_fingerprint_embedding_result.py@@ -6,8 +6,11 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from django.db import OperationalErrorfrom django.test import override_settings+from temporalio.exceptions import CancelledError+from posthog.clickhouse.client.connection import ClickHouseUser, Workloadfrom posthog.models import Team@@ -184,6 +187,34 @@ class TestFingerprintEmbeddingResultActivity:assert result == FingerprintEmbeddingMergeResult()capture_exception.assert_not_called()+ @pytest.mark.parametrize(+ "error,expect_captured",+ [+ # A drain cancels the activity, and Temporal retries it on a fresh worker.+ (CancelledError("Cancelled"), False),+ (OperationalError("server closed the connection unexpectedly"), False),+ (ValueError("boom"), True),+ ],+ )+ def test_merge_activity_captures_only_genuine_failures(self, error: Exception, expect_captured: bool) -> None:+ with (+ patch(+ "products.error_tracking.backend.temporal.fingerprint_embedding_result.activities.Team.objects.get",+ return_value=MagicMock(),+ ),+ patch(+ "products.error_tracking.backend.temporal.fingerprint_embedding_result.activities._query_closest_fingerprints",+ side_effect=error,+ ),+ patch(+ "products.error_tracking.backend.temporal.fingerprint_embedding_result.activities._capture_activity_exception"+ ) as capture_activity_exception,+ pytest.raises(type(error)),+ ):+ merge_issue_created_fingerprint_activity(_inputs())++ assert capture_activity_exception.called is expect_captured+def test_merge_fingerprint_skips_when_auto_merge_disabled(self) -> None:with override_settings(ERROR_TRACKING_AUTO_MERGE_ENABLED=False):result = _merge_fingerprint_into_closest_issue(diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.pyindex b8e1162a4e9a..df6f671879ad 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py@@ -15,6 +15,7 @@ from posthog.api.embedding_worker import generate_embeddingfrom posthog.kafka_client.routing import producer_scopefrom posthog.kafka_client.topics import KAFKA_DOCUMENT_EMBEDDINGS_TOPICfrom posthog.models import Team+from posthog.temporal.common.posthog_client import is_expected_activity_failurefrom posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connections@@ -145,17 +146,16 @@ def generate_issue_created_embedding_activity(# short blip into a burst of noisy error-tracking issues. Real bugs are still surfaced.try:return _prepare_issue_created_embedding(inputs)- except ApplicationError as error:- if error.type != EMBEDDING_SERVICE_UNAVAILABLE_ERROR_TYPE:- posthoganalytics.capture_exception(error)- raiseexcept Exception as error:- posthoganalytics.capture_exception(error)+ if not is_expected_activity_failure(error):+ posthoganalytics.capture_exception(error)raise+# The three activities below add no properties of their own, so the shared activity interceptor+# is the better reporter: it knows which failures are expected.@activity.defn[email protected](capture_exceptions=False)@close_db_connectionsdef persist_issue_created_embedding_activity(inputs: GeneratedIssueEmbedding) -> None:merge_inputs = inputs.merge_inputs@@ -186,7 +186,7 @@ def persist_issue_created_embedding_activity(inputs: GeneratedIssueEmbedding) ->@activity.defn[email protected](capture_exceptions=False)@close_db_connectionsdef merge_issue_created_fingerprint_activity(inputs: FingerprintEmbeddingResultInputs,@@ -199,7 +199,7 @@ def merge_issue_created_fingerprint_activity(@activity.defn[email protected](capture_exceptions=False)@close_db_connectionsdef emit_issue_created_internal_event_activity(inputs: IssueCreatedWorkflowInputs) -> None:produce_issue_lifecycle_internal_event(