: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(subscriptions): stop naming out-of-memory failures in AI reports (#78941)
Matt Pua6dd272a0b9ce
diff --git a/ee/tasks/subscriptions/email_subscriptions.py b/ee/tasks/subscriptions/email_subscriptions.pyindex ca569917dfbf..eef9ef60167f 100644--- a/ee/tasks/subscriptions/email_subscriptions.py+++ b/ee/tasks/subscriptions/email_subscriptions.py@@ -9,7 +9,12 @@ from posthog.utils import absolute_urifrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.models.subscription import Subscription, get_unsubscribe_token-from ee.tasks.subscriptions.subscription_utils import ASSET_GENERATION_FAILED_MESSAGE, UTM_TAGS_BASE, _has_asset_failed+from ee.tasks.subscriptions.subscription_utils import (+ ASSET_GENERATION_FAILED_MESSAGE,+ UTM_TAGS_BASE,+ _has_asset_failed,+ subscription_asset_error_message,+)logger = structlog.get_logger(__name__)@@ -26,7 +31,7 @@ def _get_asset_data_for_email(asset: ExportedAsset) -> dict:# Truncate long error messages to avoid long emailsmax_error_length = 2000if asset.exception:- error_message = str(asset.exception)+ error_message = subscription_asset_error_message(asset)if len(error_message) > max_error_length:error_message = error_message[:max_error_length] + "... (truncated)"else:diff --git a/ee/tasks/subscriptions/slack_subscriptions.py b/ee/tasks/subscriptions/slack_subscriptions.pyindex c220a31e7cf8..2a25dea37d48 100644--- a/ee/tasks/subscriptions/slack_subscriptions.py+++ b/ee/tasks/subscriptions/slack_subscriptions.py@@ -16,7 +16,12 @@ from posthog.utils import absolute_urifrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.models.subscription import Subscription-from ee.tasks.subscriptions.subscription_utils import ASSET_GENERATION_FAILED_MESSAGE, UTM_TAGS_BASE, _has_asset_failed+from ee.tasks.subscriptions.subscription_utils import (+ ASSET_GENERATION_FAILED_MESSAGE,+ UTM_TAGS_BASE,+ _has_asset_failed,+ subscription_asset_error_message,+)logger = structlog.get_logger(__name__)@@ -85,7 +90,7 @@ def _block_for_asset(asset: ExportedAsset, resource_url: str) -> dict:max_error_length = 2000if asset.exception:- exception_text = str(asset.exception)+ exception_text = subscription_asset_error_message(asset)if len(exception_text) > max_error_length:exception_text = exception_text[:max_error_length] + "... (truncated)"else:diff --git a/ee/tasks/subscriptions/subscription_utils.py b/ee/tasks/subscriptions/subscription_utils.pyindex 723d762c98fb..c39b3ee03303 100644--- a/ee/tasks/subscriptions/subscription_utils.py+++ b/ee/tasks/subscriptions/subscription_utils.py@@ -34,6 +34,23 @@ def _has_asset_failed(asset: ExportedAsset) -> bool:return (not asset.content and not asset.content_location) or asset.exception is not None+_OOM_MESSAGE_MARKER = "ran out of memory"+_OOM_EXCEPTION_TYPE = "ClickHouseQueryMemoryLimitExceeded"+++def _is_oom_exception_text(exception_text: str | None) -> bool:+ return exception_text is not None and _OOM_MESSAGE_MARKER in exception_text.lower()+++def subscription_asset_error_message(asset: ExportedAsset) -> str:+ # Recipients of scheduled subscriptions didn't author the query, so the OOM advice is+ # unactionable. Original text stays on asset.exception/exception_type for our own logs.+ is_oom_exception = asset.exception_type == _OOM_EXCEPTION_TYPE or _is_oom_exception_text(asset.exception)+ if asset.exception and not is_oom_exception:+ return asset.exception+ return ASSET_GENERATION_FAILED_MESSAGE++def generate_assets(resource: Union[Subscription, SharingConfiguration],max_asset_count: int = MAX_INSIGHTS,diff --git a/ee/tasks/test/subscriptions/test_email_subscriptions.py b/ee/tasks/test/subscriptions/test_email_subscriptions.pyindex cea358353187..1fb7bdd8e19a 100644--- a/ee/tasks/test/subscriptions/test_email_subscriptions.py+++ b/ee/tasks/test/subscriptions/test_email_subscriptions.py@@ -150,6 +150,23 @@ class TestEmailSubscriptionsTasks(APIBaseTest):assert "AI summary:" in mocked_email_messages[0].html_bodyassert "AI summary skipped" not in mocked_email_messages[0].html_body+ def test_hides_out_of_memory_cause_in_failed_asset(self, MockEmailMessage: MagicMock) -> None:+ mocked_email_messages = mock_ee_email_messages(MockEmailMessage)+ oom_error = (+ "This query ran out of memory before it could finish, usually because it's scanning too "+ "much data. Try a shorter date range or narrower filters."+ )+ failed_asset = ExportedAsset.objects.create(+ team=self.team, insight_id=self.insight.id, export_format="image/png", exception=oom_error+ )++ send_email_subscription_report("[email protected]", self.subscription, [failed_asset])++ body = mocked_email_messages[0].html_body+ assert "ran out of memory" not in body+ assert "shorter date range" not in body+ assert "Failed to generate content" in body+def test_same_recipient_gets_distinct_campaign_per_subscription(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_ee_email_messages(MockEmailMessage)diff --git a/ee/tasks/test/subscriptions/test_slack_subscriptions.py b/ee/tasks/test/subscriptions/test_slack_subscriptions.pyindex 1440d08a3c49..58c1e8a9953c 100644--- a/ee/tasks/test/subscriptions/test_slack_subscriptions.py+++ b/ee/tasks/test/subscriptions/test_slack_subscriptions.py@@ -660,6 +660,22 @@ class TestSlackErrorTruncation(APIBaseTest):assert "*My Test subscription*" in textassert ASSET_GENERATION_FAILED_MESSAGE in text+ def test_block_for_asset_hides_out_of_memory_cause(self) -> None:+ oom_error = (+ "This query ran out of memory before it could finish, usually because it's scanning too "+ "much data. Try a shorter date range or narrower filters."+ )+ asset = ExportedAsset.objects.create(+ team=self.team, insight_id=self.insight.id, export_format="image/png", exception=oom_error+ )++ block = _block_for_asset(asset, resource_url="https://app.posthog.com/insights/123456")++ text = block["text"]["text"]+ assert "ran out of memory" not in text+ assert "shorter date range" not in text+ assert ASSET_GENERATION_FAILED_MESSAGE in text+class TestSlackSummaryNotice(APIBaseTest):def setUp(self) -> None:diff --git a/ee/tasks/test/subscriptions/test_subscriptions_utils.py b/ee/tasks/test/subscriptions/test_subscriptions_utils.pyindex 0954b1a31c39..1d8cbe394156 100644--- a/ee/tasks/test/subscriptions/test_subscriptions_utils.py+++ b/ee/tasks/test/subscriptions/test_subscriptions_utils.py@@ -2,12 +2,19 @@ import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from parameterized import parameterized+from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.product_analytics.backend.models.insight import Insight-from ee.tasks.subscriptions.subscription_utils import MAX_INSIGHTS, generate_assets+from ee.tasks.subscriptions.subscription_utils import (+ ASSET_GENERATION_FAILED_MESSAGE,+ MAX_INSIGHTS,+ generate_assets,+ subscription_asset_error_message,+)from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription@@ -91,3 +98,53 @@ class TestSubscriptionsTasksUtils(APIBaseTest):assert str(e.value) == "Timed out waiting for celery task to finish"running_export_task.revoke.assert_called()+++class TestSubscriptionAssetErrorMessage(APIBaseTest):+ def _asset(self, exception: str | None, exception_type: str | None = None) -> ExportedAsset:+ return ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ exception=exception,+ exception_type=exception_type,+ )++ def setUp(self) -> None:+ super().setUp()+ self.insight = Insight.objects.create(team=self.team, short_id="123456", name="My Test subscription")++ @parameterized.expand(+ [+ (+ "passes_through_non_oom_text",+ "Unknown table 'nonexistent_table'",+ None,+ "Unknown table 'nonexistent_table'",+ ),+ (+ "replaces_out_of_memory_text",+ "This query ran out of memory before it could finish, usually because it's scanning too much data.",+ None,+ ASSET_GENERATION_FAILED_MESSAGE,+ ),+ (+ "replaces_out_of_memory_regardless_of_casing",+ "Query Ran Out Of Memory",+ None,+ ASSET_GENERATION_FAILED_MESSAGE,+ ),+ (+ "replaces_memory_limit_exception_by_type",+ "Memory limit (for query) exceeded",+ "ClickHouseQueryMemoryLimitExceeded",+ ASSET_GENERATION_FAILED_MESSAGE,+ ),+ ("falls_back_when_no_exception", None, None, ASSET_GENERATION_FAILED_MESSAGE),+ ]+ )+ def test_subscription_asset_error_message(+ self, _name: str, exception: str | None, exception_type: str | None, expected: str+ ) -> None:+ asset = self._asset(exception, exception_type)+ assert subscription_asset_error_message(asset) == expecteddiff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.pyindex b4e1a4c22a08..15d20e8df950 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py@@ -45,7 +45,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generabuild_enriched_prompt,build_frozen_prompt,)-from products.exports.backend.temporal.subscriptions.types import safe_error_message+from products.exports.backend.temporal.subscriptions.types import safe_error_message, undisclosed_query_error_typefrom ee.hogai.context.insight.query_executor import AssistantQueryExecutorfrom ee.hogai.llm import MaxChatOpenAI@@ -446,25 +446,26 @@ async def _run_steps(breakcurrent_hogql = fixed+ # type only — ClickHouse errors can echo team-scoped identifiers+ type_name = type(last_exc).__name__ if last_exc is not None else "UnknownError"+ undisclosed_type = undisclosed_query_error_type(last_exc) if last_exc is not None else Nonelogger.warning("ai_report.query_failed",trace_correlation_id=trace_correlation_id,step_description=safe_description,+ error_type=type_name,exc_info=last_exc,)if last_exc is not None:capture_exception(last_exc, {"trace_correlation_id": trace_correlation_id, "stage": "query"})- # type only — ClickHouse errors can echo team-scoped identifiers- type_name = type(last_exc).__name__ if last_exc is not None else "UnknownError"- # Explicit failure marker, distinct from a genuinely-empty result, so synthesis reports the- # metric as "could not be computed" instead of paraphrasing the failure into "no data".+ cause = "" if undisclosed_type is not None else f" ({type_name})"return (- f"### {safe_description}\n\n_{QUERY_FAILED_PREFIX} ({type_name}) — metric not computed, not empty data._",+ f"### {safe_description}\n\n_{QUERY_FAILED_PREFIX}{cause} — metric not computed, not empty data._",QueryStepDiagnostic(description=safe_description,hogql=window.render_window_filter(current_hogql),ok=False,- error_type=type_name,+ error_type=undisclosed_type or type_name,human_readable_error=safe_error_message(last_exc) if last_exc is not None else None,),)diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.pyindex 561f3694b07b..501dbf5f0407 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py@@ -6,6 +6,8 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, ResolutionError+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded+from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import (_MAX_CONCURRENT_STEPS,QUERY_FAILED_PREFIX,@@ -31,6 +33,8 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_genera)from products.exports.backend.temporal.subscriptions.types import safe_error_message+from ee.hogai.tool_errors import MaxToolRetryableError+_RP = "products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline"_SG = "products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator"# slo_operation emits through posthoganalytics.capture; patch that boundary to inspect the SLO events.@@ -262,6 +266,33 @@ async def test_run_steps_non_retryable_error_degrades_to_placeholder(mock_executassert diagnostics[0].hogql == "SELECT 1"+@patch(f"{_RP}.AssistantQueryExecutor")+async def test_run_steps_placeholder_omits_undisclosed_error_type(mock_executor_cls: MagicMock) -> None:+ mock_executor_cls.return_value.arun_and_format_query = AsyncMock(side_effect=ClickHouseQueryMemoryLimitExceeded())+ rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), _test_window(), None)+ assert failed == 1+ assert rendered[0] == f"### s0\n\n_{QUERY_FAILED_PREFIX} — metric not computed, not empty data._"+ assert diagnostics[0].error_type == "ClickHouseQueryMemoryLimitExceeded"+ assert diagnostics[0].human_readable_error is None+++@patch(f"{_RP}.AssistantQueryExecutor")+@patch(f"{_RP}._arequest_hogql_fix", new_callable=AsyncMock, return_value=None)+async def test_run_steps_placeholder_omits_wrapped_undisclosed_error_type(+ mock_hogql_fix: AsyncMock, mock_executor_cls: MagicMock+) -> None:+ error = MaxToolRetryableError("Memory limit exceeded")+ error.__cause__ = ClickHouseQueryMemoryLimitExceeded()+ mock_executor_cls.return_value.arun_and_format_query = AsyncMock(side_effect=error)++ rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), _test_window(), None)++ assert failed == 1+ assert rendered[0] == f"### s0\n\n_{QUERY_FAILED_PREFIX} — metric not computed, not empty data._"+ assert diagnostics[0].error_type == "ClickHouseQueryMemoryLimitExceeded"+ mock_hogql_fix.assert_awaited_once()++@patch(f"{_RP}._arequest_hogql_fix", new_callable=AsyncMock)@patch(f"{_RP}.AssistantQueryExecutor")async def test_run_steps_forwards_resolution_error_message_to_fix(diff --git a/products/exports/backend/temporal/subscriptions/test_types.py b/products/exports/backend/temporal/subscriptions/test_types.pyindex 6bf8aabf32f8..9c9c0a6e5bb3 100644--- a/products/exports/backend/temporal/subscriptions/test_types.py+++ b/products/exports/backend/temporal/subscriptions/test_types.py@@ -1,6 +1,16 @@from parameterized import parameterized-from products.exports.backend.temporal.subscriptions.types import DeliveryStatus, GenerateAIReportResult+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded++from products.exports.backend.temporal.subscriptions.types import (+ UNDISCLOSED_QUERY_ERROR_TYPES,+ DeliveryStatus,+ GenerateAIReportResult,+)+++def test_undisclosed_query_error_types_track_the_exception_class() -> None:+ assert ClickHouseQueryMemoryLimitExceeded.__name__ in UNDISCLOSED_QUERY_ERROR_TYPESclass TestGenerateAIReportResult:@@ -48,6 +58,18 @@ class TestGenerateAIReportResult:["ExposedHogQLError", "ResolutionError"],"All 2 queries the AI generated failed to run (ExposedHogQLError, ResolutionError), so the report could not be computed.",),+ (+ "undisclosed_type_leaves_no_detail",+ 1,+ ["ClickHouseQueryMemoryLimitExceeded"],+ "The query the AI generated failed to run, so the report could not be computed.",+ ),+ (+ "undisclosed_type_dropped_from_mixed_detail",+ 2,+ ["ClickHouseQueryMemoryLimitExceeded", "ResolutionError"],+ "All 2 queries the AI generated failed to run (ResolutionError), so the report could not be computed.",+ ),])def test_failure_error(self, _name, total: int, error_types: list[str], expected_message: str) -> None:diff --git a/products/exports/backend/temporal/subscriptions/types.py b/products/exports/backend/temporal/subscriptions/types.pyindex 128741ed2dc2..de79b9f322a5 100644--- a/products/exports/backend/temporal/subscriptions/types.py+++ b/products/exports/backend/temporal/subscriptions/types.py@@ -6,6 +6,24 @@ from posthog.hogql.errors import ExposedHogQLError, ResolutionErrorfrom posthog.slo.types import SloConfig+# AI report query failures we never name in owner/recipient-facing copy. The recipient didn't+# write the query, so the OOM advice is unactionable. Type still lands in diagnostics, logs, and+# error tracking. Held as a name (not the class) so this module stays free of Django/DRF imports+# for the Temporal sandbox; the test pins it to ClickHouseQueryMemoryLimitExceeded.__name__.+UNDISCLOSED_QUERY_ERROR_TYPES = frozenset({"ClickHouseQueryMemoryLimitExceeded"})+++def undisclosed_query_error_type(exc: BaseException) -> typing.Optional[str]:+ seen: set[int] = set()+ current: typing.Optional[BaseException] = exc+ while current is not None and id(current) not in seen:+ type_name = type(current).__name__+ if type_name in UNDISCLOSED_QUERY_ERROR_TYPES:+ return type_name+ seen.add(id(current))+ current = current.__cause__ or (None if current.__suppress_context__ else current.__context__)+ return None+def safe_error_message(exc: BaseException) -> typing.Optional[str]:"""Owner-safe snippet of an exception, or None when the text may carry team-scoped data.@@ -266,7 +284,8 @@ class GenerateAIReportResult:def failure_error(self) -> dict[str, str]:# Access-safe reason recorded on a fully-degraded delivery's error column: failure counts and# error-type names only (query_error_types are exception class names), never raw query content.- detail = f" ({', '.join(self.query_error_types)})" if self.query_error_types else ""+ disclosed_types = [t for t in self.query_error_types if t not in UNDISCLOSED_QUERY_ERROR_TYPES]+ detail = f" ({', '.join(disclosed_types)})" if disclosed_types else ""subject = ("The query the AI generated"if self.total_step_count == 1