: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
feat(exports): skip capturing errors when the creator left the org (#72700)
Alex Liderbc446bac6128
diff --git a/posthog/caching/warming.py b/posthog/caching/warming.pyindex 1c647caf7e03..4e5610e45aff 100644--- a/posthog/caching/warming.py+++ b/posthog/caching/warming.py@@ -12,6 +12,7 @@ from celery.canvas import chainfrom prometheus_client import Counter, Gaugefrom posthog.hogql.constants import LimitContext+from posthog.hogql.errors import TableAccessDeniedErrorfrom posthog.api.services.query import process_query_dictfrom posthog.caching.utils import largest_teams@@ -23,6 +24,7 @@ from posthog.hogql_queries.query_cache_base import QueryCacheManagerBasefrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models import Teamfrom posthog.ph_client import ph_scoped_capture+from posthog.query_creator_access import creator_access_revoked, report_creator_access_revokedfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueue@@ -274,4 +276,15 @@ def warm_insight_cache_task(insight_id: int, dashboard_id: Optional[int]):except CHQueryErrorTooManySimultaneousQueries:raiseexcept Exception as e:- capture_exception(e)+ # A revoked creator's access-denied error is a known limitation - report it as an event+ # rather than surfacing it in error tracking.+ if isinstance(e, TableAccessDeniedError) and creator_access_revoked(insight.created_by, insight.team):+ report_creator_access_revoked(+ user=insight.created_by,+ team=insight.team,+ source="cache_warming",+ error=e,+ properties={"insight_id": insight.pk, "dashboard_id": dashboard_id},+ )+ else:+ capture_exception(e)diff --git a/posthog/query_creator_access.py b/posthog/query_creator_access.pynew file mode 100644index 000000000000..aae8ac9face9--- /dev/null+++ b/posthog/query_creator_access.py@@ -0,0 +1,48 @@+from typing import Any, Optional++from posthog.models.organization import OrganizationMembership+from posthog.models.team import Team+from posthog.models.user import User+from posthog.ph_client import ph_scoped_capture+++def creator_access_revoked(user: Optional[User], team: Team) -> bool:+ """True when `user` no longer has access to `team`: they were deleted (`user is None`),+ deactivated, or are no longer a member of the team's org.+ """+ if user is None:+ return True+ if not user.is_active:+ return True+ return not OrganizationMembership.objects.filter(organization_id=team.organization_id, user=user).exists()+++def report_creator_access_revoked(+ *,+ user: Optional[User],+ team: Team,+ source: str,+ error: BaseException,+ properties: Optional[dict[str, Any]] = None,+) -> None:+ """Record an analytics event for a background query that failed because its creator lost access+ (see `creator_access_revoked`). Attributed to the team — the creator may be gone or anonymous.+ `source` names the caller ("export", "alert", "cache_warming").+ """+ reason = "deleted" if user is None else "deactivated" if not user.is_active else "left_org"+ # Attributed to the team — the creator may be deleted or anonymous.+ with ph_scoped_capture() as capture:+ capture(+ distinct_id=str(team.uuid),+ # Name of the PostHog analytics event we emit - not an error or log message.+ event="background query creator access revoked",+ properties={+ "source": source,+ "reason": reason,+ "team_id": team.id,+ "organization_id": str(team.organization_id),+ "creator_user_id": user.id if user else None,+ "error": str(error),+ **(properties or {}),+ },+ )diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex b4a5afaefbc5..3546738fe40a 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -10,9 +10,12 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.schema import AlertState+from posthog.hogql.errors import TableAccessDeniedError+from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.errors import CH_TRANSIENT_ERRORSfrom posthog.exceptions_capture import capture_exception+from posthog.query_creator_access import creator_access_revoked, report_creator_access_revokedfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.sync import database_sync_to_asyncfrom posthog.tasks.alerts.investigation_notifications import run_investigation_notification_safety_net@@ -250,8 +253,31 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertReshould_notify=False, # disable_invalid_alert already emailed subscribersnew_state=AlertState.ERRORED,)+ except TableAccessDeniedError as err:+ logger.exception("Alert failed to evaluate", alert_id=alert.id, exc_info=err)+ # A revoked creator's access-denied error is a known limitation - report it as an event+ # rather than capturing it, which would recur on every check until the alert is fixed.+ if creator_access_revoked(alert.created_by, alert.team):+ report_creator_access_revoked(+ user=alert.created_by,+ team=alert.team,+ source="alert",+ error=err,+ properties={"alert_id": str(alert.id), "insight_id": alert.insight_id},+ )+ error = {"message": str(err)}+ else:+ capture_exception(+ err,+ additional_properties={+ "alert_configuration_id": str(alert.id),+ "insight_id": alert.insight_id,+ "team_id": alert.team_id,+ },+ )+ error = {"message": str(err), "traceback": traceback.format_exc()}except Exception as err:- logger.exception(f"Alert id = {alert.id}, failed to evaluate", exc_info=err)+ logger.exception("Alert failed to evaluate", alert_id=alert.id, exc_info=err)capture_exception(err,additional_properties={diff --git a/posthog/test/test_query_creator_access.py b/posthog/test/test_query_creator_access.pynew file mode 100644index 000000000000..23540b43202f--- /dev/null+++ b/posthog/test/test_query_creator_access.py@@ -0,0 +1,21 @@+from posthog.test.base import BaseTest++from posthog.models import OrganizationMembership+from posthog.query_creator_access import creator_access_revoked+++class TestCreatorAccessRevoked(BaseTest):+ def test_current_member_is_not_revoked(self) -> None:+ assert creator_access_revoked(self.user, self.team) is False++ def test_none_owner_is_revoked(self) -> None:+ assert creator_access_revoked(None, self.team) is True++ def test_deactivated_owner_is_revoked(self) -> None:+ self.user.is_active = False+ self.user.save()+ assert creator_access_revoked(self.user, self.team) is True++ def test_owner_removed_from_org_is_revoked(self) -> None:+ OrganizationMembership.objects.filter(organization=self.organization, user=self.user).delete()+ assert creator_access_revoked(self.user, self.team) is Truediff --git a/products/exports/backend/tasks/csv_exporter.py b/products/exports/backend/tasks/csv_exporter.pyindex 141da37a4fd9..08f4438d933e 100644--- a/products/exports/backend/tasks/csv_exporter.py+++ b/products/exports/backend/tasks/csv_exporter.py@@ -23,6 +23,7 @@ from rest_framework_csv.renderers import CSVRendererfrom posthog.schema import QuerySchemaRootfrom posthog.hogql.constants import CSV_EXPORT_BREAKDOWN_LIMIT_INITIAL, CSV_EXPORT_BREAKDOWN_LIMIT_LOW, CSV_EXPORT_LIMIT+from posthog.hogql.errors import TableAccessDeniedErrorfrom posthog.hogql.query import LimitContextfrom posthog.api.services.query import process_query_dict@@ -37,6 +38,7 @@ from posthog.hogql_queries.insights.utils.breakdowns import ()from posthog.hogql_queries.query_runner import ExecutionModefrom posthog.jwt import PosthogJwtAudience, encode_jwt+from posthog.query_creator_access import creator_access_revoked, report_creator_access_revokedfrom posthog.security.spreadsheet_safety import sanitize_formula_injectionfrom posthog.tasks.exporter import EXPORT_TIMERfrom posthog.utils import absolute_uri@@ -695,6 +697,23 @@ def export_tabular(else:team_id = "unknown"- capture_exception(e, additional_properties={"task": "csv_export", "team_id": team_id})logger.error("csv_exporter.failed", exception=e, exc_info=True)+ # A revoked creator's access-denied error is a known limitation - report it as an event+ # rather than surfacing it in error tracking.+ if isinstance(e, TableAccessDeniedError) and creator_access_revoked(+ exported_asset.created_by, exported_asset.team+ ):+ report_creator_access_revoked(+ user=exported_asset.created_by,+ team=exported_asset.team,+ source="export",+ error=e,+ properties={+ "exported_asset_id": exported_asset.id,+ "insight_id": exported_asset.insight_id,+ "dashboard_id": exported_asset.dashboard_id,+ },+ )+ else:+ capture_exception(e, additional_properties={"task": "csv_export", "team_id": team_id})raisediff --git a/products/exports/backend/tasks/image_exporter.py b/products/exports/backend/tasks/image_exporter.pyindex 535ccc487a3c..fa7e51b1b4d2 100644--- a/products/exports/backend/tasks/image_exporter.py+++ b/products/exports/backend/tasks/image_exporter.py@@ -20,10 +20,13 @@ from prometheus_client import Counter, Histogramfrom posthog.schema import ChartDisplayType, FunnelLayout, NodeKind+from posthog.hogql.errors import TableAccessDeniedError+from posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.event_usage import AnalyticsProps, EventSourcefrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionMode+from posthog.query_creator_access import creator_access_revoked, report_creator_access_revokedfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.security.url_validation import is_url_allowedfrom posthog.tasks.exporter import EXPORT_TIMER@@ -607,6 +610,23 @@ def export_image()except Exception as e:team_id = str(exported_asset.team.id) if exported_asset else "unknown"- capture_exception(e, additional_properties={"task": "image_export", "team_id": team_id})logger.error("image_exporter.failed", exception=e, exc_info=True)+ # A revoked creator's access-denied error is a known limitation - report it as an event+ # rather than surfacing it in error tracking.+ if isinstance(e, TableAccessDeniedError) and creator_access_revoked(+ exported_asset.created_by, exported_asset.team+ ):+ report_creator_access_revoked(+ user=exported_asset.created_by,+ team=exported_asset.team,+ source="export",+ error=e,+ properties={+ "exported_asset_id": exported_asset.id,+ "insight_id": exported_asset.insight_id,+ "dashboard_id": exported_asset.dashboard_id,+ },+ )+ else:+ capture_exception(e, additional_properties={"task": "image_export", "team_id": team_id})raise