: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(exports): add SLO failure attribution (#89991)
Vasco de Krijgerc937e0fa7fb0
diff --git a/posthog/temporal/common/errors.py b/posthog/temporal/common/errors.pyindex f6b7a88ea5b5..fc6b3e65bc42 100644--- a/posthog/temporal/common/errors.py+++ b/posthog/temporal/common/errors.py@@ -1,6 +1,10 @@import traceback-from temporalio.exceptions import ApplicationError, FailureError+from temporalio.exceptions import (+ ApplicationError,+ FailureError,+ TimeoutError as TemporalTimeoutError,+)class NonReportableError(Exception):@@ -33,6 +37,15 @@ def unwrap_temporal_cause(exc: BaseException) -> ApplicationError | None:return current if isinstance(current, ApplicationError) else None+def find_temporal_timeout_error(exc: BaseException) -> TemporalTimeoutError | None:+ current: BaseException | None = exc+ while isinstance(current, FailureError):+ if isinstance(current, TemporalTimeoutError):+ return current+ current = current.cause+ return None++def resolve_failure_type(exc: BaseException) -> str:"""Temporal rebuilds a remote failure as a bare ApplicationError with the real class name on `.type`."""failure_type = getattr(exc, "type", None)diff --git a/posthog/temporal/exports/activities.py b/posthog/temporal/exports/activities.pyindex ee94f842a68f..3b7487961dc8 100644--- a/posthog/temporal/exports/activities.py+++ b/posthog/temporal/exports/activities.py@@ -9,10 +9,15 @@ from posthog.sync import database_sync_to_asyncfrom posthog.tasks import exporterfrom posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, MAX_ERROR_TRACE_CHARS, truncate_for_temporal_payloadfrom posthog.temporal.common.heartbeat import Heartbeater-from posthog.temporal.exports.types import ExportAssetActivityInputs, ExportAssetResult+from posthog.temporal.exports.types import ExportAssetActivityInputs, ExportAssetResult, export_failure_metadatafrom products.exports.backend.models.exported_asset import ExportedAsset-from products.exports.backend.tasks.failure_handler import SYSTEM_ERROR_NAMES, TIMEOUT_ERROR_NAMES, ExportCancelled+from products.exports.backend.tasks.failure_handler import (+ SYSTEM_ERROR_NAMES,+ TIMEOUT_ERROR_NAMES,+ ExportCancelled,+ export_slo_failure_details,+)logger = structlog.get_logger(__name__)@@ -43,7 +48,18 @@ async def export_asset_activity(inputs: ExportAssetActivityInputs) -> ExportAssesource=EventSource(inputs.source) if inputs.source else None,)except Exception as e:- await database_sync_to_async(asset.refresh_from_db, thread_sensitive=False)()+ try:+ await database_sync_to_async(asset.refresh_from_db, thread_sensitive=False)()+ except Exception as refresh_error:+ # Preserve the export error because it determines the SLO classification.+ logger.warning(+ "export_asset_activity.refresh_after_failure_failed",+ exported_asset_id=asset.id,+ team_id=asset.team_id,+ exception_class=type(refresh_error).__name__,+ error=str(refresh_error),+ exc_info=True,+ )exception_class = type(e).__name__error_trace = "\n".join(traceback.format_exception(e)[:5])logger.warning(@@ -62,6 +78,7 @@ async def export_asset_activity(inputs: ExportAssetActivityInputs) -> ExportAsseraise ApplicationError(truncate_for_temporal_payload(str(e), MAX_ERROR_MESSAGE_CHARS),truncate_for_temporal_payload(error_trace, MAX_ERROR_TRACE_CHARS),+ export_failure_metadata(export_slo_failure_details(e)),type=exception_class,non_retryable=exception_class not in RETRYABLE_ERROR_NAMES,) from ediff --git a/posthog/temporal/exports/types.py b/posthog/temporal/exports/types.pyindex 7202ecd0415b..b1e9e1806772 100644--- a/posthog/temporal/exports/types.py+++ b/posthog/temporal/exports/types.py@@ -1,7 +1,23 @@import dataclasses-from typing import Optional+from typing import Optional, TypedDict, cast-from posthog.temporal.common.errors import resolve_error_trace, unwrap_temporal_cause+from posthog.dataclasses import frozen+from posthog.temporal.common.errors import find_temporal_timeout_error, resolve_error_trace, unwrap_temporal_cause++from products.exports.backend.tasks.failure_handler import (+ SLO_FAILURE_CATEGORY_ACTIVITY_TIMEOUT,+ SLO_FAILURE_CATEGORY_QUERY,+ SLO_FAILURE_COMPONENT_EXPORT_WORKER,+ ExportFailureDetails,+ is_user_query_error_type,+)++_EXPORT_FAILURE_METADATA_KIND = "export_activity_failure"+++class ExportFailureMetadata(TypedDict):+ kind: str+ slo_failure_details: ExportFailureDetails@dataclasses.dataclass@@ -10,10 +26,11 @@ class ExportAssetActivityInputs:source: Optional[str] = None+@frozenclass ExportError:exception_class: strerror_trace: str = ""+ failure_details: ExportFailureDetails | None = None@dataclasses.dataclass@@ -23,8 +40,48 @@ class ExportAssetResult:error: Optional[ExportError] = None+def is_user_query_export_error(error: ExportError) -> bool:+ if error.failure_details is not None:+ return error.failure_details["failure_category"] == SLO_FAILURE_CATEGORY_QUERY+ return is_user_query_error_type(error.exception_class)+++def export_failure_metadata(slo_failure_details: ExportFailureDetails) -> ExportFailureMetadata:+ return {+ "kind": _EXPORT_FAILURE_METADATA_KIND,+ "slo_failure_details": slo_failure_details,+ }++def extract_error_details(exc: BaseException) -> ExportError | None:cause = unwrap_temporal_cause(exc)- if cause is None or not cause.type:+ if cause is None:+ timeout = find_temporal_timeout_error(exc)+ if timeout is None:+ return None+ return ExportError(+ exception_class=type(timeout).__name__,+ error_trace=resolve_error_trace(exc),+ failure_details={+ "failure_category": SLO_FAILURE_CATEGORY_ACTIVITY_TIMEOUT,+ "failure_component": SLO_FAILURE_COMPONENT_EXPORT_WORKER,+ "failure_retryable": True,+ },+ )+ if not cause.type:return None- return ExportError(exception_class=cause.type, error_trace=resolve_error_trace(exc))+ metadata = next(+ (+ detail+ for detail in reversed(cause.details)+ if isinstance(detail, dict) and detail.get("kind") == _EXPORT_FAILURE_METADATA_KIND+ ),+ None,+ )+ raw_failure_details: object = metadata.get("slo_failure_details") if metadata else None+ failure_details = cast(ExportFailureDetails, raw_failure_details) if isinstance(raw_failure_details, dict) else None+ return ExportError(+ exception_class=cause.type,+ error_trace=resolve_error_trace(exc),+ failure_details=failure_details,+ )diff --git a/posthog/temporal/exports/workflows.py b/posthog/temporal/exports/workflows.pyindex 089b8aa415f5..adc7e88993a8 100644--- a/posthog/temporal/exports/workflows.py+++ b/posthog/temporal/exports/workflows.py@@ -10,7 +10,7 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.errors import resolve_exception_classfrom posthog.temporal.exports.activities import export_asset_activityfrom posthog.temporal.exports.retry_policy import EXPORT_RETRY_POLICY-from posthog.temporal.exports.types import ExportAssetActivityInputs+from posthog.temporal.exports.types import ExportAssetActivityInputs, extract_error_details, is_user_query_export_errorfrom products.exports.backend.tasks.failure_handler import is_user_query_error_type@@ -47,6 +47,17 @@ class ExportAssetWorkflow(PostHogWorkflow):)except Exception as e:# User-query failures aren't an SLO breach -> reclassify as SUCCESS- if inputs.slo and is_user_query_error_type(resolve_exception_class(e)):- inputs.slo.outcome = SloOutcome.SUCCESS+ if inputs.slo:+ failure = extract_error_details(e)+ is_user_query_error = (+ is_user_query_export_error(failure)+ if failure is not None+ else is_user_query_error_type(resolve_exception_class(e))+ )+ if is_user_query_error:+ inputs.slo.outcome = SloOutcome.SUCCESS+ else:+ if failure and failure.failure_details:+ inputs.slo.completion_properties.update(failure.failure_details)+ inputs.slo.completion_properties["failure_stage"] = "asset_generation"raisediff --git a/posthog/temporal/session_replay/rasterize_recording/workflow.py b/posthog/temporal/session_replay/rasterize_recording/workflow.pyindex 17a0d1064b2f..3c9c04044510 100644--- a/posthog/temporal/session_replay/rasterize_recording/workflow.py+++ b/posthog/temporal/session_replay/rasterize_recording/workflow.py@@ -3,10 +3,6 @@ from typing import Anyimport temporalio.workflow as wffrom temporalio import common-from temporalio.exceptions import (- FailureError,- TimeoutError as TemporalTimeoutError,-)from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY@@ -30,6 +26,7 @@ with wf.unsafe.imports_passed_through():from posthog.temporal.common.errors import (MAX_ERROR_MESSAGE_CHARS,+ find_temporal_timeout_error,resolve_exception_class,truncate_for_temporal_payload,unwrap_temporal_cause,@@ -65,12 +62,7 @@ def _resolve_error_code(exc: BaseException) -> str:ApplicationError in its cause chain, only Temporal's TimeoutError — without this check it wouldclassify as an opaque `ActivityError` and land in the unknown bucket."""- current: BaseException | None = exc- while isinstance(current, FailureError):- if isinstance(current, TemporalTimeoutError):- return "ACTIVITY_TIMEOUT"- current = current.cause- return resolve_exception_class(exc)+ return "ACTIVITY_TIMEOUT" if find_temporal_timeout_error(exc) else resolve_exception_class(exc)def _record_outcome(counter: Counter, inputs: RasterizeRecordingInputs) -> None:diff --git a/posthog/temporal/tests/test_export_activities.py b/posthog/temporal/tests/test_export_activities.pyindex 5e11ed1a7560..4675d015b5bc 100644--- a/posthog/temporal/tests/test_export_activities.py+++ b/posthog/temporal/tests/test_export_activities.py@@ -13,9 +13,10 @@ from asgiref.sync import sync_to_asyncfrom playwright.sync_api import TimeoutError as PlaywrightTimeoutErrorfrom temporalio.client import Client, WorkflowFailureErrorfrom temporalio.exceptions import ActivityError, ApplicationError-from temporalio.testing import WorkflowEnvironment+from temporalio.testing import ActivityEnvironment, WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker+from posthog.models import Teamfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.exports.activities import export_asset_activityfrom posthog.temporal.exports.retry_policy import EXPORT_RETRY_POLICY@@ -145,3 +146,41 @@ async def test_export_asset_activity_timeout_errors_are_retryable(await activity_environment.run(export_asset_activity, ExportAssetActivityInputs(exported_asset_id=asset.id))assert exc_info.value.non_retryable is expected_non_retryable+++@patch("posthog.temporal.exports.activities.exporter")+async def test_export_asset_activity_refresh_failure_preserves_export_error(+ mock_exporter: MagicMock, activity_environment: ActivityEnvironment, team: Team+) -> None:+ asset = await sync_to_async(ExportedAsset.objects.create)(+ team=team,+ export_format=ExportedAsset.ExportFormat.PNG,+ )++ def fake_export(_exported_asset: ExportedAsset, **_kwargs: object) -> None:+ raise ValueError("render failed")++ mock_exporter.export_asset_direct = fake_export++ # A failing refresh inside the except handler must not replace the export error+ # or drop its classification metadata.+ with patch.object(ExportedAsset, "refresh_from_db", side_effect=RuntimeError("db gone")):+ with pytest.raises(ApplicationError) as exc_info:+ await activity_environment.run(export_asset_activity, ExportAssetActivityInputs(exported_asset_id=asset.id))++ assert exc_info.value.type == "ValueError"+ metadata = [+ detail+ for detail in exc_info.value.details+ if isinstance(detail, dict) and detail.get("kind") == "export_activity_failure"+ ]+ assert metadata == [+ {+ "kind": "export_activity_failure",+ "slo_failure_details": {+ "failure_category": "application",+ "failure_component": "exporter",+ "failure_retryable": False,+ },+ }+ ]diff --git a/posthog/temporal/tests/test_export_types.py b/posthog/temporal/tests/test_export_types.pynew file mode 100644index 000000000000..3d03790225fc--- /dev/null+++ b/posthog/temporal/tests/test_export_types.py@@ -0,0 +1,82 @@+import pytest++from temporalio.exceptions import (+ ActivityError,+ RetryState,+ TimeoutError as TemporalTimeoutError,+ TimeoutType,+)++from posthog.temporal.exports.types import ExportError, extract_error_details, is_user_query_export_error+++def test_extract_error_details_classifies_temporal_activity_timeout() -> None:+ timeout = TemporalTimeoutError(+ "activity timed out",+ type=TimeoutType.HEARTBEAT,+ last_heartbeat_details=[],+ )+ activity_error = ActivityError(+ "activity failed",+ scheduled_event_id=1,+ started_event_id=2,+ identity="export-worker",+ activity_type="export_asset_activity",+ activity_id="export-1",+ retry_state=RetryState.MAXIMUM_ATTEMPTS_REACHED,+ )+ activity_error.__cause__ = timeout++ failure = extract_error_details(activity_error)++ assert failure is not None+ assert failure.exception_class == "TimeoutError"+ assert failure.failure_details == {+ "failure_category": "activity_timeout",+ "failure_component": "export_worker",+ "failure_retryable": True,+ }+++ "error,expected",+ [+ (+ ExportError(+ exception_class="ValidationError",+ failure_details={+ "failure_category": "application",+ "failure_component": "exporter",+ "failure_retryable": False,+ },+ ),+ False,+ ),+ (+ ExportError(+ exception_class="SyntaxError",+ failure_details={+ "failure_category": "application",+ "failure_component": "exporter",+ "failure_retryable": False,+ },+ ),+ False,+ ),+ (+ ExportError(+ exception_class="ValidationError",+ failure_details={+ "failure_category": "query",+ "failure_component": "query",+ "failure_retryable": False,+ },+ ),+ True,+ ),+ (ExportError(exception_class="ValidationError"), True),+ ],+ ids=["django_validation_error", "builtin_syntax_error", "drf_validation_error", "legacy_name_fallback"],+)+def test_is_user_query_export_error_uses_failure_metadata(error: ExportError, expected: bool) -> None:+ assert is_user_query_export_error(error) is expecteddiff --git a/posthog/temporal/tests/test_export_workflow.py b/posthog/temporal/tests/test_export_workflow.pyindex 555ae0ad3cef..1f7a1907f7a4 100644--- a/posthog/temporal/tests/test_export_workflow.py+++ b/posthog/temporal/tests/test_export_workflow.py@@ -4,6 +4,7 @@ import pytestfrom unittest.mock import MagicMock, patchfrom django.conf import settings+from django.core.exceptions import ValidationError as DjangoValidationErrorfrom asgiref.sync import sync_to_asyncfrom temporalio.testing import WorkflowEnvironment@@ -18,12 +19,17 @@ from posthog.temporal.exports.activities import export_asset_activityfrom posthog.temporal.exports.workflows import ExportAssetWorkflow, ExportAssetWorkflowInputsfrom products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.tasks.failure_handler import ExportFailureDetailspytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]EXPORT_FORMAT = ExportedAsset.ExportFormat.PNG+class CustomQueryError(QueryError):+ pass++async def _run_export_workflow(env, asset, team, mock_exporter, fake_export):mock_exporter.export_asset_direct = fake_export@@ -149,7 +155,7 @@ async def test_transient_error_retries_and_succeeds(@pytest.mark.parametrize(- "error_factory,expected_exception_class,expected_error_msg,expected_call_count,expected_outcome",+ "error_factory,expected_exception_class,expected_error_msg,expected_call_count,expected_outcome,expected_failure_details",[(lambda: QueryError("Invalid HogQL query"),@@ -157,17 +163,73 @@ async def test_transient_error_retries_and_succeeds("QueryError: Invalid HogQL query",1,SloOutcome.SUCCESS,+ None,+ ),+ (+ lambda: CustomQueryError("Invalid custom query"),+ "CustomQueryError",+ "CustomQueryError: Invalid custom query",+ 1,+ SloOutcome.SUCCESS,+ None,+ ),+ (+ lambda: RuntimeError("Chrome crashed"),+ "RuntimeError",+ "RuntimeError: Chrome crashed",+ 1,+ SloOutcome.FAILURE,+ {+ "failure_category": "application",+ "failure_component": "exporter",+ "failure_retryable": False,+ },),- (lambda: RuntimeError("Chrome crashed"), "RuntimeError", "RuntimeError: Chrome crashed", 1, SloOutcome.FAILURE),(lambda: CHQueryErrorS3Error("S3 error", code=499),"CHQueryErrorS3Error","CHQueryErrorS3Error: Code: 499.\nS3 error",10,SloOutcome.FAILURE,+ {+ "failure_category": "storage",+ "failure_component": "object_storage",+ "failure_retryable": True,+ },),+ (+ lambda: DjangoValidationError("not a query error"),+ "ValidationError",+ "ValidationError: ['not a query error']",+ 1,+ SloOutcome.FAILURE,+ {+ "failure_category": "application",+ "failure_component": "exporter",+ "failure_retryable": False,+ },+ ),+ (+ lambda: SyntaxError("not a query error"),+ "SyntaxError",+ "SyntaxError: not a query error",+ 1,+ SloOutcome.FAILURE,+ {+ "failure_category": "application",+ "failure_component": "exporter",+ "failure_retryable": False,+ },+ ),+ ],+ ids=[+ "non_retryable_user_error",+ "query_error_subclass",+ "generic_runtime_error",+ "retryable_system_error",+ "django_validation_error",+ "builtin_syntax_error",],- ids=["non_retryable_user_error", "generic_runtime_error", "retryable_system_error"],)@patch("posthog.slo.events.posthoganalytics")@patch("posthog.temporal.exports.activities.exporter")@@ -180,6 +242,7 @@ async def test_export_failure_emits_slo_outcome(expected_error_msg: str,expected_call_count: int,expected_outcome: SloOutcome,+ expected_failure_details: ExportFailureDetails | None,):asset = await sync_to_async(ExportedAsset.objects.create)(team=team, export_format=EXPORT_FORMAT)@@ -203,3 +266,11 @@ async def test_export_failure_emits_slo_outcome(assert props["error_type"] == expected_exception_classassert props["error_message"] == expected_error_msgassert "Traceback" in props["error_trace"]+ if expected_failure_details is not None:+ assert props["failure_stage"] == "asset_generation"+ assert {key: props[key] for key in expected_failure_details} == expected_failure_details+ else:+ assert "failure_stage" not in props+ assert "failure_category" not in props+ assert "failure_component" not in props+ assert "failure_retryable" not in propsdiff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex 0e200ec6b1c5..3dc112af25e6 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -11,12 +11,13 @@ from freezegun import freeze_timefrom unittest.mock import AsyncMock, MagicMock, patchfrom django.conf import settings+from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.utils import timezoneimport pytest_asynciofrom asgiref.sync import sync_to_asyncfrom slack_sdk.errors import SlackApiError-from temporalio.client import Client+from temporalio.client import Client, WorkflowFailureErrorfrom temporalio.exceptions import ApplicationErrorfrom temporalio.testing import ActivityEnvironment, WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker@@ -31,6 +32,7 @@ from posthog.models.integration import Integrationfrom posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcomefrom posthog.temporal.common.slo_interceptor import SloInterceptorfrom posthog.temporal.exports.activities import export_asset_activity+from posthog.temporal.exports.types import ExportErrorfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile@@ -78,6 +80,7 @@ from products.exports.backend.temporal.subscriptions.workflows import (ProcessAISubscriptionWorkflow,ProcessSubscriptionWorkflow,ScheduleAllSubscriptionsWorkflow,+ _summarize_export_failure_details,)from products.product_analytics.backend.facade.models import Insight@@ -96,6 +99,10 @@ _IS_OVER_BUDGET = (_CREDIT_LIMITED_EMAIL = "products.exports.backend.temporal.subscriptions.ai_subscription.delivery.EmailMessage"+class CustomQueryError(QueryError):+ pass++async def test_subscription_workflows_accept_legacy_previous_target_payload() -> None:payload = '{"subscription_id": 1, "previous_value": "[email protected]"}'@@ -106,6 +113,56 @@ async def test_subscription_workflows_accept_legacy_previous_target_payload() ->assert update_inputs.previous_target_value == "[email protected]"+async def test_subscription_slo_failure_summary_preserves_mixed_failure_details() -> None:+ summary = _summarize_export_failure_details(+ [+ ExportError(+ exception_class="BrowserlessUnavailable",+ failure_details={+ "failure_category": "renderer_rate_limited",+ "failure_component": "browserless",+ "failure_retryable": True,+ },+ ),+ ExportError(+ exception_class="RuntimeError",+ failure_details={+ "failure_category": "application",+ "failure_component": "exporter",+ "failure_retryable": False,+ },+ ),+ ExportError(exception_class="LegacyError"),+ ]+ )++ assert summary == {+ "failure_stage": "asset_generation",+ "failure_categories": ["application", "renderer_rate_limited"],+ "failure_components": ["browserless", "exporter"],+ "failed_asset_count": 3,+ "failure_category_count": 2,+ "retryable_failed_asset_count": 1,+ "non_retryable_failed_asset_count": 1,+ "unclassified_failed_asset_count": 1,+ }+++async def test_subscription_slo_failure_summary_counts_unclassified_assets() -> None:+ summary = _summarize_export_failure_details(+ [+ ExportError(exception_class="OperationalError"),+ ExportError(exception_class="LegacyError"),+ ]+ )++ assert summary["failure_categories"] == []+ assert summary["failure_components"] == []+ assert summary["failed_asset_count"] == 2+ assert summary["failure_category_count"] == 0+ assert summary["unclassified_failed_asset_count"] == 2++async def test_email_delivery_error_is_non_retryable(team, user) -> None:subscription = await sync_to_async(create_subscription)(team=team, created_by=user)inputs = DeliverSubscriptionInputs(@@ -1907,6 +1964,27 @@ async def test_export_error_slo_outcome(None,id="user_error_keeps_slo_success",),+ pytest.param(+ lambda: CustomQueryError("Invalid custom query"),+ SloOutcome.SUCCESS,+ None,+ None,+ id="query_error_subclass_keeps_slo_success",+ ),+ pytest.param(+ lambda: DjangoValidationError("not a query error"),+ SloOutcome.FAILURE,+ "PartialExportFailure",+ "1 export(s) failed: ValidationError",+ id="django_validation_error_sets_slo_failure",+ ),+ pytest.param(+ lambda: SyntaxError("not a query error"),+ SloOutcome.FAILURE,+ "PartialExportFailure",+ "1 export(s) failed: SyntaxError",+ id="builtin_syntax_error_sets_slo_failure",+ ),],)@patch("posthog.temporal.exports.activities.exporter")@@ -2001,11 +2079,91 @@ async def test_partial_export_failure_delivers_successful_assets(assert props["error_message"] == expected_error_msgassert len(props["asset_errors"]) == 1assert "Traceback" in props["asset_errors"][0]["error_trace"]+ assert props["asset_errors"][0]["failure_category"] == "application"+ assert props["asset_errors"][0]["failure_component"] == "exporter"+ assert props["asset_errors"][0]["failure_retryable"] is False+ assert props["failure_stage"] == "asset_generation"+ assert props["failed_asset_count"] == 1+ assert props["failure_category_count"] == 1+ assert props["failure_categories"] == ["application"]+ assert props["failure_components"] == ["exporter"]+ assert props["retryable_failed_asset_count"] == 0+ assert props["non_retryable_failed_asset_count"] == 1+ assert props["unclassified_failed_asset_count"] == 0else:assert "error_type" not in propsassert props["asset_errors"] == []+@patch("posthog.temporal.exports.activities.exporter")+@patch("posthog.slo.events.posthoganalytics")+@patch("ee.tasks.subscriptions.get_metric_meter")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")+@freeze_time("2022-02-02T08:55:00.000Z")+async def test_delivery_failure_replaces_partial_export_slo_attribution(+ mock_send_email: MagicMock,+ mock_metric_meter: MagicMock,+ mock_slo_analytics: MagicMock,+ mock_exporter: MagicMock,+ temporal_client: Client,+ team,+ user,+) -> None:+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id="slo02", name="SLO stage test")+ subscription = await sync_to_async(create_subscription)(team=team, insight=insight, created_by=user)++ mock_exporter.export_asset_direct.side_effect = RuntimeError("render failed")+ mock_send_email.side_effect = EmailDeliveryError("email provider rejected delivery")++ with pytest.raises(WorkflowFailureError):+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=settings.TEMPORAL_TASK_QUEUE,+ workflows=[ProcessSubscriptionWorkflow],+ activities=SUBSCRIPTION_PROCESS_ACTIVITIES,+ interceptors=[SloInterceptor()],+ workflow_runner=UnsandboxedWorkflowRunner(),+ activity_executor=ThreadPoolExecutor(max_workers=10),+ debug_mode=True,+ ):+ await env.client.execute_workflow(+ ProcessSubscriptionWorkflow.run,+ TrackedSubscriptionInputs(+ subscription_id=subscription.id,+ team_id=subscription.team_id,+ distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]+ slo=SloConfig(+ operation=SloOperation.SUBSCRIPTION_DELIVERY,+ area=SloArea.ANALYTIC_PLATFORM,+ team_id=subscription.team_id,+ resource_id=str(subscription.id),+ distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]+ ),+ ),+ id=str(uuid.uuid4()),+ task_queue=settings.TEMPORAL_TASK_QUEUE,+ )++ completed_calls = [+ call+ for call in mock_slo_analytics.capture.call_args_list+ if call.kwargs.get("event") == "slo_operation_completed"+ and call.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY+ ]+ assert len(completed_calls) == 1+ properties = completed_calls[0].kwargs["properties"]+ assert properties["outcome"] == SloOutcome.FAILURE+ assert properties["error_type"] == "ApplicationError"+ assert properties["failure_stage"] == "delivery"+ assert properties["failure_category"] == "activity_failure"+ assert properties["failure_component"] == "subscription_delivery"+ assert properties["failure_retryable"] is False+ assert "failure_categories" not in properties+ assert "failure_components" not in properties++@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")diff --git a/products/exports/backend/tasks/failure_handler.py b/products/exports/backend/tasks/failure_handler.pyindex b94ac21ced63..b5816291ea8f 100644--- a/products/exports/backend/tasks/failure_handler.py+++ b/products/exports/backend/tasks/failure_handler.py@@ -1,5 +1,6 @@import sysfrom ssl import SSLError+from typing import TypedDictfrom django.db import OperationalError@@ -31,7 +32,13 @@ from posthog.errors import (CHQueryErrorUnknownTable,CHQueryErrorUnsupportedMethod,)-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQuerySizeExceeded, ClickHouseQueryTimeOut+from posthog.exceptions import (+ ClickHouseAtCapacity,+ ClickHouseClusterMemoryLimitExceeded,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQuerySizeExceeded,+ ClickHouseQueryTimeOut,+)from posthog.storage.object_storage import ObjectStorageError# =============================================================================@@ -56,6 +63,34 @@ FAILURE_TYPE_RENDERER_UNKNOWN = "renderer_unknown"FAILURE_TYPE_OTHER = "other"FAILURE_TYPE_UNKNOWN = "unknown"+# Low-cardinality dimensions for SLO events. Keep these stable: they are intended+# for breakdowns and alerts, unlike exception messages or stack traces.+SLO_FAILURE_CATEGORY_RENDERER_RATE_LIMITED = "renderer_rate_limited"+SLO_FAILURE_CATEGORY_RENDERER_UNAVAILABLE = "renderer_unavailable"+SLO_FAILURE_CATEGORY_RENDERER_TIMEOUT = "renderer_timeout"+SLO_FAILURE_CATEGORY_QUERY = "query"+SLO_FAILURE_CATEGORY_QUERY_CAPACITY = "query_capacity"+SLO_FAILURE_CATEGORY_STORAGE = "storage"+SLO_FAILURE_CATEGORY_TRANSIENT_DEPENDENCY = "transient_dependency"+SLO_FAILURE_CATEGORY_APPLICATION = "application"+SLO_FAILURE_CATEGORY_ACTIVITY_TIMEOUT = "activity_timeout"++SLO_FAILURE_COMPONENT_BROWSERLESS = "browserless"+SLO_FAILURE_COMPONENT_QUERY = "query"+SLO_FAILURE_COMPONENT_STORAGE = "object_storage"+SLO_FAILURE_COMPONENT_DEPENDENCY = "dependency"+SLO_FAILURE_COMPONENT_EXPORTER = "exporter"+SLO_FAILURE_COMPONENT_EXPORT_WORKER = "export_worker"+++class ExportFailureDetails(TypedDict):+ failure_category: str+ failure_component: str+ failure_retryable: bool+++RATE_LIMIT_MESSAGE_PREFIX_CHARS = 8_000+# Video renders fail with a code from the recording rasterizer rather than a Python exception, so they# classify by code (RASTERIZATION_ERROR_CODES in# nodejs/src/session-replay/recording-rasterizer/errors.ts). A code absent here classifies as@@ -201,6 +236,14 @@ SYSTEM_ERROR_NAMES = frozenset(cls.__name__ for cls in EXCEPTIONS_TO_RETRY)# covered here without needing the class itself.TIMEOUT_ERROR_NAMES = frozenset(cls.__name__ for cls in TIMEOUT_ERRORS) | {"TimeoutException"}+# Capacity saturation, not a fault in the query itself: query-scheduling limits and server-wide or+# per-user memory pressure. posthog.errors.classify_query_error groups the same three as+# RATE_LIMITED, so keep this set aligned — otherwise a single capacity incident splits across the+# query and transient_dependency categories instead of aggregating under query_capacity.+QUERY_CAPACITY_ERROR_NAMES = frozenset(+ cls.__name__ for cls in (ConcurrencyLimitExceeded, ClickHouseAtCapacity, ClickHouseClusterMemoryLimitExceeded)+)+def _is_playwright_timeout(exception: BaseException) -> bool:# playwright is a heavy import (browser automation), only needed by the actual image-export@@ -247,3 +290,67 @@ def is_user_query_error_type(exception_type: str | None) -> bool:if exception_type is None:return Falsereturn classify_failure_type(exception_type) == FAILURE_TYPE_USER+++def export_slo_failure_details(exception: Exception | str) -> ExportFailureDetails:+ """Return safe, low-cardinality SLO dimensions for an export failure.++ This deliberately does not include the exception message. It is emitted on+ every failed export/subscription SLO and must be safe to aggregate broadly.+ """++ exception_type = type(exception).__name__ if isinstance(exception, Exception) else exception+ message = str(exception)[:RATE_LIMIT_MESSAGE_PREFIX_CHARS].lower() if isinstance(exception, Exception) else ""++ if exception_type == BrowserlessUnavailable.__name__:+ if any(marker in message for marker in ("429", "too many requests", "rate limit", "rate_limited")):+ return {+ "failure_category": SLO_FAILURE_CATEGORY_RENDERER_RATE_LIMITED,+ "failure_component": SLO_FAILURE_COMPONENT_BROWSERLESS,+ "failure_retryable": True,+ }+ return {+ "failure_category": SLO_FAILURE_CATEGORY_RENDERER_UNAVAILABLE,+ "failure_component": SLO_FAILURE_COMPONENT_BROWSERLESS,+ "failure_retryable": True,+ }++ if exception_type in TIMEOUT_ERROR_NAMES:+ return {+ "failure_category": SLO_FAILURE_CATEGORY_RENDERER_TIMEOUT,+ "failure_component": SLO_FAILURE_COMPONENT_BROWSERLESS,+ "failure_retryable": exception_type != ExportCancelled.__name__,+ }++ if exception_type in QUERY_CAPACITY_ERROR_NAMES:+ return {+ "failure_category": SLO_FAILURE_CATEGORY_QUERY_CAPACITY,+ "failure_component": SLO_FAILURE_COMPONENT_QUERY,+ "failure_retryable": True,+ }++ if exception_type == ObjectStorageError.__name__ or "s3" in exception_type.lower():+ return {+ "failure_category": SLO_FAILURE_CATEGORY_STORAGE,+ "failure_component": SLO_FAILURE_COMPONENT_STORAGE,+ "failure_retryable": True,+ }++ failure_type = classify_failure_type(exception)+ if failure_type == FAILURE_TYPE_USER:+ return {+ "failure_category": SLO_FAILURE_CATEGORY_QUERY,+ "failure_component": SLO_FAILURE_COMPONENT_QUERY,+ "failure_retryable": False,+ }+ if failure_type == FAILURE_TYPE_SYSTEM:+ return {+ "failure_category": SLO_FAILURE_CATEGORY_TRANSIENT_DEPENDENCY,+ "failure_component": SLO_FAILURE_COMPONENT_DEPENDENCY,+ "failure_retryable": True,+ }+ return {+ "failure_category": SLO_FAILURE_CATEGORY_APPLICATION,+ "failure_component": SLO_FAILURE_COMPONENT_EXPORTER,+ "failure_retryable": False,+ }diff --git a/products/exports/backend/tasks/test/test_failure_handler.py b/products/exports/backend/tasks/test/test_failure_handler.pyindex d9cc4ce7e777..a66069109927 100644--- a/products/exports/backend/tasks/test/test_failure_handler.py+++ b/products/exports/backend/tasks/test/test_failure_handler.py@@ -5,12 +5,23 @@ from django.core.exceptions import ValidationError as DjangoValidationErrorfrom parameterized import parameterizedfrom rest_framework.exceptions import ValidationError+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseClusterMemoryLimitExceeded+from products.exports.backend.tasks.failure_handler import (FAILURE_TYPE_SYSTEM,FAILURE_TYPE_TIMEOUT_GENERATION,FAILURE_TYPE_UNKNOWN,FAILURE_TYPE_USER,+ SLO_FAILURE_CATEGORY_APPLICATION,+ SLO_FAILURE_CATEGORY_QUERY_CAPACITY,+ SLO_FAILURE_CATEGORY_RENDERER_RATE_LIMITED,+ SLO_FAILURE_CATEGORY_RENDERER_TIMEOUT,+ SLO_FAILURE_CATEGORY_RENDERER_UNAVAILABLE,+ SLO_FAILURE_CATEGORY_STORAGE,+ BrowserlessUnavailable,+ ExportCancelled,classify_failure_type,+ export_slo_failure_details,is_user_query_error_type,)@@ -102,3 +113,68 @@ class TestClassifyFailureType(TestCase):def test_name_string_classification_is_unchanged_for_backfill(self) -> None:# Stored rows only carry the class name, so the string path stays purely name-based.assert classify_failure_type("ValidationError") == FAILURE_TYPE_USER+++class TestExportSloFailureDetails(TestCase):+ @parameterized.expand(+ [+ (+ "browserless_rate_limit",+ BrowserlessUnavailable("Browserless returned 429 Too Many Requests"),+ SLO_FAILURE_CATEGORY_RENDERER_RATE_LIMITED,+ "browserless",+ True,+ ),+ ("render_timeout", "TimeoutError", SLO_FAILURE_CATEGORY_RENDERER_TIMEOUT, "browserless", True),+ (+ "export_cancelled",+ ExportCancelled("cancelled"),+ SLO_FAILURE_CATEGORY_RENDERER_TIMEOUT,+ "browserless",+ False,+ ),+ ("query_capacity", "ConcurrencyLimitExceeded", SLO_FAILURE_CATEGORY_QUERY_CAPACITY, "query", True),+ # ClickHouse capacity errors share the query_capacity category — classify_query_error groups+ # the same three as RATE_LIMITED. The instance path is what the export activity feeds in, and+ # ClickHouseClusterMemoryLimitExceeded subclasses a user-query error, so without an explicit+ # capacity check it would fall through to the query (user) or transient_dependency buckets.+ (+ "query_capacity_at_capacity_instance",+ ClickHouseAtCapacity(),+ SLO_FAILURE_CATEGORY_QUERY_CAPACITY,+ "query",+ True,+ ),+ (+ "query_capacity_cluster_memory_instance",+ ClickHouseClusterMemoryLimitExceeded(),+ SLO_FAILURE_CATEGORY_QUERY_CAPACITY,+ "query",+ True,+ ),+ ("storage", "CHQueryErrorS3Error", SLO_FAILURE_CATEGORY_STORAGE, "object_storage", True),+ ("unknown", "RuntimeError", SLO_FAILURE_CATEGORY_APPLICATION, "exporter", False),+ ]+ )+ def test_returns_safe_breakdown_dimensions(+ self,+ _name: str,+ exception: Exception | str,+ category: str,+ component: str,+ retryable: bool,+ ) -> None:+ assert export_slo_failure_details(exception) == {+ "failure_category": category,+ "failure_component": component,+ "failure_retryable": retryable,+ }++ def test_bounds_browserless_rate_limit_message_inspection(self) -> None:+ exception = BrowserlessUnavailable(f"{'x' * 8_000} 429 Too Many Requests")++ assert export_slo_failure_details(exception) == {+ "failure_category": SLO_FAILURE_CATEGORY_RENDERER_UNAVAILABLE,+ "failure_component": "browserless",+ "failure_retryable": True,+ }diff --git a/products/exports/backend/temporal/subscriptions/test_delivery_activities.py b/products/exports/backend/temporal/subscriptions/test_delivery_activities.pyindex b38100a674fa..0a238569895c 100644--- a/products/exports/backend/temporal/subscriptions/test_delivery_activities.py+++ b/products/exports/backend/temporal/subscriptions/test_delivery_activities.py@@ -30,6 +30,7 @@ from products.exports.backend.temporal.subscriptions.types import (DeliverSubscriptionResult,GenerateAIReportResult,SnapshotInsightsResult,+ SubscriptionTriggerType,TrackedSubscriptionInputs,)from products.exports.backend.temporal.subscriptions.workflows import (@@ -179,3 +180,66 @@ async def test_process_ai_subscription_picks_delivery_activity_from_patch(patch_assert picked is (deliver_subscription_v2 if patch_active else deliver_subscription)assert inputs.slo is not Noneassert inputs.slo.completion_properties["target_type"] == "slack"+++ "workflow_type",+ [ProcessSubscriptionWorkflow, ProcessAISubscriptionWorkflow],+ ids=["standard", "ai"],+)+async def test_schedule_update_failure_preserves_primary_failure(+ workflow_type: type[ProcessSubscriptionWorkflow] | type[ProcessAISubscriptionWorkflow],+) -> None:+ primary_error = RuntimeError("delivery failed")+ schedule_error = RuntimeError("schedule update failed")++ async def fake_execute_activity(activity: object, _inputs: object, **_kwargs: object) -> object:+ if activity is create_delivery_record:+ return uuid.uuid4()+ if activity is validate_subscription_for_delivery:+ return None+ if activity is create_export_assets:+ return CreateExportAssetsResult(exported_asset_ids=[1], total_insight_count=1)+ if activity is export_asset_activity:+ return ExportAssetResult(exported_asset_id=1, success=True)+ if activity is snapshot_subscription_insights:+ return SnapshotInsightsResult()+ if activity is generate_ai_subscription_report:+ return GenerateAIReportResult()+ if activity in (deliver_subscription, deliver_subscription_v2):+ raise primary_error+ if activity is update_delivery_record:+ return None+ if activity is advance_next_delivery_date:+ raise schedule_error+ raise AssertionError(f"unexpected activity {activity}")++ with (+ patch("temporalio.workflow.execute_activity", side_effect=fake_execute_activity),+ patch("temporalio.workflow.patched", return_value=False),+ patch("temporalio.workflow.info") as mock_info,+ patch("temporalio.workflow.uuid4", return_value=uuid.uuid4()),+ patch("temporalio.workflow.logger", MagicMock()),+ ):+ mock_info.return_value = MagicMock(workflow_id="wf-test")+ inputs = TrackedSubscriptionInputs(+ subscription_id=1,+ team_id=1,+ distinct_id="u1",+ trigger_type=SubscriptionTriggerType.SCHEDULED,+ slo=SloConfig(+ operation=SloOperation.SUBSCRIPTION_DELIVERY,+ area=SloArea.ANALYTIC_PLATFORM,+ team_id=1,+ resource_id="1",+ distinct_id="u1",+ ),+ )++ with pytest.raises(RuntimeError, match="delivery failed") as exc_info:+ await workflow_type().run(inputs)++ assert exc_info.value is primary_error+ assert inputs.slo is not None+ assert inputs.slo.completion_properties["failure_stage"] == "delivery"+ assert inputs.slo.completion_properties["failure_component"] == "subscription_delivery"diff --git a/products/exports/backend/temporal/subscriptions/workflows.py b/products/exports/backend/temporal/subscriptions/workflows.pyindex a1e5c6dad871..17aae14a594d 100644--- a/products/exports/backend/temporal/subscriptions/workflows.py+++ b/products/exports/backend/temporal/subscriptions/workflows.py@@ -3,6 +3,7 @@ import uuidimport asyncioimport datetime as dtfrom collections.abc import Callable, Coroutine+from enum import StrEnumfrom typing import Anyimport temporalio.common@@ -12,6 +13,14 @@ from temporalio.exceptions import ActivityError, ApplicationError, WorkflowAlreafrom posthog.event_usage import EventSourcefrom posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcomefrom posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.errors import (+ MAX_ERROR_MESSAGE_CHARS,+ find_temporal_timeout_error,+ resolve_error_trace,+ resolve_exception_class,+ truncate_for_temporal_payload,+ unwrap_temporal_cause,+)from posthog.temporal.exports.activities import export_asset_activityfrom posthog.temporal.exports.retry_policy import EXPORT_RETRY_POLICYfrom posthog.temporal.exports.types import (@@ -19,9 +28,13 @@ from posthog.temporal.exports.types import (ExportAssetResult,ExportError,extract_error_details,+ is_user_query_export_error,)-from products.exports.backend.tasks.failure_handler import is_user_query_error_type+from products.exports.backend.tasks.failure_handler import (+ SLO_FAILURE_CATEGORY_ACTIVITY_TIMEOUT,+ SLO_FAILURE_COMPONENT_EXPORT_WORKER,+)from products.exports.backend.temporal.subscriptions.activities import (advance_next_delivery_date,create_delivery_record,@@ -62,6 +75,29 @@ from products.exports.backend.temporal.subscriptions.types import ()+class SubscriptionFailureStage(StrEnum):+ DELIVERY_RECORD = "delivery_record"+ VALIDATION = "validation"+ ASSET_PREPARATION = "asset_preparation"+ ASSET_GENERATION = "asset_generation"+ REPORT_GENERATION = "report_generation"+ DELIVERY = "delivery"+ RECORD_UPDATE = "record_update"+ SCHEDULE_UPDATE = "schedule_update"+++_FAILURE_STAGE_COMPONENT: dict[SubscriptionFailureStage, str] = {+ SubscriptionFailureStage.DELIVERY_RECORD: "delivery_record",+ SubscriptionFailureStage.VALIDATION: "subscription_validation",+ SubscriptionFailureStage.ASSET_PREPARATION: "export_preparation",+ SubscriptionFailureStage.ASSET_GENERATION: SLO_FAILURE_COMPONENT_EXPORT_WORKER,+ SubscriptionFailureStage.REPORT_GENERATION: "ai_report_generation",+ SubscriptionFailureStage.DELIVERY: "subscription_delivery",+ SubscriptionFailureStage.RECORD_UPDATE: "delivery_record",+ SubscriptionFailureStage.SCHEDULE_UPDATE: "subscription_schedule",+}++def _to_recipient_dicts(recipient_results: list[RecipientResult]) -> list[dict]:return [{@@ -102,6 +138,54 @@ def _build_outcome_assets(return outcome_assets, successful_asset_ids+def _summarize_export_failure_details(errors: list[ExportError]) -> dict[str, str | int | list[str]]:+ """Summarize per-asset failure dimensions onto one subscription SLO event."""++ details = [error.failure_details for error in errors if error.failure_details is not None]+ categories = sorted({detail["failure_category"] for detail in details})+ components = sorted({detail["failure_component"] for detail in details})+ retryable_failure_count = sum(detail["failure_retryable"] for detail in details)+ unclassified_failure_count = len(errors) - len(details)++ return {+ "failure_stage": SubscriptionFailureStage.ASSET_GENERATION.value,+ "failure_categories": categories,+ "failure_components": components,+ "failed_asset_count": len(errors),+ "failure_category_count": len(categories),+ "retryable_failed_asset_count": retryable_failure_count,+ "non_retryable_failed_asset_count": len(details) - retryable_failure_count,+ "unclassified_failed_asset_count": unclassified_failure_count,+ }+++def _record_subscription_failure(+ slo: SloConfig | None,+ stage: SubscriptionFailureStage,+ exc: BaseException,+) -> None:+ if slo is None:+ return++ application_error = unwrap_temporal_cause(exc)+ if application_error is None and isinstance(exc, ApplicationError):+ application_error = exc+ timeout = find_temporal_timeout_error(exc)+ cause = application_error or timeout or exc++ slo.completion_properties.update(+ {+ "error_type": type(timeout).__name__ if timeout else resolve_exception_class(exc),+ "error_message": truncate_for_temporal_payload(str(cause), MAX_ERROR_MESSAGE_CHARS),+ "error_trace": resolve_error_trace(exc),+ "failure_stage": stage.value,+ "failure_category": SLO_FAILURE_CATEGORY_ACTIVITY_TIMEOUT if timeout else "activity_failure",+ "failure_component": _FAILURE_STAGE_COMPONENT[stage],+ "failure_retryable": True if timeout else bool(application_error and not application_error.non_retryable),+ }+ )++@temporalio.workflow.defn(name="schedule-all-subscriptions")class ScheduleAllSubscriptionsWorkflow(PostHogWorkflow):@staticmethod@@ -216,8 +300,10 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):assets_with_content = 0total_assets = 0asset_errors: list[ExportError] = []+ asset_failure_summary: dict[str, str | int | list[str]] | None = Nonecaught_error: BaseException | None = Nonedelivery_error: NoExportableInsightsErrorDetails | None = None+ failure_stage = SubscriptionFailureStage.DELIVERY_RECORD# Delivery record trackingdelivery_id: uuid.UUID | None = None@@ -250,6 +336,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):# Validate up-front: if the subscription is already disabled or its target# configuration is permanently broken, auto-disable and short-circuit before# the export pipeline runs.+ failure_stage = SubscriptionFailureStage.VALIDATIONabort_info = await temporalio.workflow.execute_activity(validate_subscription_for_delivery,inputs.subscription_id,@@ -267,6 +354,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):# onto SubscriptionDelivery.content_snapshot (written from within the# activity to avoid shipping multi-MB query_results across Temporal's# ~2 MiB payload boundary).+ failure_stage = SubscriptionFailureStage.ASSET_PREPARATIONprepare_result = await temporalio.workflow.execute_activity(create_export_assets,CreateExportAssetsInputs(@@ -328,6 +416,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):delivery_exported_asset_ids = prepare_result.exported_asset_ids# Phase 2: Fan-out export — one activity per insight, independent retry+ failure_stage = SubscriptionFailureStage.ASSET_GENERATIONexport_tasks = []for asset_id in prepare_result.exported_asset_ids:task = temporalio.workflow.execute_activity(@@ -355,7 +444,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):total_assets = len(outcome_assets)asset_errors = [a.error for a in outcome_assets if a.error]- non_user_errors = [e for e in asset_errors if not is_user_query_error_type(e.exception_class)]+ non_user_errors = [e for e in asset_errors if not is_user_query_export_error(e)]if inputs.slo and non_user_errors:inputs.slo.outcome = SloOutcome.FAILUREdistinct_classes = sorted({e.exception_class for e in non_user_errors})@@ -364,6 +453,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):"error_message",f"{len(non_user_errors)} export(s) failed: {', '.join(distinct_classes)}",)+ asset_failure_summary = _summarize_export_failure_details(non_user_errors)# Generate LLM change summary (best-effort, skip if not enabled).# Reads content_snapshot back from Postgres — persisted inline by@@ -399,6 +489,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):if temporalio.workflow.patched("subscription-delivery-campaign-v2")else deliver_subscription)+ failure_stage = SubscriptionFailureStage.DELIVERYdeliver_result: DeliverSubscriptionResult = await temporalio.workflow.execute_activity(delivery_activity,DeliverSubscriptionInputs(@@ -438,6 +529,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):recipient_results = details[0].get("recipient_results")if isinstance(recipient_results, list):delivery_recipient_results = recipient_results+ _record_subscription_failure(inputs.slo, failure_stage, e)caught_error = efinal_status = DeliveryStatus.FAILED# Defer the re-raise until after the finally block — see note below.@@ -464,11 +556,12 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):start_to_close_timeout=dt.timedelta(minutes=2),retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,)- except Exception:+ except Exception as update_error:temporalio.workflow.logger.exception("update_delivery_record failed (delivery history is best-effort when a prior error exists)")if caught_error is None:+ _record_subscription_failure(inputs.slo, SubscriptionFailureStage.RECORD_UPDATE, update_error)raisedelivery_failed_without_exception = bool(delivery_recipient_results) and all(@@ -497,23 +590,39 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):# The activity itself no-ops when the subscription is disabled, so a# just-auto-disabled sub doesn't get a misleading future delivery date.if inputs.trigger_type == SubscriptionTriggerType.SCHEDULED:- await temporalio.workflow.execute_activity(- advance_next_delivery_date,- inputs.subscription_id,- start_to_close_timeout=dt.timedelta(minutes=2),- retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,- )+ try:+ await temporalio.workflow.execute_activity(+ advance_next_delivery_date,+ inputs.subscription_id,+ start_to_close_timeout=dt.timedelta(minutes=2),+ retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,+ )+ except Exception as schedule_error:+ temporalio.workflow.logger.exception(+ "advance_next_delivery_date failed (schedule update is best-effort when a prior error exists)"+ )+ if caught_error is None:+ _record_subscription_failure(+ inputs.slo, SubscriptionFailureStage.SCHEDULE_UPDATE, schedule_error+ )+ raise# Enrich SLO event with per-insight detail (non-user errors only).if inputs.slo:+ if caught_error is None and asset_failure_summary is not None:+ inputs.slo.completion_properties.update(asset_failure_summary)inputs.slo.completion_properties.update({"assets_with_content": assets_with_content,"total_assets": total_assets,"asset_errors": [- {"error_type": e.exception_class, "error_trace": e.error_trace}+ {+ "error_type": e.exception_class,+ "error_trace": e.error_trace,+ **(e.failure_details or {}),+ }for e in asset_errors- if not is_user_query_error_type(e.exception_class)+ if not is_user_query_export_error(e)],})@@ -545,6 +654,7 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):final_status = DeliveryStatus.SKIPPEDdelivery_recipient_results: list[dict] = []caught_error: BaseException | None = None+ failure_stage = SubscriptionFailureStage.DELIVERY_RECORD# 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 = None@@ -567,6 +677,7 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):# Up-front validation: already-disabled (idempotency redispatch) or a# permanently broken target (e.g. unsupported target_type) auto-disables and# short-circuits before any LLM cost.+ failure_stage = SubscriptionFailureStage.VALIDATIONabort_info = await temporalio.workflow.execute_activity(validate_subscription_for_delivery,inputs.subscription_id,@@ -584,6 +695,7 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):# Phase 1: generate the report. Consent is gated inside, before any LLM cost.# The markdown is persisted onto the delivery row (read back by delivery),# never returned on the wire — it can exceed Temporal's ~2 MiB payload cap.+ failure_stage = SubscriptionFailureStage.REPORT_GENERATIONgenerate_result = await temporalio.workflow.execute_activity(generate_ai_subscription_report,GenerateAIReportInputs(subscription_id=inputs.subscription_id, delivery_id=delivery_id),@@ -615,6 +727,7 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):if temporalio.workflow.patched("subscription-delivery-campaign-v2")else deliver_subscription)+ failure_stage = SubscriptionFailureStage.DELIVERYdeliver_result = await temporalio.workflow.execute_activity(delivery_activity,DeliverSubscriptionInputs(@@ -651,6 +764,7 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):recipient_results = details[0].get("recipient_results")if isinstance(recipient_results, list):delivery_recipient_results = recipient_results+ _record_subscription_failure(inputs.slo, failure_stage, e)caught_error = efinal_status = DeliveryStatus.FAILED@@ -671,11 +785,12 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):start_to_close_timeout=dt.timedelta(minutes=2),retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,)- except Exception:+ except Exception as update_error:temporalio.workflow.logger.exception("update_delivery_record failed (delivery history is best-effort when a prior error exists)")if caught_error is None:+ _record_subscription_failure(inputs.slo, SubscriptionFailureStage.RECORD_UPDATE, update_error)raiseif (@@ -701,12 +816,22 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):# no-ops when the subscription is disabled, so a just-auto-disabled sub# doesn't get a misleading future delivery date.if inputs.trigger_type == SubscriptionTriggerType.SCHEDULED:- await temporalio.workflow.execute_activity(- advance_next_delivery_date,- inputs.subscription_id,- start_to_close_timeout=dt.timedelta(minutes=2),- retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,- )+ try:+ await temporalio.workflow.execute_activity(+ advance_next_delivery_date,+ inputs.subscription_id,+ start_to_close_timeout=dt.timedelta(minutes=2),+ retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,+ )+ except Exception as schedule_error:+ temporalio.workflow.logger.exception(+ "advance_next_delivery_date failed (schedule update is best-effort when a prior error exists)"+ )+ if caught_error is None:+ _record_subscription_failure(+ inputs.slo, SubscriptionFailureStage.SCHEDULE_UPDATE, schedule_error+ )+ raise# Auto-disable aborts (consent revoked / prompt invalid) return normally rather# than raising, so they record delivery status FAILED but keep the SLO outcome