Skip to content

: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.

fix(subscriptions): explain query memory failures (#88537)

Vasco de Krijger2618cc177dd8
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index 9ab97f8591f8..9769f75a524a 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -65,6 +65,7 @@ from products.exports.backend.temporal.subscriptions.types import (
AI_REPORT_CHARTS_KEY,
AI_REPORT_DIAGNOSTICS_KEY,
AI_REPORT_PROMPT_SNAPSHOT_KEY,
+ AI_REPORT_QUERY_FAILURE_TYPE,
AI_REPORT_SNAPSHOT_KEY,
ProcessSubscriptionWorkflowInputs,
SubscriptionTriggerType,
@@ -1523,6 +1524,11 @@ class AIReportQueryDiagnosticSerializer(serializers.Serializer):
error_type = serializers.CharField(
allow_null=True, help_text="Exception class name when the query failed; null on success."
)
+ error_code = serializers.CharField(
+ allow_null=True,
+ required=False,
+ help_text="Stable query API error code when available; null on success and for unclassified errors.",
+ )
human_readable_error = serializers.CharField(
allow_null=True,
required=False,
@@ -1533,6 +1539,10 @@ class AIReportQueryDiagnosticSerializer(serializers.Serializer):
class SubscriptionDeliverySerializer(serializers.ModelSerializer):
+ AI_REPORT_SCRUBBED_ERROR = {
+ "type": AI_REPORT_QUERY_FAILURE_TYPE,
+ "message": "The report could not be computed.",
+ }
# Delivery fields that embed the query-derived AI report, mapped to the value each returns when
# scrubbed for a caller without query access (content_snapshot is a non-null object, the rest
# nullable). Single source of truth — keep in sync when adding AI-derived delivery fields.
@@ -1661,6 +1671,8 @@ class SubscriptionDeliverySerializer(serializers.ModelSerializer):
# user-authored and already readable on the subscription, so it is deliberately not scrubbed.
if self.context.get("hide_ai_report"):
data.update(self.AI_REPORT_SCRUBBED)
+ if isinstance(data.get("error"), dict) and data["error"].get("type") == AI_REPORT_QUERY_FAILURE_TYPE:
+ data["error"] = self.AI_REPORT_SCRUBBED_ERROR
return data
# The AI report now ships via the typed ai_report / ai_report_diagnostics / ai_report_prompt
# fields, so drop the same keys from content_snapshot to avoid shipping the report twice.
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index 31f9f4be6563..34ea730d5ecd 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -36,6 +36,7 @@ from products.exports.backend.temporal.subscriptions.types import (
AI_REPORT_CHARTS_KEY,
AI_REPORT_DIAGNOSTICS_KEY,
AI_REPORT_PROMPT_SNAPSHOT_KEY,
+ AI_REPORT_QUERY_FAILURE_TYPE,
AI_REPORT_SNAPSHOT_KEY,
ProcessSubscriptionWorkflowInputs,
SubscriptionTriggerType,
@@ -2382,6 +2383,19 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
generated_hogql = "SELECT count() FROM events"
# The safe error message on a failed step is query-derived too, so it is scrubbed with the diagnostics.
scrubbed_error_message = "Unable to resolve field 'adoption_rate'"
+ query_error_code = "hogql_resolution_error"
+ query_failure_error = {
+ "type": AI_REPORT_QUERY_FAILURE_TYPE,
+ "code": query_error_code,
+ "message": "The query the AI generated failed to run (ResolutionError), so the report could not be computed.",
+ "details": [
+ {
+ "type": "ResolutionError",
+ "code": query_error_code,
+ "message": scrubbed_error_message,
+ }
+ ],
+ }
content_snapshot: dict = {"insights": [{"id": 1, "name": "Secret", "query_results": [[1, 2, 3]]}]}
if is_ai:
# AI deliveries also persist the rendered report and per-step query diagnostics; the
@@ -2394,6 +2408,7 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
"hogql": "SELECT bad",
"ok": False,
"error_type": "ResolutionError",
+ "error_code": query_error_code,
"human_readable_error": scrubbed_error_message,
},
]
@@ -2413,6 +2428,7 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
content_snapshot=content_snapshot,
change_summary="Signups up 20% week over week",
recipient_results=[{"recipient": "[email protected]", "status": "success"}],
+ error=query_failure_error if is_ai else None,
)
if restrict:
self._restrict_query_access()
@@ -2431,7 +2447,12 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
assert data[AI_REPORT_DIAGNOSTICS_KEY] is None
assert data[AI_REPORT_CHARTS_KEY] is None
assert generated_hogql not in str(data)
+ assert query_error_code not in str(data)
assert scrubbed_error_message not in str(data)
+ assert data["error"] == {
+ "type": AI_REPORT_QUERY_FAILURE_TYPE,
+ "message": "The report could not be computed.",
+ }
# The prompt is user-authored (not query-derived) and already readable on the parent
# subscription, so it stays visible even for a query-restricted caller.
assert data[AI_REPORT_PROMPT_SNAPSHOT_KEY] == "Weekly growth recap"
@@ -2448,7 +2469,12 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
assert row[AI_REPORT_CHARTS_KEY] is None
assert row[AI_REPORT_PROMPT_SNAPSHOT_KEY] == "Weekly growth recap"
assert generated_hogql not in str(row)
+ assert query_error_code not in str(row)
assert scrubbed_error_message not in str(row)
+ assert row["error"] == {
+ "type": AI_REPORT_QUERY_FAILURE_TYPE,
+ "message": "The report could not be computed.",
+ }
else:
assert data["content_snapshot"]["insights"][0]["name"] == "Secret"
assert data["change_summary"] == "Signups up 20% week over week"
@@ -2457,9 +2483,11 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
# diagnostics (including the generated HogQL) — the intended debugging surface.
assert data[AI_REPORT_SNAPSHOT_KEY] == "# Weekly report"
assert data[AI_REPORT_DIAGNOSTICS_KEY][0]["hogql"] == generated_hogql
+ assert data[AI_REPORT_DIAGNOSTICS_KEY][1]["error_code"] == query_error_code
# The safe error message on the failed step is part of the query-access debugging surface.
assert data[AI_REPORT_DIAGNOSTICS_KEY][1]["human_readable_error"] == scrubbed_error_message
assert data[AI_REPORT_PROMPT_SNAPSHOT_KEY] == "Weekly growth recap"
+ assert data["error"] == query_failure_error
# The typed fields are the contract: the report must not be shipped twice, so the
# AI keys are stripped from content_snapshot (the non-AI scaffold stays intact).
assert data[AI_REPORT_CHARTS_KEY] == [
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 26de7574672d..b43253256a9a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5553,9 +5553,9 @@ snapshots:
products-subscriptions-subscription-delivery-history--with-deliveries--light:
hash: v1.k794b7964.ba95c5a833ef7dae5b452bfa017e4137569815aa6ed992a446573ce6ab750a56.kOt7J7rBOwnM2w1SrZlUwZql3Lrf_-B8SBpOzVDrD3s
products-subscriptions-subscription-delivery-history--with-expanded-ai-report--dark:
- hash: v1.k794b7964.97fcc8d80e221fe797031b6305839d6eab0a541ecd0b25c44f4cdc5cc87ebf24.bwex_AJU92hp189meQnsGtKMxG_bE6cHz4ttkuRidJI
+ hash: v1.k794b7964.33d81839a4a8e93617b73875e22f679e3081bd656a504a19159c8277849fe049.9W4kEUxrPQsBjuNSLR3a6ytg1ILRIOasdEun3lWqThY
products-subscriptions-subscription-delivery-history--with-expanded-ai-report--light:
- hash: v1.k794b7964.abb8a6720e2c7721af4bee507fd0c8541e9ac3fff7f31e5656832b1b15d059a5.qUzovkPIA8XLDBf8m97cGPr7OcISB3fQhlB97WEW8R0
+ hash: v1.k794b7964.705254d95cbbbbf294877071928aef78ca7d6522ada3655560ba3e998821cd38.pfF0Zz143PJdqtf2CBEltnmJ4WWXGmtR9jeU8ytuNdk
products-subscriptions-subscription-delivery-history--with-expanded-summary--dark:
hash: v1.k794b7964.9d825454b80602e3cca17fa872553832e01b929728eb3b554b98a7f0d63b01be.Amp7jiLWQltIcWNKpEimC7DjTEsQ4cc1mtxoGU_hEFs
products-subscriptions-subscription-delivery-history--with-expanded-summary--light:
diff --git a/posthog/errors.py b/posthog/errors.py
index efa9747f42a6..20de3ba3dfca 100644
--- a/posthog/errors.py
+++ b/posthog/errors.py
@@ -40,6 +40,8 @@ class ExposedCHQueryError(InternalCHQueryError):
"""User-safe ClickHouse query error. Subclasses have user_safe=True in ErrorCodeMeta,
which classify_query_error() uses to categorize them as USER_ERROR."""
+ user_safe = True
+
def __str__(self) -> str:
message: str = str(self.message)
try:
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 19f0a632a04d..eaf60c855d78 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -101,11 +101,13 @@ class ClickHouseBytesLimitExceeded(ValidationError):
class ClickHouseQueryTimeOut(APIException):
+ user_safe = True
status_code = 504
default_detail = "Query has hit the max execution time before completing. See our docs for how to improve your query performance. You may need to materialize."
class ClickHouseQueryMemoryLimitExceeded(APIException):
+ user_safe = True
# Custom code in the actionable-validation family (400/512/513) the frontend routes to the
# "problem with this query" panel. Distinct from 512 (query-too-slow) so an out-of-memory
# failure is never mistaken for a timeout on either the client or in status-based alerting.
diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.py
index 7c482ff20dfe..15a6200ec4ac 100644
--- a/posthog/temporal/tests/test_subscriptions_workflows.py
+++ b/posthog/temporal/tests/test_subscriptions_workflows.py
@@ -57,7 +57,10 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.activities
_skip_ai_delivery_over_credit_limit_sync,
generate_ai_subscription_report,
)
-from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import AiReportResult
+from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import (
+ AiReportResult,
+ QueryStepDiagnostic,
+)
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import PromptRejectedError
from products.exports.backend.temporal.subscriptions.delivery_common import deliver_email
from products.exports.backend.temporal.subscriptions.types import (
@@ -2563,13 +2566,35 @@ async def test_generate_ai_report_persists_report_for_delivery(team, user):
with patch(
_GENERATE_REPORT,
- return_value=AiReportResult(markdown="# Report", diagnostics=(), window_end_utc="2026-06-25T12:00:00+00:00"),
+ return_value=AiReportResult(
+ markdown="# Report",
+ diagnostics=(
+ QueryStepDiagnostic(
+ description="adoption",
+ hogql="SELECT expensive",
+ ok=False,
+ error_type="ClickHouseQueryMemoryLimitExceeded",
+ error_code="clickhouse_memory_limit_exceeded",
+ human_readable_error="Query exceeded the memory limit.",
+ ),
+ ),
+ window_end_utc="2026-06-25T12:00:00+00:00",
+ ),
):
result = await ActivityEnvironment().run(
generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
)
assert result.aborted is False
+ assert result.failed_step_count == 1
+ assert result.total_step_count == 1
+ assert result.query_errors == [
+ {
+ "type": "ClickHouseQueryMemoryLimitExceeded",
+ "code": "clickhouse_memory_limit_exceeded",
+ "message": "Query exceeded the memory limit.",
+ }
+ ]
# The report is handed to delivery via the row, not the activity return value.
refreshed = await sync_to_async(SubscriptionDelivery.objects.get)(pk=delivery.id)
assert refreshed.content_snapshot["ai_report"] == "# Report"
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
index eeb6254a7c7c..3d5725cf4914 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
@@ -44,6 +44,7 @@ from products.exports.backend.temporal.subscriptions.types import (
DeliverSubscriptionResult,
GenerateAIReportInputs,
GenerateAIReportResult,
+ QueryErrorDetails,
RecipientResult,
)
@@ -81,31 +82,67 @@ def _snapshot_report(snapshot: dict | None) -> str | None:
class DiagnosticCounts:
failed_step_count: int
total_step_count: int
- error_types: list[str]
+ query_errors: list[QueryErrorDetails]
+ @property
+ def error_types(self) -> list[str]:
+ return sorted({error["type"] for error in self.query_errors if error["type"]})
-def _tally_diagnostics(steps: list[tuple[bool, str | None]]) -> DiagnosticCounts:
- # Failed/total step counts plus sorted distinct failure types from (ok, error_type)
- # pairs — shared by the persisted-snapshot and in-memory diagnostic paths.
- failed = [error_type for ok, error_type in steps if not ok]
- error_types = sorted({str(error_type) for error_type in failed if error_type})
- return DiagnosticCounts(failed_step_count=len(failed), total_step_count=len(steps), error_types=error_types)
+
+def _query_error_details(
+ error_type: str | None, error_code: str | None, error_message: str | None
+) -> QueryErrorDetails:
+ return {
+ "type": error_type,
+ "code": error_code,
+ "message": error_message,
+ }
+
+
+def _string_or_none(value: object) -> str | None:
+ return value if isinstance(value, str) else None
+
+
+def _tally_diagnostics(steps: list[QueryErrorDetails | None]) -> DiagnosticCounts:
+ # One typed object keeps every failed query's type, code, and safe message paired. None marks a
+ # successful step. The same representation is built from persisted and in-memory diagnostics.
+ query_errors = [step for step in steps if step is not None]
+ return DiagnosticCounts(
+ failed_step_count=len(query_errors),
+ total_step_count=len(steps),
+ query_errors=query_errors,
+ )
def _snapshot_diagnostic_counts(snapshot: dict | None) -> DiagnosticCounts:
# The prior run's failure shape, read back from the persisted diagnostics on Temporal redispatch.
diagnostics = snapshot.get(AI_REPORT_DIAGNOSTICS_KEY) if snapshot else None
if not isinstance(diagnostics, list):
- return DiagnosticCounts(failed_step_count=0, total_step_count=0, error_types=[])
+ return DiagnosticCounts(failed_step_count=0, total_step_count=0, query_errors=[])
# Only well-formed dict entries count — a malformed one would inflate the total and mask an
# all-failed report; `ok is not False` keeps a missing/None ok out of the failed set.
return _tally_diagnostics(
- [(d.get("ok") is not False, d.get("error_type")) for d in diagnostics if isinstance(d, dict)]
+ [
+ None
+ if d.get("ok") is not False
+ else _query_error_details(
+ _string_or_none(d.get("error_type")),
+ _string_or_none(d.get("error_code")),
+ _string_or_none(d.get("human_readable_error")),
+ )
+ for d in diagnostics
+ if isinstance(d, dict)
+ ]
)
def _report_diagnostic_counts(result: AiReportResult) -> DiagnosticCounts:
- return _tally_diagnostics([(d.ok, d.error_type) for d in result.diagnostics])
+ return _tally_diagnostics(
+ [
+ None if d.ok else _query_error_details(d.error_type, d.error_code, d.human_readable_error)
+ for d in result.diagnostics
+ ]
+ )
async def _persist_ai_report(delivery_id: uuid.UUID, result: AiReportResult, prompt: str | None) -> None:
@@ -231,7 +268,7 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Gen
aborted=False,
failed_step_count=counts.failed_step_count,
total_step_count=counts.total_step_count,
- query_error_types=counts.error_types,
+ query_errors=counts.query_errors,
target_type=subscription.target_type,
)
@@ -323,7 +360,7 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Gen
aborted=False,
failed_step_count=counts.failed_step_count,
total_step_count=counts.total_step_count,
- query_error_types=counts.error_types,
+ query_errors=counts.query_errors,
target_type=subscription.target_type,
)
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
index cfe30acb8ef6..3f913f5e3816 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
@@ -61,7 +61,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_genera
build_enriched_prompt,
build_frozen_prompt,
)
-from products.exports.backend.temporal.subscriptions.types import safe_error_message, undisclosed_query_error_type
+from products.exports.backend.temporal.subscriptions.types import safe_query_error_details
from ee.hogai.context.insight.query_executor import AssistantQueryExecutor
from ee.hogai.llm import MaxChatOpenAI
@@ -164,9 +164,9 @@ class QueryStepDiagnostic:
hogql: str
ok: bool
error_type: Optional[str]
- # Safe-to-surface failure reason; set only for query-structure errors (see _safe_error_message), else None.
human_readable_error: Optional[str] = None
chart_dropped_reason: Optional[ChartFailureReason] = None
+ error_code: Optional[str] = None
@dataclass(frozen=True)
@@ -570,11 +570,11 @@ async def _run_steps(
max_retries=_MAX_QUERY_FIX_RETRIES,
error_type=type(exc).__name__,
)
+ error_details = safe_query_error_details(exc)
fixed = await _arequest_hogql_fix(
original_hogql=current_hogql,
- # Forward the safe message (exposed/resolution errors describe the field/property the
- # planner referenced, which is what the fixer needs); fall back to the type name.
- error_message=safe_error_message(exc) or type(exc).__name__,
+ # Forward explicitly safe detail when available; fall back to the type name.
+ error_message=(error_details["message"] if error_details else None) or type(exc).__name__,
step_description=safe_description,
# The planner's project schema (event/property names) — a schema-blind fixer just
# re-guesses the wrong name, so give it the same grounding the planner had.
@@ -587,9 +587,8 @@ async def _run_steps(
break
current_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 None
+ error_details = safe_query_error_details(last_exc) if last_exc is not None else None
logger.warning(
"ai_report.query_failed",
trace_correlation_id=trace_correlation_id,
@@ -599,15 +598,18 @@ async def _run_steps(
)
if last_exc is not None:
capture_exception(last_exc, {"trace_correlation_id": trace_correlation_id, "stage": "query"})
- cause = "" if undisclosed_type is not None else f" ({type_name})"
+ # Safe query details belong in the owner-only diagnostics below. The rendered output is fed
+ # into synthesis and eventually delivered to recipients, who may not have query access.
+ cause = "" if error_details else f" ({type_name})"
return StepOutcome(
rendered=f"### {safe_description}\n\n_{QUERY_FAILED_PREFIX}{cause} — metric not computed, not empty data._",
diagnostic=QueryStepDiagnostic(
description=safe_description,
hogql=window.render_window_filter(current_hogql),
ok=False,
- error_type=undisclosed_type or type_name,
- human_readable_error=safe_error_message(last_exc) if last_exc is not None else None,
+ error_type=type_name,
+ error_code=error_details["code"] if error_details else None,
+ human_readable_error=error_details["message"] if error_details else None,
),
)
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py
index 6c0b4c39650e..30c06c0d852e 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py
@@ -68,7 +68,12 @@ async def test_persist_ai_report_writes_markdown_query_diagnostics_and_prompt(te
diagnostics=(
QueryStepDiagnostic(description="adoption", hogql="SELECT count()", ok=True, error_type=None),
QueryStepDiagnostic(
- description="reliability", hogql="SELECT bad", ok=False, error_type="ResolutionError"
+ description="reliability",
+ hogql="SELECT bad",
+ ok=False,
+ error_type="QueryError",
+ error_code="hogql_query_error",
+ human_readable_error="Unable to resolve field 'reliability'",
),
),
),
@@ -83,6 +88,7 @@ async def test_persist_ai_report_writes_markdown_query_diagnostics_and_prompt(te
"hogql": "SELECT count()",
"ok": True,
"error_type": None,
+ "error_code": None,
"human_readable_error": None,
"chart_dropped_reason": None,
},
@@ -90,9 +96,10 @@ async def test_persist_ai_report_writes_markdown_query_diagnostics_and_prompt(te
"description": "reliability",
"hogql": "SELECT bad",
"ok": False,
- "error_type": "ResolutionError",
- "human_readable_error": None,
+ "error_type": "QueryError",
+ "human_readable_error": "Unable to resolve field 'reliability'",
"chart_dropped_reason": None,
+ "error_code": "hogql_query_error",
},
]
# The generating prompt is captured so the delivery is reproducible and the viewer can show it.
@@ -162,14 +169,31 @@ async def test_persist_ai_report_omits_blank_prompt(team, user, prompt) -> None:
class TestReportDiagnosticCounts:
@parameterized.expand(
[
- ("all_ok", [True, True], 0, 2, []),
- ("partial", [True, False], 1, 2, ["ResolutionError"]),
- ("all_failed", [False, False], 2, 2, ["ResolutionError"]),
- ("none", [], 0, 0, []),
+ ("all_ok", [True, True], 0, 2, [], []),
+ (
+ "partial",
+ [True, False],
+ 1,
+ 2,
+ ["ResolutionError"],
+ [{"type": "ResolutionError", "code": None, "message": None}],
+ ),
+ (
+ "all_failed",
+ [False, False],
+ 2,
+ 2,
+ ["ResolutionError"],
+ [
+ {"type": "ResolutionError", "code": None, "message": None},
+ {"type": "ResolutionError", "code": None, "message": None},
+ ],
+ ),
+ ("none", [], 0, 0, [], []),
]
)
def test_counts_failures_and_distinct_error_types(
- self, _name, oks, expected_failed, expected_total, expected_types
+ self, _name, oks, expected_failed, expected_total, expected_types, expected_errors
):
result = AiReportResult(
markdown="report",
@@ -184,9 +208,13 @@ class TestReportDiagnosticCounts:
for i, ok in enumerate(oks)
),
)
- assert _report_diagnostic_counts(result) == DiagnosticCounts(
- failed_step_count=expected_failed, total_step_count=expected_total, error_types=expected_types
+ counts = _report_diagnostic_counts(result)
+ assert counts == DiagnosticCounts(
+ failed_step_count=expected_failed,
+ total_step_count=expected_total,
+ query_errors=expected_errors,
)
+ assert counts.error_types == expected_types
def test_distinct_error_types_are_sorted_and_deduped(self):
result = AiReportResult(
@@ -198,8 +226,57 @@ class TestReportDiagnosticCounts:
QueryStepDiagnostic(description="c", hogql="z", ok=False, error_type="ResolutionError"),
),
)
+ counts = _report_diagnostic_counts(result)
+ assert counts == DiagnosticCounts(
+ failed_step_count=3,
+ total_step_count=3,
+ query_errors=[
+ {"type": "ResolutionError", "code": None, "message": None},
+ {"type": "ExposedHogQLError", "code": None, "message": None},
+ {"type": "ResolutionError", "code": None, "message": None},
+ ],
+ )
+ assert counts.error_types == ["ExposedHogQLError", "ResolutionError"]
+
+ def test_pairs_each_safe_query_error_with_its_type(self):
+ result = AiReportResult(
+ markdown="report",
+ window_end_utc=_WINDOW_END_UTC,
+ diagnostics=(
+ QueryStepDiagnostic(
+ description="memory",
+ hogql="SELECT expensive",
+ ok=False,
+ error_type="ClickHouseQueryMemoryLimitExceeded",
+ error_code="clickhouse_memory_limit_exceeded",
+ human_readable_error="Query exceeded the memory limit.",
+ ),
+ QueryStepDiagnostic(
+ description="resolution",
+ hogql="SELECT bad",
+ ok=False,
+ error_type="QueryError",
+ error_code="hogql_query_error",
+ human_readable_error="Unable to resolve field 'bad'",
+ ),
+ ),
+ )
+
assert _report_diagnostic_counts(result) == DiagnosticCounts(
- failed_step_count=3, total_step_count=3, error_types=["ExposedHogQLError", "ResolutionError"]
+ failed_step_count=2,
+ total_step_count=2,
+ query_errors=[
+ {
+ "type": "ClickHouseQueryMemoryLimitExceeded",
+ "code": "clickhouse_memory_limit_exceeded",
+ "message": "Query exceeded the memory limit.",
+ },
+ {
+ "type": "QueryError",
+ "code": "hogql_query_error",
+ "message": "Unable to resolve field 'bad'",
+ },
+ ],
)
@@ -214,20 +291,35 @@ async def test_snapshot_diagnostic_counts_reads_persisted_failure_shape(team, us
window_end_utc=_WINDOW_END_UTC,
diagnostics=(
QueryStepDiagnostic(description="ok step", hogql="SELECT 1", ok=True, error_type=None),
- QueryStepDiagnostic(description="bad step", hogql="SELECT bad", ok=False, error_type="ResolutionError"),
+ QueryStepDiagnostic(
+ description="bad step",
+ hogql="SELECT bad",
+ ok=False,
+ error_type="QueryError",
+ error_code="hogql_query_error",
+ human_readable_error="Unable to resolve field 'bad'",
+ ),
),
),
prompt=None,
)
assert _snapshot_diagnostic_counts(await _load_snapshot(delivery.id)) == DiagnosticCounts(
- failed_step_count=1, total_step_count=2, error_types=["ResolutionError"]
+ failed_step_count=1,
+ total_step_count=2,
+ query_errors=[
+ {
+ "type": "QueryError",
+ "code": "hogql_query_error",
+ "message": "Unable to resolve field 'bad'",
+ }
+ ],
)
async def test_snapshot_diagnostic_counts_handles_missing_diagnostics(team, user) -> None:
delivery = await _create_delivery(team, user)
# Empty content_snapshot (nothing persisted yet) and a fully-missing snapshot both report nothing failed.
- empty_counts = DiagnosticCounts(failed_step_count=0, total_step_count=0, error_types=[])
+ empty_counts = DiagnosticCounts(failed_step_count=0, total_step_count=0, query_errors=[])
assert _snapshot_diagnostic_counts(await _load_snapshot(delivery.id)) == empty_counts
assert _snapshot_diagnostic_counts(None) == empty_counts
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.py
index 76fc36225582..1317f852d9c3 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,10 +6,12 @@ import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from parameterized import parameterized
+from rest_framework.exceptions import APIException
-from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, ResolutionError
+from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, QueryError, ResolutionError
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
+from posthog.errors import ExposedCHQueryError
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
from products.exports.backend.temporal.subscriptions.ai_subscription.charts import (
ChartFailureReason,
@@ -43,7 +45,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_genera
ReportWindow,
StoredPlanInvalidError,
)
-from products.exports.backend.temporal.subscriptions.types import safe_error_message
+from products.exports.backend.temporal.subscriptions.types import safe_error_message, safe_query_error_details
from ee.hogai.context.insight.query_executor import FormattedQueryResult
from ee.hogai.tool_errors import MaxToolRetryableError
@@ -104,6 +106,81 @@ def _spec_with_window_placeholder() -> EnrichedPromptSpec:
)
+def _wrap(
+ outer: BaseException, *, cause: BaseException | None = None, context: BaseException | None = None
+) -> BaseException:
+ if cause is not None:
+ outer.__cause__ = cause
+ if context is not None:
+ outer.__context__ = context
+ return outer
+
+
+ "exc,expected",
+ [
+ (
+ ClickHouseQueryMemoryLimitExceeded(),
+ {
+ "type": "ClickHouseQueryMemoryLimitExceeded",
+ "code": ClickHouseQueryMemoryLimitExceeded.default_code,
+ "message": ClickHouseQueryMemoryLimitExceeded.default_detail,
+ },
+ ),
+ (
+ ClickHouseQueryTimeOut(),
+ {
+ "type": "ClickHouseQueryTimeOut",
+ "code": ClickHouseQueryTimeOut.default_code,
+ "message": ClickHouseQueryTimeOut.default_detail,
+ },
+ ),
+ (ResolutionError("Database is not set"), None),
+ (
+ QueryError("Unknown field: signups"),
+ {"type": "QueryError", "code": "hogql_query_error", "message": "Unknown field: signups"},
+ ),
+ (
+ ExposedHogQLError("Unable to resolve field 'operaton'"),
+ {
+ "type": "ExposedHogQLError",
+ "code": "hogql_error",
+ "message": "Unable to resolve field 'operaton'",
+ },
+ ),
+ (
+ ExposedCHQueryError("Invalid aggregate", code_name="illegal_aggregation"),
+ {
+ "type": "ExposedCHQueryError",
+ "code": "illegal_aggregation",
+ "message": "Invalid aggregate",
+ },
+ ),
+ (_wrap(Exception("outer"), cause=ResolutionError("Database is not set")), None),
+ (
+ _wrap(RuntimeError("outer"), context=ExposedHogQLError("Unknown field: revenue")),
+ {"type": "ExposedHogQLError", "code": "hogql_error", "message": "Unknown field: revenue"},
+ ),
+ # Only explicitly marked API exceptions are safe. A generic one may carry team-scoped detail.
+ (APIException("internal detail with a team-scoped id"), None),
+ ],
+)
+def test_safe_query_error_details_matches_query_api(exc: BaseException, expected: dict[str, str] | None) -> None:
+ assert safe_query_error_details(exc) == expected
+
+
+def test_safe_query_error_details_uses_exception_safety_marker() -> None:
+ class UserSafeQueryError(Exception):
+ user_safe = True
+ code_name = "safe_query_error"
+
+ assert safe_query_error_details(UserSafeQueryError("Safe detail")) == {
+ "type": "UserSafeQueryError",
+ "code": "safe_query_error",
+ "message": "Safe detail",
+ }
+
+
def _slo_completed(capture_mock: MagicMock) -> dict:
for call in capture_mock.call_args_list:
if call.kwargs.get("event") == "slo_operation_completed":
@@ -300,7 +377,9 @@ async def test_run_steps_non_retryable_error_degrades_to_placeholder(mock_execut
@patch(f"{_RP}.AssistantQueryExecutor")
-async def test_run_steps_placeholder_omits_undisclosed_error_type(mock_executor_cls: MagicMock) -> None:
+async def test_run_steps_keeps_recipient_copy_generic_and_records_safe_query_error(
+ mock_executor_cls: MagicMock,
+) -> None:
mock_executor_cls.return_value.arun_format_and_capture = AsyncMock(side_effect=ClickHouseQueryMemoryLimitExceeded())
execution = await _run_steps(
_spec(steps=1), MagicMock(), MagicMock(), _test_window(), None, charts_enabled_for_team=True
@@ -308,12 +387,13 @@ async def test_run_steps_placeholder_omits_undisclosed_error_type(mock_executor_
assert execution.failed_count == 1
assert execution.rendered[0] == f"### s0\n\n_{QUERY_FAILED_PREFIX} — metric not computed, not empty data._"
assert execution.diagnostics[0].error_type == "ClickHouseQueryMemoryLimitExceeded"
- assert execution.diagnostics[0].human_readable_error is None
+ assert execution.diagnostics[0].error_code == ClickHouseQueryMemoryLimitExceeded.default_code
+ assert execution.diagnostics[0].human_readable_error == ClickHouseQueryMemoryLimitExceeded.default_detail
@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(
+async def test_run_steps_keeps_wrapped_error_out_of_recipient_copy_and_records_safe_query_error(
mock_hogql_fix: AsyncMock, mock_executor_cls: MagicMock
) -> None:
error = MaxToolRetryableError("Memory limit exceeded")
@@ -326,20 +406,20 @@ async def test_run_steps_placeholder_omits_wrapped_undisclosed_error_type(
assert execution.failed_count == 1
assert execution.rendered[0] == f"### s0\n\n_{QUERY_FAILED_PREFIX} — metric not computed, not empty data._"
- assert execution.diagnostics[0].error_type == "ClickHouseQueryMemoryLimitExceeded"
+ assert execution.diagnostics[0].error_type == "MaxToolRetryableError"
+ assert execution.diagnostics[0].error_code == ClickHouseQueryMemoryLimitExceeded.default_code
+ assert execution.diagnostics[0].human_readable_error == ClickHouseQueryMemoryLimitExceeded.default_detail
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(
+async def test_run_steps_forwards_exposed_query_error_message_to_fix(
mock_executor_cls: MagicMock, mock_fix: AsyncMock
) -> None:
- # ResolutionError names the field the planner referenced — its message, not just the type name,
- # must reach the fix LLM so it can actually repair the query.
mock_executor_cls.return_value.arun_format_and_capture = AsyncMock(
side_effect=[
- ResolutionError("Unable to resolve field 'operaton'"),
+ QueryError("Unable to resolve field 'operaton'"),
FormattedQueryResult(formatted="formatted table", fallback_used=False, response=_RESPONSE),
]
)
@@ -456,27 +536,18 @@ async def test_run_steps_bounds_concurrent_query_execution(mock_executor_cls: Ma
assert max_concurrent == _MAX_CONCURRENT_STEPS
-def _wrap(
- outer: BaseException, *, cause: BaseException | None = None, context: BaseException | None = None
-) -> BaseException:
- if cause is not None:
- outer.__cause__ = cause
- if context is not None:
- outer.__context__ = context
- return outer
-
-
@pytest.mark.parametrize(
"exc,expected",
[
(ExposedHogQLError("Unable to resolve field 'operaton'"), "Unable to resolve field 'operaton'"),
- (ResolutionError("Unknown field: signups"), "Unknown field: signups"),
- # A plain InternalHogQLError (not a ResolutionError) can echo team-scoped data — stays type-only.
+ (QueryError("Unknown field: signups"), "Unknown field: signups"),
+ (ClickHouseQueryMemoryLimitExceeded(), ClickHouseQueryMemoryLimitExceeded.default_detail),
+ (ResolutionError("Database is not set"), None),
(InternalHogQLError("internal detail with a team-scoped id"), None),
(ValueError("boom"), None),
# A generic error wrapping a safe error surfaces the wrapped message (executors wrap like this).
(
- _wrap(Exception("wrapper"), cause=ResolutionError("Unable to resolve field 'x'")),
+ _wrap(Exception("wrapper"), cause=QueryError("Unable to resolve field 'x'")),
"Unable to resolve field 'x'",
),
(_wrap(RuntimeError("boom"), context=ExposedHogQLError("bad thing")), "bad thing"),
diff --git a/products/exports/backend/temporal/subscriptions/test_types.py b/products/exports/backend/temporal/subscriptions/test_types.py
index 9c9c0a6e5bb3..d0494b5a00bb 100644
--- a/products/exports/backend/temporal/subscriptions/test_types.py
+++ b/products/exports/backend/temporal/subscriptions/test_types.py
@@ -1,11 +1,12 @@
from parameterized import parameterized
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
from products.exports.backend.temporal.subscriptions.types import (
UNDISCLOSED_QUERY_ERROR_TYPES,
DeliveryStatus,
GenerateAIReportResult,
+ QueryErrorDetails,
)
@@ -14,6 +15,17 @@ def test_undisclosed_query_error_types_track_the_exception_class() -> None:
class TestGenerateAIReportResult:
+ def test_query_error_types_are_derived_for_new_results(self) -> None:
+ result = GenerateAIReportResult(
+ query_errors=[
+ {"type": "QueryError", "code": "hogql_query_error", "message": "Unknown field"},
+ {"type": "ExposedHogQLError", "code": "hogql_error", "message": "Invalid query"},
+ {"type": "QueryError", "code": "hogql_query_error", "message": "Unknown field"},
+ ]
+ )
+
+ assert result.query_error_types == ["ExposedHogQLError", "QueryError"]
+
# all_queries_failed is the single source of truth for the workflow's FAILED-vs-COMPLETED decision,
# so a regression here (dropping the zero-steps guard, or flipping >= ) would silently mislabel a
# fully-degraded report as completed.
@@ -38,43 +50,88 @@ class TestGenerateAIReportResult:
"single_no_types",
1,
[],
+ [],
"The query the AI generated failed to run, so the report could not be computed.",
),
(
"multiple_no_types",
3,
[],
+ [],
"All 3 queries the AI generated failed to run, so the report could not be computed.",
),
(
"single_with_type",
1,
["ExposedHogQLError"],
+ [],
"The query the AI generated failed to run (ExposedHogQLError), so the report could not be computed.",
),
(
"multiple_with_types",
2,
- ["ExposedHogQLError", "ResolutionError"],
- "All 2 queries the AI generated failed to run (ExposedHogQLError, ResolutionError), so the report could not be computed.",
+ ["ExposedHogQLError", "QueryError"],
+ [],
+ "All 2 queries the AI generated failed to run (ExposedHogQLError, QueryError), so the report could not be computed.",
),
(
- "undisclosed_type_leaves_no_detail",
+ "memory_limit_has_actionable_reason",
+ 1,
+ [],
+ [
+ {
+ "type": "ClickHouseQueryMemoryLimitExceeded",
+ "code": ClickHouseQueryMemoryLimitExceeded.default_code,
+ "message": ClickHouseQueryMemoryLimitExceeded.default_detail,
+ }
+ ],
+ "The query the AI generated failed to run, so the report could not be computed.",
+ ),
+ (
+ "timeout_has_actionable_reason",
+ 2,
+ [],
+ [
+ {
+ "type": "ClickHouseQueryTimeOut",
+ "code": ClickHouseQueryTimeOut.default_code,
+ "message": ClickHouseQueryTimeOut.default_detail,
+ },
+ {
+ "type": "QueryError",
+ "code": "hogql_query_error",
+ "message": "Unknown field",
+ },
+ ],
+ "All 2 queries the AI generated failed to run (ClickHouseQueryTimeOut, QueryError), so the report could not be computed.",
+ ),
+ (
+ "legacy_memory_limit_without_details_stays_generic",
1,
["ClickHouseQueryMemoryLimitExceeded"],
+ [],
"The query the AI generated failed to run, so the report could not be computed.",
),
(
- "undisclosed_type_dropped_from_mixed_detail",
+ "legacy_mixed_failure_omits_memory_limit_type",
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:
- result = GenerateAIReportResult(failed_step_count=total, total_step_count=total, query_error_types=error_types)
- assert result.failure_error() == {"message": expected_message, "type": "AIReportQueryFailure"}
+ def test_failure_error(
+ self, _name, total: int, error_types: list[str], query_errors: list[QueryErrorDetails], expected_message: str
+ ) -> None:
+ result = GenerateAIReportResult(
+ failed_step_count=total, total_step_count=total, query_error_types=error_types, query_errors=query_errors
+ )
+ expected_error: dict[str, object] = {"message": expected_message, "type": "AIReportQueryFailure"}
+ if query_errors:
+ expected_error["code"] = query_errors[0]["code"]
+ expected_error["details"] = query_errors
+ assert result.failure_error() == expected_error
# delivered_status maps a shipped report to the status the workflow records: fully degraded (every query
# failed) → FAILED with the failure detail attached; partial or clean → COMPLETED with no generation
diff --git a/products/exports/backend/temporal/subscriptions/types.py b/products/exports/backend/temporal/subscriptions/types.py
index 76334a423b7f..5c5795495e2d 100644
--- a/products/exports/backend/temporal/subscriptions/types.py
+++ b/products/exports/backend/temporal/subscriptions/types.py
@@ -2,53 +2,56 @@ import uuid
import typing
import dataclasses
-from posthog.hogql.errors import ExposedHogQLError, ResolutionError
+from posthog.hogql.errors import ExposedHogQLError
from 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__.
+# Type names of these failures never appear in recipient-facing copy. When a safe code and message
+# exist, they are available to query-access owners; this mask only governs the legacy fallback that
+# has no persisted details. The type still lands in diagnostics, logs, and error tracking.
UNDISCLOSED_QUERY_ERROR_TYPES = frozenset({"ClickHouseQueryMemoryLimitExceeded"})
-def undisclosed_query_error_type(exc: BaseException) -> typing.Optional[str]:
+class QueryErrorDetails(typing.TypedDict):
+ """A failed query's type paired with its optional safe code and message."""
+
+ type: typing.Optional[str]
+ code: typing.Optional[str]
+ message: typing.Optional[str]
+
+
+def safe_query_error_details(exc: BaseException) -> typing.Optional[QueryErrorDetails]:
+ """Return stable details for an explicitly safe query exception in a wrapped exception chain."""
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
+ if isinstance(current, ExposedHogQLError) or getattr(type(current), "user_safe", False) is True:
+ code = getattr(current, "code_name", None)
+ if not isinstance(code, str):
+ get_codes = getattr(current, "get_codes", None)
+ code = get_codes() if callable(get_codes) else None
+
+ raw_detail = getattr(current, "detail", None)
+ message = str(raw_detail) if isinstance(raw_detail, str) else str(current)
+ if isinstance(code, str) and message:
+ return {
+ "type": type(current).__name__,
+ "code": code,
+ "message": message.replace("\x00", ""),
+ }
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.
-
- HogQL/ClickHouse error text can echo team-scoped identifiers (query data, internal
- names), so only the query-structure error classes (which describe the field/property the
- query referenced) are safe to surface to the subscription owner — the same trust boundary
- the HogQL repair loop uses when forwarding to the fixer. Everything else returns None so
- the caller falls back to a generic message. Executors often wrap a resolution/exposed
- error in a generic Exception, so walk the __cause__/__context__ chain for a wrapped safe
- message.
-
- The result is persisted to Postgres jsonb columns, so NUL bytes are stripped (Postgres
- rejects them); callers of the sibling raw "message" field already expect this scrub. The
- walk honours ``raise ... from None`` (``__suppress_context__``) — a deliberately severed
- chain stays severed, so an internal error the author meant to hide is never surfaced.
+ """Owner-safe snippet of a query exception, or None when its text may carry team-scoped data.
+
+ Uses the single classifier above so every consumer shares the same allowlist, wrapped-chain
+ handling, and NUL stripping. Everything else returns None and callers use a generic fallback.
"""
- seen: set[int] = set()
- current: typing.Optional[BaseException] = exc
- while current is not None and id(current) not in seen:
- if isinstance(current, (ExposedHogQLError, ResolutionError)):
- return str(current).replace("\x00", "")
- seen.add(id(current))
- current = current.__cause__ or (None if current.__suppress_context__ else current.__context__)
- return None
+ details = safe_query_error_details(exc)
+ return details["message"] if details else None
class DeliveryStatus:
@@ -102,6 +105,9 @@ AI_REPORT_PROMPT_SNAPSHOT_KEY = "ai_report_prompt"
# Per-step query diagnostics (generated HogQL + failure type) so a degraded report is debuggable
# after the fact. Written alongside the markdown; never shipped to recipients.
AI_REPORT_DIAGNOSTICS_KEY = "ai_report_diagnostics"
+# Top-level delivery error type for a report whose generated queries all failed. Shared with the
+# serializer's query-access scrub so a rename cannot accidentally expose query-derived details.
+AI_REPORT_QUERY_FAILURE_TYPE = "AIReportQueryFailure"
# The analysis window's end for this run, as a UTC ISO instant. The next run anchors its window here
# (exactly gap-free); rows written before this key existed fall back to finished_at.
AI_REPORT_WINDOW_END_KEY = "ai_report_window_end"
@@ -257,7 +263,7 @@ class GenerateAIReportInputs:
delivery_id: uuid.UUID
[email protected](frozen=False)
class GenerateAIReportResult:
"""Outcome of the generation phase. `aborted` signals a terminal pre-delivery
failure (consent revoked, prompt invalid) that already auto-disabled the
@@ -274,30 +280,49 @@ class GenerateAIReportResult:
recipient_results: list[RecipientResult] = dataclasses.field(default_factory=list)
failed_step_count: int = 0
total_step_count: int = 0
+ # Kept for Temporal histories written before query_errors existed. New results derive it in
+ # __post_init__ so callers only provide the richer representation.
query_error_types: list[str] = dataclasses.field(default_factory=list)
target_type: str = ""
+ query_errors: list[QueryErrorDetails] = dataclasses.field(default_factory=list)
+
+ def __post_init__(self) -> None:
+ if not self.query_error_types and self.query_errors:
+ self.query_error_types = sorted({error["type"] for error in self.query_errors if error["type"]})
@property
def all_queries_failed(self) -> bool:
# Single source of truth for the "fully degraded" judgement, so callers don't re-derive it.
return bool(self.total_step_count) and self.failed_step_count >= self.total_step_count
- 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.
- disclosed_types = [t for t in self.query_error_types if t not in UNDISCLOSED_QUERY_ERROR_TYPES]
+ def failure_error(self) -> dict[str, typing.Any]:
+ all_error_types = set(self.query_error_types)
+ all_error_types.update(error["type"] for error in self.query_errors if error["type"])
+ disclosed_types = sorted(t for t in all_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
else f"All {self.total_step_count} queries the AI generated"
)
- return {
+ error: dict[str, typing.Any] = {
"message": f"{subject} failed to run{detail}, so the report could not be computed.",
- "type": "AIReportQueryFailure",
+ "type": AI_REPORT_QUERY_FAILURE_TYPE,
}
- def delivered_status(self) -> tuple[str, typing.Optional[dict[str, str]]]:
+ safe_errors: list[dict[str, str]] = []
+ for query_error in self.query_errors:
+ error_type = query_error["type"]
+ code = query_error["code"]
+ message = query_error["message"]
+ if error_type and code and message:
+ safe_errors.append({"type": error_type, "code": code, "message": message})
+ if safe_errors:
+ error["code"] = safe_errors[0]["code"]
+ error["details"] = safe_errors
+ return error
+
+ def delivered_status(self) -> tuple[str, typing.Optional[dict[str, typing.Any]]]:
# Status to record once the report shipped: a fully-degraded report (every query failed) is FAILED
# with its failure detail — recording it COMPLETED would misrepresent an empty report. Partial
# failures stay COMPLETED. Owns this mapping so the workflow can't diverge from the judgement above.
diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.ts
index 6b2a55d3663c..fb4047e14b15 100644
--- a/products/subscriptions/frontend/generated/api.schemas.ts
+++ b/products/subscriptions/frontend/generated/api.schemas.ts
@@ -480,6 +480,11 @@ export interface AIReportQueryDiagnosticApi {
* @nullable
*/
error_type: string | null
+ /**
+ * Stable query API error code when available; null on success and for unclassified errors.
+ * @nullable
+ */
+ error_code?: string | null
/**
* Human-readable failure reason, present only for query errors safe to surface to the subscription owner (e.g. an unresolved field name); null on success and for internal errors, which expose error_type only.
* @nullable
diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionAiReportDelivery.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionAiReportDelivery.tsx
index 70fae8e468b3..d5e8ec1d3ff2 100644
--- a/products/subscriptions/frontend/scenes/components/SubscriptionAiReportDelivery.tsx
+++ b/products/subscriptions/frontend/scenes/components/SubscriptionAiReportDelivery.tsx
@@ -1,9 +1,10 @@
import { useMemo } from 'react'
-import { LemonCollapse, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { LemonBanner, LemonCollapse, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import { renderDetailWithLinks } from 'lib/utils/renderDetailWithLinks'
import type {
AIReportQueryDiagnosticApi,
@@ -357,9 +358,13 @@ function GeneratedQueries({ diagnostics }: { diagnostics: readonly AIReportQuery
content: (
<div className="flex flex-col gap-2">
{d.ok === false ? (
- <div className={d.human_readable_error ? 'text-danger' : 'text-secondary'}>
- {queryFailureReason(d)}
- </div>
+ d.human_readable_error ? (
+ <LemonBanner type="error" hideIcon className="!min-h-0">
+ {renderDetailWithLinks(d.human_readable_error)}
+ </LemonBanner>
+ ) : (
+ <div className="text-secondary">{queryFailureReason(d)}</div>
+ )
) : null}
{d.hogql ? (
<CodeSnippet language={Language.SQL} compact>
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9ea381f0e960..c7c39e254662 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -113,6 +113,11 @@ export namespace Schemas {
* @nullable
*/
error_type: string | null;
+ /**
+ * Stable query API error code when available; null on success and for unclassified errors.
+ * @nullable
+ */
+ error_code?: string | null;
/**
* Human-readable failure reason, present only for query errors safe to surface to the subscription owner (e.g. an unresolved field name); null on success and for internal errors, which expose error_type only.
* @nullable