: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(replay): mark recording exports failed instead of leaving them running (#64999)
Paul D'Ambra5e11f990a83f
diff --git a/posthog/temporal/session_replay/export_recording/__init__.py b/posthog/temporal/session_replay/export_recording/__init__.pyindex 9ba77d9c7908..fb1b8aba5f53 100644--- a/posthog/temporal/session_replay/export_recording/__init__.py+++ b/posthog/temporal/session_replay/export_recording/__init__.py@@ -5,6 +5,7 @@ from posthog.temporal.session_replay.export_recording.activities import (export_recording_data,export_recording_data_prefix,export_replay_clickhouse_rows,+ mark_export_failed,store_export_data,)from posthog.temporal.session_replay.export_recording.workflow import ExportRecordingWorkflow@@ -20,5 +21,6 @@ EXPORT_RECORDING_ACTIVITIES = [export_recording_data,export_recording_data_prefix,export_replay_clickhouse_rows,+ mark_export_failed,store_export_data,]diff --git a/posthog/temporal/session_replay/export_recording/activities.py b/posthog/temporal/session_replay/export_recording/activities.pyindex d81a2a4aa5c1..2a670d9c17ad 100644--- a/posthog/temporal/session_replay/export_recording/activities.py+++ b/posthog/temporal/session_replay/export_recording/activities.py@@ -2,11 +2,12 @@ import jsonimport uuidimport base64import shutil-from datetime import datetime+from datetime import datetime, timedeltafrom pathlib import Pathfrom uuid import uuid4from django.conf import settings+from django.utils import timezoneimport pytzfrom temporalio import activity@@ -21,12 +22,23 @@ from posthog.session_recordings.session_recording_v2_service import fetch_blocksfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.logger import get_write_only_logger-from posthog.temporal.session_replay.export_recording.types import ExportContext, ExportRecordingInput, RedisConfig+from posthog.temporal.session_replay.export_recording.types import (+ ExportContext,+ ExportRecordingInput,+ MarkExportFailedInput,+ RedisConfig,+)from products.replay.backend.models.exported_recording import ExportedRecordingLOGGER = get_write_only_logger()+# Set safely beyond the export workflow's maximum legitimate lifetime (build 3h + parallel export+# 6h + store 6h + cleanup 3h, which a workflow-level retry can roughly double) so an actively+# running export is never reaped. Anything older is wedged (e.g. a worker died before its failure+# handler ran). We reap these opportunistically when a new export starts.+STALE_EXPORT_AFTER = timedelta(hours=48)+def _redis_url(config: RedisConfig) -> str:return config.redis_url or settings.SESSION_RECORDING_REDIS_URL@@ -42,6 +54,8 @@ async def build_recording_export_context(input: ExportRecordingInput) -> ExportClogger = LOGGER.bind()logger.info(f"Building export context for recording {input.exported_recording_id}")+ await _reap_stale_exports(logger)+export_record = (await ExportedRecording.objects.select_related("team").only("status", "session_id", "team__id")@@ -288,6 +302,51 @@ async def store_export_data(input: ExportContext) -> None:logger.info(f"Updated ExportedRecording {input.exported_recording_id} with export_location {s3_key}")+async def mark_export_failed(input: MarkExportFailedInput) -> None:+ logger = LOGGER.bind()+ logger.warning(f"Marking export {input.exported_recording_id} as failed: {input.error_message}")++ try:+ export_record = await ExportedRecording.objects.aget(id=input.exported_recording_id)+ except ExportedRecording.DoesNotExist:+ # the row was deleted while the export ran; there is nothing left to mark failed+ logger.warning(f"Export {input.exported_recording_id} no longer exists; nothing to mark failed")+ return++ if export_record.status == ExportedRecording.Status.COMPLETE:+ # a post-upload step (e.g. cleanup) can fail after the export already succeeded; never+ # flip a completed export back to failed+ logger.info(f"Export {input.exported_recording_id} already complete; not marking failed")+ return++ export_record.status = ExportedRecording.Status.FAILED+ # error messages (e.g. ClickHouse exceptions) can be very long; keep the row sane+ export_record.error_message = input.error_message[:2000]+ await database_sync_to_async(export_record.save)(update_fields=["status", "error_message"])++ logger.info(f"Marked ExportedRecording {input.exported_recording_id} as failed")+++def _mark_stale_exports_failed() -> int:+ cutoff = timezone.now() - STALE_EXPORT_AFTER+ return ExportedRecording.objects.filter(+ status__in=[ExportedRecording.Status.PENDING, ExportedRecording.Status.RUNNING],+ created_at__lt=cutoff,+ ).update(status=ExportedRecording.Status.FAILED, error_message="timed out")+++async def _reap_stale_exports(logger) -> None:+ # best-effort fallback: a worker can die before its failure handler runs, leaving a row stuck+ # in RUNNING. We have no scheduled sweep, so reap on the next export. Never let this block one.+ try:+ count = await database_sync_to_async(_mark_stale_exports_failed)()+ if count:+ logger.warning(f"Reaped {count} stale recording export(s) before starting this one")+ except Exception:+ logger.warning("Failed to reap stale exports; continuing with this export", exc_info=True)++@activity.defnasync def cleanup_export_data(input: ExportContext) -> None:logger = LOGGER.bind()diff --git a/posthog/temporal/session_replay/export_recording/types.py b/posthog/temporal/session_replay/export_recording/types.pyindex 2a089ef2d116..2a2ea49e3bc1 100644--- a/posthog/temporal/session_replay/export_recording/types.py+++ b/posthog/temporal/session_replay/export_recording/types.py@@ -19,3 +19,8 @@ class ExportContext(BaseModel):session_id: strteam_id: intredis_config: RedisConfig+++class MarkExportFailedInput(BaseModel):+ exported_recording_id: UUID+ error_message: strdiff --git a/posthog/temporal/session_replay/export_recording/workflow.py b/posthog/temporal/session_replay/export_recording/workflow.pyindex b7279f2eea9d..7e09ddbb7d40 100644--- a/posthog/temporal/session_replay/export_recording/workflow.py+++ b/posthog/temporal/session_replay/export_recording/workflow.py@@ -11,9 +11,10 @@ from posthog.temporal.session_replay.export_recording.activities import (export_recording_data,export_recording_data_prefix,export_replay_clickhouse_rows,+ mark_export_failed,store_export_data,)-from posthog.temporal.session_replay.export_recording.types import ExportRecordingInput+from posthog.temporal.session_replay.export_recording.types import ExportRecordingInput, MarkExportFailedInput@workflow.defn(name="export-recording")@@ -22,6 +23,29 @@ class ExportRecordingWorkflow(PostHogWorkflow):@workflow.runasync def run(self, input: ExportRecordingInput) -> None:+ try:+ await self._export(input)+ except Exception as e:+ # the export status is set to RUNNING up front and only flipped to COMPLETE on the+ # happy path. Without this, a failed/timed-out export sits in RUNNING forever. Record+ # the failure on the row, then re-raise so Temporal still marks the workflow failed.+ # asyncio.TaskGroup wraps a failing parallel activity in an ExceptionGroup whose str()+ # is generic, so surface the underlying messages instead.+ message = "; ".join(str(sub) for sub in e.exceptions) if isinstance(e, BaseExceptionGroup) else str(e)+ try:+ await workflow.execute_activity(+ mark_export_failed,+ MarkExportFailedInput(exported_recording_id=input.exported_recording_id, error_message=message),+ start_to_close_timeout=timedelta(minutes=1),+ schedule_to_close_timeout=timedelta(minutes=10),+ retry_policy=common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=5)),+ )+ except Exception:+ # don't let a failure to record the failure mask the original error+ workflow.logger.exception("Failed to mark export as failed")+ raise++ async def _export(self, input: ExportRecordingInput) -> None:export_context = await workflow.execute_activity(build_recording_export_context,input,@@ -94,13 +118,18 @@ class ExportRecordingWorkflow(PostHogWorkflow):),)- await workflow.execute_activity(- cleanup_export_data,- export_context,- start_to_close_timeout=timedelta(minutes=5),- schedule_to_close_timeout=timedelta(hours=3),- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )+ try:+ await workflow.execute_activity(+ cleanup_export_data,+ export_context,+ start_to_close_timeout=timedelta(minutes=5),+ schedule_to_close_timeout=timedelta(hours=3),+ retry_policy=common.RetryPolicy(+ maximum_attempts=2,+ initial_interval=timedelta(minutes=1),+ ),+ )+ except Exception:+ # cleanup only frees Redis keys that already carry a TTL, and it runs after the export+ # is uploaded and marked COMPLETE. A failure here must not fail an otherwise-good export.+ workflow.logger.warning("Export cleanup failed; Redis keys will expire via their TTL")diff --git a/posthog/temporal/tests/session_replay/export_recording/test_activities.py b/posthog/temporal/tests/session_replay/export_recording/test_activities.pyindex 9da7e10f4e9f..4568f28d2e49 100644--- a/posthog/temporal/tests/session_replay/export_recording/test_activities.py+++ b/posthog/temporal/tests/session_replay/export_recording/test_activities.py@@ -1,13 +1,17 @@import jsonimport base64+from datetime import timedeltafrom uuid import UUID, uuid4import pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.utils import timezone+from posthog.session_recordings.recordings.errors import BlockFetchErrorfrom posthog.session_recordings.session_recording_v2_service import RecordingBlockfrom posthog.temporal.session_replay.export_recording.activities import (+ _mark_stale_exports_failed,_redis_key,_redis_url,build_recording_export_context,@@ -16,9 +20,15 @@ from posthog.temporal.session_replay.export_recording.activities import (export_recording_data,export_recording_data_prefix,export_replay_clickhouse_rows,+ mark_export_failed,store_export_data,)-from posthog.temporal.session_replay.export_recording.types import ExportContext, ExportRecordingInput, RedisConfig+from posthog.temporal.session_replay.export_recording.types import (+ ExportContext,+ ExportRecordingInput,+ MarkExportFailedInput,+ RedisConfig,+)from products.replay.backend.models.exported_recording import ExportedRecording@@ -83,6 +93,8 @@ async def test_build_recording_export_context_success():mock_qs.select_related.assert_called_once_with("team")mock_qs.select_related.return_value.only.assert_called_once_with("status", "session_id", "team__id")mock_qs.select_related.return_value.only.return_value.aget.assert_called_once_with(id=TEST_RECORDING_ID)+ # stale exports are reaped opportunistically when a new export starts+ mock_qs.filter.assert_called_once()@pytest.mark.asyncio@@ -174,6 +186,65 @@ async def test_export_event_clickhouse_rows_success():assert call_args[0][1] == TEST_REDIS_CONFIG.redis_ttl+async def test_mark_export_failed_sets_status_and_truncated_message():+ mock_record = MagicMock()+ mock_record.save = MagicMock()++ mock_async_save = AsyncMock()++ with (+ patch("posthog.temporal.session_replay.export_recording.activities.ExportedRecording.objects") as mock_objects,+ patch("posthog.temporal.session_replay.export_recording.activities.database_sync_to_async") as mock_db_sync,+ ):+ mock_objects.aget = AsyncMock(return_value=mock_record)+ mock_db_sync.return_value = mock_async_save++ await mark_export_failed(+ MarkExportFailedInput(exported_recording_id=TEST_RECORDING_ID, error_message="x" * 5000)+ )++ mock_objects.aget.assert_called_once_with(id=TEST_RECORDING_ID)+ assert mock_record.status == ExportedRecording.Status.FAILED+ assert mock_record.error_message == "x" * 2000+ mock_db_sync.assert_called_once_with(mock_record.save)+ mock_async_save.assert_awaited_once_with(update_fields=["status", "error_message"])+++async def test_mark_export_failed_does_not_overwrite_completed_export():+ mock_record = MagicMock()+ mock_record.status = ExportedRecording.Status.COMPLETE+ mock_record.save = MagicMock()++ with (+ patch("posthog.temporal.session_replay.export_recording.activities.ExportedRecording.objects") as mock_objects,+ patch("posthog.temporal.session_replay.export_recording.activities.database_sync_to_async") as mock_db_sync,+ ):+ mock_objects.aget = AsyncMock(return_value=mock_record)+ mock_db_sync.side_effect = lambda fn: AsyncMock(return_value=fn())++ await mark_export_failed(+ MarkExportFailedInput(exported_recording_id=TEST_RECORDING_ID, error_message="cleanup blew up")+ )++ assert mock_record.status == ExportedRecording.Status.COMPLETE+ mock_db_sync.assert_not_called()+++async def test_mark_export_failed_handles_deleted_export():+ with (+ patch("posthog.temporal.session_replay.export_recording.activities.ExportedRecording.objects") as mock_objects,+ patch("posthog.temporal.session_replay.export_recording.activities.database_sync_to_async") as mock_db_sync,+ ):+ mock_objects.aget = AsyncMock(side_effect=ExportedRecording.DoesNotExist)++ await mark_export_failed(MarkExportFailedInput(exported_recording_id=TEST_RECORDING_ID, error_message="boom"))++ mock_db_sync.assert_not_called()++@pytest.mark.asyncioasync def test_export_recording_data_prefix_success():export_id = uuid4()@@ -552,3 +623,32 @@ async def test_cleanup_export_data_no_manifest():mock_redis.delete.assert_called_once()delete_args = mock_redis.delete.call_args[0]assert len(delete_args) == 4+++ "status,age_hours,expect_swept",+ [+ (ExportedRecording.Status.RUNNING, 49, True),+ (ExportedRecording.Status.PENDING, 49, True),+ # still within the export workflow's max legitimate lifetime - must not be reaped+ (ExportedRecording.Status.RUNNING, 13, False),+ (ExportedRecording.Status.PENDING, 1, False),+ (ExportedRecording.Status.COMPLETE, 49, False),+ (ExportedRecording.Status.FAILED, 49, False),+ ],+)+def test_mark_stale_exports_failed_only_sweeps_old_unfinished(team, status, age_hours, expect_swept):+ record = ExportedRecording.objects.create(team=team, session_id="s", reason="r", status=status)+ ExportedRecording.objects.filter(pk=record.pk).update(created_at=timezone.now() - timedelta(hours=age_hours))++ swept = _mark_stale_exports_failed()+ record.refresh_from_db()++ if expect_swept:+ assert swept == 1+ assert record.status == ExportedRecording.Status.FAILED+ assert record.error_message == "timed out"+ else:+ assert swept == 0+ assert record.status == statusdiff --git a/posthog/temporal/tests/session_replay/export_recording/test_workflow.py b/posthog/temporal/tests/session_replay/export_recording/test_workflow.pyindex 642af87e7a90..4bb6ac7d98a2 100644--- a/posthog/temporal/tests/session_replay/export_recording/test_workflow.py+++ b/posthog/temporal/tests/session_replay/export_recording/test_workflow.py@@ -1,7 +1,14 @@from uuid import UUID+import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from posthog.temporal.session_replay.export_recording.activities import mark_export_failed+from posthog.temporal.session_replay.export_recording.types import ExportRecordingInput, MarkExportFailedInputfrom posthog.temporal.session_replay.export_recording.workflow import ExportRecordingWorkflow+WORKFLOW = "posthog.temporal.session_replay.export_recording.workflow.workflow"+def test_export_recording_workflow_parse_inputs():result = ExportRecordingWorkflow.parse_inputs(['{"exported_recording_id": "01938a67-1234-7000-8000-000000000001"}'])@@ -24,3 +31,49 @@ def test_export_recording_workflow_parse_inputs_with_redis_config():assert result.exported_recording_id == UUID("01938a67-1234-7000-8000-000000000001")assert result.redis_config.redis_url == "redis://custom-redis:6380"assert result.redis_config.redis_ttl == 7200+++async def test_export_recording_workflow_marks_failed_on_export_error():+ recording_id = UUID("01938a67-1234-7000-8000-000000000099")+ marked: list[MarkExportFailedInput] = []++ async def fake_execute_activity(activity_fn, arg, **kwargs):+ if activity_fn is mark_export_failed:+ marked.append(arg)+ return None+ raise RuntimeError("no column 'sharded_events.properties_group_ai_large'")++ with (+ patch(f"{WORKFLOW}.execute_activity", new=AsyncMock(side_effect=fake_execute_activity)),+ patch(f"{WORKFLOW}.logger", new=MagicMock()),+ ):+ with pytest.raises(RuntimeError):+ await ExportRecordingWorkflow().run(ExportRecordingInput(exported_recording_id=recording_id))++ # the export is marked failed (not left RUNNING) with a non-empty error recorded+ assert len(marked) == 1+ assert marked[0].exported_recording_id == recording_id+ assert marked[0].error_message+++async def test_export_recording_workflow_reraises_original_when_marking_also_fails():+ recording_id = UUID("01938a67-1234-7000-8000-000000000098")+ original = RuntimeError("original export error")++ # the failure handler itself fails (e.g. DB unreachable) - this must not mask the original error+ async def fake_execute_activity(activity_fn, arg, **kwargs):+ if activity_fn is mark_export_failed:+ raise RuntimeError("could not reach the database")+ raise original++ with (+ patch(f"{WORKFLOW}.execute_activity", new=AsyncMock(side_effect=fake_execute_activity)),+ patch(f"{WORKFLOW}.logger", new=MagicMock()),+ ):+ with pytest.raises(RuntimeError) as exc_info:+ await ExportRecordingWorkflow().run(ExportRecordingInput(exported_recording_id=recording_id))++ # the original export error propagates, not the secondary marking failure+ assert exc_info.value is original