Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(exports): record why a video export failed (#83404)

Kim Svatos Dugan1cc1123655d5
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 7ba7baaac9bd..e28111a2c9a4 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -48,6 +48,7 @@ from posthog.tasks.tasks import (
clickhouse_send_license_usage,
delete_expired_delegation_invites,
delete_expired_exported_assets,
+ fail_stuck_video_exports,
find_flags_with_enriched_analytics,
ingestion_lag,
kill_stale_queued_task_runs,
@@ -805,6 +806,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="delete expired exported assets",
)
+ # Hourly rather than daily: until this runs, a dead video export still reads as in progress
+ # to whoever is waiting on it.
+ sender.add_periodic_task(
+ crontab(minute=str(randrange(0, 60))),
+ fail_stuck_video_exports.s(),
+ name="fail stuck video exports",
+ )
+
# Daily cleanup of expired onboarding delegation invites. `pre_delete` re-enables
# the delegator's onboarding, so a missed sweep strands delegators on the "waiting
# for teammate" screen forever.
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index a12487d459ca..100822a80dab 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -120,6 +120,19 @@ def delete_expired_exported_assets() -> None:
ExportedAsset.delete_expired_assets()
+@shared_task(ignore_result=True, soft_time_limit=300, time_limit=360)
+def fail_stuck_video_exports() -> None:
+ """Give up on video exports whose render workflow died without recording a reason.
+
+ The workflow records its own failures, but not the ones where it never got to run: its execution
+ timeout firing, a dispatch failure, a lost worker. Without this sweep those rows stay
+ indistinguishable from a render still in progress.
+ """
+ from products.exports.backend.stuck_exports import fail_stuck_video_exports as run_sweep
+
+ run_sweep()
+
+
@shared_task(ignore_result=True, soft_time_limit=300, time_limit=360)
@skip_team_scope_audit
def delete_expired_delegation_invites() -> None:
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index a37ec2b010b5..0142d2816b8e 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -117,6 +117,7 @@
'posthog.tasks.tasks.delete_expired_delegation_invites',
'posthog.tasks.tasks.delete_expired_exported_assets',
'posthog.tasks.tasks.demo_reset_master_team',
+ 'posthog.tasks.tasks.fail_stuck_video_exports',
'posthog.tasks.tasks.find_flags_with_enriched_analytics',
'posthog.tasks.tasks.ingestion_lag',
'posthog.tasks.tasks.kill_stale_queued_task_runs',
diff --git a/posthog/temporal/session_replay/rasterize_recording/__init__.py b/posthog/temporal/session_replay/rasterize_recording/__init__.py
index e2092a59fe87..28fe3aa6f486 100644
--- a/posthog/temporal/session_replay/rasterize_recording/__init__.py
+++ b/posthog/temporal/session_replay/rasterize_recording/__init__.py
@@ -3,6 +3,7 @@ from posthog.temporal.session_replay.rasterize_recording.activities import (
bump_stuck_counter_activity,
clear_stuck_counter_activity,
finalize_rasterization,
+ record_rasterization_failure,
)
from posthog.temporal.session_replay.rasterize_recording.workflow import RasterizeRecordingWorkflow
@@ -12,4 +13,5 @@ RASTERIZE_RECORDING_ACTIVITIES = [
finalize_rasterization,
bump_stuck_counter_activity,
clear_stuck_counter_activity,
+ record_rasterization_failure,
]
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/__init__.py b/posthog/temporal/session_replay/rasterize_recording/activities/__init__.py
index 00f7a336bb31..3e14443c3acf 100644
--- a/posthog/temporal/session_replay/rasterize_recording/activities/__init__.py
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/__init__.py
@@ -1,4 +1,5 @@
from .rasterize import build_rasterization_input, finalize_rasterization
+from .record_failure import record_rasterization_failure
from .stuck_counter import (
BumpStuckCounterInput,
bump_stuck_counter_activity,
@@ -13,4 +14,5 @@ __all__ = [
"clear_stuck_counter_activity",
"finalize_rasterization",
"read_stuck_session_ids",
+ "record_rasterization_failure",
]
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
index 7d46a3d74d02..306f4ec434d2 100644
--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from typing import Any
from django.conf import settings
from django.db import close_old_connections, transaction
@@ -7,9 +8,11 @@ import structlog
from temporalio import activity
from temporalio.exceptions import ApplicationError
+from posthog.ph_client import ph_background_capture
from posthog.session_recordings.recordings.recording_api_jwt import mint_recording_api_token, recording_api_jwt_enabled
from posthog.storage import object_storage
+from products.exports.backend.analytics import capture_export_event
from products.exports.backend.models.exported_asset import ExportedAsset, is_valid_session_recording_id
from ..types import (
@@ -33,16 +36,25 @@ logger = structlog.get_logger(__name__)
_RASTERIZE_TOKEN_TTL = RASTERIZE_RENDER_TIMEOUT * RASTERIZE_RENDER_MAX_ATTEMPTS + timedelta(hours=1)
_RENDER_FINGERPRINT_KEY = "render_fingerprint"
+
+# Fields cleared when a render succeeds, so a row that failed and was re-rendered doesn't keep
+# showing the old reason next to its content.
+_FAILURE_FIELDS = ["exception", "exception_type", "failure_type"]
_PERSISTED_OUTPUT_FIELDS: frozenset[str] = frozenset(
{"video_duration_s", "playback_speed", "truncated", "file_size_bytes", "inactivity_periods"}
)
+def report_export_event(asset: ExportedAsset, event: str, **properties: Any) -> None:
+ """Report an export lifecycle event through the client suited to a long-lived worker."""
+ capture_export_event(asset, event, ph_background_capture(), **properties)
+
+
@activity.defn
def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResult:
close_old_connections()
- asset = ExportedAsset.objects.get(pk=exported_asset_id)
+ asset = ExportedAsset.objects.select_related("team__organization", "created_by").get(pk=exported_asset_id)
ctx = asset.export_context or {}
session_id = ctx.get("session_recording_id")
@@ -123,8 +135,21 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResul
cached = _try_synthesize_cached_output(asset, ctx, fingerprint)
if cached is not None:
+ # A cache hit returns straight to the workflow without reaching finalize_rasterization, so
+ # this is the only place it can report an outcome. Both events fire so started/succeeded
+ # counts stay comparable.
+ report_export_event(asset, "export started", cached=True)
+ report_export_event(asset, "export succeeded", cached=True)
return BuildRasterizationResult(cached_output=cached, render_fingerprint=fingerprint)
+ report_export_event(
+ asset,
+ "export started",
+ playback_speed=playback_speed,
+ recording_fps=recording_fps,
+ output_format=output_format,
+ )
+
return BuildRasterizationResult(activity_input=activity_input, render_fingerprint=fingerprint)
@@ -177,7 +202,11 @@ def finalize_rasterization(inputs: FinalizeRasterizationInput) -> None:
# Row lock serializes the JSONB read-modify-write against prep_session_video_asset_activity.
with transaction.atomic():
- asset = ExportedAsset.objects.select_for_update().get(pk=inputs.exported_asset_id)
+ asset = (
+ ExportedAsset.objects.select_related("team__organization", "created_by")
+ .select_for_update(of=("self",))
+ .get(pk=inputs.exported_asset_id)
+ )
asset.content_location = result.s3_uri[len(prefix) :]
if asset.export_context is None:
@@ -195,7 +224,11 @@ def finalize_rasterization(inputs: FinalizeRasterizationInput) -> None:
)
asset.export_context[_RENDER_FINGERPRINT_KEY] = inputs.render_fingerprint
- asset.save(update_fields=["content_location", "export_context"])
+ asset.exception = None
+ asset.exception_type = None
+ asset.failure_type = None
+
+ asset.save(update_fields=["content_location", "export_context", *_FAILURE_FIELDS])
logger.info(
"rasterization_finalized",
@@ -205,3 +238,13 @@ def finalize_rasterization(inputs: FinalizeRasterizationInput) -> None:
file_size_bytes=result.file_size_bytes,
render_fingerprint=inputs.render_fingerprint,
)
+
+ report_export_event(
+ asset,
+ "export succeeded",
+ cached=False,
+ duration_ms=round(result.timings.total_s * 1000, 2),
+ video_duration_s=result.video_duration_s,
+ file_size_bytes=result.file_size_bytes,
+ truncated=result.truncated,
+ )
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/record_failure.py b/posthog/temporal/session_replay/rasterize_recording/activities/record_failure.py
new file mode 100644
index 000000000000..c314a2db0362
--- /dev/null
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/record_failure.py
@@ -0,0 +1,58 @@
+from django.db import close_old_connections
+
+import structlog
+from temporalio import activity
+
+from products.exports.backend.models.exported_asset import ExportedAsset
+from products.exports.backend.tasks.failure_handler import (
+ FAILURE_TYPE_USER,
+ classify_rasterization_failure,
+ rasterization_failure_message,
+)
+
+from ..types import RecordRasterizationFailureInput
+from .rasterize import report_export_event
+
+logger = structlog.get_logger(__name__)
+
+
+def record_rasterization_failure(inputs: RecordRasterizationFailureInput) -> None:
+ """Persist why a render failed and report it, so the asset is a terminal state rather than a gap.
+
+ Without this the row keeps `has_content=False` and no exception forever, which reads identically
+ to a render that is still working.
+ """
+ close_old_connections()
+
+ asset = ExportedAsset.objects.select_related("team__organization", "created_by").get(pk=inputs.exported_asset_id)
+
+ if asset.exception:
+ # Keep the first reason recorded. A later sweep or retry has less information than whichever
+ # attempt actually saw the failure.
+ return
+
+ failure_type = classify_rasterization_failure(inputs.error_code)
+
+ asset.exception = rasterization_failure_message(inputs.error_code)
+ asset.exception_type = inputs.error_code
+ asset.failure_type = failure_type
+ asset.save(update_fields=["exception", "exception_type", "failure_type"])
+
+ logger.warning(
+ "rasterization_failed",
+ asset_id=asset.id,
+ error_code=inputs.error_code,
+ failure_type=failure_type,
+ error_message=inputs.error_message,
+ )
+
+ report_export_event(
+ asset,
+ "export failed",
+ error=inputs.error_message,
+ error_code=inputs.error_code,
+ failure_type=failure_type,
+ # Named to match what the other export formats report, so failures compare across all of them.
+ is_user_error=failure_type == FAILURE_TYPE_USER,
+ )
diff --git a/posthog/temporal/session_replay/rasterize_recording/types.py b/posthog/temporal/session_replay/rasterize_recording/types.py
index 2a14e67cd324..e53659ebaa43 100644
--- a/posthog/temporal/session_replay/rasterize_recording/types.py
+++ b/posthog/temporal/session_replay/rasterize_recording/types.py
@@ -96,6 +96,19 @@ class FinalizeRasterizationInput(BaseModel, frozen=True):
render_fingerprint: str
+class RecordRasterizationFailureInput(BaseModel, frozen=True):
+ """The renderer's own error code and message, resolved in the workflow before the activity runs.
+
+ The code is the rasterizer's `RasterizationErrorCode`, which Temporal carries as the failure
+ type. Without persisting it the reason lives only in workflow history, where neither the user nor
+ a failure-rate breakdown can reach it.
+ """
+
+ exported_asset_id: int
+ error_code: str
+ error_message: str
+
+
# Output destination fields — excluded so bucket/prefix changes don't invalidate caches.
# recording_api_token is per-run and ephemeral, so it must never participate in the cache key.
_FINGERPRINT_EXCLUDE: set[str] = {"team_id", "session_id", "s3_bucket", "s3_key_prefix", "recording_api_token"}
diff --git a/posthog/temporal/session_replay/rasterize_recording/workflow.py b/posthog/temporal/session_replay/rasterize_recording/workflow.py
index 2c1c233b7484..2b893699d8e6 100644
--- a/posthog/temporal/session_replay/rasterize_recording/workflow.py
+++ b/posthog/temporal/session_replay/rasterize_recording/workflow.py
@@ -3,6 +3,10 @@ from typing import Any
import temporalio.workflow as wf
from temporalio import common
+from temporalio.exceptions import (
+ FailureError,
+ TimeoutError as TemporalTimeoutError,
+)
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY
@@ -24,12 +28,20 @@ with wf.unsafe.imports_passed_through():
["product", "task_queue"],
)
+from posthog.temporal.common.errors import (
+ MAX_ERROR_MESSAGE_CHARS,
+ resolve_exception_class,
+ truncate_for_temporal_payload,
+ unwrap_temporal_cause,
+)
+
from .activities import (
BumpStuckCounterInput,
build_rasterization_input,
bump_stuck_counter_activity,
clear_stuck_counter_activity,
finalize_rasterization,
+ record_rasterization_failure,
)
from .types import (
RASTERIZE_RENDER_MAX_ATTEMPTS,
@@ -38,8 +50,28 @@ from .types import (
FinalizeRasterizationInput,
RasterizationActivityOutput,
RasterizeRecordingInputs,
+ RecordRasterizationFailureInput,
)
+# Gates the failure-recording activity added to the except branch. In-flight executions recorded
+# their history without it, so replaying them against an unconditional call fails as non-determinism.
+_RECORD_FAILURE_PATCH = "rasterize-record-failure-2026-08"
+
+
+def _resolve_error_code(exc: BaseException) -> str:
+ """The code recorded onto the asset when the renderer produced none of its own.
+
+ A render activity killed by a heartbeat or start-to-close timeout (lost or wedged worker) has no
+ ApplicationError in its cause chain, only Temporal's TimeoutError — without this check it would
+ classify 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)
+
def _record_outcome(counter: Counter, inputs: RasterizeRecordingInputs) -> None:
if wf.unsafe.is_replaying():
@@ -63,10 +95,12 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):
async def run(self, inputs: RasterizeRecordingInputs) -> RasterizationActivityOutput:
try:
result = await self._run(inputs)
- except Exception:
+ except Exception as exc:
# Count runs, not attempts: only the final scheduled attempt is a failed run.
if self._is_final_attempt():
_record_outcome(RASTERIZATION_FAILED_COUNTER, inputs)
+ if wf.patched(_RECORD_FAILURE_PATCH):
+ await self._record_failure(inputs, exc)
await self._maybe_bump_stuck_counter()
raise
await self._maybe_clear_stuck_counter()
@@ -83,6 +117,27 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):
max_attempts = cls._max_attempts()
return max_attempts is not None and 0 < max_attempts <= wf.info().attempt
+ async def _record_failure(self, inputs: RasterizeRecordingInputs, exc: BaseException) -> None:
+ """Write the renderer's own reason onto the asset before the workflow fails.
+
+ Swallows its own errors: losing the reason is worse than the render failing, but masking the
+ render's failure would be worse still.
+ """
+ cause = unwrap_temporal_cause(exc) or exc
+ try:
+ await wf.execute_activity(
+ record_rasterization_failure,
+ RecordRasterizationFailureInput(
+ exported_asset_id=inputs.exported_asset_id,
+ error_code=_resolve_error_code(exc),
+ error_message=truncate_for_temporal_payload(str(cause), MAX_ERROR_MESSAGE_CHARS),
+ ),
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=common.RetryPolicy(maximum_attempts=3),
+ )
+ except Exception as record_exc:
+ wf.logger.warning("rasterize.record_failure_failed", extra={"error": str(record_exc)})
+
async def _maybe_bump_stuck_counter(self) -> None:
info = wf.info()
max_attempts = self._max_attempts()
diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
index 77012da5a1f6..c14f20202fce 100644
--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
@@ -1,6 +1,7 @@
import pytest
from unittest.mock import MagicMock, patch
+from django.conf import settings
from django.test import override_settings
from parameterized import parameterized
@@ -20,11 +21,22 @@ from posthog.temporal.session_replay.rasterize_recording.types import (
compute_params_fingerprint,
)
+from products.exports.backend.models.exported_asset import ExportedAsset
+
MOCK_SETTINGS = MagicMock()
MOCK_SETTINGS.OBJECT_STORAGE_BUCKET = "posthog"
MOCK_SETTINGS.OBJECT_STORAGE_EXPORTS_FOLDER = "exports"
[email protected](autouse=True)
+def reported_events():
+ """Keeps the analytics client out of these unit tests, and exposes what would have been reported."""
+ with patch(
+ "posthog.temporal.session_replay.rasterize_recording.activities.rasterize.report_export_event"
+ ) as reporter:
+ yield reporter
+
+
def _make_asset(
pk: int = 42,
team_id: int = 1,
@@ -50,6 +62,7 @@ def _patches(asset: MagicMock, head_object_return: dict | None = None):
# finalize_rasterization wraps its read-modify-write in transaction.atomic
# + select_for_update; both need to be mockable here.
mock_qs.select_for_update.return_value.get.return_value = asset
+ mock_qs.select_related.return_value.select_for_update.return_value.get.return_value = asset
head_mock = MagicMock(return_value=head_object_return)
class _NoopAtomic:
@@ -403,6 +416,37 @@ class TestBuildRasterizationCache:
assert result.cached_output.truncated is False
assert result.cached_output.inactivity_periods == []
+ def test_cache_hit_reports_started_and_success(self, reported_events):
+ """A cache hit returns to the workflow without reaching finalize, so if it doesn't report
+ here it never reports at all, and the export looks like it never finished."""
+ asset = _make_asset(pk=50, export_context={"session_recording_id": "s1"})
+ fp = self._fingerprint_for(asset)
+ cached_asset = _make_asset(
+ pk=50,
+ export_context=self._ctx_with_render(fp),
+ content_location="exports/mp4/team-1/task-50/video.mp4",
+ )
+ # _fingerprint_for ran the activity to get the fingerprint, so drop what that reported.
+ reported_events.reset_mock()
+
+ patches, _ = _patches(cached_asset, head_object_return={"ContentLength": 99000})
+ with patches[0], patches[1], patches[2], patches[3], patches[4]:
+ build_rasterization_input(50)
+
+ assert [(call.args[1], call.kwargs.get("cached")) for call in reported_events.call_args_list] == [
+ ("export started", True),
+ ("export succeeded", True),
+ ]
+
+ def test_render_reports_started(self, reported_events):
+ asset = _make_asset(pk=42, export_context={"session_recording_id": "s1"})
+
+ patches, _ = _patches(asset)
+ with patches[0], patches[1], patches[2], patches[3], patches[4]:
+ build_rasterization_input(42)
+
+ assert [call.args[1] for call in reported_events.call_args_list] == ["export started"]
+
def test_cache_miss_when_fingerprint_differs(self):
asset = _make_asset(
pk=50,
@@ -557,7 +601,27 @@ class TestFinalizeRasterization:
assert asset.export_context["file_size_bytes"] == 12345
assert asset.export_context["session_recording_id"] == "s1"
assert asset.export_context["render_fingerprint"] == "abc1234567890def"
- asset.save.assert_called_once_with(update_fields=["content_location", "export_context"])
+ asset.save.assert_called_once_with(
+ update_fields=["content_location", "export_context", "exception", "exception_type", "failure_type"]
+ )
+ # A re-render must not leave the previous attempt's reason sitting next to fresh content.
+ assert asset.exception is None
+ assert asset.exception_type is None
+ assert asset.failure_type is None
+
+ def test_reports_success(self, reported_events):
+ asset = _make_asset(pk=42, export_context={"session_recording_id": "s1"})
+ result = self._make_result(file_size_bytes=12345)
+
+ patches, _ = _patches(asset)
+ with patches[0], patches[1], patches[2], patches[3], patches[4]:
+ finalize_rasterization(
+ FinalizeRasterizationInput(exported_asset_id=42, result=result, render_fingerprint="abc")
+ )
+
+ assert [(call.args[1], call.kwargs.get("cached")) for call in reported_events.call_args_list] == [
+ ("export succeeded", False)
+ ]
def test_wrong_s3_prefix_raises(self):
asset = _make_asset(pk=42)
@@ -583,6 +647,38 @@ class TestFinalizeRasterization:
assert asset.export_context["render_fingerprint"] == "x"
asset.save.assert_called_once()
+ @pytest.mark.django_db
+ def test_finalizes_against_a_real_database(self, team):
+ """The rest of this class mocks the ORM, so it cannot catch a query the database rejects.
+
+ The row is read with both `select_related` and `select_for_update`, and Postgres refuses a row
+ lock that reaches the nullable side of the resulting outer join.
+ """
+ asset = ExportedAsset.objects.create(
+ team=team,
+ export_format=ExportedAsset.ExportFormat.MP4,
+ export_context={"session_recording_id": "s1"},
+ exception="an earlier attempt failed",
+ exception_type="TIMEOUT",
+ failure_type="timeout_generation",
+ )
+ result = self._make_result(
+ s3_uri=f"s3://{settings.OBJECT_STORAGE_BUCKET}/exports/mp4/team-1/task-1/video.mp4",
+ )
+
+ # The activity drops stale connections because it runs in a long-lived worker; here that would
+ # close the connection holding the test's transaction open.
+ with patch("posthog.temporal.session_replay.rasterize_recording.activities.rasterize.close_old_connections"):
+ finalize_rasterization(
+ FinalizeRasterizationInput(exported_asset_id=asset.id, result=result, render_fingerprint="abc")
+ )
+
+ asset.refresh_from_db()
+ assert asset.content_location == "exports/mp4/team-1/task-1/video.mp4"
+ assert asset.exception is None
+ assert asset.exception_type is None
+ assert asset.failure_type is None
+
def test_inactivity_periods_round_trip(self):
period = InactivityPeriod(ts_from_s=1.0, ts_to_s=2.0, active=True)
as_dict = period.model_dump()
diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_record_failure.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_record_failure.py
new file mode 100644
index 000000000000..660d935015bc
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_record_failure.py
@@ -0,0 +1,89 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.temporal.session_replay.rasterize_recording.activities.record_failure import record_rasterization_failure
+from posthog.temporal.session_replay.rasterize_recording.types import RecordRasterizationFailureInput
+
+from products.exports.backend.tasks.failure_handler import (
+ FAILURE_TYPE_OTHER,
+ FAILURE_TYPE_RENDERER_UNKNOWN,
+ FAILURE_TYPE_SYSTEM,
+ FAILURE_TYPE_TIMEOUT_GENERATION,
+ FAILURE_TYPE_UNKNOWN,
+ FAILURE_TYPE_USER,
+)
+
+_MODULE = "posthog.temporal.session_replay.rasterize_recording.activities.record_failure"
+
+
+def _make_asset(exception: str | None = None) -> MagicMock:
+ asset = MagicMock()
+ asset.id = 42
+ asset.exception = exception
+ asset.save = MagicMock()
+ return asset
+
+
+def _run(asset: MagicMock, error_code: str = "TIMEOUT", error_message: str = "render timed out"):
+ mock_qs = MagicMock()
+ mock_qs.select_related.return_value.get.return_value = asset
+
+ with (
+ patch(f"{_MODULE}.ExportedAsset.objects", mock_qs),
+ patch(f"{_MODULE}.close_old_connections"),
+ patch(f"{_MODULE}.report_export_event") as reporter,
+ ):
+ record_rasterization_failure(
+ RecordRasterizationFailureInput(
+ exported_asset_id=42,
+ error_code=error_code,
+ error_message=error_message,
+ )
+ )
+ return reporter
+
+
+class TestRecordRasterizationFailure:
+ @parameterized.expand(
+ [
+ ("timeout", "TIMEOUT", FAILURE_TYPE_TIMEOUT_GENERATION),
+ ("compositor_deadlock", "BEGINFRAME_DEADLOCK", FAILURE_TYPE_TIMEOUT_GENERATION),
+ ("no_snapshots", "NO_SNAPSHOTS", FAILURE_TYPE_USER),
+ ("upload_failed", "S3_UPLOAD_UNDECODABLE_RESPONSE", FAILURE_TYPE_SYSTEM),
+ ("worker_death_timeout", "ACTIVITY_TIMEOUT", FAILURE_TYPE_TIMEOUT_GENERATION),
+ # The renderer's catch-alls have their own buckets so they can't hide in "unknown".
+ ("renderer_crash", "UNKNOWN", FAILURE_TYPE_RENDERER_UNKNOWN),
+ ("unrecognized_browser_code", "OTHER", FAILURE_TYPE_OTHER),
+ # An unmapped code must land in "unknown" rather than being absorbed into a real bucket,
+ # so a code the rasterizer adds later shows up as needing classification.
+ ("unrecognized", "SOMETHING_NEW", FAILURE_TYPE_UNKNOWN),
+ ]
+ )
+ def test_persists_the_renderers_code_and_its_classification(self, _name, error_code, expected_failure_type):
+ asset = _make_asset()
+
+ _run(asset, error_code=error_code)
+
+ assert asset.exception_type == error_code
+ assert asset.failure_type == expected_failure_type
+ asset.save.assert_called_once_with(update_fields=["exception", "exception_type", "failure_type"])
+
+ def test_records_a_message_for_the_user_not_the_raw_error(self):
+ """`exception` is rendered in the export UI, so it carries guidance and the raw text goes to
+ the event and the log instead."""
+ asset = _make_asset()
+
+ reporter = _run(asset, error_code="NO_SNAPSHOTS", error_message="[NO_SNAPSHOTS] no events for session")
+
+ assert asset.exception == "This recording has no playable data, so there is nothing to export."
+ assert reporter.call_args.kwargs["error"] == "[NO_SNAPSHOTS] no events for session"
+
+ def test_keeps_an_already_recorded_reason(self):
+ """The sweep and a later retry both reach this activity, and neither saw the actual failure."""
+ asset = _make_asset(exception="already recorded")
+
+ reporter = _run(asset)
+
+ asset.save.assert_not_called()
+ reporter.assert_not_called()
diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py
index ded9112397e2..0e84c0e10804 100644
--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py
@@ -3,12 +3,20 @@ import uuid
import pytest
import temporalio.worker
+import temporalio.workflow
from temporalio import activity
from temporalio.api.enums.v1 import IndexedValueType
from temporalio.api.operatorservice.v1 import AddSearchAttributesRequest
+from temporalio.client import WorkflowHistory
from temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttributes
+from temporalio.exceptions import (
+ ActivityError,
+ ApplicationError,
+ TimeoutError as TemporalTimeoutError,
+ TimeoutType,
+)
from temporalio.testing import WorkflowEnvironment
-from temporalio.worker import Worker
+from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY
from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import BumpStuckCounterInput
@@ -17,8 +25,17 @@ from posthog.temporal.session_replay.rasterize_recording.types import (
FinalizeRasterizationInput,
RasterizationActivityOutput,
RasterizeRecordingInputs,
+ RecordRasterizationFailureInput,
)
-from posthog.temporal.session_replay.rasterize_recording.workflow import RasterizeRecordingWorkflow
+from posthog.temporal.session_replay.rasterize_recording.workflow import RasterizeRecordingWorkflow, _resolve_error_code
+
+
+def _record_failure_into(calls: list[RecordRasterizationFailureInput]):
+ @activity.defn(name="record_rasterization_failure")
+ async def record_mocked(inputs: RecordRasterizationFailureInput) -> None:
+ calls.append(inputs)
+
+ return record_mocked
async def _register_search_attributes(env: WorkflowEnvironment) -> None:
@@ -46,6 +63,7 @@ def _search_attributes(team_id: int = 7, session_id: str = "sess-123") -> TypedS
@pytest.mark.asyncio
async def test_terminal_failure_bumps_stuck_counter():
bump_calls: list[BumpStuckCounterInput] = []
+ record_calls: list[RecordRasterizationFailureInput] = []
@activity.defn(name="build_rasterization_input")
async def build_failing(_exported_asset_id: int) -> BuildRasterizationResult:
@@ -66,7 +84,7 @@ async def test_terminal_failure_bumps_stuck_counter():
env.client,
task_queue=task_queue,
workflows=[RasterizeRecordingWorkflow],
- activities=[build_failing, finalize_unused, bump_mocked],
+ activities=[build_failing, finalize_unused, bump_mocked, _record_failure_into(record_calls)],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
with pytest.raises(Exception):
@@ -81,6 +99,77 @@ async def test_terminal_failure_bumps_stuck_counter():
)
assert bump_calls == [BumpStuckCounterInput(team_id=7, session_id="sess-123")]
+ # The code has to come off the wrapped cause, not the ActivityError Temporal raises here.
+ # Reading the wrapper would classify every video failure identically.
+ assert [(call.exported_asset_id, call.error_code) for call in record_calls] == [(42, "RuntimeError")]
+
+
+def _scheduled_activities(history: WorkflowHistory) -> list[str]:
+ return [
+ event.activity_task_scheduled_event_attributes.activity_type.name
+ for event in history.events
+ if event.HasField("activity_task_scheduled_event_attributes")
+ ]
+
+
+async def test_failure_recording_stays_behind_its_patch(monkeypatch):
+ """A video export already running when this deploys must not gain a command mid-flight.
+
+ An execution replaying a history that predates the patch has to take the old path exactly, or it
+ dies with a non-determinism error rather than finishing. Asserting the pre-patch run schedules no
+ failure activity is what holds the gate in place: drop the gate and this run gains one.
+ """
+
+ @activity.defn(name="build_rasterization_input")
+ async def build_failing(_exported_asset_id: int) -> BuildRasterizationResult:
+ raise RuntimeError("synthetic prep failure")
+
+ @activity.defn(name="finalize_rasterization")
+ async def finalize_unused(_inputs: FinalizeRasterizationInput) -> None:
+ pass
+
+ @activity.defn(name="bump_stuck_counter_activity")
+ async def bump_noop(_inputs: BumpStuckCounterInput) -> None:
+ pass
+
+ async def _run_to_failure(env: WorkflowEnvironment, task_queue: str) -> WorkflowHistory:
+ handle = await env.client.start_workflow(
+ RasterizeRecordingWorkflow.run,
+ RasterizeRecordingInputs(exported_asset_id=42),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ search_attributes=_search_attributes(),
+ )
+ with pytest.raises(Exception):
+ await handle.result()
+ return await handle.fetch_history()
+
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ await _register_search_attributes(env)
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[RasterizeRecordingWorkflow],
+ activities=[build_failing, finalize_unused, bump_noop, _record_failure_into([])],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ # `patched` reports False against a history recorded before the patch existed.
+ monkeypatch.setattr(temporalio.workflow, "patched", lambda _patch_id: False)
+ pre_patch_history = await _run_to_failure(env, task_queue)
+ monkeypatch.undo()
+
+ patched_history = await _run_to_failure(env, task_queue)
+
+ assert "record_rasterization_failure" not in _scheduled_activities(pre_patch_history)
+ assert "record_rasterization_failure" in _scheduled_activities(patched_history)
+
+ await Replayer(
+ workflows=[RasterizeRecordingWorkflow],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ).replay_workflow(pre_patch_history)
@pytest.mark.asyncio
@@ -216,7 +305,7 @@ async def test_failure_does_not_increment_rasterization_counter():
env.client,
task_queue=task_queue,
workflows=[RasterizeRecordingWorkflow],
- activities=[build_failing, finalize_unused, bump_noop],
+ activities=[build_failing, finalize_unused, bump_noop, _record_failure_into([])],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
with pytest.raises(Exception):
@@ -253,7 +342,7 @@ async def test_bump_failure_does_not_break_workflow_failure():
env.client,
task_queue=task_queue,
workflows=[RasterizeRecordingWorkflow],
- activities=[build_failing, finalize_unused, bump_failing],
+ activities=[build_failing, finalize_unused, bump_failing, _record_failure_into([])],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
with pytest.raises(Exception):
@@ -265,3 +354,35 @@ async def test_bump_failure_does_not_break_workflow_failure():
retry_policy=RetryPolicy(maximum_attempts=1),
search_attributes=_search_attributes(),
)
+
+
+def test_resolve_error_code_maps_temporal_timeouts():
+ """A worker that dies by heartbeat or start-to-close timeout raises no ApplicationError, so
+ without the explicit TimeoutError check the asset would classify as an opaque ActivityError.
+ The TimeoutError sits directly on the raised error or one wrapper deeper depending on where
+ the deadline fired."""
+ timeout = TemporalTimeoutError("activity timed out", type=TimeoutType.START_TO_CLOSE, last_heartbeat_details=[])
+ wrapped = _activity_error()
+ wrapped.__cause__ = timeout
+
+ assert _resolve_error_code(timeout) == "ACTIVITY_TIMEOUT"
+ assert _resolve_error_code(wrapped) == "ACTIVITY_TIMEOUT"
+
+
+def test_resolve_error_code_keeps_the_renderers_own_code():
+ error = _activity_error()
+ error.__cause__ = ApplicationError("render failed", type="NO_SNAPSHOTS")
+
+ assert _resolve_error_code(error) == "NO_SNAPSHOTS"
+
+
+def _activity_error() -> ActivityError:
+ return ActivityError(
+ "activity failed",
+ scheduled_event_id=1,
+ started_event_id=1,
+ identity="worker",
+ activity_type="rasterize",
+ activity_id="1",
+ retry_state=None,
+ )
diff --git a/products/exports/backend/analytics.py b/products/exports/backend/analytics.py
new file mode 100644
index 000000000000..a363a66db5e5
--- /dev/null
+++ b/products/exports/backend/analytics.py
@@ -0,0 +1,26 @@
+from collections.abc import Callable
+from typing import Any
+
+from posthog.event_usage import groups
+
+from products.exports.backend.models.exported_asset import ExportedAsset
+
+
+def capture_export_event(
+ asset: ExportedAsset,
+ event: str,
+ capture: Callable[..., None],
+ **properties: Any,
+) -> None:
+ """Emit an export lifecycle event with the shape every export format reports.
+
+ The caller supplies `capture` because the right client depends on the process it runs in: a
+ Temporal worker has no request cycle whose end flushes the module-level client, and a Celery task
+ can exit before that client's background consumer delivers anything.
+ """
+ capture(
+ distinct_id=asset.created_by.distinct_id if asset.created_by else str(asset.team.uuid),
+ event=event,
+ properties={**asset.get_analytics_metadata(), **properties},
+ groups=groups(asset.team.organization, asset.team),
+ )
diff --git a/products/exports/backend/api/exports.py b/products/exports/backend/api/exports.py
index f268417f7f48..13fa908aa5db 100644
--- a/products/exports/backend/api/exports.py
+++ b/products/exports/backend/api/exports.py
@@ -26,7 +26,6 @@ from posthog.models.organization import Organization
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
from posthog.security.url_validation import is_url_allowed
-from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.settings.temporal import TEMPORAL_WORKFLOW_MAX_ATTEMPTS
from posthog.slo.types import SloArea, SloConfig, SloOperation
from posthog.temporal.common.client import async_connect
@@ -37,12 +36,12 @@ from posthog.temporal.session_replay.rasterize_recording.types import (
RasterizeRecordingInputs,
)
-from products.exports.backend.facade.api import EXPORT_WORKFLOW_TIMEOUT
from products.exports.backend.models.exported_asset import (
ExportedAsset,
get_content_response,
is_valid_session_recording_id,
)
+from products.exports.backend.stuck_exports import STUCK_EXPORT_MESSAGE, is_stuck_export
from products.product_analytics.backend.models.insight import Insight
# Full video exports per team per calendar month, tiered by plan.
@@ -61,37 +60,6 @@ def get_full_video_exports_limit_for_organization(organization: Organization | N
logger = 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."""
diff --git a/products/exports/backend/models/exported_asset.py b/products/exports/backend/models/exported_asset.py
index f265739858e7..8ea55a428c8e 100644
--- a/products/exports/backend/models/exported_asset.py
+++ b/products/exports/backend/models/exported_asset.py
@@ -224,6 +224,9 @@ class ExportedAsset(models.Model):
"export_format": self.export_format,
"dashboard_id": self.dashboard_id,
"insight_id": self.insight_id,
+ # Scanner-driven renders (replay_vision) report through the same pipeline; without this
+ # flag their volume is indistinguishable from user exports in failure-rate comparisons.
+ "is_system": bool(self.is_system),
}
def get_public_content_url(self, expiry_delta: Optional[timedelta] = None):
diff --git a/products/exports/backend/stuck_exports.py b/products/exports/backend/stuck_exports.py
new file mode 100644
index 000000000000..e4bae4b814d8
--- /dev/null
+++ b/products/exports/backend/stuck_exports.py
@@ -0,0 +1,105 @@
+from datetime import timedelta
+
+from django.utils.timezone import now
+
+import structlog
+
+from posthog.ph_client import ph_scoped_capture
+from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
+from posthog.temporal.session_replay.rasterize_recording.types import RASTERIZE_WORKFLOW_TIMEOUT
+
+from products.exports.backend.analytics import capture_export_event
+from products.exports.backend.facade.api import EXPORT_WORKFLOW_TIMEOUT
+from products.exports.backend.models.exported_asset import ExportedAsset
+from products.exports.backend.tasks.failure_handler import FAILURE_TYPE_TIMEOUT_GENERATION
+
+logger = 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)
+
+# Bounds one sweep so a large backlog can't hold a worker; the next run picks up the rest.
+_SWEEP_BATCH_SIZE = 500
+
+
+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
+
+
+def fail_stuck_video_exports() -> int:
+ """Record a terminal failure on video exports whose workflow died without reporting one.
+
+ The workflow's own failure path cannot cover every case. When its execution timeout fires the
+ body never runs, and a dispatch failure or a lost worker leaves no execution to run it at all.
+ Those rows otherwise stay indistinguishable from a render still in progress, for as long as they
+ exist.
+ """
+ cutoff = now() - RASTERIZE_WORKFLOW_TIMEOUT - _STUCK_EXPORT_GRACE
+ # Cross-team by design: a beat task with no request context, sweeping every team's exports.
+ stuck = (
+ ExportedAsset.objects.filter(
+ export_format__in=list(ExportedAsset.RASTERIZED_FORMATS),
+ content__isnull=True,
+ content_location__isnull=True,
+ exception__isnull=True,
+ created_at__lt=cutoff,
+ )
+ # System assets (replay_vision scanners) reuse one contentless row per session across scans,
+ # so an old created_at doesn't prove nothing is rendering it — the sweep would fail a row
+ # mid-render and its first-writer check would then suppress the renderer's real outcome.
+ # Those rows have their own expiry; a scanner re-render also retries them naturally.
+ .exclude(is_system=True)
+ .select_related("team__organization", "created_by")
+ # Oldest first, so a backlog larger than one batch drains in bounded order instead of
+ # re-sampling arbitrary rows each run.
+ .order_by("created_at")[:_SWEEP_BATCH_SIZE]
+ )
+
+ failed = 0
+ with ph_scoped_capture() as capture:
+ for asset in stuck:
+ asset.exception = STUCK_EXPORT_MESSAGE
+ # Distinct from the renderer's own TIMEOUT: this one never reported anything at all, which
+ # points at the workflow or the worker rather than at the render.
+ asset.exception_type = "WORKFLOW_TIMEOUT"
+ asset.failure_type = FAILURE_TYPE_TIMEOUT_GENERATION
+ asset.save(update_fields=["exception", "exception_type", "failure_type"])
+
+ capture_export_event(
+ asset,
+ "export failed",
+ capture,
+ error=STUCK_EXPORT_MESSAGE,
+ error_code="WORKFLOW_TIMEOUT",
+ failure_type=FAILURE_TYPE_TIMEOUT_GENERATION,
+ is_user_error=False,
+ )
+ failed += 1
+
+ if failed:
+ logger.info("stuck_video_exports_failed", count=failed)
+ return failed
diff --git a/products/exports/backend/tasks/failure_handler.py b/products/exports/backend/tasks/failure_handler.py
index 524619d74ef1..915feca6ea94 100644
--- a/products/exports/backend/tasks/failure_handler.py
+++ b/products/exports/backend/tasks/failure_handler.py
@@ -42,6 +42,8 @@ from posthog.storage.object_storage import ObjectStorageError
# - "user": Errors the user can fix by modifying their query or reducing scope
# - "system": Infrastructure/capacity errors that may resolve with retries
# - "timeout_generation": Export timed out during asset generation
+# - "renderer_unknown": The video renderer crashed with an exception it has no code for
+# - "other": The in-browser player reported an error code the renderer doesn't recognize
# - "unknown": Errors needing investigation to properly classify
#
# These tuples are authoritative. Historical rows have best-effort accuracy.
@@ -50,8 +52,62 @@ from posthog.storage.object_storage import ObjectStorageError
FAILURE_TYPE_USER = "user"
FAILURE_TYPE_SYSTEM = "system"
FAILURE_TYPE_TIMEOUT_GENERATION = "timeout_generation"
+FAILURE_TYPE_RENDERER_UNKNOWN = "renderer_unknown"
+FAILURE_TYPE_OTHER = "other"
FAILURE_TYPE_UNKNOWN = "unknown"
+# 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
+# "unknown", which is the signal to add it rather than a bucket to grow silently.
+RASTERIZATION_CODE_TO_FAILURE_TYPE: dict[str, str] = {
+ "TIMEOUT": FAILURE_TYPE_TIMEOUT_GENERATION,
+ "CAPTURE_ABORTED": FAILURE_TYPE_TIMEOUT_GENERATION,
+ "BEGINFRAME_DEADLOCK": FAILURE_TYPE_TIMEOUT_GENERATION,
+ # A property of the recording or the request rather than a fault in our infrastructure. Bucketing
+ # these as "system" would put them in front of whoever watches infra alerts.
+ "NO_SNAPSHOTS": FAILURE_TYPE_USER,
+ "INVALID_INPUT": FAILURE_TYPE_USER,
+ # Reaching the recording's data failed, which nobody exporting it can do anything about.
+ "DATA_LOAD_FAILED": FAILURE_TYPE_SYSTEM,
+ "S3_UPLOAD_UNDECODABLE_RESPONSE": FAILURE_TYPE_SYSTEM,
+ "INIT_FAILED": FAILURE_TYPE_SYSTEM,
+ "BLOCK_LISTING_FAILED": FAILURE_TYPE_SYSTEM,
+ # The render activity died without producing a code at all: heartbeat or start-to-close timeout
+ # from a lost or wedged worker. Not the renderer's own TIMEOUT, but still a render that ran out
+ # of time. Resolved in the workflow's _record_failure, not a rasterizer code.
+ "ACTIVITY_TIMEOUT": FAILURE_TYPE_TIMEOUT_GENERATION,
+ # The renderer's own catch-all codes get their own buckets so "unknown" keeps meaning exactly
+ # one thing: a code missing from this map that someone needs to add.
+ "UNKNOWN": FAILURE_TYPE_RENDERER_UNKNOWN,
+ "OTHER": FAILURE_TYPE_OTHER,
+}
+
+# Shown to whoever asked for the export, so each one says what happened and what to do next. A
+# recording with no data will never render, so telling that user to retry would send them in a loop.
+_RASTERIZATION_MESSAGES: dict[str, str] = {
+ "TIMEOUT": "This recording took too long to render. Try exporting a shorter part of it.",
+ "CAPTURE_ABORTED": "The render stopped before it finished. Try exporting a shorter part of the recording.",
+ "BEGINFRAME_DEADLOCK": "The render stopped responding. Try exporting a shorter part of the recording.",
+ "NO_SNAPSHOTS": "This recording has no playable data, so there is nothing to export.",
+ "INVALID_INPUT": "This export request was not valid. Contact support if it keeps happening.",
+ "DATA_LOAD_FAILED": "We could not load this recording's data. Try the export again in a few minutes.",
+ "S3_UPLOAD_UNDECODABLE_RESPONSE": "The finished video could not be saved. Try the export again.",
+ "INIT_FAILED": "The video renderer could not start. Try the export again.",
+ "BLOCK_LISTING_FAILED": "We could not read this recording. Try the export again in a few minutes.",
+ "ACTIVITY_TIMEOUT": "This recording took too long to render. Try exporting a shorter part of it.",
+}
+
+_RASTERIZATION_FALLBACK_MESSAGE = "The video export failed. Try again, and contact support if it keeps failing."
+
+
+def classify_rasterization_failure(error_code: str | None) -> str:
+ return RASTERIZATION_CODE_TO_FAILURE_TYPE.get(error_code or "", FAILURE_TYPE_UNKNOWN)
+
+
+def rasterization_failure_message(error_code: str | None) -> str:
+ return _RASTERIZATION_MESSAGES.get(error_code or "", _RASTERIZATION_FALLBACK_MESSAGE)
+
class ExportCancelled(Exception):
"""Raised when an export is canceled due to timeout."""
diff --git a/products/exports/backend/tests/test_stuck_exports.py b/products/exports/backend/tests/test_stuck_exports.py
new file mode 100644
index 000000000000..edc26d052ffb
--- /dev/null
+++ b/products/exports/backend/tests/test_stuck_exports.py
@@ -0,0 +1,88 @@
+from datetime import timedelta
+
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils.timezone import now
+
+from parameterized import parameterized
+
+from posthog.temporal.session_replay.rasterize_recording.types import RASTERIZE_WORKFLOW_TIMEOUT
+
+from products.exports.backend.models.exported_asset import ExportedAsset
+from products.exports.backend.stuck_exports import fail_stuck_video_exports
+from products.exports.backend.tasks.failure_handler import FAILURE_TYPE_TIMEOUT_GENERATION
+
+_PAST_ENVELOPE = RASTERIZE_WORKFLOW_TIMEOUT + timedelta(minutes=1)
+
+
+class TestFailStuckVideoExports(APIBaseTest):
+ """The workflow records its own failures, but not the ones where it never ran: its execution
+ timeout firing, a dispatch failure, a lost worker. This sweep is the only thing that closes those.
+ """
+
+ def _create(self, age: timedelta = _PAST_ENVELOPE, **overrides) -> ExportedAsset:
+ fields: dict = {
+ "team": self.team,
+ "export_format": ExportedAsset.ExportFormat.MP4,
+ "export_context": {"session_recording_id": "s1"},
+ "created_by": self.user,
+ }
+ fields.update(overrides)
+ with freeze_time(now() - age):
+ return ExportedAsset.objects.create(**fields)
+
+ def test_fails_a_video_export_whose_workflow_never_reported_back(self) -> None:
+ asset = self._create()
+
+ with patch("products.exports.backend.stuck_exports.ph_scoped_capture"):
+ self.assertEqual(fail_stuck_video_exports(), 1)
+
+ asset.refresh_from_db()
+ self.assertIsNotNone(asset.exception)
+ self.assertEqual(asset.exception_type, "WORKFLOW_TIMEOUT")
+ self.assertEqual(asset.failure_type, FAILURE_TYPE_TIMEOUT_GENERATION)
+
+ @parameterized.expand(
+ [
+ # Still inside the envelope, so the render may well be working.
+ ("within_envelope", {"age": timedelta(minutes=5)}),
+ # Already terminal, so the sweep has nothing to add and must not overwrite the reason.
+ ("already_failed", {"exception": "the renderer said why"}),
+ ("has_content_location", {"content_location": "exports/mp4/team-1/task-1/v.mp4"}),
+ ("has_inline_content", {"content": b"video bytes"}),
+ # Rendered by a different pipeline, which answers to a different deadline.
+ ("not_a_video_export", {"export_format": ExportedAsset.ExportFormat.PNG}),
+ # replay_vision reuses one contentless system row per session across scans, so an old
+ # created_at doesn't prove nothing is rendering it right now.
+ ("system_render", {"is_system": True}),
+ ]
+ )
+ def test_leaves_other_exports_alone(self, _name, overrides: dict) -> None:
+ asset = self._create(**overrides)
+ exception_before = asset.exception
+
+ with patch("products.exports.backend.stuck_exports.ph_scoped_capture"):
+ self.assertEqual(fail_stuck_video_exports(), 0)
+
+ asset.refresh_from_db()
+ self.assertEqual(asset.exception, exception_before)
+
+ def test_reports_each_export_it_fails(self) -> None:
+ self._create()
+ self._create()
+
+ with patch("products.exports.backend.stuck_exports.capture_export_event") as capture_event:
+ with patch("products.exports.backend.stuck_exports.ph_scoped_capture"):
+ fail_stuck_video_exports()
+
+ self.assertEqual([call.args[1] for call in capture_event.call_args_list], ["export failed"] * 2)
+
+ def test_does_not_report_the_same_export_twice(self) -> None:
+ """Runs hourly, so an export it already failed must drop out of the next sweep."""
+ self._create()
+
+ with patch("products.exports.backend.stuck_exports.ph_scoped_capture"):
+ self.assertEqual(fail_stuck_video_exports(), 1)
+ self.assertEqual(fail_stuck_video_exports(), 0)