:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(subscriptions): degraded AI report status + in-app report viewer (#66797)
Vasco de Krijgerd5bf26731ad7
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex c4104f95c925..f23bb52e129a 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -55,6 +55,9 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generasanitize_prompt,)from products.exports.backend.temporal.subscriptions.types import (+ AI_REPORT_DIAGNOSTICS_KEY,+ AI_REPORT_PROMPT_SNAPSHOT_KEY,+ AI_REPORT_SNAPSHOT_KEY,ProcessSubscriptionWorkflowInputs,SubscriptionTriggerType,)@@ -1089,11 +1092,46 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mreturn Response(status=status.HTTP_202_ACCEPTED)+class AIReportQueryDiagnosticSerializer(serializers.Serializer):+ # Per-step query diagnostics persisted alongside the report markdown. Query-derived (the generated+ # HogQL is here), so it is scrubbed for callers without query access — never shipped to recipients.+ description = serializers.CharField(help_text="What this query step was meant to compute.")+ hogql = serializers.CharField(help_text="The HogQL the assistant generated for this step.")+ ok = serializers.BooleanField(help_text="Whether the query ran successfully.")+ error_type = serializers.CharField(+ allow_null=True, help_text="Exception class name when the query failed; null on success."+ )+ human_readable_error = serializers.CharField(+ allow_null=True,+ required=False,+ help_text="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.",+ )++class SubscriptionDeliverySerializer(serializers.ModelSerializer):# 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, change_summary- # nullable text). Single source of truth — keep in sync when adding AI-derived delivery fields.- AI_REPORT_SCRUBBED: ClassVar[dict[str, dict | None]] = {"content_snapshot": {}, "change_summary": None}+ # 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.+ # ai_report_prompt is user-authored (not query-derived) and already readable on the parent+ # subscription, so it is intentionally not scrubbed.+ AI_REPORT_SCRUBBED: ClassVar[dict[str, object | None]] = {+ "content_snapshot": {},+ "change_summary": None,+ "ai_report": None,+ "ai_report_diagnostics": None,+ }++ ai_report = serializers.SerializerMethodField(+ help_text="AI-generated report markdown delivered by this run. Null for non-AI deliveries or runs without a persisted report."+ )+ ai_report_diagnostics = serializers.SerializerMethodField(+ help_text="Per-step query diagnostics (generated HogQL + failure type) for this report. Null for non-AI deliveries or runs without persisted diagnostics."+ )+ ai_report_prompt = serializers.SerializerMethodField(+ help_text="The subscription's prompt as it was when this report was generated. Null for older deliveries and non-AI deliveries."+ )class Meta:model = SubscriptionDelivery@@ -1115,6 +1153,9 @@ class SubscriptionDeliverySerializer(serializers.ModelSerializer):"last_updated_at","finished_at","change_summary",+ "ai_report",+ "ai_report_diagnostics",+ "ai_report_prompt",]read_only_fields = fieldsextra_kwargs = {@@ -1144,13 +1185,52 @@ class SubscriptionDeliverySerializer(serializers.ModelSerializer):"change_summary": {"help_text": "AI-generated summary included in this delivery, when one was produced."},}+ def _content_snapshot_text(self, delivery: SubscriptionDelivery, key: str) -> Optional[str]:+ snapshot = delivery.content_snapshot+ if not isinstance(snapshot, dict):+ return None+ value = snapshot.get(key)+ return value if isinstance(value, str) and value else None++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_ai_report(self, delivery: SubscriptionDelivery) -> Optional[str]:+ return self._content_snapshot_text(delivery, AI_REPORT_SNAPSHOT_KEY)++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_ai_report_prompt(self, delivery: SubscriptionDelivery) -> Optional[str]:+ return self._content_snapshot_text(delivery, AI_REPORT_PROMPT_SNAPSHOT_KEY)++ @extend_schema_field(AIReportQueryDiagnosticSerializer(many=True, allow_null=True))+ def get_ai_report_diagnostics(self, delivery: SubscriptionDelivery) -> Optional[list[dict]]:+ snapshot = delivery.content_snapshot+ if not isinstance(snapshot, dict):+ return None+ diagnostics = snapshot.get(AI_REPORT_DIAGNOSTICS_KEY)+ return diagnostics if isinstance(diagnostics, list) else None+def to_representation(self, instance):data = super().to_representation(instance)# The viewset sets this flag when an AI prompt delivery is read by a caller without query# access; scrub the query-derived report so subscription:read (or a self-granted query:read- # scope) can't read analytics the user isn't allowed to run themselves.+ # scope) can't read analytics the user isn't allowed to run themselves. ai_report_prompt is+ # 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)+ 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.+ # The non-AI scaffold (insights, dashboard, total_insight_count) stays intact.+ snapshot = data.get("content_snapshot")+ if isinstance(snapshot, dict) and (+ AI_REPORT_SNAPSHOT_KEY in snapshot+ or AI_REPORT_PROMPT_SNAPSHOT_KEY in snapshot+ or AI_REPORT_DIAGNOSTICS_KEY in snapshot+ ):+ data["content_snapshot"] = {+ key: value+ for key, value in snapshot.items()+ if key not in (AI_REPORT_SNAPSHOT_KEY, AI_REPORT_PROMPT_SNAPSHOT_KEY, AI_REPORT_DIAGNOSTICS_KEY)+ }return datadiff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex cd5b99cfe658..1847a079f158 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -30,6 +30,9 @@ from products.exports.backend.models.subscription import (SubscriptionDelivery,)from products.exports.backend.temporal.subscriptions.types import (+ AI_REPORT_DIAGNOSTICS_KEY,+ AI_REPORT_PROMPT_SNAPSHOT_KEY,+ AI_REPORT_SNAPSHOT_KEY,ProcessSubscriptionWorkflowInputs,SubscriptionTriggerType,)@@ -1983,14 +1986,24 @@ 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.subscriptiongenerated_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'"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}+ content_snapshot[AI_REPORT_SNAPSHOT_KEY] = "# Weekly report"+ content_snapshot[AI_REPORT_DIAGNOSTICS_KEY] = [+ {"description": "weekly signups", "hogql": generated_hogql, "ok": True, "error_type": None},+ {+ "description": "adoption",+ "hogql": "SELECT bad",+ "ok": False,+ "error_type": "ResolutionError",+ "human_readable_error": scrubbed_error_message,+ },]+ content_snapshot[AI_REPORT_PROMPT_SNAPSHOT_KEY] = "Weekly growth recap"delivery = SubscriptionDelivery.objects.create(subscription=subscription,team=self.team,@@ -2015,8 +2028,15 @@ 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.+ # The query-derived report and diagnostics are scrubbed per-field; the generated HogQL+ # must not appear at all (defence-in-depth across content_snapshot and the typed fields).+ assert data[AI_REPORT_SNAPSHOT_KEY] is None+ assert data[AI_REPORT_DIAGNOSTICS_KEY] is Noneassert generated_hogql not in str(data)+ assert scrubbed_error_message not in str(data)+ # 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"# 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/"@@ -2025,18 +2045,81 @@ 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 row[AI_REPORT_SNAPSHOT_KEY] is None+ assert row[AI_REPORT_DIAGNOSTICS_KEY] is None+ assert row[AI_REPORT_PROMPT_SNAPSHOT_KEY] == "Weekly growth recap"assert generated_hogql not in str(row)+ assert scrubbed_error_message 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+ # A query-access caller on an AI delivery legitimately receives the report and the+ # 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+ # 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"+ # 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 AI_REPORT_SNAPSHOT_KEY not in data["content_snapshot"]+ assert AI_REPORT_DIAGNOSTICS_KEY not in data["content_snapshot"]+ assert AI_REPORT_PROMPT_SNAPSHOT_KEY not in data["content_snapshot"]# 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"}]+ @parameterized.expand(+ [+ (+ "report_prompt_and_diagnostics",+ {+ AI_REPORT_SNAPSHOT_KEY: "# Report",+ AI_REPORT_PROMPT_SNAPSHOT_KEY: "Weekly growth recap",+ AI_REPORT_DIAGNOSTICS_KEY: [+ {"description": "d", "hogql": "SELECT 1", "ok": True, "error_type": None}+ ],+ },+ "# Report",+ "Weekly growth recap",+ [{"description": "d", "hogql": "SELECT 1", "ok": True, "error_type": None}],+ ),+ # Deliveries created before prompt/diagnostics snapshotting only carry the report.+ ("report_without_prompt", {AI_REPORT_SNAPSHOT_KEY: "# Report"}, "# Report", None, None),+ ("absent_keys", {}, None, None, None),+ ("non_string_values", {AI_REPORT_SNAPSHOT_KEY: 123, AI_REPORT_PROMPT_SNAPSHOT_KEY: ""}, None, None, None),+ ]+ )+ def test_delivery_exposes_ai_report_fields(+ self, _name, snapshot, expected_report, expected_prompt, expected_diagnostics+ ):+ delivery = self._create_delivery(idempotency_key=f"ai-fields-{_name}", content_snapshot=snapshot)++ response = self.client.get(+ f"/api/environments/{self.team.id}/subscriptions/{self.subscription.id}/deliveries/{delivery.id}/"+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ data = response.json()+ assert data[AI_REPORT_SNAPSHOT_KEY] == expected_report+ assert data[AI_REPORT_PROMPT_SNAPSHOT_KEY] == expected_prompt+ assert data[AI_REPORT_DIAGNOSTICS_KEY] == expected_diagnostics+ # The typed fields are the contract — the AI keys are stripped from content_snapshot so the+ # report is not shipped twice (the snapshot stays a dict, just without the AI keys).+ for ai_key in (AI_REPORT_SNAPSHOT_KEY, AI_REPORT_PROMPT_SNAPSHOT_KEY, AI_REPORT_DIAGNOSTICS_KEY):+ assert ai_key not in data["content_snapshot"]+ # The list endpoint serves the delivery history table, so it must expose the same fields.+ list_response = self.client.get(+ f"/api/environments/{self.team.id}/subscriptions/{self.subscription.id}/deliveries/"+ )+ assert list_response.status_code == status.HTTP_200_OK, list_response.json()+ row = next(r for r in list_response.json()["results"] if r["id"] == str(delivery.id))+ assert row[AI_REPORT_SNAPSHOT_KEY] == expected_report+ assert row[AI_REPORT_PROMPT_SNAPSHOT_KEY] == expected_prompt+ assert row[AI_REPORT_DIAGNOSTICS_KEY] == expected_diagnostics+ for ai_key in (AI_REPORT_SNAPSHOT_KEY, AI_REPORT_PROMPT_SNAPSHOT_KEY, AI_REPORT_DIAGNOSTICS_KEY):+ assert ai_key not in row["content_snapshot"]+def test_can_list_deliveries(self):d1 = self._create_delivery(idempotency_key="key-1")d2 = self._create_delivery(idempotency_key="key-2")diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 9cfb2eb00447..0daa6d994c95 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6877,13 +6877,17 @@ snapshots:scenes-app-subscriptions-subscription-delivery-history--empty--light:hash: v1.k794b7964.3c29a7e8a6ea51f198398ecf0dbede063bcc76ebe7ffe9cb845a10e29a546b42.CR678XpTQlJgVQS_shJF51dcPQhOg_lZKNuDzEstzbUscenes-app-subscriptions-subscription-delivery-history--with-deliveries--dark:- hash: v1.k794b7964.ce55b51294cff97be9c7058bbe18876232141f6778c9e8bda9245e121b469dd2.po0mX3j9fbHsLuA1dNWNK7Lp7Ub8bXz0Eq48l6kVy-g+ hash: v1.k794b7964.a4eec8ebddff1a14ea03a8eebfcc37e9c72c79813c42a30f1820f081b0e8c865.6e0q6GiTDR-BGZhMt9cf0loRZddPkr2ierQk8s1DXeEscenes-app-subscriptions-subscription-delivery-history--with-deliveries--light:- hash: v1.k794b7964.5b8ff104f58ca8b01a2f34e7a5bb3eb9c5b2709475c51c8d2196ea0853a53048.H6gMJ0rTKEDxwxvn_fIA8vgT-CnHSQ2M0LV_5mEI3Mc+ hash: v1.k794b7964.ba95c5a833ef7dae5b452bfa017e4137569815aa6ed992a446573ce6ab750a56.5adBLBJYoAidGzoM0E5NP2ON7563AEDCoAFlBhFNias+ scenes-app-subscriptions-subscription-delivery-history--with-expanded-ai-report--dark:+ hash: v1.k794b7964.97fcc8d80e221fe797031b6305839d6eab0a541ecd0b25c44f4cdc5cc87ebf24.uUrtZ2bLDU7BxMLUWBa7q5sqig9oh_Gorhfn94F4RTY+ scenes-app-subscriptions-subscription-delivery-history--with-expanded-ai-report--light:+ hash: v1.k794b7964.abb8a6720e2c7721af4bee507fd0c8541e9ac3fff7f31e5656832b1b15d059a5.dWFBMlLGfxqAiPKo5oz1OAa5-jonJCyE-Rr_mNCW8e0scenes-app-subscriptions-subscription-delivery-history--with-expanded-summary--dark:- hash: v1.k794b7964.65afd02ab759b07036f9831b398bd100469d3e1b7c28ec5fc2b8433e3c945e88.QmvRnPBmMFIqgDbjm70gRBwdeRpHxSORo9WS8djbqcQ+ hash: v1.k794b7964.9d825454b80602e3cca17fa872553832e01b929728eb3b554b98a7f0d63b01be.0yatf93qe--xfQgkYLmnt1cT1GfWryPJQWCRNHvTESQscenes-app-subscriptions-subscription-delivery-history--with-expanded-summary--light:- hash: v1.k794b7964.b877da4f4e781a7d626f24f58c661b21e299c991bf73ea0d114cebdaa4daf77e.70r_22l4J5aH5KdO_3WbwcoFI02gtN2H5Vou5d9lp_I+ hash: v1.k794b7964.e8ea5acdf82c72e927990f4672e1615f9b8269abc31a3feb639fa9b993babad0.IRJkilIOj_v_8XjyFVxmWECDo8vBzlepnIV0yABpTt0scenes-app-subscriptions-subscription-summary--dashboard-many-destinations--dark:hash: v1.k794b7964.d8cc3d07d97916c815948be5aec81b895def2c9b5e34eece4fb05bfcbb4fe751.vj4u5-fIXtMDGIsQvXpW_WCCN_7gGt_7R9k5RlXS7fgscenes-app-subscriptions-subscription-summary--dashboard-many-destinations--light:diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionAiReportDelivery.test.ts b/frontend/src/scenes/subscriptions/components/SubscriptionAiReportDelivery.test.tsnew file mode 100644index 000000000000..63d91b71fed8--- /dev/null+++ b/frontend/src/scenes/subscriptions/components/SubscriptionAiReportDelivery.test.ts@@ -0,0 +1,68 @@+import type {+ AIReportQueryDiagnosticApi,+ SubscriptionDeliveryApi,+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'+import { SubscriptionDeliveryStatusEnumApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'++import { isPartialDelivery, queryFailureReason, queryStatusLabel } from './SubscriptionAiReportDelivery'++const diagnostic = (ok: boolean): AIReportQueryDiagnosticApi => ({+ description: 'q',+ hogql: 'SELECT 1',+ ok,+ error_type: ok ? null : 'ResolutionError',+})++describe('SubscriptionAiReportDelivery helpers', () => {+ describe('isPartialDelivery', () => {+ it.each<[string, SubscriptionDeliveryApi['status'], AIReportQueryDiagnosticApi[] | null, boolean]>([+ // A completed delivery that couldn't run some queries is "partial", not a clean success.+ [+ 'completed with a failed query',+ SubscriptionDeliveryStatusEnumApi.Completed,+ [diagnostic(true), diagnostic(false)],+ true,+ ],+ ['completed with all queries ok', SubscriptionDeliveryStatusEnumApi.Completed, [diagnostic(true)], false],+ // A fully-failed delivery is its own "Failed" state, never "partial".+ ['failed status', SubscriptionDeliveryStatusEnumApi.Failed, [diagnostic(false)], false],+ // Scrubbed/absent diagnostics (query-restricted caller, or a non-AI delivery) → not partial.+ ['completed with scrubbed diagnostics', SubscriptionDeliveryStatusEnumApi.Completed, null, false],+ ])('%s', (_name, status, diagnostics, expected) => {+ expect(isPartialDelivery({ status, ai_report_diagnostics: diagnostics })).toBe(expected)+ })+ })++ describe('queryStatusLabel', () => {+ it.each<[string, boolean, string | null, string | null, string]>([+ ['succeeded query', true, null, null, 'OK'],+ // A resolution/exposed error (message present) surfaces its specific type.+ [+ 'failed with a surfaceable error',+ false,+ 'ResolutionError',+ "Unable to resolve field 'x'",+ 'ResolutionError',+ ],+ // A generic internal exception (no message) collapses to "Failed", not a cryptic class name.+ ['failed with an internal exception', false, 'Exception', null, 'Failed'],+ ])('%s', (_name, ok, error_type, human_readable_error, expected) => {+ expect(queryStatusLabel({ ok, error_type, human_readable_error })).toBe(expected)+ })+ })++ describe('queryFailureReason', () => {+ it.each<[string, boolean, string | null, string | null]>([+ ['succeeded query has no reason', true, null, null],+ [+ 'surfaceable error shows its message',+ false,+ "Unable to resolve field 'x'",+ "Unable to resolve field 'x'",+ ],+ ['internal error shows a generic note', false, null, 'This query failed to run due to an internal error.'],+ ])('%s', (_name, ok, human_readable_error, expected) => {+ expect(queryFailureReason({ ok, human_readable_error })).toBe(expected)+ })+ })+})diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionAiReportDelivery.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionAiReportDelivery.tsxnew file mode 100644index 000000000000..099d6f5d9305--- /dev/null+++ b/frontend/src/scenes/subscriptions/components/SubscriptionAiReportDelivery.tsx@@ -0,0 +1,174 @@+import { LemonCollapse, LemonTag, Tooltip } from '@posthog/lemon-ui'+import type {+ AIReportQueryDiagnosticApi,+ SubscriptionDeliveryApi,+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'+import { SubscriptionDeliveryStatusEnumApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'++/** A completed AI delivery whose report couldn't compute some queries still shipped — but with missing+ * metrics — so it reads as "Partial", not a clean "Completed". Derived from the (query:viewer-gated)+ * diagnostics the viewer already has; a query-restricted caller (diagnostics scrubbed) sees "Completed". */+export function isPartialDelivery(row: Pick<SubscriptionDeliveryApi, 'status' | 'ai_report_diagnostics'>): boolean {+ if (row.status !== SubscriptionDeliveryStatusEnumApi.Completed) {+ return false+ }+ return (row.ai_report_diagnostics ?? []).some((d) => d.ok === false)+}++/** The "Partial" status tag for a completed delivery whose report couldn't compute some queries. Null when+ * the delivery isn't partial (or its diagnostics are scrubbed), so the caller falls back to the plain tag. */+export function partialDeliveryTag(row: SubscriptionDeliveryApi): JSX.Element | null {+ if (!isPartialDelivery(row)) {+ return null+ }+ const diagnostics = row.ai_report_diagnostics ?? []+ const failed = diagnostics.filter((d) => d.ok === false).length+ return (+ <Tooltip+ title={`${failed} of ${diagnostics.length} queries failed — those metrics are missing from the report.`}+ >+ <LemonTag type="warning" className="cursor-help">+ Partial+ </LemonTag>+ </Tooltip>+ )+}++/** Header label for a query outcome. A failed query shows its specific error type only when we can also+ * explain it (a message is present, i.e. a resolution/exposed HogQL error); a generic/internal exception+ * collapses to a plain "Failed" so a cryptic class name like "Exception" never leaks into the header. */+export function queryStatusLabel(+ d: Pick<AIReportQueryDiagnosticApi, 'ok' | 'error_type' | 'human_readable_error'>+): string {+ if (d.ok !== false) {+ return 'OK'+ }+ return d.human_readable_error && d.error_type ? d.error_type : 'Failed'+}++/** Failure reason shown in a failed query's expanded panel: the safe message when we have one, otherwise a+ * plain internal-error note (we deliberately don't surface internal exception text). Null for a succeeded query. */+export function queryFailureReason(d: Pick<AIReportQueryDiagnosticApi, 'ok' | 'human_readable_error'>): string | null {+ if (d.ok !== false) {+ return null+ }+ return d.human_readable_error || 'This query failed to run due to an internal error.'+}++function queryStatusTag(d: AIReportQueryDiagnosticApi): JSX.Element {+ return <LemonTag type={d.ok === false ? 'danger' : 'success'}>{queryStatusLabel(d)}</LemonTag>+}++function diagnosticsSummary(diagnostics: readonly AIReportQueryDiagnosticApi[]): string {+ const total = diagnostics.length+ const failed = diagnostics.filter((d) => d.ok === false).length+ const noun = total === 1 ? 'query' : 'queries'+ return failed === 0 ? `${total} ${noun} · all succeeded` : `${total} ${noun} · ${failed} failed`+}++const failedIndexes = (diagnostics: readonly AIReportQueryDiagnosticApi[]): number[] =>+ diagnostics.map((d, i) => (d.ok === false ? i : -1)).filter((i) => i >= 0)++/** Whether a delivery row has any AI-generated detail to expand: an AI summary, the generating prompt,+ * the delivered report, or per-query diagnostics. Single source of truth for the table's `rowExpandable`+ * and `ExpandedDeliveryRow`'s early return, so the two can't disagree on which rows are expandable. */+export function deliveryRowHasExpandableContent(row: SubscriptionDeliveryApi): boolean {+ return (+ Boolean(row.change_summary) ||+ Boolean(row.ai_report) ||+ Boolean(row.ai_report_prompt) ||+ (row.ai_report_diagnostics ?? []).length > 0+ )+}++/**+ * Per-query accordion: one compact header per generated query (status + description); expand a query for its+ * SQL. Failed queries are open by default so a degraded report stays loud and debuggable.+ */+function GeneratedQueries({ diagnostics }: { diagnostics: readonly AIReportQueryDiagnosticApi[] }): JSX.Element {+ return (+ <div className="flex flex-col gap-1">+ <div className="text-secondary">{diagnosticsSummary(diagnostics)}</div>+ <LemonCollapse+ size="small"+ multiple+ defaultActiveKeys={failedIndexes(diagnostics)}+ panels={diagnostics.map((d, index) => ({+ key: index,+ header: (+ <div className="flex items-center gap-2">+ {queryStatusTag(d)}+ <span>{d.description || 'Query'}</span>+ </div>+ ),+ content: (+ <div className="flex flex-col gap-2">+ {d.ok === false ? (+ <div className={d.human_readable_error ? 'text-danger' : 'text-secondary'}>+ {queryFailureReason(d)}+ </div>+ ) : null}+ {d.hogql ? (+ <CodeSnippet language={Language.SQL} compact>+ {d.hogql}+ </CodeSnippet>+ ) : (+ <span className="text-secondary">No query captured.</span>+ )}+ </div>+ ),+ }))}+ />+ </div>+ )+}++/** Expanded detail for a delivery row: the AI summary, the prompt at generation time, the delivered report,+ * and the per-query accordion. Returns null when there's nothing AI-generated to show. */+export function ExpandedDeliveryRow({ row }: { row: SubscriptionDeliveryApi }): JSX.Element | null {+ const diagnostics = row.ai_report_diagnostics ?? []+ const report = row.ai_report+ const prompt = row.ai_report_prompt+ if (!deliveryRowHasExpandableContent(row)) {+ return null+ }+ return (+ <div className="px-4 py-3 text-sm flex flex-col gap-4">+ {row.change_summary ? (+ <div className="whitespace-pre-wrap">+ <div className="text-xs font-semibold uppercase tracking-wide text-secondary mb-1">AI summary</div>+ {row.change_summary}+ </div>+ ) : null}+ {prompt ? (+ <div className="whitespace-pre-wrap">+ <div className="text-xs font-semibold uppercase tracking-wide text-secondary mb-1">+ Prompt at time of generation+ </div>+ {prompt}+ </div>+ ) : null}+ {report ? (+ <div className="flex flex-col gap-1">+ <div className="text-xs font-semibold uppercase tracking-wide text-secondary">Delivered report</div>+ <div className="max-h-96 overflow-auto rounded border bg-bg-light p-3">+ {/* LLM-generated content: disableImages so an image URL in the report can't auto-fire a+ request (tracking pixel / IP leak / internal-address probe) when a teammate opens this. */}+ <LemonMarkdown disableImages>{report}</LemonMarkdown>+ </div>+ </div>+ ) : null}+ {diagnostics.length > 0 ? (+ <div className="flex flex-col gap-2">+ <div className="text-xs font-semibold uppercase tracking-wide text-secondary">+ Generated queries+ </div>+ <GeneratedQueries diagnostics={diagnostics} />+ </div>+ ) : null}+ </div>+ )+}diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.stories.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.stories.tsxindex 155d72120fe6..c2612e2b6412 100644--- a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.stories.tsx+++ b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.stories.tsx@@ -67,6 +67,19 @@ export const WithExpandedSummary: Story = {},}+// AI-prompt delivery expanded: the rendered report markdown plus the per-query accordion (the failed query open).+const EXPANDED_AI_REPORT_STORY_IDS: ReadonlySet<string> = new Set(['del-ai-report'])++export const WithExpandedAiReport: Story = {+ args: {+ deliveriesPage: pageWithRows,+ deliveriesPageLoading: false,+ loadDeliveriesPage: noopLoadPage,+ onTestDelivery: noopTestDelivery,+ __storyOnlyInitiallyExpandedDeliveryIds: EXPANDED_AI_REPORT_STORY_IDS,+ },+}+export const Empty: Story = {args: {deliveriesPage: { results: [], next: null, previous: null },diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsxindex 051aa07e3f3c..779b1585e150 100644--- a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx+++ b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx@@ -21,6 +21,11 @@ import {import { TZLabel } from 'lib/components/TZLabel'import type { DeliveryFeedback } from '../subscriptionSceneLogic'+import {+ deliveryRowHasExpandableContent,+ ExpandedDeliveryRow,+ partialDeliveryTag,+} from './SubscriptionAiReportDelivery'import { SubscriptionDeliveryDestinationCell } from './SubscriptionDestinationCell'import { TARGET_TYPE_LABEL } from './subscriptionLabels'@@ -66,7 +71,8 @@ function deliveryStatusTag(row: SubscriptionDeliveryApi): JSX.Element {</Tooltip>)}- return <LemonTag type={tagType}>{label}</LemonTag>+ // A completed-but-degraded delivery reads as "Partial" rather than a clean "Completed".+ return partialDeliveryTag(row) ?? <LemonTag type={tagType}>{label}</LemonTag>}/** Matches `SubscriptionTriggerType` in Temporal (`scheduled`, `manual`, `target_change`). */@@ -91,20 +97,11 @@ function deliveryTriggerLabel(triggerType: string): string {/** LemonTag and text cells share a row height; middle-align `td` so badges line up with copy. */const DELIVERY_TABLE_CELL_CLASS = 'align-middle'-function ExpandedSummaryRow({ summary }: { summary: string }): JSX.Element {- return (- <div className="px-4 py-3 text-sm whitespace-pre-wrap">- <div className="text-xs font-semibold uppercase tracking-wide text-secondary mb-1">AI summary</div>- {summary}- </div>- )-}--// Module-scope const keeps the reference stable across parent re-renders.+// Module-scope const keeps the reference stable across parent re-renders. The expanded-row view and its+// per-query helpers live in SubscriptionAiReportDelivery — this table just wires them into the row.const DELIVERY_TABLE_EXPANDABLE = {- rowExpandable: (row: SubscriptionDeliveryApi) => Boolean(row.change_summary),- expandedRowRender: (row: SubscriptionDeliveryApi) =>- row.change_summary ? <ExpandedSummaryRow summary={row.change_summary} /> : <></>,+ rowExpandable: deliveryRowHasExpandableContent,+ expandedRowRender: (row: SubscriptionDeliveryApi) => <ExpandedDeliveryRow row={row} />,}// Only called from storybook visual tests — production use ignores the optional set.diff --git a/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts b/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.tsindex 9a8592df38d0..2dfc5dedcb61 100644--- a/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts+++ b/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts@@ -91,6 +91,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [target_value: '[email protected]',exported_asset_ids: [],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Starting,error: null,@@ -99,6 +102,57 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [last_updated_at: '2026-04-07T10:05:02Z',finished_at: null,},+ {+ // AI-prompt delivery: the delivered report markdown, the prompt it was generated from, and the+ // per-query diagnostics (one failed) ship via the typed fields, gated behind query:viewer (the+ // backend scrubs them to null and content_snapshot to {} otherwise). content_snapshot no longer+ // carries the AI keys — the typed fields are the contract. The report embeds an off-PostHog image so+ // the (pre-expanded) story exercises disableImages: it must render as a link, never an auto-loading <img>.+ id: 'del-ai-report',+ subscription: 1,+ temporal_workflow_id: 'wf-ai-report',+ idempotency_key: 'idem-ai-report',+ trigger_type: 'manual',+ scheduled_at: null,+ target_type: 'email',+ target_value: '[email protected]',+ exported_asset_ids: [],+ content_snapshot: {},+ ai_report:+ '## Weekly Hedgebox report\n\n| Metric | Value |\n| --- | --- |\n| Daily active users | 89 |\n| New signups | 56 |\n| File uploads | 429 |\n| File downloads | 324 |\n\nEngagement is up week-over-week, led by uploads.\n\n',+ ai_report_prompt:+ 'Summarize weekly Hedgebox engagement: daily active users, new signups, file uploads and downloads, and call out any week-over-week movement.',+ ai_report_diagnostics: [+ {+ description: 'Daily active users (7-day total)',+ hogql: 'SELECT count(DISTINCT person_id) AS dau FROM events WHERE timestamp >= now() - INTERVAL 7 DAY',+ ok: true,+ error_type: null,+ human_readable_error: null,+ },+ {+ description: 'New signups',+ hogql: "SELECT count() AS signups FROM events WHERE event = 'signed_up' AND timestamp >= now() - INTERVAL 7 DAY",+ ok: true,+ error_type: null,+ human_readable_error: null,+ },+ {+ description: 'First-ever signups per user',+ hogql: 'SELECT first_ever(event) OVER (PARTITION BY person_id) FROM events',+ ok: false,+ error_type: 'ExposedHogQLError',+ human_readable_error: "Unknown function: 'first_ever'",+ },+ ],+ recipient_results: [],+ status: SubscriptionDeliveryStatusEnumApi.Completed,+ error: null,+ change_summary: null,+ created_at: '2026-04-07T09:30:00Z',+ last_updated_at: '2026-04-07T09:30:20Z',+ finished_at: '2026-04-07T09:30:22Z',+ },{id: 'del-1',subscription: 1,@@ -111,6 +165,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [exported_asset_ids: [],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Completed,error: null,@@ -131,6 +188,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [target_value: '[email protected]',exported_asset_ids: [],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Skipped,error: null,@@ -150,6 +210,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [target_value: '[email protected]',exported_asset_ids: [],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Failed,error: { message: 'SMTP timeout' },@@ -169,6 +232,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [target_value: 'C12345|#alerts-analytics-platform',exported_asset_ids: [1, 2],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Completed,error: null,@@ -189,6 +255,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [target_value: 'https://hooks.example.com/subscription/abc',exported_asset_ids: [],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Failed,error: { message: 'HTTP 502 from webhook' },@@ -208,6 +277,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [target_value: '[email protected], [email protected]',exported_asset_ids: [],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Completed,error: null,@@ -227,6 +299,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [target_value: '[email protected]',exported_asset_ids: [],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Completed,error: null,@@ -246,6 +321,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [target_value: '[email protected]',exported_asset_ids: [],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Failed,error: { message: 'Export timed out' },@@ -265,6 +343,9 @@ export const MOCK_SUBSCRIPTION_DELIVERIES: SubscriptionDeliveryApi[] = [target_value: '[email protected]',exported_asset_ids: [],content_snapshot: {},+ ai_report: null,+ ai_report_diagnostics: null,+ ai_report_prompt: null,recipient_results: [],status: SubscriptionDeliveryStatusEnumApi.Completed,error: null,diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.pyindex 4a520ce7532f..772860e26ba1 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py@@ -1,5 +1,6 @@import uuidimport datetime as dt+import dataclassesfrom datetime import datetimefrom django.utils import timezone as tz@@ -29,6 +30,9 @@ from products.exports.backend.temporal.subscriptions.delivery_common import (deliver_slack,)from products.exports.backend.temporal.subscriptions.types import (+ AI_REPORT_DIAGNOSTICS_KEY,+ AI_REPORT_PROMPT_SNAPSHOT_KEY,+ AI_REPORT_SNAPSHOT_KEY,DeliverSubscriptionInputs,DeliverSubscriptionResult,GenerateAIReportInputs,@@ -42,37 +46,59 @@ from ee.tasks.subscriptions.auto_disable import AI_CONSENT_REVOKED_DISABLE_REASOLOGGER = get_logger(__name__)-# `SubscriptionDelivery.content_snapshot` key the AI report markdown is written under by-# `generate_ai_subscription_report` and read back by `_deliver_ai_subscription`. The markdown-# 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._CREDIT_RESET_FALLBACK_DAYS = 31-async def _load_ai_report(delivery_id: uuid.UUID) -> str | None:+async def _load_snapshot(delivery_id: uuid.UUID) -> dict | None:+ # Single read of the delivery's content_snapshot (both the AI report markdown and the+ # diagnostics live here). DoesNotExist is tolerated: a missing row just means "no report yet".@database_sync_to_async(thread_sensitive=False)- def _read() -> str | None:- # DoesNotExist is tolerated here (read side): a missing row just means "no report yet".+ def _read() -> dict | None:try:snapshot = SubscriptionDelivery.objects.values_list("content_snapshot", flat=True).get(pk=delivery_id)except SubscriptionDelivery.DoesNotExist:return None- if not isinstance(snapshot, dict):- return None- report = snapshot.get(AI_REPORT_SNAPSHOT_KEY)- return report if isinstance(report, str) and report else None+ return snapshot if isinstance(snapshot, dict) else Nonereturn await _read()-async def _persist_ai_report(delivery_id: uuid.UUID, result: AiReportResult) -> None:+def _snapshot_report(snapshot: dict | None) -> str | None:+ report = snapshot.get(AI_REPORT_SNAPSHOT_KEY) if snapshot else None+ return report if isinstance(report, str) and report else None+++async def _load_ai_report(delivery_id: uuid.UUID) -> str | None:+ return _snapshot_report(await _load_snapshot(delivery_id))+++def _tally_diagnostics(steps: list[tuple[bool, str | None]]) -> tuple[int, int, list[str]]:+ # (failed_step_count, total_step_count, 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 (len(failed), len(steps), error_types)+++def _snapshot_diagnostic_counts(snapshot: dict | None) -> tuple[int, int, list[str]]:+ # 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 (0, 0, [])+ # 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)]+ )+++def _report_diagnostic_counts(result: AiReportResult) -> tuple[int, int, list[str]]:+ return _tally_diagnostics([(d.ok, d.error_type) for d in result.diagnostics])+++async def _persist_ai_report(delivery_id: uuid.UUID, result: AiReportResult, prompt: str | None) -> None:@database_sync_to_async(thread_sensitive=False)def _write() -> None:# No DoesNotExist guard: create_delivery_record always writes this row before@@ -81,10 +107,9 @@ async def _persist_ai_report(delivery_id: uuid.UUID, result: AiReportResult) ->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- ],+ AI_REPORT_DIAGNOSTICS_KEY: [dataclasses.asdict(d) for d in result.diagnostics],+ # prompt is None for non-AI subs; "" if cleared — omit either.+ **({AI_REPORT_PROMPT_SNAPSHOT_KEY: prompt} if prompt else {}),}delivery.save(update_fields=["content_snapshot", "last_updated_at"])@@ -183,9 +208,17 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Gen# Idempotency on Temporal redispatch: if a prior attempt already produced the report,# don't re-bill the LLM — the point of the generate -> deliver split is one LLM run.- if await _load_ai_report(inputs.delivery_id) is not None:+ # One snapshot read serves both the "already generated?" check and the prior failure shape.+ snapshot = await _load_snapshot(inputs.delivery_id)+ if _snapshot_report(snapshot) is not None:await LOGGER.ainfo("generate_ai_subscription_report.already_generated", subscription_id=subscription.id)- return GenerateAIReportResult(aborted=False)+ failed_count, total_count, error_types = _snapshot_diagnostic_counts(snapshot)+ return GenerateAIReportResult(+ aborted=False,+ failed_step_count=failed_count,+ total_step_count=total_count,+ query_error_types=error_types,+ )# Consent is gated once here, before any LLM cost — creation-time gates don't catch an# org that revokes AI-data-processing approval later. Auto-disable so it stops re-firing.@@ -255,8 +288,14 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Genaborted = 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, report_result)- return GenerateAIReportResult(aborted=False)+ await _persist_ai_report(inputs.delivery_id, report_result, subscription.prompt)+ failed_count, total_count, error_types = _report_diagnostic_counts(report_result)+ return GenerateAIReportResult(+ aborted=False,+ failed_step_count=failed_count,+ total_step_count=total_count,+ query_error_types=error_types,+ )async def _deliver_ai_subscription(diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.pyindex a34c6bd4159e..b675858a35c1 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py@@ -88,6 +88,30 @@ _RETRYABLE_QUERY_ERRORS: tuple[type[BaseException], ...] = ()+def _all_queries_failed_notice(total_steps: int) -> str:+ noun = "the query" if total_steps == 1 else f"all {total_steps} queries"+ return (+ f"> ⚠️ This report could not be generated — {noun} the assistant wrote failed to run. "+ "Use the Manage subscription link to review the generated queries and the errors they hit.\n\n"+ )+++def _safe_error_message(exc: BaseException) -> Optional[str]:+ # HogQL/ClickHouse error text can echo team-scoped identifiers, so only the query-structure error+ # classes (which describe the field/property the planner 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 stays type-only. Executors often wrap a resolution/exposed error in a+ # generic Exception, so walk the __cause__/__context__ chain and surface the wrapped safe message.+ seen: set[int] = set()+ current: Optional[BaseException] = exc+ while current is not None and id(current) not in seen:+ if isinstance(current, (ExposedHogQLError, ResolutionError)):+ return str(current)+ seen.add(id(current))+ current = current.__cause__ or current.__context__+ return None++class ReportStage(StrEnum):PLANNER = "planner"QUERY = "query"@@ -111,6 +135,8 @@ class QueryStepDiagnostic:hogql: strok: boolerror_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@dataclass(frozen=True)@@ -168,6 +194,11 @@ async def generate_ai_report(failed_steps=failed_count,total_steps=total_steps,)+ if total_steps and failed_count == total_steps:+ # Every query failed, so the body is all "could not be computed" placeholders. Lead with a+ # deterministic notice (not left to the synthesis LLM) so the recipient gets a clear signal+ # instead of a confident-looking but empty report.+ report = _all_queries_failed_notice(total_steps) + reportreturn AiReportResult(markdown=report, diagnostics=tuple(diagnostics))@@ -307,14 +338,9 @@ async def _run_steps()fixed = await _arequest_hogql_fix(original_hogql=current_hogql,- # Forward the message for exposed errors and ResolutionError. ResolutionError messages- # describe query structure — usually the field/property the planner itself referenced- # (e.g. "Unable to resolve field 'operaton'"), which is what the fixer needs. A few raise- # sites wrap a nested exception, but those describe query shape, not cluster topology, so- # the leak risk stays low. Other internal errors (parsing/impossible-AST) stay type-only.- error_message=(- str(exc) if isinstance(exc, (ExposedHogQLError, ResolutionError)) else type(exc).__name__- ),+ # 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__,step_description=safe_description,team=team,user=user,@@ -338,7 +364,13 @@ async def _run_steps(# metric as "could not be computed" instead of paraphrasing the failure into "no data".return (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),+ QueryStepDiagnostic(+ description=safe_description,+ hogql=current_hogql,+ ok=False,+ error_type=type_name,+ human_readable_error=_safe_error_message(last_exc) if last_exc is not None else None,+ ),)async def run_step_bounded(step: QueryPlanStep) -> tuple[str, QueryStepDiagnostic]: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.pyindex c3f190851346..cf86d15ffcca 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@@ -4,17 +4,24 @@ from zoneinfo import ZoneInfoimport pytestfrom asgiref.sync import sync_to_async+from parameterized import parameterizedfrom products.exports.backend.models.subscription import Subscription, SubscriptionDeliveryfrom products.exports.backend.temporal.subscriptions.ai_subscription.activities import (- AI_REPORT_DIAGNOSTICS_KEY,- AI_REPORT_SNAPSHOT_KEY,+ _load_snapshot,_persist_ai_report,+ _report_diagnostic_counts,+ _snapshot_diagnostic_counts,)from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import (AiReportResult,QueryStepDiagnostic,)+from products.exports.backend.temporal.subscriptions.types import (+ AI_REPORT_DIAGNOSTICS_KEY,+ AI_REPORT_PROMPT_SNAPSHOT_KEY,+ AI_REPORT_SNAPSHOT_KEY,+)from products.product_analytics.backend.models.insight import Insightpytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]@@ -45,7 +52,7 @@ 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:+async def test_persist_ai_report_writes_markdown_query_diagnostics_and_prompt(team, user) -> None:delivery = await _create_delivery(team, user)await _persist_ai_report(@@ -59,11 +66,106 @@ async def test_persist_ai_report_writes_markdown_and_query_diagnostics(team, use),),),+ prompt="weekly adoption + reliability report",)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"},+ {+ "description": "adoption",+ "hogql": "SELECT count()",+ "ok": True,+ "error_type": None,+ "human_readable_error": None,+ },+ {+ "description": "reliability",+ "hogql": "SELECT bad",+ "ok": False,+ "error_type": "ResolutionError",+ "human_readable_error": None,+ },]+ # The generating prompt is captured so the delivery is reproducible and the viewer can show it.+ assert snapshot[AI_REPORT_PROMPT_SNAPSHOT_KEY] == "weekly adoption + reliability report"++[email protected]("prompt", [None, ""])+async def test_persist_ai_report_omits_blank_prompt(team, user, prompt) -> None:+ # A non-AI sub passes prompt=None and a cleared prompt passes ""; neither should write the key+ # (so the viewer doesn't render an empty "prompt at time of generation" block).+ delivery = await _create_delivery(team, user)++ await _persist_ai_report(+ delivery.id,+ AiReportResult(markdown="# report", diagnostics=()),+ prompt=prompt,+ )++ snapshot = await _snapshot(delivery.id)+ assert AI_REPORT_PROMPT_SNAPSHOT_KEY not in snapshot+++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, []),+ ]+ )+ def test_counts_failures_and_distinct_error_types(+ self, _name, oks, expected_failed, expected_total, expected_types+ ):+ result = AiReportResult(+ markdown="report",+ diagnostics=tuple(+ QueryStepDiagnostic(+ description=f"step {i}",+ hogql="SELECT 1",+ ok=ok,+ error_type=None if ok else "ResolutionError",+ )+ for i, ok in enumerate(oks)+ ),+ )+ assert _report_diagnostic_counts(result) == (expected_failed, expected_total, expected_types)++ def test_distinct_error_types_are_sorted_and_deduped(self):+ result = AiReportResult(+ markdown="report",+ diagnostics=(+ QueryStepDiagnostic(description="a", hogql="x", ok=False, error_type="ResolutionError"),+ QueryStepDiagnostic(description="b", hogql="y", ok=False, error_type="ExposedHogQLError"),+ QueryStepDiagnostic(description="c", hogql="z", ok=False, error_type="ResolutionError"),+ ),+ )+ assert _report_diagnostic_counts(result) == (3, 3, ["ExposedHogQLError", "ResolutionError"])+++# On Temporal redispatch the report is already persisted, so the failure shape is read back from the+# snapshot rather than recomputed — the persist -> load -> count round-trip must match what was written.+async def test_snapshot_diagnostic_counts_reads_persisted_failure_shape(team, user) -> None:+ delivery = await _create_delivery(team, user)+ await _persist_ai_report(+ delivery.id,+ AiReportResult(+ markdown="report",+ 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"),+ ),+ ),+ prompt=None,+ )++ assert _snapshot_diagnostic_counts(await _load_snapshot(delivery.id)) == (1, 2, ["ResolutionError"])+++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.+ assert _snapshot_diagnostic_counts(await _load_snapshot(delivery.id)) == (0, 0, [])+ assert _snapshot_diagnostic_counts(None) == (0, 0, [])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 05ea312b8bd0..b09c54016b70 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@@ -3,15 +3,17 @@ import asyncioimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch-from posthog.hogql.errors import ExposedHogQLError, ResolutionError+from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, ResolutionErrorfrom products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import (_MAX_CONCURRENT_STEPS,QUERY_FAILED_PREFIX,AiReportStageError,QueryStepDiagnostic,+ _all_queries_failed_notice,_arequest_hogql_fix,_run_steps,+ _safe_error_message,generate_ai_report,)from products.exports.backend.temporal.subscriptions.ai_subscription.schemas import (@@ -111,7 +113,9 @@ async def test_degraded_report_still_synthesizes(result = await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window_days=7)- assert result.markdown == "# Weekly report"+ # Every query failed, so the delivered report leads with the deterministic failure notice+ # prepended to the synthesis output, not a bare confident-looking report.+ assert result.markdown == _all_queries_failed_notice(1) + "# 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"),@@ -271,6 +275,10 @@ async def test_run_steps_breaks_early_when_fix_returns_same_query(# Executor ran exactly once (no rerun of the identical fixed query); the fix was requested once.assert mock_executor_cls.return_value.arun_and_format_query.await_count == 1mock_fix.assert_awaited_once()+ # An ExposedHogQLError is safe to surface, so the diagnostic carries the human-readable reason+ # (not just the type) for the delivery viewer to show.+ assert diagnostics[0].error_type == "ExposedHogQLError"+ assert diagnostics[0].human_readable_error == "bad query"@patch(f"{_RP}.AssistantQueryExecutor")@@ -297,3 +305,35 @@ async def test_run_steps_bounds_concurrent_query_execution(mock_executor_cls: Maawait _run_steps(_spec(steps=_MAX_CONCURRENT_STEPS * 2), MagicMock(), MagicMock(), None)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+++ "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.+ (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'")),+ "Unable to resolve field 'x'",+ ),+ (_wrap(RuntimeError("boom"), context=ExposedHogQLError("bad thing")), "bad thing"),+ # A generic error wrapping only generic errors stays type-only.+ (_wrap(Exception("outer"), cause=ValueError("inner")), None),+ ],+)+def test_safe_error_message_only_surfaces_query_structure_errors(exc, expected):+ assert _safe_error_message(exc) == expecteddiff --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.pyindex be848fb29a5e..0fbd35bc17e9 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@@ -78,8 +78,9 @@ class TestAIReportPipelineIntegration(ClickhouseTestMixin, NonAtomicBaseTest):report = await generate_ai_report(team=self.team, user=self.user, prompt="x", window_days=7)- assert report.markdown == "# Degraded report"assert "Query failed to run" in captured["human"]+ assert "could not be generated" in report.markdown+ assert "# Degraded report" in report.markdown# 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)diff --git a/products/exports/backend/temporal/subscriptions/test_types.py b/products/exports/backend/temporal/subscriptions/test_types.pynew file mode 100644index 000000000000..6bf8aabf32f8--- /dev/null+++ b/products/exports/backend/temporal/subscriptions/test_types.py@@ -0,0 +1,72 @@+from parameterized import parameterized++from products.exports.backend.temporal.subscriptions.types import DeliveryStatus, GenerateAIReportResult+++class TestGenerateAIReportResult:+ # 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.+ @parameterized.expand(+ [+ ("no_steps_aborted_or_skipped", 0, 0, False),+ ("partial_failure", 1, 2, False),+ ("all_failed", 2, 2, True),+ ("single_step_failed", 1, 1, True),+ ]+ )+ def test_all_queries_failed(self, _name, failed: int, total: int, expected: bool) -> None:+ result = GenerateAIReportResult(failed_step_count=failed, total_step_count=total)+ assert result.all_queries_failed is expected++ # failure_error builds the access-safe reason recorded on a fully-degraded delivery's error column.+ # A regression that dropped the singular/plural subject or the error-type detail — or interpolated+ # raw query content instead of the class-name strings — would surface as a message mismatch here.+ @parameterized.expand(+ [+ (+ "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.",+ ),+ ]+ )+ 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"}++ # 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+ # error. Guards the workflow's FAILED-vs-COMPLETED wiring against a dropped check or a flipped comparison.+ @parameterized.expand(+ [+ ("all_failed", 2, 2, DeliveryStatus.FAILED, True),+ ("single_step_failed", 1, 1, DeliveryStatus.FAILED, True),+ ("partial_stays_completed", 1, 2, DeliveryStatus.COMPLETED, False),+ ("no_steps_stays_completed", 0, 0, DeliveryStatus.COMPLETED, False),+ ]+ )+ def test_delivered_status(self, _name, failed: int, total: int, expected_status: str, expects_error: bool) -> None:+ result = GenerateAIReportResult(failed_step_count=failed, total_step_count=total)+ status, error = result.delivered_status()+ assert status == expected_status+ assert error == (result.failure_error() if expects_error else None)diff --git a/products/exports/backend/temporal/subscriptions/types.py b/products/exports/backend/temporal/subscriptions/types.pyindex 703fe038327e..e5ee833d5ab5 100644--- a/products/exports/backend/temporal/subscriptions/types.py+++ b/products/exports/backend/temporal/subscriptions/types.py@@ -24,6 +24,17 @@ class DeliveryStatus:# workflow sandbox can route by resource type without importing the Django model.AI_PROMPT_RESOURCE_TYPE = "ai_prompt"+# `SubscriptionDelivery.content_snapshot` keys for the AI report. The markdown and prompt can+# exceed Temporal's ~2 MiB payload cap, so they travel through Postgres by reference rather than+# on the wire (the same pattern insight snapshots use). They live alongside the workflow types so+# the API serializer can import them without pulling in the LLM delivery stack.+AI_REPORT_SNAPSHOT_KEY = "ai_report"+# The prompt that generated the report, captured at generation time so the delivery is reproducible.+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"+class SubscriptionTriggerType:"""How a subscription delivery was triggered.@@ -167,11 +178,44 @@ class GenerateAIReportResult:subscription; the workflow records `recipient_results` as FAILED and skips delivery.`skipped` signals an over-AI-credit-budget skip: generation rescheduled the sub pastthe credit reset and notified the owner — the workflow records SKIPPED (not FAILED,- the sub isn't broken) and skips delivery."""+ the sub isn't broken) and skips delivery.++ The query-failure counts let the workflow flag a fully-degraded report (every query failed →+ FAILED, not COMPLETED) without re-reading the per-query detail from content_snapshot."""aborted: bool = Falseskipped: bool = Falserecipient_results: list[RecipientResult] = dataclasses.field(default_factory=list)+ failed_step_count: int = 0+ total_step_count: int = 0+ query_error_types: list[str] = dataclasses.field(default_factory=list)++ @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.+ detail = f" ({', '.join(self.query_error_types)})" if self.query_error_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 {+ "message": f"{subject} failed to run{detail}, so the report could not be computed.",+ "type": "AIReportQueryFailure",+ }++ def delivered_status(self) -> tuple[str, typing.Optional[dict[str, str]]]:+ # 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.+ if self.all_queries_failed:+ return DeliveryStatus.FAILED, self.failure_error()+ return DeliveryStatus.COMPLETED, None@dataclasses.dataclassdiff --git a/products/exports/backend/temporal/subscriptions/workflows.py b/products/exports/backend/temporal/subscriptions/workflows.pyindex c0db06c39e7b..d1d9d28fc016 100644--- a/products/exports/backend/temporal/subscriptions/workflows.py+++ b/products/exports/backend/temporal/subscriptions/workflows.py@@ -451,6 +451,9 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):final_status = DeliveryStatus.SKIPPEDdelivery_recipient_results: list[dict] = []caught_error: BaseException | None = None+ # Set when a delivered-but-degraded report should record a reason without an exception+ # (every generated query failed). Falls through to update_delivery_record's error column.+ generation_error: dict | None = Nonetry:delivery_id = await temporalio.workflow.execute_activity(@@ -527,7 +530,13 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):retry_policy=SUBSCRIPTION_DELIVER_RETRY_POLICY,)delivery_recipient_results = _to_recipient_dicts(deliver_result.recipient_results)- final_status = DeliveryStatus.COMPLETED++ # A report whose every generated query failed computed no metrics, so it records FAILED with+ # the failure detail the delivery history surfaces on hover (see delivered_status). The report+ # email already went out above (with the leading failure notice), so FAILED here means "empty+ # report", not "not delivered" — recipient_results can still show successful sends. Partial+ # failures stay COMPLETED; their per-query diagnostics live in content_snapshot for the viewer.+ final_status, generation_error = generate_result.delivered_status()except Exception as e:# Preserve recipient outcomes carried in non-retryable delivery errors so the@@ -552,7 +561,7 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):recipient_results=delivery_recipient_results or None,error={"message": str(caught_error)[:500], "type": type(caught_error).__name__}if caught_error- else None,+ else generation_error,finished=True,),start_to_close_timeout=dt.timedelta(minutes=2),diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.tsindex 70a63db29c88..8618c8271d71 100644--- a/products/subscriptions/frontend/generated/api.schemas.ts+++ b/products/subscriptions/frontend/generated/api.schemas.ts@@ -396,6 +396,25 @@ export const SubscriptionDeliveryStatusEnumApi = {Skipped: 'skipped',} as const+export interface AIReportQueryDiagnosticApi {+ /** What this query step was meant to compute. */+ description: string+ /** The HogQL the assistant generated for this step. */+ hogql: string+ /** Whether the query ran successfully. */+ ok: boolean+ /**+ * Exception class name when the query failed; null on success.+ * @nullable+ */+ error_type: 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+ */+ human_readable_error?: string | null+}+export interface SubscriptionDeliveryApi {/** Primary key for this delivery row. */readonly id: string@@ -449,6 +468,21 @@ export interface SubscriptionDeliveryApi {* @nullable*/readonly change_summary: string | null+ /**+ * AI-generated report markdown delivered by this run. Null for non-AI deliveries or runs without a persisted report.+ * @nullable+ */+ readonly ai_report: string | null+ /**+ * Per-step query diagnostics (generated HogQL + failure type) for this report. Null for non-AI deliveries or runs without persisted diagnostics.+ * @nullable+ */+ readonly ai_report_diagnostics: readonly AIReportQueryDiagnosticApi[] | null+ /**+ * The subscription's prompt as it was when this report was generated. Null for older deliveries and non-AI deliveries.+ * @nullable+ */+ readonly ai_report_prompt: string | null}export interface PaginatedSubscriptionDeliveryListApi {diff --git a/products/subscriptions/mcp/tools.yaml b/products/subscriptions/mcp/tools.yamlindex 5865d013b4ca..859da64b1d9c 100644--- a/products/subscriptions/mcp/tools.yaml+++ b/products/subscriptions/mcp/tools.yaml@@ -92,13 +92,17 @@ tools:List delivery history for a subscription — one row per send attempt. Each entry includes status (starting,completed, failed, skipped), trigger_type (scheduled, manual, target_change), and timestamps (created_at,finished_at). Filter with status=failed to quickly surface failed deliveries. Results are cursor-paginated- newest first. content_snapshot, recipient_results, and error are excluded to match what the web UI exposes- and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.+ newest first. content_snapshot, recipient_results, and error are excluded to avoid leaking recipient+ identifiers or upstream response bodies that may contain tokens / PII. ai_report (the full report markdown)+ and ai_report_diagnostics (per-query debug detail) are also excluded here to keep list responses small —+ fetch a single delivery with subscriptions-deliveries-retrieve to read the report.response:exclude:- content_snapshot- recipient_results- error+ - ai_report+ - ai_report_diagnosticssubscriptions-deliveries-retrieve:operation: subscriptions_deliveries_retrieveenabled: true@@ -113,13 +117,17 @@ tools:Fetch a single subscription delivery attempt by id. Returns status, trigger_type, target_type, target_value,timestamps, workflow/idempotency metadata, and exported_asset_ids. content_snapshot (the frozendashboard/insight state at send time) is not returned — use the insight/dashboard tools for current state.- recipient_results and error are also excluded to match what the web UI exposes and to avoid leaking- recipient identifiers or upstream response bodies that may contain tokens / PII.+ recipient_results and error are also excluded to avoid leaking recipient identifiers or upstream response+ bodies that may contain tokens / PII. Unlike the list tool, ai_report (the full report markdown for+ AI-prompt subscriptions) is returned here, alongside ai_report_prompt (the prompt it was generated from).+ ai_report_diagnostics (per-query generated HogQL + failure types) is excluded to keep the response focused+ on the report itself.response:exclude:- content_snapshot- recipient_results- error+ - ai_report_diagnosticssubscriptions-list:operation: subscriptions_listenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 1964bf5f0922..bd8d449956c5 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7396,7 +7396,7 @@}},"subscriptions-deliveries-list": {- "description": "List delivery history for a subscription — one row per send attempt. Each entry includes status (starting, completed, failed, skipped), trigger_type (scheduled, manual, target_change), and timestamps (created_at, finished_at). Filter with status=failed to quickly surface failed deliveries. Results are cursor-paginated newest first. content_snapshot, recipient_results, and error are excluded to match what the web UI exposes and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.",+ "description": "List delivery history for a subscription — one row per send attempt. Each entry includes status (starting, completed, failed, skipped), trigger_type (scheduled, manual, target_change), and timestamps (created_at, finished_at). Filter with status=failed to quickly surface failed deliveries. Results are cursor-paginated newest first. content_snapshot, recipient_results, and error are excluded to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII. ai_report (the full report markdown) and ai_report_diagnostics (per-query debug detail) are also excluded here to keep list responses small — fetch a single delivery with subscriptions-deliveries-retrieve to read the report.","category": "Subscriptions","feature": "subscriptions","summary": "List subscription deliveries",@@ -7410,7 +7410,7 @@}},"subscriptions-deliveries-retrieve": {- "description": "Fetch a single subscription delivery attempt by id. Returns status, trigger_type, target_type, target_value, timestamps, workflow/idempotency metadata, and exported_asset_ids. content_snapshot (the frozen dashboard/insight state at send time) is not returned — use the insight/dashboard tools for current state. recipient_results and error are also excluded to match what the web UI exposes and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.",+ "description": "Fetch a single subscription delivery attempt by id. Returns status, trigger_type, target_type, target_value, timestamps, workflow/idempotency metadata, and exported_asset_ids. content_snapshot (the frozen dashboard/insight state at send time) is not returned — use the insight/dashboard tools for current state. recipient_results and error are also excluded to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII. Unlike the list tool, ai_report (the full report markdown for AI-prompt subscriptions) is returned here, alongside ai_report_prompt (the prompt it was generated from). ai_report_diagnostics (per-query generated HogQL + failure types) is excluded to keep the response focused on the report itself.","category": "Subscriptions","feature": "subscriptions","summary": "Get subscription delivery",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f48921d44f15..48721bfa3652 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7907,7 +7907,7 @@}},"subscriptions-deliveries-list": {- "description": "List delivery history for a subscription — one row per send attempt. Each entry includes status (starting, completed, failed, skipped), trigger_type (scheduled, manual, target_change), and timestamps (created_at, finished_at). Filter with status=failed to quickly surface failed deliveries. Results are cursor-paginated newest first. content_snapshot, recipient_results, and error are excluded to match what the web UI exposes and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.",+ "description": "List delivery history for a subscription — one row per send attempt. Each entry includes status (starting, completed, failed, skipped), trigger_type (scheduled, manual, target_change), and timestamps (created_at, finished_at). Filter with status=failed to quickly surface failed deliveries. Results are cursor-paginated newest first. content_snapshot, recipient_results, and error are excluded to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII. ai_report (the full report markdown) and ai_report_diagnostics (per-query debug detail) are also excluded here to keep list responses small — fetch a single delivery with subscriptions-deliveries-retrieve to read the report.","category": "Subscriptions","feature": "subscriptions","summary": "List subscription deliveries",@@ -7921,7 +7921,7 @@}},"subscriptions-deliveries-retrieve": {- "description": "Fetch a single subscription delivery attempt by id. Returns status, trigger_type, target_type, target_value, timestamps, workflow/idempotency metadata, and exported_asset_ids. content_snapshot (the frozen dashboard/insight state at send time) is not returned — use the insight/dashboard tools for current state. recipient_results and error are also excluded to match what the web UI exposes and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.",+ "description": "Fetch a single subscription delivery attempt by id. Returns status, trigger_type, target_type, target_value, timestamps, workflow/idempotency metadata, and exported_asset_ids. content_snapshot (the frozen dashboard/insight state at send time) is not returned — use the insight/dashboard tools for current state. recipient_results and error are also excluded to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII. Unlike the list tool, ai_report (the full report markdown for AI-prompt subscriptions) is returned here, alongside ai_report_prompt (the prompt it was generated from). ai_report_diagnostics (per-query generated HogQL + failure types) is excluded to keep the response focused on the report itself.","category": "Subscriptions","feature": "subscriptions","summary": "Get subscription delivery",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 670df602dd24..92381c72d67f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -31,6 +31,25 @@ export namespace Schemas {AiGenerationClusters: '$ai_generation_clusters',} as const;+ export interface AIReportQueryDiagnostic {+ /** What this query step was meant to compute. */+ description: string;+ /** The HogQL the assistant generated for this step. */+ hogql: string;+ /** Whether the query ran successfully. */+ ok: boolean;+ /**+ * Exception class name when the query failed; null on success.+ * @nullable+ */+ error_type: 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+ */+ human_readable_error?: string | null;+ }+export type AccessControlLevel = typeof AccessControlLevel[keyof typeof AccessControlLevel];@@ -34292,6 +34311,21 @@ export namespace Schemas {* @nullable*/readonly change_summary: string | null;+ /**+ * AI-generated report markdown delivered by this run. Null for non-AI deliveries or runs without a persisted report.+ * @nullable+ */+ readonly ai_report: string | null;+ /**+ * Per-step query diagnostics (generated HogQL + failure type) for this report. Null for non-AI deliveries or runs without persisted diagnostics.+ * @nullable+ */+ readonly ai_report_diagnostics: readonly AIReportQueryDiagnostic[] | null;+ /**+ * The subscription's prompt as it was when this report was generated. Null for older deliveries and non-AI deliveries.+ * @nullable+ */+ readonly ai_report_prompt: string | null;}export interface PaginatedSubscriptionDeliveryList {diff --git a/services/mcp/src/tools/generated/subscriptions.ts b/services/mcp/src/tools/generated/subscriptions.tsindex 6fe38fc765b5..4f94483774f6 100644--- a/services/mcp/src/tools/generated/subscriptions.ts+++ b/services/mcp/src/tools/generated/subscriptions.ts@@ -131,7 +131,13 @@ const subscriptionsDeliveriesList = (): ToolBase<const filtered = {...result,results: (result.results ?? []).map((item: any) =>- omitResponseFields(item, ['content_snapshot', 'recipient_results', 'error'])+ omitResponseFields(item, [+ 'content_snapshot',+ 'recipient_results',+ 'error',+ 'ai_report',+ 'ai_report_diagnostics',+ ])),} as typeof resultreturn await withPostHogUrl(context, filtered, '/subscriptions')@@ -152,7 +158,12 @@ const subscriptionsDeliveriesRetrieve = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.subscription_id))}/deliveries/${encodeURIComponent(String(params.id))}/`,})- const filtered = omitResponseFields(result, ['content_snapshot', 'recipient_results', 'error']) as typeof result+ const filtered = omitResponseFields(result, [+ 'content_snapshot',+ 'recipient_results',+ 'error',+ 'ai_report_diagnostics',+ ]) as typeof resultreturn filtered},})