: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-imports): stop tracking non-JSON REST responses as error-tracking noise (#73146)
Tom Owers752eb7cf97b5
diff --git a/posthog/temporal/common/errors.py b/posthog/temporal/common/errors.pyindex 6a28ae1f7933..abf7935e5f73 100644--- a/posthog/temporal/common/errors.py+++ b/posthog/temporal/common/errors.py@@ -2,6 +2,15 @@ import tracebackfrom temporalio.exceptions import ApplicationError, FailureError++class NonReportableError(Exception):+ """Marker for an expected, handled condition that must still fail the activity but should not+ be reported to error tracking. The activity interceptor re-raises these without capturing them,+ the same way it skips cancellations and egress backpressure. Subclass it for a failure that is+ always caused by the customer's config or the upstream API (never a PostHog defect) and that+ retrying can't resolve, so a tracked exception would only be noise."""++# Bound error strings so a multi-MB str(e) (ClickHouse 5xx body, Playwright HTML dump)# can't blow out Temporal's 2 MiB payload limit.MAX_ERROR_MESSAGE_CHARS = 8_000diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.pyindex c0daef9d01a7..016c55c998ed 100644--- a/posthog/temporal/common/posthog_client.py+++ b/posthog/temporal/common/posthog_client.py@@ -16,6 +16,7 @@ from temporalio.worker import (from posthog.egress.transport.transport import EgressBudgetExhaustedfrom posthog.exceptions_capture import ambient_exception_properties+from posthog.temporal.common.errors import NonReportableErrorfrom posthog.temporal.common.interceptor import ALL_TASK_QUEUESfrom posthog.temporal.common.logger import get_write_only_loggerfrom posthog.temporal.common.shutdown import WorkerShuttingDownError@@ -70,11 +71,13 @@ class _PostHogClientActivityInboundInterceptor(ActivityInboundInterceptor):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), and our own egress-budget backpressure (a deliberate "defer and retry later"- # signal that our rate limiter already records via record_outbound_decision) are expected- # control flow, not defects — re-raise without reporting them to error tracking.+ # worker), our own egress-budget backpressure (a deliberate "defer and retry later"+ # signal that our rate limiter already records via record_outbound_decision), and errors+ # explicitly marked non-reportable (expected customer/upstream conditions, e.g. a REST+ # API serving a login page instead of JSON) are expected control flow, not defects —+ # re-raise without reporting them to error tracking.if temporalio.exceptions.is_cancelled_exception(e) or isinstance(- e, EgressBudgetExhausted | WorkerShuttingDownError+ e, EgressBudgetExhausted | WorkerShuttingDownError | NonReportableError):raiseactivity_info = activity.info()diff --git a/posthog/temporal/tests/common/test_error_tracking.py b/posthog/temporal/tests/common/test_error_tracking.pyindex ac56e12aab7e..dae785e3564e 100644--- a/posthog/temporal/tests/common/test_error_tracking.py+++ b/posthog/temporal/tests/common/test_error_tracking.py@@ -16,6 +16,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.egress.github.transport import GitHubEgressBudgetExhaustedfrom posthog.exceptions_capture import bind_exception_context+from posthog.temporal.common.errors import NonReportableErrorfrom posthog.temporal.common.posthog_client import PostHogClientInterceptorfrom posthog.temporal.common.shutdown import WorkerShuttingDownError@@ -163,6 +164,28 @@ class WorkerShuttingDownActivityWorkflow:)+class _MarkedNonReportableError(NonReportableError):+ pass+++async def non_reportable_activity(inputs: OptionallyFailingInputs) -> None:+ raise _MarkedNonReportableError("expected upstream condition; job fails but no error-tracking capture")+++class NonReportableActivityWorkflow:+ @workflow.run+ async def run(self, inputs: OptionallyFailingInputs) -> None:+ await workflow.execute_activity(+ non_reportable_activity,+ inputs,+ start_to_close_timeout=dt.timedelta(minutes=1),+ heartbeat_timeout=dt.timedelta(seconds=5),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )++@workflow.defnclass DirectlyFailingWorkflow:@workflow.run@@ -363,6 +386,35 @@ async def test_worker_shutting_down_is_not_captured(temporal_client: Client):mock_ph_capture.assert_not_called()+async def test_non_reportable_error_is_not_captured(temporal_client: Client):+ """A NonReportableError (an expected customer/upstream condition, e.g. a REST source served a+ login page instead of JSON) still fails the activity, but the interceptor must re-raise it+ without reporting it to error tracking."""+ task_queue = "TEST-TASK-QUEUE"+ workflow_id = str(uuid.uuid4())++ with patch("posthog.temporal.common.posthog_client.capture_exception") as mock_ph_capture:+ async with Worker(+ temporal_client,+ task_queue=task_queue,+ workflows=[NonReportableActivityWorkflow],+ activities=[non_reportable_activity],+ interceptors=[PostHogClientInterceptor()],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ with pytest.raises(WorkflowFailureError):+ await temporal_client.execute_workflow(+ "NonReportableActivityWorkflow",+ OptionallyFailingInputs(fail=True),+ id=workflow_id,+ task_queue=task_queue,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )++ mock_ph_capture.assert_not_called()++@pytest.mark.asyncioasync def test_workflow_only_error_is_captured(temporal_client: Client):task_queue = "TEST-TASK-QUEUE"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.pyindex fc93514d2384..589482625651 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py@@ -16,6 +16,8 @@ from requests.exceptions import ()from tenacity import RetryCallState, retry, retry_if_exception_type+from posthog.temporal.common.errors import NonReportableError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom .auth import auth_secret_values@@ -33,12 +35,17 @@ class RESTClientRetryableError(Exception):self.retry_after = retry_after-class RESTClientNonRetryableError(Exception):+class RESTClientNonRetryableError(NonReportableError):"""A response that retrying can never turn into usable data.Not a subclass of RESTClientRetryableError so the tenacity retry — which onlyreissues RESTClientRetryableError — stops immediately instead of re-fetching adeterministic failure.++ Raised only for a 2xx response whose body is not JSON (an auth/login page, an HTML+ error page, plain text) — always a customer/upstream condition, never a PostHog defect.+ Subclasses NonReportableError so the activity interceptor stops it from becoming+ error-tracking noise while the job still fails with the message."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.pyindex 68cdb272bbef..6b4d3efcba71 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py@@ -8,6 +8,8 @@ from unittest.mock import MagicMock, patchfrom requests import Responsefrom requests.exceptions import ChunkedEncodingError, ProxyError+from posthog.temporal.common.errors import NonReportableError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuthfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.exceptions import (IgnoreResponseException,@@ -378,11 +380,14 @@ class TestRESTClient:mock_session.send.return_value = _make_non_json_response(content)client = RESTClient(base_url="https://api.example.com")- with pytest.raises(RESTClientNonRetryableError, match="Non-JSON response from"):+ with pytest.raises(RESTClientNonRetryableError, match="Non-JSON response from") as ctx:list(client.paginate(path="/items", paginator=SinglePagePaginator()))assert mock_session.send.call_count == 1mock_sleep.assert_not_called()+ # A non-JSON 2xx body is always a customer/upstream condition, so it must carry the+ # non-reportable marker the activity interceptor uses to keep it out of error tracking.+ assert isinstance(ctx.value, NonReportableError)@patch("tenacity.nap.time.sleep")@patch(