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.

feat(subscriptions): persist AI report query diagnostics for debugging (#62309)

Vasco de Krijger52d1fd2825aa
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index 76b7df03439a..8b03af1f0087 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -1804,9 +1804,10 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
@parameterized.expand(
[
- # The delivered report is query-derived only for AI prompt subscriptions, so its content
- # is hidden from a query-restricted member there — but insight deliveries (no prompt) and
- # members who keep query access still see the full snapshot.
+ # The delivered report is query-derived only for AI prompt subscriptions, so its content —
+ # including the ai_report_diagnostics generated HogQL — is hidden from a query-restricted
+ # member there, but insight deliveries (no prompt) and members who keep query access still
+ # see the full snapshot.
("ai_restricted", True, True, True),
("ai_with_access", True, False, False),
("insight_restricted", False, True, False),
@@ -1814,6 +1815,15 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
)
def test_ai_delivery_report_hidden_without_query_access(self, _name, is_ai, restrict, expect_hidden):
subscription = self._create_ai_subscription() if is_ai else self.subscription
+ generated_hogql = "SELECT count() FROM events"
+ 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
+ # diagnostics embed the generated HogQL, which must never reach a query-restricted caller.
+ content_snapshot["ai_report"] = "# Weekly report"
+ content_snapshot["ai_report_diagnostics"] = [
+ {"description": "weekly signups", "hogql": generated_hogql, "ok": True, "error_type": None}
+ ]
delivery = SubscriptionDelivery.objects.create(
subscription=subscription,
team=self.team,
@@ -1823,7 +1833,7 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
target_type="email",
target_value="[email protected]",
status=SubscriptionDelivery.Status.COMPLETED,
- content_snapshot={"insights": [{"id": 1, "name": "Secret", "query_results": [[1, 2, 3]]}]},
+ content_snapshot=content_snapshot,
change_summary="Signups up 20% week over week",
recipient_results=[{"recipient": "[email protected]", "status": "success"}],
)
@@ -1838,6 +1848,8 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
if expect_hidden:
assert data["content_snapshot"] == {}
assert data["change_summary"] is None
+ # Defence-in-depth against a future per-key scrub: the generated HogQL must not appear at all.
+ assert generated_hogql not in str(data)
# The list endpoint shares the same get_serializer_context path, so it scrubs too.
list_response = self.client.get(
f"/api/environments/{self.team.id}/subscriptions/{subscription.id}/deliveries/"
@@ -1846,9 +1858,14 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):
row = next(r for r in list_response.json()["results"] if r["id"] == str(delivery.id))
assert row["content_snapshot"] == {}
assert row["change_summary"] is None
+ assert generated_hogql not in str(row)
else:
assert data["content_snapshot"]["insights"][0]["name"] == "Secret"
assert data["change_summary"] == "Signups up 20% week over week"
+ if is_ai:
+ # A query-access caller on an AI delivery legitimately receives the diagnostics,
+ # including the generated HogQL — this is the intended debugging surface.
+ assert data["content_snapshot"]["ai_report_diagnostics"][0]["hogql"] == generated_hogql
# Delivery metadata stays visible regardless — only the query-derived report is scrubbed.
assert data["status"] == "completed"
assert data["recipient_results"] == [{"recipient": "[email protected]", "status": "success"}]
diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.py
index dde74c60026c..c94e17ae38e0 100644
--- a/posthog/temporal/tests/test_subscriptions_workflows.py
+++ b/posthog/temporal/tests/test_subscriptions_workflows.py
@@ -50,6 +50,7 @@ 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.spec_generator import PromptRejectedError
from products.exports.backend.temporal.subscriptions.types import (
CreateDeliveryRecordInputs,
@@ -78,8 +79,8 @@ from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscr
pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]
-_GENERATE_MARKDOWN = (
- "products.exports.backend.temporal.subscriptions.ai_subscription.activities.generate_ai_subscription_markdown"
+_GENERATE_REPORT = (
+ "products.exports.backend.temporal.subscriptions.ai_subscription.activities.build_ai_subscription_report"
)
_IS_OVER_BUDGET = (
"products.exports.backend.temporal.subscriptions.ai_subscription.activities.is_team_over_ai_credit_budget"
@@ -2084,7 +2085,7 @@ async def test_generate_ai_report_prompt_rejected_aborts_and_auto_disables(team,
delivery = await _create_ai_delivery(sub)
with (
- patch(_GENERATE_MARKDOWN, side_effect=PromptRejectedError("Prompt is empty.")),
+ patch(_GENERATE_REPORT, side_effect=PromptRejectedError("Prompt is empty.")),
patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription"),
):
result = await ActivityEnvironment().run(
@@ -2105,7 +2106,7 @@ async def test_generate_ai_report_persists_report_for_delivery(team, user):
sub = await _create_ai_subscription(team, user)
delivery = await _create_ai_delivery(sub)
- with patch(_GENERATE_MARKDOWN, return_value="# Report"):
+ with patch(_GENERATE_REPORT, return_value=AiReportResult(markdown="# Report", diagnostics=())):
result = await ActivityEnvironment().run(
generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
)
@@ -2179,7 +2180,7 @@ async def test_generate_ai_report_skips_regeneration_when_already_persisted(team
sub = await _create_ai_subscription(team, user)
delivery = await _create_ai_delivery(sub, report="# Already here")
- with patch(_GENERATE_MARKDOWN) as mock_generate:
+ with patch(_GENERATE_REPORT) as mock_generate:
result = await ActivityEnvironment().run(
generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
)
@@ -2198,7 +2199,7 @@ async def test_generate_ai_report_skips_when_over_credit_budget(team, user):
with (
patch(_IS_OVER_BUDGET, return_value=True),
- patch(_GENERATE_MARKDOWN) as mock_generate,
+ patch(_GENERATE_REPORT) as mock_generate,
patch(_CREDIT_LIMITED_EMAIL) as mock_email,
):
result = await ActivityEnvironment().run(
@@ -2222,7 +2223,7 @@ async def test_generate_ai_report_credit_check_fails_open(team, user):
with (
patch(_IS_OVER_BUDGET, side_effect=RuntimeError("quota cache unavailable")),
- patch(_GENERATE_MARKDOWN, return_value="# Report") as mock_generate,
+ patch(_GENERATE_REPORT, return_value=AiReportResult(markdown="# Report", diagnostics=())) as mock_generate,
):
result = await ActivityEnvironment().run(
generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
@@ -2243,7 +2244,7 @@ async def test_generate_ai_report_already_generated_bypasses_credit_gate(team, u
with (
patch(_IS_OVER_BUDGET, return_value=True) as mock_over_budget,
- patch(_GENERATE_MARKDOWN) as mock_generate,
+ patch(_GENERATE_REPORT) as mock_generate,
):
result = await ActivityEnvironment().run(
generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
@@ -2370,7 +2371,7 @@ async def test_skip_helper_falls_back_when_billing_period_unsynced(team, user):
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch(_CREDIT_LIMITED_EMAIL)
@patch("products.exports.backend.temporal.subscriptions.ai_subscription.activities.send_email_ai_subscription_report")
-@patch(_GENERATE_MARKDOWN)
+@patch(_GENERATE_REPORT)
@patch(_IS_OVER_BUDGET, return_value=True)
@freeze_time("2022-02-02T08:55:00.000Z")
@pytest.mark.asyncio
@@ -2425,8 +2426,8 @@ async def test_schedule_ai_subscription_over_credit_budget_lands_skipped(
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch("products.exports.backend.temporal.subscriptions.ai_subscription.activities.send_email_ai_subscription_report")
@patch(
- "products.exports.backend.temporal.subscriptions.ai_subscription.activities.generate_ai_subscription_markdown",
- return_value="# AI Report",
+ "products.exports.backend.temporal.subscriptions.ai_subscription.activities.build_ai_subscription_report",
+ return_value=AiReportResult(markdown="# AI Report", diagnostics=()),
)
@freeze_time("2022-02-02T08:55:00.000Z")
@pytest.mark.asyncio
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
index a4f15d1885c6..4a520ce7532f 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
@@ -16,11 +16,12 @@ from posthog.sync import database_sync_to_async
from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery
from products.exports.backend.temporal.subscriptions.ai_subscription.delivery import (
- generate_ai_subscription_markdown,
+ build_ai_subscription_report,
send_email_ai_subscription_credit_limited,
send_email_ai_subscription_report,
send_slack_ai_subscription_report,
)
+from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import AiReportResult
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import PromptRejectedError
from products.exports.backend.temporal.subscriptions.delivery_common import (
auto_disable_and_return,
@@ -46,6 +47,9 @@ LOGGER = get_logger(__name__)
# can exceed Temporal's ~2 MiB payload cap, so it travels through Postgres by reference rather
# than on the wire — the same pattern insight snapshots use.
AI_REPORT_SNAPSHOT_KEY = "ai_report"
+# Companion key holding per-step query diagnostics (the 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"
# If the org's AI-credit balance isn't synced yet, reschedule roughly a billing cycle out so a
# skipped sub still moves forward instead of re-firing every tick.
@@ -68,13 +72,20 @@ async def _load_ai_report(delivery_id: uuid.UUID) -> str | None:
return await _read()
-async def _persist_ai_report(delivery_id: uuid.UUID, markdown: str) -> None:
+async def _persist_ai_report(delivery_id: uuid.UUID, result: AiReportResult) -> None:
@database_sync_to_async(thread_sensitive=False)
def _write() -> None:
# No DoesNotExist guard: create_delivery_record always writes this row before
# generation runs, so a missing row is a wiring bug — let it raise loudly.
delivery = SubscriptionDelivery.objects.get(pk=delivery_id)
- delivery.content_snapshot = {**(delivery.content_snapshot or {}), AI_REPORT_SNAPSHOT_KEY: markdown}
+ delivery.content_snapshot = {
+ **(delivery.content_snapshot or {}),
+ AI_REPORT_SNAPSHOT_KEY: result.markdown,
+ AI_REPORT_DIAGNOSTICS_KEY: [
+ {"description": d.description, "hogql": d.hogql, "ok": d.ok, "error_type": d.error_type}
+ for d in result.diagnostics
+ ],
+ }
delivery.save(update_fields=["content_snapshot", "last_updated_at"])
await _write()
@@ -221,7 +232,7 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Gen
return GenerateAIReportResult(skipped=True)
try:
- markdown = await generate_ai_subscription_markdown(subscription)
+ report_result = await build_ai_subscription_report(subscription)
except PromptRejectedError as exc:
# Structurally permanent: no creator, prompt now fails sanitization, or the
# planner returned a malformed plan. Re-firing wastes LLM tokens every cycle.
@@ -244,7 +255,7 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Gen
aborted = await auto_disable_and_return(subscription, AI_PROMPT_INVALID_DISABLE_REASON, recipient_results)
return GenerateAIReportResult(aborted=True, recipient_results=aborted.recipient_results)
- await _persist_ai_report(inputs.delivery_id, markdown)
+ await _persist_ai_report(inputs.delivery_id, report_result)
return GenerateAIReportResult(aborted=False)
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
index 3a6064a93057..bb56bef14ac9 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
@@ -16,7 +16,10 @@ from posthog.sync import database_sync_to_async
from posthog.utils import absolute_uri
from products.exports.backend.models.subscription import Subscription, get_unsubscribe_token
-from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import generate_ai_report
+from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import (
+ AiReportResult,
+ generate_ai_report,
+)
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import PromptRejectedError
from ee.tasks.subscriptions.slack_subscriptions import (
@@ -158,7 +161,7 @@ def _resolve_subscription_actors(subscription: Subscription) -> tuple[Team, User
return subscription.team, subscription.created_by
-async def generate_ai_subscription_markdown(subscription: Subscription) -> str:
+async def build_ai_subscription_report(subscription: Subscription) -> AiReportResult:
team, user = await database_sync_to_async(_resolve_subscription_actors, thread_sensitive=False)(subscription)
# created_by is FK SET_NULL; the pipeline requires a non-None user
if user is None:
@@ -320,7 +323,7 @@ async def send_slack_ai_subscription_report(
__all__ = [
- "generate_ai_subscription_markdown",
+ "build_ai_subscription_report",
"render_ai_email_html",
"send_email_ai_subscription_report",
"send_slack_ai_subscription_report",
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py b/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py
index 98823ad08da0..c80be5701097 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py
@@ -239,8 +239,8 @@ Format guidelines:
data" can only be determined if the data explicitly establishes it — if it cannot (the events
table only contains events that fired), say plainly that it can't be determined from the available
data rather than guessing. Do NOT fabricate a list of inactive events.
-- Distinguish query *errors* from *empty* data. A result block whose body reads "Query failed to
- run …" means that query errored — report that the metric could not be computed this run, and do
+- Distinguish query *errors* from *empty* data. A result whose body contains the marker
+ "{{{failure_marker}}}" means that query errored — report the metric as "could not be computed", and do
NOT call it zero, empty, or "no data". Only say a metric has "no data" when a query actually ran and
returned no rows. Either way, keep it to one line and move on.
- Keep it under ~400 words. Clarity over comprehensiveness.
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 4647aa22431a..271e15af31f4 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
@@ -1,5 +1,6 @@
import uuid
import asyncio
+from dataclasses import dataclass
from datetime import UTC, datetime
from enum import StrEnum
from typing import Optional, Union
@@ -52,6 +53,11 @@ _HOGQL_STEP_TIMEOUT_SECONDS = 60.0
# The executor already truncates; this is defense-in-depth against a giant value.
_QUERY_RESULT_MAX_CHARS = 50_000
+# The marker a failed step renders. The synthesis prompt keys off it to report "could not be computed"
+# instead of "no data"; it's injected into that prompt (the {{{failure_marker}}} placeholder) from this
+# same constant in `_synthesize`, so the rendered marker and the prompt instruction can't drift apart.
+QUERY_FAILED_PREFIX = "Query failed to run"
+
# Per-step query-fix budget: the planner occasionally emits HogQL that fails to parse, so we feed the
# error back and ask for a rewrite rather than dropping the step. Worst case per step is one original
# run plus _MAX_QUERY_FIX_RETRIES × (fix LLM + rerun); steps run concurrently via asyncio.gather.
@@ -82,6 +88,23 @@ class AiReportStageError(Exception):
super().__init__(f"AI report failed at {stage} stage: {original}")
+@dataclass(frozen=True)
+class QueryStepDiagnostic:
+ # Per-step audit record persisted to the delivery's content_snapshot. The generated HogQL and the
+ # failure type are otherwise discarded once the report renders, leaving a "could not be computed"
+ # line with no way to see which query ran or why it failed.
+ description: str
+ hogql: str
+ ok: bool
+ error_type: Optional[str]
+
+
+@dataclass(frozen=True)
+class AiReportResult:
+ markdown: str
+ diagnostics: tuple[QueryStepDiagnostic, ...]
+
+
async def generate_ai_report(
*,
team: Team,
@@ -89,7 +112,7 @@ async def generate_ai_report(
prompt: Optional[str],
window_days: int,
trace_correlation_id: Optional[Union[int, str]] = None,
-) -> str:
+) -> AiReportResult:
if user is None:
raise PromptRejectedError("AI report must have a user to run.")
@@ -107,7 +130,7 @@ async def generate_ai_report(
spec = await _plan(
team=team, user=user, prompt=prompt, window_days=window_days, trace_id=trace_correlation_id
)
- rendered_results, failed_count = await _execute_plan(spec, team, user, trace_correlation_id)
+ rendered_results, failed_count, diagnostics = await _execute_plan(spec, team, user, trace_correlation_id)
report = await _synthesize(spec, rendered_results, team, user, trace_correlation_id)
except PromptRejectedError:
# A rejected prompt is the input guard doing its job, not a service failure — keep it out of
@@ -131,7 +154,7 @@ async def generate_ai_report(
failed_steps=failed_count,
total_steps=total_steps,
)
- return report
+ return AiReportResult(markdown=report, diagnostics=tuple(diagnostics))
async def _plan(
@@ -156,7 +179,7 @@ async def _execute_plan(
team: Team,
user: User,
trace_correlation_id: Optional[Union[int, str]],
-) -> tuple[list[str], int]:
+) -> tuple[list[str], int, list[QueryStepDiagnostic]]:
try:
return await _run_steps(spec, team, user, trace_correlation_id)
except Exception as exc:
@@ -190,6 +213,9 @@ async def _synthesize(
synthesis_prompt = await database_sync_to_async(resolve_prompt, thread_sensitive=False)(
team, SYNTHESIS_PROMPT_NAME, AI_SUBSCRIPTION_SYNTHESIS_PROMPT
)
+ # Inject the failure marker from the same constant the placeholder renders, so the prompt's
+ # "treat this as an error, not 'no data'" instruction can't drift from what _run_steps emits.
+ synthesis_prompt = render_prompt(synthesis_prompt, {"failure_marker": QUERY_FAILED_PREFIX})
try:
# database_sync_to_async (not to_thread): MaxChatOpenAI reads billing/quota from the ORM
@@ -222,10 +248,10 @@ async def _run_steps(
team: Team,
user: User,
trace_correlation_id: Optional[Union[int, str]],
-) -> tuple[list[str], int]:
+) -> tuple[list[str], int, list[QueryStepDiagnostic]]:
executor = AssistantQueryExecutor(team, datetime.now(tz=UTC), user=user)
- async def run_step(step: QueryPlanStep) -> tuple[str, bool]:
+ async def run_step(step: QueryPlanStep) -> tuple[str, QueryStepDiagnostic]:
current_hogql = step.hogql
last_exc: Optional[BaseException] = None
# planner output — strip framing markers so it can't break the <query_results> envelope
@@ -240,7 +266,10 @@ async def _run_steps(
)
# result values are attacker-influenceable (public project tokens) — strip framing markers
safe_formatted = strip_llm_framing_markers(formatted, _QUERY_RESULT_MAX_CHARS)
- return (f"### {safe_description}\n\n{safe_formatted}", True)
+ return (
+ f"### {safe_description}\n\n{safe_formatted}",
+ QueryStepDiagnostic(description=safe_description, hogql=current_hogql, ok=True, error_type=None),
+ )
except Exception as exc:
last_exc = exc
if attempt >= _MAX_QUERY_FIX_RETRIES or not isinstance(exc, _RETRYABLE_QUERY_ERRORS):
@@ -285,14 +314,15 @@ async def _run_steps(
# 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".
return (
- f"### {safe_description}\n\n_Query failed to run ({type_name}) — metric not computed, not empty data._",
- False,
+ f"### {safe_description}\n\n_{QUERY_FAILED_PREFIX} ({type_name}) — metric not computed, not empty data._",
+ QueryStepDiagnostic(description=safe_description, hogql=current_hogql, ok=False, error_type=type_name),
)
- step_results: list[tuple[str, bool]] = await asyncio.gather(*(run_step(step) for step in spec.plan.steps))
+ step_results = await asyncio.gather(*(run_step(step) for step in spec.plan.steps))
rendered = [text for text, _ in step_results]
- failed_count = sum(1 for _, ok in step_results if not ok)
- return rendered, failed_count
+ diagnostics = [diag for _, diag in step_results]
+ failed_count = sum(1 for diag in diagnostics if not diag.ok)
+ return rendered, failed_count, diagnostics
async def _arequest_hogql_fix(
@@ -342,4 +372,4 @@ async def _arequest_hogql_fix(
return fixed or None
-__all__ = ["generate_ai_report", "AiReportStageError", "ReportStage"]
+__all__ = ["generate_ai_report", "AiReportResult", "QueryStepDiagnostic", "AiReportStageError", "ReportStage"]
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
new file mode 100644
index 000000000000..c3f190851346
--- /dev/null
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py
@@ -0,0 +1,69 @@
+from datetime import datetime
+from zoneinfo import ZoneInfo
+
+import pytest
+
+from asgiref.sync import sync_to_async
+
+from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery
+from products.exports.backend.temporal.subscriptions.ai_subscription.activities import (
+ AI_REPORT_DIAGNOSTICS_KEY,
+ AI_REPORT_SNAPSHOT_KEY,
+ _persist_ai_report,
+)
+from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import (
+ AiReportResult,
+ QueryStepDiagnostic,
+)
+from products.product_analytics.backend.models.insight import Insight
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]
+
+
+@sync_to_async
+def _create_delivery(team, user) -> SubscriptionDelivery:
+ insight = Insight.objects.create(team=team, name="Pageviews", created_by=user)
+ subscription = Subscription.objects.create(
+ team=team,
+ insight=insight,
+ created_by=user,
+ target_type=Subscription.SubscriptionTarget.EMAIL,
+ target_value="[email protected]",
+ frequency=Subscription.SubscriptionFrequency.WEEKLY,
+ start_date=datetime(2022, 1, 1, 9, 0, tzinfo=ZoneInfo("UTC")),
+ )
+ return SubscriptionDelivery.objects.create(
+ subscription=subscription,
+ team=team,
+ status=SubscriptionDelivery.Status.STARTING,
+ content_snapshot={},
+ )
+
+
+@sync_to_async
+def _snapshot(delivery_id) -> dict:
+ return SubscriptionDelivery.objects.values_list("content_snapshot", flat=True).get(pk=delivery_id)
+
+
+async def test_persist_ai_report_writes_markdown_and_query_diagnostics(team, user) -> None:
+ delivery = await _create_delivery(team, user)
+
+ await _persist_ai_report(
+ delivery.id,
+ AiReportResult(
+ markdown="# Weekly report",
+ diagnostics=(
+ QueryStepDiagnostic(description="adoption", hogql="SELECT count()", ok=True, error_type=None),
+ QueryStepDiagnostic(
+ description="reliability", hogql="SELECT bad", ok=False, error_type="ResolutionError"
+ ),
+ ),
+ ),
+ )
+
+ snapshot = await _snapshot(delivery.id)
+ assert snapshot[AI_REPORT_SNAPSHOT_KEY] == "# Weekly report"
+ assert snapshot[AI_REPORT_DIAGNOSTICS_KEY] == [
+ {"description": "adoption", "hogql": "SELECT count()", "ok": True, "error_type": None},
+ {"description": "reliability", "hogql": "SELECT bad", "ok": False, "error_type": "ResolutionError"},
+ ]
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 d9205473ee5c..860d9c7c96c9 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
@@ -1,10 +1,12 @@
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
-from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.errors import ExposedHogQLError, ResolutionError
from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import (
+ QUERY_FAILED_PREFIX,
AiReportStageError,
+ QueryStepDiagnostic,
_arequest_hogql_fix,
_run_steps,
generate_ai_report,
@@ -67,12 +69,19 @@ async def test_successful_report_emits_slo_success(
mock_bep: MagicMock, mock_run: AsyncMock, mock_chat: MagicMock, mock_capture: MagicMock
) -> None:
mock_bep.return_value = _spec(steps=2)
- mock_run.return_value = (["### s0\n\nok", "### s1\n\nok"], 0)
+ mock_run.return_value = (
+ ["### s0\n\nok", "### s1\n\nok"],
+ 0,
+ [
+ QueryStepDiagnostic(description="s0", hogql="SELECT 1", ok=True, error_type=None),
+ QueryStepDiagnostic(description="s1", hogql="SELECT 2", ok=True, error_type=None),
+ ],
+ )
mock_chat.return_value.invoke.return_value = MagicMock(content="# Report")
result = await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window_days=7)
- assert result == "# Report"
+ assert result.markdown == "# Report"
props = _slo_completed(mock_capture)
assert props["operation"] == "ai_subscription_prompt_generation"
assert props["outcome"] == "success"
@@ -93,12 +102,17 @@ async def test_degraded_report_still_synthesizes(
mock_run.return_value = (
["### s0\n\n_Query failed to run (ExposedHogQLError) — metric not computed, not empty data._"],
1,
+ [QueryStepDiagnostic(description="s0", hogql="SELECT bad", ok=False, error_type="ExposedHogQLError")],
)
mock_chat.return_value.invoke.return_value = MagicMock(content="# Weekly report")
result = await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window_days=7)
- assert result == "# Weekly report"
+ assert result.markdown == "# Weekly report"
+ # The failed step's generated HogQL + error type are surfaced for persistence/debugging.
+ assert result.diagnostics == (
+ QueryStepDiagnostic(description="s0", hogql="SELECT bad", ok=False, error_type="ExposedHogQLError"),
+ )
# A degraded-but-shipped report is an SLO success, tagged so the coverage signal survives.
props = _slo_completed(mock_capture)
assert props["outcome"] == "success"
@@ -115,7 +129,11 @@ async def test_synthesis_failure_wrapped_with_stage(
mock_bep: MagicMock, mock_run: AsyncMock, mock_chat: MagicMock, mock_capture: MagicMock
) -> None:
mock_bep.return_value = _spec(steps=1)
- mock_run.return_value = (["### s0\n\nok"], 0)
+ mock_run.return_value = (
+ ["### s0\n\nok"],
+ 0,
+ [QueryStepDiagnostic(description="s0", hogql="SELECT 1", ok=True, error_type=None)],
+ )
mock_chat.return_value.invoke.side_effect = RuntimeError("synth boom")
with pytest.raises(AiReportStageError) as exc_info:
@@ -169,9 +187,53 @@ async def test_request_hogql_fix_returns_none_on_wrong_type(mock_chat: MagicMock
@patch(f"{_RP}.AssistantQueryExecutor")
async def test_run_steps_non_retryable_error_degrades_to_placeholder(mock_executor_cls: MagicMock) -> None:
mock_executor_cls.return_value.arun_and_format_query = AsyncMock(side_effect=RuntimeError("boom"))
- rendered, failed = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
+ rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
assert failed == 1
assert "Query failed to run" in rendered[0]
+ assert diagnostics[0].ok is False
+ assert diagnostics[0].error_type == "RuntimeError"
+ assert diagnostics[0].hogql == "SELECT 1"
+
+
+@patch(f"{_RP}._arequest_hogql_fix", new_callable=AsyncMock)
+@patch(f"{_RP}.AssistantQueryExecutor")
+async def test_run_steps_forwards_resolution_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_and_format_query = AsyncMock(
+ side_effect=[ResolutionError("Unable to resolve field 'operaton'"), ("formatted table", None)]
+ )
+ mock_fix.return_value = "SELECT fixed"
+ await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
+ assert mock_fix.await_args is not None
+ assert mock_fix.await_args.kwargs["error_message"] == "Unable to resolve field 'operaton'"
+
+
+@patch(_SLO_CAPTURE)
+@patch(f"{_RP}.MaxChatOpenAI")
+@patch(f"{_RP}._run_steps", new_callable=AsyncMock)
+@patch(f"{_RP}.build_enriched_prompt")
+async def test_synthesis_prompt_carries_the_failure_marker(
+ mock_bep: MagicMock, mock_run: AsyncMock, mock_chat: MagicMock, _mock_capture: MagicMock
+) -> None:
+ # The marker is injected into the synthesis prompt from the same constant the placeholder renders, so
+ # the prompt's "this is an error, not 'no data'" instruction can't drift from what _run_steps emits.
+ mock_bep.return_value = _spec(steps=1)
+ mock_run.return_value = (
+ ["### s0\n\nfailed"],
+ 1,
+ [QueryStepDiagnostic(description="s0", hogql="SELECT bad", ok=False, error_type="ExposedHogQLError")],
+ )
+ mock_chat.return_value.invoke.return_value = MagicMock(content="# Report")
+
+ await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window_days=7)
+
+ (messages,) = mock_chat.return_value.invoke.call_args[0]
+ system_message = messages[0][1]
+ assert QUERY_FAILED_PREFIX in system_message # {{{failure_marker}}} substituted from the constant
+ assert "{{{" not in system_message # no placeholder left unrendered
@patch(f"{_RP}._arequest_hogql_fix", new_callable=AsyncMock)
@@ -182,10 +244,13 @@ async def test_run_steps_retries_then_succeeds(mock_executor_cls: MagicMock, moc
side_effect=[ExposedHogQLError("bad query"), ("formatted table", None)]
)
mock_fix.return_value = "SELECT fixed"
- rendered, failed = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
+ rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
assert failed == 0
assert "formatted table" in rendered[0]
mock_fix.assert_awaited_once()
+ # The diagnostic tracks the fixed query (current_hogql), not the original SELECT 1.
+ assert diagnostics[0].ok is True
+ assert diagnostics[0].hogql == "SELECT fixed"
@patch(f"{_RP}._arequest_hogql_fix", new_callable=AsyncMock)
@@ -197,7 +262,7 @@ async def test_run_steps_breaks_early_when_fix_returns_same_query(
# degrade rather than burn the retry budget on an identical query.
mock_executor_cls.return_value.arun_and_format_query = AsyncMock(side_effect=ExposedHogQLError("bad query"))
mock_fix.return_value = "SELECT 1" # identical to QueryPlanStep.hogql in _spec()
- rendered, failed = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
+ rendered, failed, diagnostics = await _run_steps(_spec(steps=1), MagicMock(), MagicMock(), None)
assert failed == 1
assert "Query failed to run" in rendered[0]
# Executor ran exactly once (no rerun of the identical fixed query); the fix was requested once.
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline_integration.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline_integration.py
index 02c2b42d3745..e956ed4a00c2 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline_integration.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline_integration.py
@@ -65,7 +65,7 @@ class TestAIReportPipelineIntegration(ClickhouseTestMixin, NonAtomicBaseTest):
report = await generate_ai_report(team=self.team, user=self.user, prompt="how many events", window_days=7)
- assert report == "# Report"
+ assert report.markdown == "# Report"
assert "$pageview" in captured["human"]
assert "signed_up" in captured["human"]
@@ -77,5 +77,7 @@ class TestAIReportPipelineIntegration(ClickhouseTestMixin, NonAtomicBaseTest):
report = await generate_ai_report(team=self.team, user=self.user, prompt="x", window_days=7)
- assert report == "# Degraded report"
+ assert report.markdown == "# Degraded report"
assert "Query failed to run" in captured["human"]
+ # The degraded step's generated HogQL + error type are captured for persistence/debugging.
+ assert any(not d.ok and d.error_type for d in report.diagnostics)