:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(exports): match the stuck-export threshold to each render pipeline (#83400)
Kim Svatos Dugan864135fe383e
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.pyindex c0f2805f655b..5b068b7d386b 100644--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py@@ -54,8 +54,7 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResullogger.warning("rasterize.malformed_session_recording_id", asset_id=exported_asset_id)raise ValueError(f"ExportedAsset {exported_asset_id} has a malformed session_recording_id")- format_map = {"video/webm": "webm", "video/mp4": "mp4", "image/gif": "gif"}- output_format = format_map.get(asset.export_format, "mp4")+ output_format = ExportedAsset.RASTERIZED_FORMATS.get(asset.export_format, "mp4")s3_key_prefix = f"{settings.OBJECT_STORAGE_EXPORTS_FOLDER}/{output_format}/team-{asset.team_id}/task-{asset.id}"diff --git a/posthog/temporal/session_replay/rasterize_recording/types.py b/posthog/temporal/session_replay/rasterize_recording/types.pyindex ab2bc3eda35d..1c988b7a37d4 100644--- a/posthog/temporal/session_replay/rasterize_recording/types.py+++ b/posthog/temporal/session_replay/rasterize_recording/types.py@@ -9,6 +9,12 @@ from pydantic import BaseModel, model_validatorRASTERIZE_RENDER_TIMEOUT = timedelta(minutes=30)RASTERIZE_RENDER_MAX_ATTEMPTS = 2+# Envelope for the whole workflow: the render's retry budget plus room for the prep and finalize+# activities and queue wait. The exports API uses this both as the workflow's execution_timeout and+# as the age at which it reports an export stuck, so the two can't drift and start calling a render+# that is still legitimately working a failure.+RASTERIZE_WORKFLOW_TIMEOUT = RASTERIZE_RENDER_TIMEOUT * RASTERIZE_RENDER_MAX_ATTEMPTS + timedelta(minutes=15)+class RasterizeRecordingInputs(BaseModel, frozen=True):"""Input to the RasterizeRecordingWorkflow."""diff --git a/products/exports/backend/api/exports.py b/products/exports/backend/api/exports.pyindex 0013e2fc20bf..f268417f7f48 100644--- a/products/exports/backend/api/exports.py+++ b/products/exports/backend/api/exports.py@@ -32,7 +32,10 @@ from posthog.slo.types import SloArea, SloConfig, SloOperationfrom posthog.temporal.common.client import async_connectfrom posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEYfrom posthog.temporal.exports.workflows import ExportAssetWorkflow, ExportAssetWorkflowInputs-from posthog.temporal.session_replay.rasterize_recording.types import RasterizeRecordingInputs+from posthog.temporal.session_replay.rasterize_recording.types import (+ RASTERIZE_WORKFLOW_TIMEOUT,+ RasterizeRecordingInputs,+)from products.exports.backend.facade.api import EXPORT_WORKFLOW_TIMEOUTfrom products.exports.backend.models.exported_asset import (@@ -58,6 +61,37 @@ def get_full_video_exports_limit_for_organization(organization: Organization | Nlogger = structlog.get_logger(__name__)+STUCK_EXPORT_MESSAGE = "Export failed without throwing an exception. Please try to rerun this export and contact support if it fails to complete multiple times."++# Slack on top of a pipeline's envelope before we call an export stuck, so a render finishing right+# at its deadline isn't reported as a failure.+_STUCK_EXPORT_GRACE = timedelta(seconds=30)+++def stuck_export_threshold(instance: ExportedAsset) -> timedelta:+ """How long an export may sit without content before nothing can still be working on it.++ Matched to whichever pipeline renders the format: video renders get the rasterize workflow's+ envelope, dataset exports the export workflow's, and everything else the HogQL query timeout it+ inherits from the Celery exporter.+ """+ if instance.is_rasterized_export:+ return RASTERIZE_WORKFLOW_TIMEOUT+ if instance.is_dataset_export:+ return EXPORT_WORKFLOW_TIMEOUT+ return timedelta(seconds=HOGQL_INCREASED_MAX_EXECUTION_TIME)+++def is_stuck_export(instance: ExportedAsset) -> bool:+ """No content, no recorded exception, and past the point its pipeline could still be rendering.++ Nothing will ever mark these failed on their own — whatever was rendering them died without+ writing a reason back to the row.+ """+ if instance.has_content or instance.exception:+ return False+ return instance.created_at < now() - stuck_export_threshold(instance) - _STUCK_EXPORT_GRACE+class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):"""Standard ExportedAsset serializer that doesn't return content."""@@ -88,39 +122,17 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Moderead_only_fields = ["id", "created_at", "has_content", "filename", "expires_after", "exception"]def to_representation(self, instance):- """Override to show stuck exports as having an exception."""+ """Override to show stuck exports as having an exception.++ Must stay free of side effects. A stuck export reads as stuck on every serialization of the+ row, so anything emitted here — an analytics event, a write — repeats for the life of the+ asset and on every poll of the list. Terminal state is recorded once, by whichever pipeline+ fails the export.+ """data = super().to_representation(instance)- timeout = (- EXPORT_WORKFLOW_TIMEOUT- if instance.is_dataset_export- else timedelta(seconds=HOGQL_INCREASED_MAX_EXECUTION_TIME)- )- timeout_threshold = now() - timeout - timedelta(seconds=30)- if (- timeout_threshold- and instance.created_at < timeout_threshold- and not instance.has_content- and not instance.exception- ):- timeout_message = f"Export failed without throwing an exception. Please try to rerun this export and contact support if it fails to complete multiple times."- data["exception"] = timeout_message-- distinct_id = (- self.context["request"].user.distinct_id- if "request" in self.context and self.context["request"].user- else str(instance.team.uuid)- )- posthoganalytics.capture(- distinct_id=distinct_id,- event="export timeout error returned",- properties={- **instance.get_analytics_metadata(),- "timeout_message": timeout_message,- "stuck_duration_seconds": (now() - instance.created_at).total_seconds(),- },- groups=groups(instance.team.organization, instance.team),- )+ if is_stuck_export(instance):+ data["exception"] = STUCK_EXPORT_MESSAGEreturn data@@ -147,7 +159,7 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Mode# Check full video export limit for team (video session recording exports)export_format = data.get("export_format")- is_full_video_export = export_format in ("video/mp4", "video/webm", "image/gif") and export_context.get(+ is_full_video_export = export_format in ExportedAsset.RASTERIZED_FORMATS and export_context.get("session_recording_id")@@ -159,7 +171,7 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Modeexisting_full_video_exports_count = (ExportedAsset.objects.filter(team_id=self.context["team_id"],- export_format__in=["video/mp4", "video/webm", "image/gif"],+ export_format__in=list(ExportedAsset.RASTERIZED_FORMATS),export_context__session_recording_id__isnull=False,created_at__gte=start_of_month,)@@ -269,7 +281,7 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Mode)if not force_async:- if instance.export_format in ("video/mp4", "video/webm", "image/gif"):+ if instance.is_rasterized_export:# recordings-onlyif not (instance.export_context and instance.export_context.get("session_recording_id")):raise serializers.ValidationError(@@ -290,7 +302,7 @@ class ExportedAssetSerializer(UserAccessControlSerializerMixin, serializers.Modetask_queue=settings.SESSION_REPLAY_TASK_QUEUE,retry_policy=RetryPolicy(maximum_attempts=int(TEMPORAL_WORKFLOW_MAX_ATTEMPTS)),id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,- execution_timeout=timedelta(hours=1),+ execution_timeout=RASTERIZE_WORKFLOW_TIMEOUT,search_attributes=TypedSearchAttributes(search_attributes=[SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=team.id),diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.pyindex bcf75f4c2b9e..e2e2480b8ca5 100644--- a/products/exports/backend/api/test/test_exports.py+++ b/products/exports/backend/api/test/test_exports.py@@ -32,6 +32,7 @@ from posthog.settings import (OBJECT_STORAGE_SECRET_ACCESS_KEY,)from posthog.tasks import exporter+from posthog.temporal.session_replay.rasterize_recording.types import RASTERIZE_WORKFLOW_TIMEOUTfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile@@ -744,26 +745,68 @@ class TestExports(APIBaseTest):self.assertIsNone(recent_export.exception)self.assertIsNone(completed_export.exception)+ DATASET_EXPORT_CONTEXT = {+ "kind": DATASET_EXPORT_KIND,+ "dataset_id": "302b0ee8-18a2-45d1-91a9-1a347853f6e5",+ "dataset_revision": 1,+ }+ VIDEO_EXPORT_CONTEXT = {"session_recording_id": "01890a0e-0000-0000-0000-000000000000"}+@parameterized.expand([+ # A png still answers to the HogQL query timeout it inherits from the Celery exporter.(- "standard_export_timeout",+ "png_past_query_timeout",+ ExportedAsset.ExportFormat.PNG,+ None,+ timedelta(seconds=HOGQL_INCREASED_MAX_EXECUTION_TIME + 31),+ True,+ ),+ (+ "dataset_within_workflow_timeout",+ ExportedAsset.ExportFormat.JSONL,+ DATASET_EXPORT_CONTEXT,timedelta(seconds=HOGQL_INCREASED_MAX_EXECUTION_TIME + 31),False,),- ("dataset_workflow_timeout", EXPORT_WORKFLOW_TIMEOUT + timedelta(seconds=31), True),+ (+ "dataset_past_workflow_timeout",+ ExportedAsset.ExportFormat.JSONL,+ DATASET_EXPORT_CONTEXT,+ EXPORT_WORKFLOW_TIMEOUT + timedelta(seconds=31),+ True,+ ),+ # A video render legitimately runs well past the query timeout, so measuring it against+ # that timeout reports long recordings as failed while they are still rendering.+ (+ "video_within_workflow_timeout",+ ExportedAsset.ExportFormat.MP4,+ VIDEO_EXPORT_CONTEXT,+ timedelta(seconds=HOGQL_INCREASED_MAX_EXECUTION_TIME + 31),+ False,+ ),+ (+ "video_past_workflow_timeout",+ ExportedAsset.ExportFormat.MP4,+ VIDEO_EXPORT_CONTEXT,+ RASTERIZE_WORKFLOW_TIMEOUT + timedelta(seconds=31),+ True,+ ),])- def test_list_uses_the_dataset_workflow_timeout(self, _name, age: timedelta, expected_failed: bool) -> None:+ def test_stuck_threshold_matches_the_rendering_pipeline(+ self,+ _name,+ export_format: str,+ export_context: Optional[dict],+ age: timedelta,+ expected_failed: bool,+ ) -> None:with freeze_time(now() - age):- dataset_export = ExportedAsset.objects.create(+ export = ExportedAsset.objects.create(team=self.team,- export_format=ExportedAsset.ExportFormat.JSONL,- export_context={- "kind": DATASET_EXPORT_KIND,- "dataset_id": "302b0ee8-18a2-45d1-91a9-1a347853f6e5",- "dataset_revision": 1,- },+ export_format=export_format,+ export_context=export_context,created_by=self.user,)@@ -771,7 +814,28 @@ class TestExports(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)results_by_id = {result["id"]: result for result in response.json()["results"]}- self.assertEqual(results_by_id[dataset_export.id]["exception"] is not None, expected_failed)+ self.assertEqual(results_by_id[export.id]["exception"] is not None, expected_failed)++ def test_listing_stuck_exports_emits_no_analytics_events(self) -> None:+ """Reporting stuck exports is a read path, so polling the list must not emit events.++ An event emitted while serializing fires once per asset per request for as long as the row+ stays incomplete, so the count reflects how often clients poll rather than how many exports+ failed.+ """+ with freeze_time(now() - RASTERIZE_WORKFLOW_TIMEOUT - timedelta(minutes=1)):+ ExportedAsset.objects.create(+ team=self.team,+ export_format=ExportedAsset.ExportFormat.MP4,+ export_context=self.VIDEO_EXPORT_CONTEXT,+ created_by=self.user,+ )++ with patch("posthoganalytics.capture") as mock_capture:+ response = self.client.get(f"/api/projects/{self.team.id}/exports")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([call for call in mock_capture.call_args_list if "export" in str(call)], [])def test_retrieve_shows_stuck_export_as_failed_in_response(self) -> None:with freeze_time(now() - timedelta(seconds=2 * HOGQL_INCREASED_MAX_EXECUTION_TIME)):diff --git a/products/exports/backend/models/exported_asset.py b/products/exports/backend/models/exported_asset.pyindex d10b6d8be9f2..f265739858e7 100644--- a/products/exports/backend/models/exported_asset.py+++ b/products/exports/backend/models/exported_asset.py@@ -85,6 +85,14 @@ class ExportedAsset(models.Model):ExportFormat.JSONL,]+ # Formats rendered by the Temporal rasterizer (headless Chromium replaying the recording) rather+ # than the browserless image/CSV path. Values are the ffmpeg output format each one renders to.+ RASTERIZED_FORMATS: dict[str, str] = {+ ExportFormat.MP4: "mp4",+ ExportFormat.WEBM: "webm",+ ExportFormat.GIF: "gif",+ }+# Relationsteam = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE, null=True)@@ -199,6 +207,12 @@ class ExportedAsset(models.Model):and (self.export_context or {}).get("kind") == DATASET_EXPORT_KIND)+ @property+ def is_rasterized_export(self) -> bool:+ """Rendered by the rasterize-recording Temporal workflow, so it lives under that workflow's+ timing envelope rather than the query/screenshot timeouts the other formats inherit."""+ return self.export_format in self.RASTERIZED_FORMATS+@propertydef is_session_recording_export(self) -> bool:"""Teammates may retrieve by id if they can view the linked session recording."""