: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(aio): prevent unwanted evaluation disabled emails (#104753)
posthog[bot]80b1ef2f2c92
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 56fb41a65925..b13ca3c2321e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11297,9 +11297,9 @@ snapshots:scenes-app-settings-user--settings-user-navigation--light:hash: v1.k794b7964.a4061da91e7c33e6b70809f56174bcdf6367de383cdf7f4bd44ce933ac4ef789.CL6GK2S3yJDBY8GcRukzMatIbh7G5prl8YxdZYxf3c0scenes-app-settings-user--settings-user-notifications--dark:- hash: v1.k794b7964.71bacadb9ac5b0c487720425bf966d89a9c54f455faa1a892ff5ea907f6e329e.zXpXJ8VNwNQLHAZ2zdWcAv4Dlrp2aYxY6RxMaQt2SPU+ hash: v1.k794b7964.2204e0a2e6d5fadb35dbbe13c68b9af2fe4052473a34e9562299bddfb7687eb1.xG738ieu2EfqR-FhuyuG916gXJawaPw_aCHVcVvWGbcscenes-app-settings-user--settings-user-notifications--light:- hash: v1.k794b7964.f4d030083926f31fbda564b41ee7405b79debd470db6396116423813ae948342.TrlewkCNonzpNstsoZTjggpzXBAbvkl6_CCV8Y8XmkI+ hash: v1.k794b7964.6dc077d049e7b4c5ce8c3a623b281a7d02f43647a2f3edcb7c624555296246eb.XJPMz9qmz5R2ocrf49XL8yyGAF2bRbZfPe9VTyyzK4wscenes-app-settings-user--settings-user-profile--dark:hash: v1.k794b7964.5f1d9971d5da44a5868c6f1cfc633fa5e2f90d0f31e9ed651783f949512350ab.3b41GlzDKrj_9lsTioV2GDzEZDpVY2GAiAEmGjKdA9cscenes-app-settings-user--settings-user-profile--light:diff --git a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsxindex 232076ceb320..4356508ae5ac 100644--- a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx+++ b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx@@ -24,6 +24,7 @@ enum NotificationBlock {CommentMentions = 'comment-mentions',ApiKeyExposure = 'api-key-exposure',MaterializedViewSync = 'materialized-view-sync',+ AiEvaluationDisabled = 'ai-evaluation-disabled',}const NOTIFICATION_BLOCK_ORDER = Object.values(NotificationBlock)@@ -43,6 +44,7 @@ const NOTIFICATION_DEFAULTS: BooleanNotificationSettings = {discussions_mentioned: true,all_weekly_digest_disabled: false,project_api_key_exposed: true,+ ai_evaluation_disabled: true,materialized_view_sync_failed: false,materialized_view_sync_failed_daily: true,materialized_view_sync_failed_immediate: false,@@ -563,6 +565,16 @@ export function UpdateEmailPreferences(): JSX.Element {/></div>),+ [NotificationBlock.AiEvaluationDisabled]: (+ <div className="border rounded p-4">+ <SimpleSwitch+ setting="ai_evaluation_disabled"+ label="Disabled AI evaluations"+ description="Get notified when an AI observability evaluation stops because of an error"+ dataAttr="ai_evaluation_disabled_enabled"+ />+ </div>+ ),[NotificationBlock.MaterializedViewSync]: (<div className="border rounded p-4 space-y-3"><SimpleSwitchdiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 75fc9df59f80..ae3331f2c5eb 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -475,6 +475,7 @@ export interface NotificationSettings {discussions_mentioned: booleandata_pipeline_error_threshold?: numberproject_api_key_exposed?: boolean+ ai_evaluation_disabled?: booleanmaterialized_view_sync_failed?: booleanmaterialized_view_sync_failed_daily?: booleanmaterialized_view_sync_failed_immediate?: booleandiff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex ff9b48ca13eb..7187f89df2b8 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -2280,6 +2280,7 @@ class TestUserAPI(APIBaseTest):"error_tracking_weekly_digest": True,"data_pipeline_error_threshold": 0.1,"project_api_key_exposed": True,+ "ai_evaluation_disabled": True,"materialized_view_sync_failed": True,"materialized_view_sync_failed_daily": True,"materialized_view_sync_failed_immediate": False,@@ -2303,6 +2304,7 @@ class TestUserAPI(APIBaseTest):"error_tracking_weekly_digest": True,"data_pipeline_error_threshold": 0.1,"project_api_key_exposed": True,+ "ai_evaluation_disabled": True,"materialized_view_sync_failed": True,"materialized_view_sync_failed_daily": True,"materialized_view_sync_failed_immediate": False,@@ -2574,6 +2576,7 @@ class TestUserAPI(APIBaseTest):"error_tracking_weekly_digest": True, # Default value"data_pipeline_error_threshold": 0.01, # Default value"project_api_key_exposed": True, # Default value+ "ai_evaluation_disabled": True, # Default value"materialized_view_sync_failed": False, # Default value"materialized_view_sync_failed_daily": True, # Default value"materialized_view_sync_failed_immediate": False, # Default valuediff --git a/posthog/models/user.py b/posthog/models/user.pyindex bb240a43c0fc..8fe1ac994813 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -52,6 +52,7 @@ class Notifications(TypedDict, total=False):float # Failure rate threshold (0.0 to 1.0) - only notify if failure rate exceeds this)project_api_key_exposed: bool+ ai_evaluation_disabled: bool # One email each time an AI observability evaluation is auto-disabledmaterialized_view_sync_failed: boolmaterialized_view_sync_failed_daily: bool # One digest a day summarizing failing viewsmaterialized_view_sync_failed_immediate: bool # One email each time a view starts failing@@ -78,6 +79,7 @@ NOTIFICATION_DEFAULTS: Notifications = {"all_weekly_digest_disabled": False, # Weekly digests enabled by default"data_pipeline_error_threshold": 0.01, # Default: notify when failure rate exceeds 1%"project_api_key_exposed": True, # Private project API key (secure API key) exposure alerts enabled by default+ "ai_evaluation_disabled": True, # Auto-disabled evaluation emails enabled by default"materialized_view_sync_failed": False, # Materialized view failure disabled by default"materialized_view_sync_failed_daily": True, # Digest is the default delivery once failures are turned on"materialized_view_sync_failed_immediate": False,diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex e0d0de509ff7..49bb3e859f7a 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -78,6 +78,7 @@ class NotificationSetting(Enum):ERROR_TRACKING_WEEKLY_DIGEST = "error_tracking_weekly_digest"DISCUSSIONS_MENTIONED = "discussions_mentioned"PROJECT_API_KEY_EXPOSED = "project_api_key_exposed"+ AI_EVALUATION_DISABLED = "ai_evaluation_disabled"MATERIALIZED_VIEW_SYNC_FAILED = "materialized_view_sync_failed"MATERIALIZED_VIEW_SYNC_FAILED_DAILY = "materialized_view_sync_failed_daily"MATERIALIZED_VIEW_SYNC_FAILED_IMMEDIATE = "materialized_view_sync_failed_immediate"@@ -91,6 +92,7 @@ NotificationSettingType = Literal["error_tracking_weekly_digest","discussions_mentioned","project_api_key_exposed",+ "ai_evaluation_disabled","materialized_view_sync_failed","materialized_view_sync_failed_daily","materialized_view_sync_failed_immediate",@@ -346,6 +348,9 @@ def should_send_notification(elif notification_type == NotificationSetting.PROJECT_API_KEY_EXPOSED.value:return settings.get(notification_type, True)+ elif notification_type == NotificationSetting.AI_EVALUATION_DISABLED.value:+ return settings.get(notification_type, True)+elif notification_type == NotificationSetting.MATERIALIZED_VIEW_SYNC_FAILED.value:return settings.get(notification_type, False)diff --git a/posthog/templates/email/ai_observability_evaluation_disabled.html b/posthog/templates/email/ai_observability_evaluation_disabled.htmlindex 7c6c94359537..cc06c4e30536 100644--- a/posthog/templates/email/ai_observability_evaluation_disabled.html+++ b/posthog/templates/email/ai_observability_evaluation_disabled.html@@ -31,4 +31,7 @@or<a href="https://posthog.com/docs/ai-engineering?{{ utm_tags }}"target="_blank"><b>read our documentation</b></a>.+ <br />+ <br />+ <a href="{% absolute_uri '/settings/user-notifications' %}">Manage these notifications in PostHog</a>{% endblock %}diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex e3c6bcd99ac6..40ece693ef46 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -26,6 +26,7 @@ from posthog.temporal.ai_observability.evaluation_types import EvaluationActivitfrom posthog.temporal.ai_observability.metrics import increment_emit_event_outcomefrom posthog.temporal.ai_observability.team_capture import capture_ai_internal_for_team+from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.ai_observability.backend.models.evaluations import Evaluation, EvaluationStatusfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey@@ -127,9 +128,10 @@ async def disable_evaluation_activity() -> bool:"""Transition an evaluation into the ERROR state when the workflow hits a terminal skippable error.- Returns True only for the first workflow that disables the evaluation. Later in-flight+ Returns True only for the first workflow that disables a running evaluation. Later in-flightworkflows can hit the same terminal error after the first transition, but shouldn't send- duplicate disabled notifications or write duplicate activity log rows.+ duplicate disabled notifications or write duplicate activity log rows. An evaluation that was+ already off keeps its new error state, but returns False, because nothing was disabled."""def _disable() -> bool:@@ -142,8 +144,9 @@ async def disable_evaluation_activity(if evaluation.status == EvaluationStatus.ERROR and not evaluation.enabled:return False+ was_enabled = evaluation.enabledevaluation.set_status("error", reason, status_reason_detail)- return True+ return was_enabledreturn await database_sync_to_async(_disable)()@@ -173,10 +176,11 @@ _STATUS_REASON_SUBJECTS = {@temporalio.activity.defnasync def send_evaluation_disabled_email_activity(inputs: SendEvaluationDisabledEmailInputs) -> None:- """Email org members when an evaluation enters the ERROR state."""+ """Email subscribed org members who can view the evaluation when it enters the ERROR state."""def _send() -> None:from posthog.email import EmailMessage, is_email_available+ from posthog.tasks.email import NotificationSetting, get_members_to_notifyif not is_email_available(with_absolute_urls=True):logger.info(@@ -192,6 +196,15 @@ async def send_evaluation_disabled_email_activity(inputs: SendEvaluationDisabledlogger.warning("Team not found for evaluation disabled email", team_id=inputs.team_id)return+ evaluation = Evaluation.objects.filter(id=inputs.evaluation_id, team_id=team.id, deleted=False).first()+ if evaluation is None:+ logger.info(+ "Evaluation not found for evaluation disabled email",+ team_id=inputs.team_id,+ evaluation_id=inputs.evaluation_id,+ )+ return+settings_url = f"/project/{team.pk}/settings/project-ai-observability#ai-observability-byok"evaluation_url = f"/project/{team.pk}/ai-evals/evaluations/{inputs.evaluation_id}"campaign_key = f"llm_analytics_eval_disabled_{inputs.evaluation_id}_{inputs.status_reason}"@@ -213,8 +226,9 @@ async def send_evaluation_disabled_email_activity(inputs: SendEvaluationDisabled},)- for user in team.organization.members.all():- message.add_user_recipient(user)+ for membership in get_members_to_notify(team, NotificationSetting.AI_EVALUATION_DISABLED.value):+ if UserAccessControl(membership.user, team).check_access_level_for_object(evaluation, "viewer"):+ message.add_user_recipient(membership.user)if message.to:message.send()diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 292850ffccc3..186e69a6bd59 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -7,7 +7,7 @@ import pytestfrom unittest.mock import AsyncMock, MagicMock, patchimport posthoganalytics-from asgiref.sync import sync_to_async+from asgiref.sync import async_to_sync, sync_to_asyncfrom parameterized import parameterizedfrom pydantic import ValidationError as PydanticValidationErrorfrom temporalio import activity@@ -17,10 +17,12 @@ from temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Workerfrom posthog.api.capture import CaptureInternalError-from posthog.models import Organization, Team+from posthog.constants import AvailableFeature+from posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.temporal.ai_observability.sentiment.extraction import truncate_to_head_tailfrom posthog.temporal.ai_observability.sentiment.schema import SentimentResult+from products.access_control.backend.models.access_control import AccessControlfrom products.ai_observability.backend.llm.errors import (AuthenticationError,ContextWindowExceededError,@@ -1656,7 +1658,8 @@ class TestRunEvaluationWorkflow:@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_disable_evaluation_activity(self, setup_data):+ @pytest.mark.parametrize("initial_status,expected_disabled", [("active", True), ("paused", False)])+ async def test_disable_evaluation_activity(self, setup_data, initial_status: str, expected_disabled: bool) -> None:from posthog.models.activity_logging.activity_log import ActivityLogevaluation = setup_data["evaluation"]@@ -1665,17 +1668,21 @@ class TestRunEvaluationWorkflow:directory = await sync_to_async(lambda: EvaluationDirectory.objects.for_team(team.id).create(team=team, name="Quality"))()- await sync_to_async(lambda: Evaluation.objects.filter(id=evaluation.id).update(directory=directory))()+ await sync_to_async(+ lambda: Evaluation.objects.filter(id=evaluation.id).update(+ directory=directory, status=initial_status, enabled=expected_disabled+ )+ )()await sync_to_async(evaluation.refresh_from_db)()- assert evaluation.enabled+ assert evaluation.enabled is expected_disableddisabled = await disable_evaluation_activity(str(evaluation.id), team.id, "hog_error", "Must return boolean, got int: 42")await sync_to_async(evaluation.refresh_from_db)()- assert disabled is True+ assert disabled is expected_disabledassert not evaluation.enabledassert evaluation.status == "error"assert evaluation.status_reason == "hog_error"@@ -1688,7 +1695,7 @@ class TestRunEvaluationWorkflow:detail = logs[0].detailassert detail is not Nonefields = {c["field"]: c for c in detail["changes"]}- assert fields["status"]["before"] == "active"+ assert fields["status"]["before"] == initial_statusassert fields["status"]["after"] == "error"assert fields["status_reason"]["after"] == "hog_error"assert fields["status_reason_detail"]["after"] == "Must return boolean, got int: 42"@@ -2886,29 +2893,81 @@ class TestExecuteHogEvalActivityAllowsNA:class TestSendEvaluationDisabledEmailActivity:@pytest.fixturedef setup_data(self, db):- from posthog.models import Organization, Team, User-organization = Organization.objects.create(name="Test Org")- User.objects.create_and_join(organization=organization, email="[email protected]", password="password")+ user = User.objects.create_and_join(organization=organization, email="[email protected]", password="password")team = Team.objects.create(organization=organization, name="Test Team")- return {"team": team, "organization": organization}+ evaluation = Evaluation.objects.create(+ team=team,+ name="My Eval",+ created_by=user,+ evaluation_type="hog",+ evaluation_config={"source": "return true"},+ output_type="boolean",+ )+ return {"team": team, "organization": organization, "evaluation": evaluation}- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- async def test_sends_email_with_evaluation_disabled_template(self, setup_data):+ @pytest.mark.django_db+ @pytest.mark.parametrize(+ "notification_enabled,project_access,evaluation_access,object_access,should_receive",+ [+ pytest.param(None, None, None, None, True, id="enabled-by-default"),+ pytest.param(True, None, "viewer", None, True, id="viewer-opted-in"),+ pytest.param(False, None, "viewer", None, False, id="viewer-opted-out"),+ pytest.param(None, "none", "viewer", None, False, id="no-project-access"),+ pytest.param(None, None, "none", None, False, id="no-evaluation-access"),+ pytest.param(None, None, "viewer", "none", False, id="evaluation-object-denied"),+ pytest.param(None, None, "none", "viewer", True, id="evaluation-object-granted"),+ ],+ )+ def test_sends_email_with_evaluation_disabled_template(+ self,+ setup_data,+ notification_enabled: bool | None,+ project_access: str | None,+ evaluation_access: str | None,+ object_access: str | None,+ should_receive: bool,+ ) -> None:team = setup_data["team"]+ organization = setup_data["organization"]+ evaluation = setup_data["evaluation"]+ organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ organization.save()+ member = User.objects.create_and_join(organization, "[email protected]", "password")+ membership = OrganizationMembership.objects.get(organization=organization, user=member)+ if notification_enabled is not None:+ member.partial_notification_settings = {"ai_evaluation_disabled": notification_enabled}+ member.save(update_fields=["partial_notification_settings"])+ for resource, resource_id, access_level in [+ ("project", str(team.id), project_access),+ ("evaluation", None, evaluation_access),+ ("evaluation", str(evaluation.id), object_access),+ ]:+ if access_level is not None:+ AccessControl.objects.create(+ team=team,+ resource=resource,+ resource_id=resource_id,+ access_level=access_level,+ organization_member=membership,+ )with (patch("posthog.email.is_email_available", return_value=True),patch("posthog.email.EmailMessage") as mock_email_class,):mock_message = MagicMock()+ mock_message.to = []+ mock_message.add_user_recipient.side_effect = lambda user: mock_message.to.append(user.email)mock_email_class.return_value = mock_message- await send_evaluation_disabled_email_activity(+ async_to_sync(send_evaluation_disabled_email_activity)(SendEvaluationDisabledEmailInputs(team_id=team.id,- evaluation_id="eval-123",+ evaluation_id=str(evaluation.id),evaluation_name="My Eval",status_reason="provider_key_required",human_readable_reason="Add a provider API key to run this evaluation.",@@ -2925,21 +2984,80 @@ class TestSendEvaluationDisabledEmailActivity:assert "provider_key_required" in call_kwargs["campaign_key"]# It also includes the disable timestamp so a later same-reason disable sends a fresh email.assert "1782388800000000" in call_kwargs["campaign_key"]+ expected_recipients = {"[email protected]", "[email protected]"} if should_receive else {"[email protected]"}+ assert set(mock_message.to) == expected_recipientsmock_message.send.assert_called_once()- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- async def test_skips_when_email_not_available(self, setup_data):+ @pytest.mark.django_db+ def test_does_not_email_a_member_who_turned_the_notification_off(self, setup_data) -> None:+ team = setup_data["team"]+ user = setup_data["organization"].members.get()+ user.partial_notification_settings = {"ai_evaluation_disabled": False}+ user.save(update_fields=["partial_notification_settings"])++ with (+ patch("posthog.email.is_email_available", return_value=True),+ patch("posthog.email.EmailMessage") as mock_email_class,+ ):+ mock_message = MagicMock()+ mock_message.to = []+ mock_email_class.return_value = mock_message++ async_to_sync(send_evaluation_disabled_email_activity)(+ SendEvaluationDisabledEmailInputs(+ team_id=team.id,+ evaluation_id=str(setup_data["evaluation"].id),+ evaluation_name="My Eval",+ status_reason="provider_key_required",+ human_readable_reason="reason",+ )+ )++ mock_message.add_user_recipient.assert_not_called()+ mock_message.send.assert_not_called()++ @pytest.mark.django_db+ @pytest.mark.parametrize("unavailable_reason", ["deleted", "missing", "different-team"])+ def test_skips_unavailable_evaluation(self, setup_data, unavailable_reason: str) -> None:+ evaluation = setup_data["evaluation"]+ evaluation_id = str(evaluation.id)+ if unavailable_reason == "deleted":+ evaluation.deleted = True+ evaluation.save(update_fields=["deleted"])+ elif unavailable_reason == "missing":+ evaluation_id = str(uuid.uuid4())+ else:+ evaluation.team = Team.objects.create(organization=setup_data["organization"], name="Other project")+ evaluation.save(update_fields=["team"])++ with (+ patch("posthog.email.is_email_available", return_value=True),+ patch("posthog.email.EmailMessage") as mock_email_class,+ ):+ async_to_sync(send_evaluation_disabled_email_activity)(+ SendEvaluationDisabledEmailInputs(+ team_id=setup_data["team"].id,+ evaluation_id=evaluation_id,+ evaluation_name="My Eval",+ status_reason="provider_key_required",+ human_readable_reason="reason",+ )+ )++ mock_email_class.assert_not_called()++ @pytest.mark.django_db+ def test_skips_when_email_not_available(self, setup_data) -> None:team = setup_data["team"]with (patch("posthog.email.is_email_available", return_value=False),patch("posthog.email.EmailMessage") as mock_email_class,):- await send_evaluation_disabled_email_activity(+ async_to_sync(send_evaluation_disabled_email_activity)(SendEvaluationDisabledEmailInputs(team_id=team.id,- evaluation_id="eval-123",+ evaluation_id=str(setup_data["evaluation"].id),evaluation_name="My Eval",status_reason="provider_key_required",human_readable_reason="reason",