: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
chore(replay): remove export-recording and import-recording workflows (#65971)
Tue Haulund43f6257a037d
diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.pyindex 8f787cba4885..ee3f941ed092 100644--- a/posthog/admin/admins/team_admin.py+++ b/posthog/admin/admins/team_admin.py@@ -4,7 +4,7 @@ import jsonimport uuidimport asyncioimport hashlib-import tempfile+import dataclassesfrom datetime import datetime, timedeltafrom decimal import Decimal, InvalidOperationfrom typing import Any@@ -33,10 +33,9 @@ from posthog.admin.inlines.organization_member_for_related_inline import Organizfrom posthog.admin.inlines.team_experiments_config_inline import TeamExperimentsConfigInlinefrom posthog.admin.inlines.team_marketing_analytics_config_inline import TeamMarketingAnalyticsConfigInlinefrom posthog.admin.inlines.user_product_list_inline import UserProductListInline-from posthog.cloud_utils import is_cloudfrom posthog.llm.gateway_internal_client import AIGatewayInternalError, AIGatewayNotConfigured, add_credit, get_walletfrom posthog.models import Team-from posthog.models.activity_logging.activity_log import Detail, log_activity+from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, log_activityfrom posthog.models.group_type_mapping import invalidate_group_types_cachefrom posthog.models.remote_config import RemoteConfigfrom posthog.models.team.team import DEPRECATED_ATTRS@@ -47,7 +46,6 @@ from posthog.personhog_client.proto import (GetGroupTypeMappingsByTeamIdRequest,UpdateGroupTypeMappingRequest,)-from posthog.session_recordings.recordings import recording_s3_clientfrom posthog.storage.gateway_credential_cache import validate_overspend_allowance_usdfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.common.search_attributes import POSTHOG_TEAM_ID_KEY@@ -59,10 +57,6 @@ from posthog.temporal.session_replay.delete_recordings.types import (RecordingsWithSessionIdsInput,RecordingsWithTeamInput,)-from posthog.temporal.session_replay.import_recording.types import ImportRecordingInput--from products.replay.backend.models.exported_recording import ExportedRecording-from products.replay.backend.services.export_recording import ReplayActivityContext, trigger_recording_exportlogger = get_logger()@@ -70,6 +64,11 @@ logger = get_logger()MAX_CREDIT_USD = Decimal("1000000")[email protected](frozen=True)+class ReplayActivityContext(ActivityContextBase):+ reason: str++class TeamAdminForm(ModelForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)@@ -137,8 +136,6 @@ class TeamAdmin(admin.ModelAdmin):"updated_at","internal_properties","remote_config_cache_actions",- "export_individual_replay",- "import_individual_replay","delete_recordings","api_token_display","admit_state",@@ -266,8 +263,6 @@ class TeamAdmin(admin.ModelAdmin):{"classes": ["collapse"],"fields": [- "export_individual_replay",- "import_individual_replay","delete_recordings",],},@@ -497,39 +492,6 @@ class TeamAdmin(admin.ModelAdmin):props.append("API_QUERIES_RATE_LIMIT_BYPASS")return format_html("<span>{}</span>", ", ".join(props) or "-")- @admin.display(description="Export individual session replay data")- def export_individual_replay(self, team: Team):- if not team.pk:- return "-"- # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)- return mark_safe(- render_to_string(- "admin/posthog/team/export_individual_replay.html",- {- "team": team,- "export_url": f"/admin/posthog/team/{team.pk}/export-replay/",- "export_history_url": f"/admin/posthog/team/{team.pk}/export-history/",- },- request=getattr(self, "_current_request", None),- )- )-- @admin.display(description="Import individual session replay data")- def import_individual_replay(self, team: Team):- if not team.pk:- return "-"- # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)- return mark_safe(- render_to_string(- "admin/posthog/team/import_individual_replay.html",- {- "team": team,- "import_url": f"/admin/posthog/team/{team.pk}/import-replay/",- },- request=getattr(self, "_current_request", None),- )- )-@admin.display(description="API token")def api_token_display(self, team: Team):if not team.pk:@@ -846,26 +808,6 @@ class TeamAdmin(admin.ModelAdmin):self.admin_site.admin_view(self.rebuild_cache),name="posthog_team_rebuild_cache",),- path(- "<path:object_id>/export-replay/",- self.admin_site.admin_view(self.export_replay_view),- name="posthog_team_export_replay",- ),- path(- "<path:object_id>/import-replay/",- self.admin_site.admin_view(self.import_replay_view),- name="posthog_team_import_replay",- ),- path(- "<path:object_id>/export-history/",- self.admin_site.admin_view(self.export_history_view),- name="posthog_team_export_history",- ),- path(- "<path:object_id>/download-export/<uuid:export_id>/",- self.admin_site.admin_view(self.download_export_view),- name="posthog_team_download_export",- ),path("<path:object_id>/set-api-token/",self.admin_site.admin_view(self.set_api_token_view),@@ -959,60 +901,6 @@ class TeamAdmin(admin.ModelAdmin):messages.success(request, f"API token updated for team '{team.name}'.")return redirect(reverse("admin:posthog_team_change", args=[object_id]))- def export_replay_view(self, request, object_id):- team = Team.objects.get(pk=object_id)-- if request.method == "GET":- context = {- **self.admin_site.each_context(request),- "team": team,- "title": f"Export Session Replay - {team.name}",- }- return render(request, "admin/posthog/team/export_replay_form.html", context)-- session_id = request.POST.get("session_id", "").strip()- reason = request.POST.get("reason", "").strip()-- if not session_id:- messages.error(request, "Session ID is required")- return redirect(reverse("admin:posthog_team_export_replay", args=[object_id]))-- if not reason:- messages.error(request, "Reason is required")- return redirect(reverse("admin:posthog_team_export_replay", args=[object_id]))-- logger.info(- "export_replay_triggered",- team_id=team.id,- session_id=session_id,- reason=reason,- triggered_by=request.user.email,- )-- try:- export_record = trigger_recording_export(- team=team,- session_id=session_id,- reason=reason,- user=request.user,- was_impersonated=False,- )-- messages.success(- request,- f"Export triggered for session '{session_id}' on team '{team.name}' by {request.user.email}. Export ID: {export_record.id}",- )- except Exception as e:- logger.exception(- "export_replay_failed",- team_id=team.id,- session_id=session_id,- error=str(e),- )- messages.error(request, f"Export failed: {e}")-- return redirect(reverse("admin:posthog_team_export_history", args=[object_id]))-def view_cache(self, request, object_id):team = Team.objects.get(pk=object_id)hypercache = RemoteConfig.get_hypercache()@@ -1042,133 +930,6 @@ class TeamAdmin(admin.ModelAdmin):self.message_user(request, f"Cache rebuilt for team '{team.name}' (token: {team.api_token})")return redirect(reverse("admin:posthog_team_change", args=[object_id]))- def import_replay_view(self, request, object_id):- if is_cloud():- messages.error(request, "Importing session replays is not allowed on cloud")- return redirect(reverse("admin:posthog_team_change", args=[object_id]))-- team = Team.objects.get(pk=object_id)-- if request.method == "GET":- context = {- **self.admin_site.each_context(request),- "team": team,- "title": f"Import Session Replay - {team.name}",- }- return render(request, "admin/posthog/team/import_replay_form.html", context)-- reason = request.POST.get("reason", "").strip()- import_file: UploadedFile | None = request.FILES.get("import_file")-- if not import_file:- messages.error(request, "Import file is required")- return redirect(reverse("admin:posthog_team_import_replay", args=[object_id]))-- if not reason:- messages.error(request, "Reason is required")- return redirect(reverse("admin:posthog_team_import_replay", args=[object_id]))-- if not import_file.name or not import_file.name.endswith(".zip"):- messages.error(request, "Import file must be a .zip file")- return redirect(reverse("admin:posthog_team_import_replay", args=[object_id]))-- logger.info(- "import_replay_triggered",- team_id=team.id,- file_name=import_file.name,- file_size=import_file.size,- reason=reason,- triggered_by=request.user.email,- )-- try:- with tempfile.NamedTemporaryFile(delete=False, suffix=".zip") as tmp_file:- for chunk in import_file.chunks():- tmp_file.write(chunk)- tmp_file_path = tmp_file.name-- temporal = sync_connect()- workflow_input = ImportRecordingInput(team_id=team.id, export_file=tmp_file_path)- workflow_id = f"import-recording-{team.id}-{uuid.uuid4()}"-- asyncio.run(- temporal.start_workflow(- "import-recording",- workflow_input,- id=workflow_id,- task_queue=settings.SESSION_REPLAY_TASK_QUEUE,- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )- )-- log_activity(- organization_id=team.organization_id,- team_id=team.id,- user=request.user,- was_impersonated=False,- item_id=None,- scope="Replay",- activity="imported",- detail=Detail(- name=f"Session replay import from {import_file.name}",- type="admin_import",- context=ReplayActivityContext(reason=reason),- ),- )-- messages.success(- request,- f"Import triggered for team '{team.name}' by {request.user.email}.",- )- except Exception as e:- logger.exception(- "import_replay_failed",- team_id=team.id,- error=str(e),- )- messages.error(request, f"Import failed: {e}")-- return redirect(reverse("admin:posthog_team_export_history", args=[object_id]))-- def export_history_view(self, request, object_id):- team = Team.objects.get(pk=object_id)-- exports = ExportedRecording.objects.filter(team=team).order_by("-created_at")[:50]-- context = {- **self.admin_site.each_context(request),- "team": team,- "exports": exports,- "title": f"Export History - {team.name}",- }- return render(request, "admin/posthog/team/export_history.html", context)-- def download_export_view(self, request, object_id, export_id):- team = Team.objects.get(pk=object_id)- try:- export = ExportedRecording.objects.get(id=export_id, team=team)-- if not export.export_location:- messages.error(request, "Export content not available yet")- return redirect(reverse("admin:posthog_team_export_history", args=[object_id]))-- content = recording_s3_client.recording_s3_client().download_file(export.export_location)-- response = HttpResponse(content, content_type="application/zip")- filename = f"export-{export.session_id}.zip"- response["Content-Disposition"] = f'attachment; filename="{filename}"'- return response-- except ExportedRecording.DoesNotExist:- messages.error(request, "Export not found")- return redirect(reverse("admin:posthog_team_export_history", args=[object_id]))- except Exception as e:- messages.error(request, f"Failed to download export: {e}")- return redirect(reverse("admin:posthog_team_export_history", args=[object_id]))-def _get_delete_workflows(self, team_id: int) -> list[dict]:"""Fetch recent delete-recordings workflows for this team from Temporal."""try:diff --git a/posthog/admin/inlines/team_inline.py b/posthog/admin/inlines/team_inline.pyindex becc373ae729..49974e2707ac 100644--- a/posthog/admin/inlines/team_inline.py+++ b/posthog/admin/inlines/team_inline.py@@ -42,8 +42,6 @@ class TeamInline(TabularInlinePaginated):if fnot in ("internal_properties",- "export_individual_replay",- "import_individual_replay","delete_recordings","remote_config_cache_actions","api_token_display",diff --git a/posthog/management/commands/execute_temporal_workflow.py b/posthog/management/commands/execute_temporal_workflow.pyindex 30e0f8a3f028..115e7975c852 100644--- a/posthog/management/commands/execute_temporal_workflow.py+++ b/posthog/management/commands/execute_temporal_workflow.py@@ -21,8 +21,6 @@ from posthog.temporal.quota_limiting import WORKFLOWS as QUOTA_LIMITING_WORKFLOWfrom posthog.temporal.salesforce_enrichment import WORKFLOWS as SALESFORCE_ENRICHMENT_WORKFLOWSfrom posthog.temporal.session_replay.delete_recordings import DELETE_RECORDINGS_WORKFLOWSfrom posthog.temporal.session_replay.enforce_max_replay_retention import ENFORCE_MAX_REPLAY_RETENTION_WORKFLOWS-from posthog.temporal.session_replay.export_recording import EXPORT_RECORDING_WORKFLOWS-from posthog.temporal.session_replay.import_recording import IMPORT_RECORDING_WORKFLOWSfrom posthog.temporal.session_replay.rasterize_recording import RASTERIZE_RECORDING_WORKFLOWSfrom posthog.temporal.session_replay.summarization_sweep import SUMMARIZATION_SWEEP_WORKFLOWSfrom posthog.temporal.session_replay.surfacing_scoring_sweep import SURFACING_SCORING_SWEEP_WORKFLOWS@@ -148,8 +146,6 @@ class Command(BaseCommand):+ TEST_WORKFLOWS+ DELETE_RECORDINGS_WORKFLOWS+ ENFORCE_MAX_REPLAY_RETENTION_WORKFLOWS- + EXPORT_RECORDING_WORKFLOWS- + IMPORT_RECORDING_WORKFLOWS+ WEEKLY_DIGEST_WORKFLOWS+ DATA_MODELING_WORKFLOWS+ LLM_ANALYTICS_WORKFLOWSdiff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex fc8410a4a952..256b78f99d4e 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -120,12 +120,10 @@ from posthog.temporal.session_replay.enforce_max_replay_retention import (ENFORCE_MAX_REPLAY_RETENTION_ACTIVITIES,ENFORCE_MAX_REPLAY_RETENTION_WORKFLOWS,)-from posthog.temporal.session_replay.export_recording import EXPORT_RECORDING_ACTIVITIES, EXPORT_RECORDING_WORKFLOWSfrom posthog.temporal.session_replay.gemini_cleanup_sweep import (GEMINI_CLEANUP_SWEEP_ACTIVITIES,GEMINI_CLEANUP_SWEEP_WORKFLOWS,)-from posthog.temporal.session_replay.import_recording import IMPORT_RECORDING_ACTIVITIES, IMPORT_RECORDING_WORKFLOWSfrom posthog.temporal.session_replay.rasterize_recording import (RASTERIZE_RECORDING_ACTIVITIES,RASTERIZE_RECORDING_WORKFLOWS,@@ -339,8 +337,6 @@ _task_queue_specs = [+ COUNT_PLAYLIST_ITEMS_WORKFLOWS+ DELETE_RECORDINGS_WORKFLOWS+ ENFORCE_MAX_REPLAY_RETENTION_WORKFLOWS- + EXPORT_RECORDING_WORKFLOWS- + IMPORT_RECORDING_WORKFLOWS+ RASTERIZE_RECORDING_WORKFLOWS+ REPLAY_COUNT_METRICS_WORKFLOWS+ SESSION_SUMMARY_WORKFLOWS@@ -351,8 +347,6 @@ _task_queue_specs = [+ COUNT_PLAYLIST_ITEMS_ACTIVITIES+ DELETE_RECORDINGS_ACTIVITIES+ ENFORCE_MAX_REPLAY_RETENTION_ACTIVITIES- + EXPORT_RECORDING_ACTIVITIES- + IMPORT_RECORDING_ACTIVITIES+ RASTERIZE_RECORDING_ACTIVITIES+ REPLAY_COUNT_METRICS_ACTIVITIES+ SESSION_SUMMARY_ACTIVITIESdiff --git a/posthog/management/commands/start_temporal_workflow.py b/posthog/management/commands/start_temporal_workflow.pyindex 71b2c251324e..257e7c6b98cc 100644--- a/posthog/management/commands/start_temporal_workflow.py+++ b/posthog/management/commands/start_temporal_workflow.py@@ -19,8 +19,6 @@ from posthog.temporal.salesforce_enrichment import WORKFLOWS as SALESFORCE_ENRICfrom posthog.temporal.session_replay.count_playlist_items import COUNT_PLAYLIST_ITEMS_WORKFLOWSfrom posthog.temporal.session_replay.delete_recordings import DELETE_RECORDINGS_WORKFLOWSfrom posthog.temporal.session_replay.enforce_max_replay_retention import ENFORCE_MAX_REPLAY_RETENTION_WORKFLOWS-from posthog.temporal.session_replay.export_recording import EXPORT_RECORDING_WORKFLOWS-from posthog.temporal.session_replay.import_recording import IMPORT_RECORDING_WORKFLOWSfrom posthog.temporal.session_replay.rasterize_recording import RASTERIZE_RECORDING_WORKFLOWSfrom posthog.temporal.session_replay.replay_count_metrics import REPLAY_COUNT_METRICS_WORKFLOWSfrom posthog.temporal.session_replay.summarization_sweep import SUMMARIZATION_SWEEP_WORKFLOWS@@ -150,8 +148,6 @@ class Command(BaseCommand):+ COUNT_PLAYLIST_ITEMS_WORKFLOWS+ DELETE_RECORDINGS_WORKFLOWS+ ENFORCE_MAX_REPLAY_RETENTION_WORKFLOWS- + EXPORT_RECORDING_WORKFLOWS- + IMPORT_RECORDING_WORKFLOWS+ RASTERIZE_RECORDING_WORKFLOWS+ REPLAY_COUNT_METRICS_WORKFLOWS+ SUMMARIZATION_SWEEP_WORKFLOWSdiff --git a/posthog/templates/admin/posthog/team/export_history.html b/posthog/templates/admin/posthog/team/export_history.htmldeleted file mode 100644index 2157c9ee39ed..000000000000--- a/posthog/templates/admin/posthog/team/export_history.html+++ /dev/null@@ -1,57 +0,0 @@-{% extends "admin/base_site.html" %}-{% load i18n %}--{% block content %}-<p><a href="{% url 'admin:posthog_team_change' team.pk %}">← Back to team</a></p>--{% if exports %}-<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">- <thead>- <tr style="background: #f5f5f5;">- <th style="padding: 10px; text-align: left; border-bottom: 2px solid #ddd;">ID</th>- <th style="padding: 10px; text-align: left; border-bottom: 2px solid #ddd;">Session ID</th>- <th style="padding: 10px; text-align: left; border-bottom: 2px solid #ddd;">Reason</th>- <th style="padding: 10px; text-align: left; border-bottom: 2px solid #ddd;">Created By</th>- <th style="padding: 10px; text-align: left; border-bottom: 2px solid #ddd;">Created At</th>- <th style="padding: 10px; text-align: left; border-bottom: 2px solid #ddd;">Status</th>- <th style="padding: 10px; text-align: left; border-bottom: 2px solid #ddd;">Download</th>- </tr>- </thead>- <tbody>- {% for export in exports %}- <tr style="border-bottom: 1px solid #eee;">- <td style="padding: 10px;">{{ export.id }}</td>- <td style="padding: 10px;">{{ export.session_id }}</td>- <td style="padding: 10px;">{{ export.reason|default:"-" }}</td>- <td style="padding: 10px;">{{ export.created_by.email|default:"-" }}</td>- <td style="padding: 10px;">{{ export.created_at }}</td>- <td style="padding: 10px;">- {% if export.is_expired %}- <span style="color: gray;">Expired</span>- {% elif export.status == "complete" %}- <span style="color: green;">Complete</span>- {% elif export.status == "failed" %}- <span style="color: red;">Failed</span>- {% elif export.status == "running" %}- <span style="color: blue;">Running</span>- {% else %}- <span style="color: orange;">Pending</span>- {% endif %}- </td>- <td style="padding: 10px;">- {% if export.is_expired %}- -- {% elif export.export_location %}- <a href="/admin/posthog/team/{{ team.pk }}/download-export/{{ export.id }}/" class="button" style="font-size: 11px;">Download</a>- {% else %}- -- {% endif %}- </td>- </tr>- {% endfor %}- </tbody>-</table>-{% else %}-<p style="margin-top: 20px; color: #666;">No exports found for this team.</p>-{% endif %}-{% endblock %}diff --git a/posthog/templates/admin/posthog/team/export_individual_replay.html b/posthog/templates/admin/posthog/team/export_individual_replay.htmldeleted file mode 100644index 7e2705aad12f..000000000000--- a/posthog/templates/admin/posthog/team/export_individual_replay.html+++ /dev/null@@ -1,9 +0,0 @@-{% load i18n %}--<div style="margin: 10px 0;">- <p>Prepares an export of an individual session so that you can test locally</p>- <p><strong>With great power comes great responsibility</strong></p>-- <a class="button" href="{{ export_url }}" style="margin-right: 10px;">Export session replay</a>- <a class="button" href="{{ export_history_url }}">View past exports</a>-</div>diff --git a/posthog/templates/admin/posthog/team/export_replay_form.html b/posthog/templates/admin/posthog/team/export_replay_form.htmldeleted file mode 100644index 7dd920258a35..000000000000--- a/posthog/templates/admin/posthog/team/export_replay_form.html+++ /dev/null@@ -1,23 +0,0 @@-{% extends "admin/base_site.html" %}-{% load i18n %}--{% block content %}-<p>Prepares an export of an individual session so that you can test locally.</p>-<p><strong>With great power comes great responsibility.</strong></p>--<form method="post">- {% csrf_token %}- <div style="margin: 20px 0;">- <label for="session_id" style="display: block; margin-bottom: 5px; font-weight: bold;">Session ID:</label>- <input type="text" id="session_id" name="session_id" style="width: 400px; padding: 8px;" required />- </div>- <div style="margin: 20px 0;">- <label for="reason" style="display: block; margin-bottom: 5px; font-weight: bold;">Reason:</label>- <input type="text" id="reason" name="reason" style="width: 400px; padding: 8px;" placeholder="e.g. Customer support ticket #1234" required />- </div>- <div style="margin-top: 20px;">- <input type="submit" class="default" value="Generate export" style="padding: 10px 20px;" />- <a href="{% url 'admin:posthog_team_change' team.pk %}" style="margin-left: 10px;">Cancel</a>- </div>-</form>-{% endblock %}diff --git a/posthog/templates/admin/posthog/team/import_individual_replay.html b/posthog/templates/admin/posthog/team/import_individual_replay.htmldeleted file mode 100644index 3169fc66e6ab..000000000000--- a/posthog/templates/admin/posthog/team/import_individual_replay.html+++ /dev/null@@ -1,8 +0,0 @@-{% load i18n %}--<div style="margin: 10px 0;">- <p>Import a previously exported session replay zip file</p>- <p><strong>With this additional great power comes entirely another great responsibility</strong></p>-- <a class="button" href="{{ import_url }}" style="margin-right: 10px;">Import session replay</a>-</div>diff --git a/posthog/templates/admin/posthog/team/import_replay_form.html b/posthog/templates/admin/posthog/team/import_replay_form.htmldeleted file mode 100644index d8b184a9ebb4..000000000000--- a/posthog/templates/admin/posthog/team/import_replay_form.html+++ /dev/null@@ -1,23 +0,0 @@-{% extends "admin/base_site.html" %}-{% load i18n %}--{% block content %}-<p>Import a previously exported session replay zip file.</p>-<p><strong>With this additional great power comes entirely another great responsibility.</strong></p>--<form method="post" enctype="multipart/form-data">- {% csrf_token %}- <div style="margin: 20px 0;">- <label for="import_file" style="display: block; margin-bottom: 5px; font-weight: bold;">Zip file:</label>- <input type="file" id="import_file" name="import_file" accept=".zip" required />- </div>- <div style="margin: 20px 0;">- <label for="reason" style="display: block; margin-bottom: 5px; font-weight: bold;">Reason:</label>- <input type="text" id="reason" name="reason" style="width: 400px; padding: 8px;" placeholder="e.g. Testing session replay locally" required />- </div>- <div style="margin-top: 20px;">- <input type="submit" class="default" value="Import replay data" style="padding: 10px 20px;" />- <a href="{% url 'admin:posthog_team_change' team.pk %}" style="margin-left: 10px;">Cancel</a>- </div>-</form>-{% endblock %}diff --git a/posthog/temporal/session_replay/export_recording/__init__.py b/posthog/temporal/session_replay/export_recording/__init__.pydeleted file mode 100644index fb1b8aba5f53..000000000000--- a/posthog/temporal/session_replay/export_recording/__init__.py+++ /dev/null@@ -1,26 +0,0 @@-from posthog.temporal.session_replay.export_recording.activities import (- build_recording_export_context,- cleanup_export_data,- export_event_clickhouse_rows,- 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--EXPORT_RECORDING_WORKFLOWS = [- ExportRecordingWorkflow,-]--EXPORT_RECORDING_ACTIVITIES = [- build_recording_export_context,- cleanup_export_data,- export_event_clickhouse_rows,- 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.pydeleted file mode 100644index 2a670d9c17ad..000000000000--- a/posthog/temporal/session_replay/export_recording/activities.py+++ /dev/null@@ -1,371 +0,0 @@-import json-import uuid-import base64-import shutil-from datetime import datetime, timedelta-from pathlib import Path-from uuid import uuid4--from django.conf import settings-from django.utils import timezone--import pytz-from temporalio import activity--from posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from posthog.redis import get_async_client-from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents-from posthog.session_recordings.recordings import recording_s3_client-from posthog.session_recordings.recordings.errors import BlockFetchError, RecordingDeletedError-from posthog.session_recordings.recordings.recording_api_client import recording_api_client-from posthog.session_recordings.session_recording_v2_service import fetch_blocks_from_recording_api-from posthog.sync import database_sync_to_async-from posthog.temporal.common.clickhouse import get_client-from posthog.temporal.common.logger import get_write_only_logger-from posthog.temporal.session_replay.export_recording.types import (- ExportContext,- ExportRecordingInput,- MarkExportFailedInput,- RedisConfig,-)--from products.replay.backend.models.exported_recording import ExportedRecording--LOGGER = 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---def _redis_key(export_id: uuid.UUID, key_type: str, suffix: str = "") -> str:- base_key = f"export-recording:{export_id}:{key_type}"- return f"{base_key}:{suffix}" if suffix else base_key---async def build_recording_export_context(input: ExportRecordingInput) -> ExportContext:- logger = 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")- .aget(id=input.exported_recording_id)- )-- export_record.status = ExportedRecording.Status.RUNNING- await database_sync_to_async(export_record.save)(update_fields=["status"])-- logger.info(f"Built export context for session {export_record.session_id}")-- return ExportContext(- export_id=uuid.uuid4(),- exported_recording_id=input.exported_recording_id,- session_id=export_record.session_id,- team_id=export_record.team.id,- redis_config=input.redis_config,- )---async def export_replay_clickhouse_rows(input: ExportContext) -> None:- tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=input.team_id)- logger = LOGGER.bind()- logger.info(f"Exporting Replay ClickHouse rows for session {input.session_id}")-- query: str = SessionReplayEvents.get_metadata_query(format="JSON")- parameters = {- "team_id": input.team_id,- "session_id": input.session_id,- "python_now": datetime.now(pytz.timezone("UTC")),- }-- ch_query_id = str(uuid4())- logger.info(f"Querying ClickHouse with query_id: {ch_query_id}")-- raw_response: bytes = b""- async with get_client() as client:- async with client.aget_query(query=query, query_parameters=parameters, query_id=ch_query_id) as ch_response:- raw_response = await ch_response.content.read()-- logger.info(f"Received {len(raw_response)} bytes from ClickHouse")-- redis_key = _redis_key(input.export_id, "replay-events")- r = get_async_client(_redis_url(input.redis_config))- await r.setex(redis_key, input.redis_config.redis_ttl, raw_response)-- logger.info(f"Wrote replay ClickHouse metadata to Redis key {redis_key}")---async def export_event_clickhouse_rows(input: ExportContext) -> None:- tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=input.team_id)- logger = LOGGER.bind()- logger.info(f"Exporting event ClickHouse rows for session {input.session_id}")-- # Exclude internal materialized columns: mat_/dmat_ materialized properties and the- # properties_group_* map columns. The latter churn (added/dropped by migrations, e.g.- # properties_group_ai_large), and a bare SELECT * breaks with "no column ... in table- # 'sharded_events'" whenever the distributed and sharded schemas are briefly out of step.- # They duplicate data already in `properties`, so an export never needs them.- query: str = """- SELECT * EXCEPT('mat_.*|dmat_.*|properties_group_.*')- FROM events- WHERE- team_id = %(team_id)s AND- $session_id = %(session_id)s AND- timestamp <= now() AND- timestamp >= now() - interval 90 day- LIMIT 400000- FORMAT JSON- """- parameters = {- "team_id": input.team_id,- "session_id": input.session_id,- }-- ch_query_id = str(uuid4())- logger.info(f"Querying ClickHouse with query_id: {ch_query_id}")-- raw_response: bytes = b""- async with get_client() as client:- async with client.aget_query(query=query, query_parameters=parameters, query_id=ch_query_id) as ch_response:- raw_response = await ch_response.content.read()-- logger.info(f"Received {len(raw_response)} bytes from ClickHouse")-- redis_key = _redis_key(input.export_id, "events")- r = get_async_client(_redis_url(input.redis_config))- await r.setex(redis_key, input.redis_config.redis_ttl, raw_response)-- logger.info(f"Wrote event ClickHouse data to Redis key {redis_key}")---async def export_recording_data_prefix(input: ExportContext) -> None:- logger = LOGGER.bind()- logger.info(f"Exporting recording data prefix for session {input.session_id}")-- recording_blocks = await fetch_blocks_from_recording_api(input.session_id, input.team_id)-- if not recording_blocks:- logger.warning("No recording blocks found, skipping prefix export...")- return-- first_block = recording_blocks[0]- s3_path = first_block.key-- prefix = "/".join(s3_path.split("/")[:-1])-- logger.info(f"Found S3 prefix: {prefix}")-- redis_key = _redis_key(input.export_id, "s3-prefix")- r = get_async_client(_redis_url(input.redis_config))- await r.setex(redis_key, input.redis_config.redis_ttl, prefix)-- logger.info(f"Wrote S3 prefix to Redis key {redis_key}")---async def export_recording_data(input: ExportContext) -> None:- logger = LOGGER.bind()- logger.info(f"Exporting recording data for session {input.session_id}")-- recording_blocks = await fetch_blocks_from_recording_api(input.session_id, input.team_id)-- logger.info(f"Found {len(recording_blocks)} blocks to export")-- block_manifest: list[dict] = []-- r = get_async_client(_redis_url(input.redis_config))- async with recording_api_client() as storage:- for block in recording_blocks:- filename = block.key.split("/")[-1]- block_offset = block.start_byte-- try:- block_data = await storage.fetch_block(- block.key, block.start_byte, block.end_byte, input.session_id, input.team_id- )- logger.info(f"Successfully fetched block data ({len(block_data)} bytes)")- except RecordingDeletedError:- raise- except BlockFetchError:- logger.warning(f"Failed to fetch block {block.key}, skipping...")- continue-- redis_key = _redis_key(input.export_id, "block", filename)- encoded_data = base64.b64encode(block_data).decode("utf-8")- await r.setex(redis_key, input.redis_config.redis_ttl, encoded_data)-- block_manifest.append(- {- "filename": filename,- "offset": block_offset,- "redis_key": redis_key,- }- )-- logger.info(f"Wrote block data to Redis key {redis_key}")-- manifest_key = _redis_key(input.export_id, "block-manifest")- await r.setex(manifest_key, input.redis_config.redis_ttl, json.dumps(block_manifest))-- logger.info(f"Exported {len(block_manifest)} recording blocks to Redis")---async def store_export_data(input: ExportContext) -> None:- logger = LOGGER.bind()- logger.info(f"Storing export data for session {input.session_id}")-- export_dir = Path("/tmp") / str(input.export_id)- export_dir.mkdir(parents=True, exist_ok=True)-- r = get_async_client(_redis_url(input.redis_config))- replay_events_data = await r.get(_redis_key(input.export_id, "replay-events"))- events_data = await r.get(_redis_key(input.export_id, "events"))- s3_prefix = await r.get(_redis_key(input.export_id, "s3-prefix"))- block_manifest_raw = await r.get(_redis_key(input.export_id, "block-manifest"))-- clickhouse_dir = export_dir / "clickhouse"- clickhouse_dir.mkdir(parents=True, exist_ok=True)-- if replay_events_data:- replay_events_path = clickhouse_dir / "session-replay-events.json"- with replay_events_path.open("wb") as f:- f.write(replay_events_data if isinstance(replay_events_data, bytes) else replay_events_data.encode())- logger.info(f"Wrote replay events to {replay_events_path}")-- if events_data:- events_path = clickhouse_dir / "events.json"- with events_path.open("wb") as f:- f.write(events_data if isinstance(events_data, bytes) else events_data.encode())- logger.info(f"Wrote events to {events_path}")-- if s3_prefix:- s3_prefix_path = export_dir / "s3_prefix.txt"- with s3_prefix_path.open("w") as f:- f.write(s3_prefix if isinstance(s3_prefix, str) else s3_prefix.decode())- logger.info(f"Wrote S3 prefix to {s3_prefix_path}")-- if block_manifest_raw:- data_dir = export_dir / "data"- data_dir.mkdir(parents=True, exist_ok=True)-- block_manifest = json.loads(block_manifest_raw)- for block_info in block_manifest:- block_data_encoded = await r.get(block_info["redis_key"])- if not block_data_encoded:- logger.warning(f"Missing block data for {block_info['filename']}, skipping...")- continue-- block_data = base64.b64decode(block_data_encoded)- block_offset = block_info["offset"]-- output_path = data_dir / block_info["filename"]- with output_path.open("wb") as f:- f.write(b"\x00" * block_offset)- f.write(block_data)- f.write(b"\x00" * 1024)-- logger.info(f"Wrote block data to {output_path}")-- zip_path = Path("/tmp") / f"{input.export_id}.zip"- shutil.make_archive(str(zip_path.with_suffix("")), "zip", export_dir)-- logger.info(f"Created zip archive at {zip_path}")-- s3_key = f"session_recording_exports/{input.team_id}/{input.session_id}/{input.export_id}.zip"-- async with recording_s3_client.async_recording_s3_client() as storage:- await storage.upload_file(s3_key, str(zip_path))- logger.info(f"Uploaded zip archive to S3 at {s3_key}")-- zip_path.unlink()- shutil.rmtree(export_dir)-- export_record = await ExportedRecording.objects.aget(id=input.exported_recording_id)- export_record.export_location = s3_key- export_record.status = ExportedRecording.Status.COMPLETE- await database_sync_to_async(export_record.save)(update_fields=["export_location", "status"])-- 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)---async def cleanup_export_data(input: ExportContext) -> None:- logger = LOGGER.bind()- logger.info(f"Cleaning up export data for session {input.session_id}")-- keys_to_delete = [- _redis_key(input.export_id, "replay-events"),- _redis_key(input.export_id, "events"),- _redis_key(input.export_id, "s3-prefix"),- _redis_key(input.export_id, "block-manifest"),- ]-- r = get_async_client(_redis_url(input.redis_config))- block_manifest_raw = await r.get(_redis_key(input.export_id, "block-manifest"))- if block_manifest_raw:- block_manifest = json.loads(block_manifest_raw)- for block_info in block_manifest:- keys_to_delete.append(block_info["redis_key"])-- if keys_to_delete:- deleted_count = await r.delete(*keys_to_delete)- logger.info(f"Deleted {deleted_count} Redis keys for export {input.export_id}")diff --git a/posthog/temporal/session_replay/export_recording/types.py b/posthog/temporal/session_replay/export_recording/types.pydeleted file mode 100644index 2a2ea49e3bc1..000000000000--- a/posthog/temporal/session_replay/export_recording/types.py+++ /dev/null@@ -1,26 +0,0 @@-from uuid import UUID--from pydantic import BaseModel---class RedisConfig(BaseModel):- redis_url: str | None = None # Defaults to settings.SESSION_RECORDING_REDIS_URL- redis_ttl: int = 3600 * 6 # 6 hours---class ExportRecordingInput(BaseModel):- exported_recording_id: UUID- redis_config: RedisConfig = RedisConfig()---class ExportContext(BaseModel):- export_id: UUID- exported_recording_id: UUID- session_id: str- team_id: int- redis_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.pydeleted file mode 100644index 7e09ddbb7d40..000000000000--- a/posthog/temporal/session_replay/export_recording/workflow.py+++ /dev/null@@ -1,135 +0,0 @@-import asyncio-from datetime import timedelta--from temporalio import common, workflow--from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.session_replay.export_recording.activities import (- build_recording_export_context,- cleanup_export_data,- export_event_clickhouse_rows,- 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, MarkExportFailedInput--[email protected](name="export-recording")-class ExportRecordingWorkflow(PostHogWorkflow):- inputs_cls = ExportRecordingInput-- @workflow.run- async 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,- 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),- ),- )-- async with asyncio.TaskGroup() as export_tasks:- export_tasks.create_task(- workflow.execute_activity(- export_replay_clickhouse_rows,- export_context,- start_to_close_timeout=timedelta(minutes=30),- schedule_to_close_timeout=timedelta(hours=3),- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )- )- export_tasks.create_task(- workflow.execute_activity(- export_event_clickhouse_rows,- export_context,- start_to_close_timeout=timedelta(minutes=30),- schedule_to_close_timeout=timedelta(hours=3),- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )- )- export_tasks.create_task(- workflow.execute_activity(- export_recording_data,- export_context,- start_to_close_timeout=timedelta(hours=3),- schedule_to_close_timeout=timedelta(hours=6),- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )- )- export_tasks.create_task(- workflow.execute_activity(- export_recording_data_prefix,- 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),- ),- )- )-- await workflow.execute_activity(- store_export_data,- export_context,- start_to_close_timeout=timedelta(hours=3),- schedule_to_close_timeout=timedelta(hours=6),- 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/session_replay/import_recording/__init__.py b/posthog/temporal/session_replay/import_recording/__init__.pydeleted file mode 100644index 7e2282714ca9..000000000000--- a/posthog/temporal/session_replay/import_recording/__init__.py+++ /dev/null@@ -1,18 +0,0 @@-from posthog.temporal.session_replay.import_recording.activities import (- build_import_context,- cleanup_import_data,- import_event_clickhouse_rows,- import_recording_data,- import_replay_clickhouse_rows,-)-from posthog.temporal.session_replay.import_recording.workflow import ImportRecordingWorkflow--IMPORT_RECORDING_WORKFLOWS = [ImportRecordingWorkflow]--IMPORT_RECORDING_ACTIVITIES = [- build_import_context,- cleanup_import_data,- import_event_clickhouse_rows,- import_recording_data,- import_replay_clickhouse_rows,-]diff --git a/posthog/temporal/session_replay/import_recording/activities.py b/posthog/temporal/session_replay/import_recording/activities.pydeleted file mode 100644index f426f62f76aa..000000000000--- a/posthog/temporal/session_replay/import_recording/activities.py+++ /dev/null@@ -1,276 +0,0 @@-import json-import shutil-import zipfile-from pathlib import Path-from uuid import uuid4--from temporalio import activity--from posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from posthog.session_recordings.recordings import recording_s3_client-from posthog.temporal.common.clickhouse import get_client-from posthog.temporal.common.logger import get_write_only_logger-from posthog.temporal.session_replay.import_recording.types import ImportContext, ImportRecordingInput--LOGGER = get_write_only_logger()---async def build_import_context(input: ImportRecordingInput) -> ImportContext:- logger = LOGGER.bind()- logger.info(f"Building import context for zip file {input.export_file}")-- zip_path = Path(input.export_file)- if not zip_path.exists():- raise RuntimeError(f"Zip file does not exist: {input.export_file}")-- import_id = uuid4()- import_dir = Path("/tmp") / str(import_id)- import_dir.mkdir(parents=True, exist_ok=True)-- with zipfile.ZipFile(zip_path, "r") as f_zip:- f_zip.extractall(import_dir)-- logger.info(f"Extracted zip file to {import_dir}")-- s3_prefix_file = import_dir / "s3_prefix.txt"-- if not s3_prefix_file.exists():- raise RuntimeError("Missing s3_prefix.txt")-- s3_prefix = s3_prefix_file.read_text().strip()- logger.info(f"Found S3 prefix: {s3_prefix}")-- replay_events_file = import_dir / "clickhouse" / "session-replay-events.json"- if not replay_events_file.exists():- raise RuntimeError("Missing session-replay-events.json")-- with replay_events_file.open("r") as f:- replay_data = json.load(f)-- if not replay_data.get("data") or len(replay_data["data"]) == 0:- raise RuntimeError("Missing data in session-replay-events.json")-- first_row = replay_data["data"][0]- session_id = first_row.get("session_id")- logger.info(f"Found session_id: {session_id}")-- return ImportContext(team_id=input.team_id, import_id=import_id, s3_prefix=s3_prefix, session_id=session_id)---async def import_recording_data(input: ImportContext) -> None:- logger = LOGGER.bind()- logger.info(f"Importing recording data for session {input.session_id}")-- data_dir = Path("/tmp") / str(input.import_id) / "data"-- data_files = list(data_dir.iterdir())- logger.info(f"Found {len(data_files)} data files to import")-- async with recording_s3_client.async_recording_s3_client() as storage:- for data_file in data_files:- s3_key = f"{input.s3_prefix}/{data_file.name}"- logger.info(f"Uploading {data_file.name} to {s3_key}")-- await storage.upload_file(s3_key, str(data_file))- logger.info(f"Successfully uploaded {data_file.name}")-- logger.info(f"Imported {len(data_files)} recording data files")---# Query uses input() function with JSONEachRow to pass data in request body (not query string)-# This avoids HTTP 400 errors when block_first_timestamps/block_last_timestamps/block_urls are large-REPLAY_INSERT_QUERY = """-INSERT INTO writable_session_replay_events (- session_id,- team_id,- distinct_id,- min_first_timestamp,- max_last_timestamp,- first_url,- click_count,- keypress_count,- mouse_activity_count,- active_milliseconds,- console_log_count,- console_warn_count,- console_error_count,- snapshot_source,- snapshot_library,- retention_period_days,- block_first_timestamps,- block_last_timestamps,- block_urls-)-SELECT- any(session_id),- any(team_id),- any(distinct_id),- any(min_first_timestamp),- any(max_last_timestamp),- argMinState(first_url, min_first_timestamp),- any(click_count),- any(keypress_count),- any(mouse_activity_count),- any(active_milliseconds),- any(console_log_count),- any(console_warn_count),- any(console_error_count),- argMinState(snapshot_source, min_first_timestamp),- argMinState(snapshot_library, min_first_timestamp),- any(retention_period_days),- any(block_first_timestamps),- any(block_last_timestamps),- any(block_urls)-FROM input('- session_id String,- team_id Int64,- distinct_id String,- min_first_timestamp DateTime64(6, \\'UTC\\'),- max_last_timestamp DateTime64(6, \\'UTC\\'),- first_url Nullable(String),- click_count Int64,- keypress_count Int64,- mouse_activity_count Int64,- active_milliseconds Int64,- console_log_count Int64,- console_warn_count Int64,- console_error_count Int64,- snapshot_source LowCardinality(Nullable(String)),- snapshot_library Nullable(String),- retention_period_days Int64,- block_first_timestamps Array(DateTime64(6, \\'UTC\\')),- block_last_timestamps Array(DateTime64(6, \\'UTC\\')),- block_urls Array(String)-')-FORMAT JSONEachRow-"""---async def import_replay_clickhouse_rows(input: ImportContext) -> None:- tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=input.team_id)- logger = LOGGER.bind()- logger.info(f"Importing replay ClickHouse rows for session {input.session_id}")-- replay_events_file = Path("/tmp") / str(input.import_id) / "clickhouse" / "session-replay-events.json"- with replay_events_file.open("r") as f:- replay_data = json.load(f)-- rows = replay_data.get("data", [])- if not rows:- raise RuntimeError("Missing data in session-replay-events.json")-- logger.info(f"Importing {len(rows)} replay event rows")-- try:- async with get_client() as client:- for idx, row in enumerate(rows):- json_row = json.dumps(- {- "session_id": row["session_id"],- "team_id": int(input.team_id),- "distinct_id": row["distinct_id"],- "min_first_timestamp": row["start_time"],- "max_last_timestamp": row["end_time"],- "first_url": row["first_url"],- "click_count": int(row["click_count"]),- "keypress_count": int(row["keypress_count"]),- "mouse_activity_count": int(row["mouse_activity_count"]),- "active_milliseconds": int(row["active_seconds"] * 1000),- "console_log_count": int(row["console_log_count"]),- "console_warn_count": int(row["console_warn_count"]),- "console_error_count": int(row["console_error_count"]),- "snapshot_source": row["snapshot_source"],- "snapshot_library": None,- "retention_period_days": int(row["retention_period_days"]),- "block_first_timestamps": row["block_first_timestamps"],- "block_last_timestamps": row["block_last_timestamps"],- "block_urls": row["block_urls"],- }- )- full_query = REPLAY_INSERT_QUERY + "\n" + json_row- ch_query_id = str(uuid4())- await client.execute_query(full_query, query_id=ch_query_id)- logger.info(f"Inserted row {idx + 1}/{len(rows)} with query_id: {ch_query_id}")- except Exception:- logger.exception("Failed to import replay event rows")- raise-- logger.info(f"Successfully imported {len(rows)} replay event rows")---async def import_event_clickhouse_rows(input: ImportContext) -> None:- tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=input.team_id)- logger = LOGGER.bind()- logger.info(f"Importing event ClickHouse rows for session {input.session_id}")-- events_file = Path("/tmp") / str(input.import_id) / "clickhouse" / "events.json"- if not events_file.exists():- logger.warning("No events.json found, skipping")- return-- with events_file.open("r") as f:- events_data = json.load(f)-- rows = events_data.get("data", [])- if not rows:- logger.warning("No event rows to import")- return-- logger.info(f"Importing {len(rows)} event rows")-- query = """- INSERT INTO writable_events (- uuid,- team_id,- event,- distinct_id,- properties,- timestamp,- created_at,- person_id,- person_properties,- elements_chain- ) VALUES- """-- try:- async with get_client() as client:- for idx, row in enumerate(rows):- row_tuple = (- row["uuid"],- input.team_id,- row["event"],- row["distinct_id"],- row["properties"],- row["timestamp"],- row["created_at"],- row["person_id"],- row["person_properties"],- row["elements_chain"],- )- ch_query_id = str(uuid4())- await client.execute_query(query, row_tuple, query_id=ch_query_id)- logger.info(f"Inserted row {idx + 1}/{len(rows)} with query_id: {ch_query_id}")- except Exception:- logger.exception("Failed to import event rows")- raise-- logger.info(f"Successfully imported {len(rows)} event rows")---async def cleanup_import_data(input: ImportContext) -> None:- logger = LOGGER.bind()- logger.info(f"Cleaning up import data for session {input.session_id}")-- import_dir = Path("/tmp") / str(input.import_id)-- if import_dir.exists():- shutil.rmtree(import_dir)- logger.info(f"Deleted import directory {import_dir}")- else:- logger.warning(f"Import directory {import_dir} does not exist, skipping cleanup")diff --git a/posthog/temporal/session_replay/import_recording/types.py b/posthog/temporal/session_replay/import_recording/types.pydeleted file mode 100644index 7e761bf6a955..000000000000--- a/posthog/temporal/session_replay/import_recording/types.py+++ /dev/null@@ -1,15 +0,0 @@-from uuid import UUID--from pydantic import BaseModel---class ImportRecordingInput(BaseModel):- team_id: int- export_file: str---class ImportContext(BaseModel):- team_id: int- import_id: UUID- s3_prefix: str- session_id: strdiff --git a/posthog/temporal/session_replay/import_recording/workflow.py b/posthog/temporal/session_replay/import_recording/workflow.pydeleted file mode 100644index f4e4d9850c01..000000000000--- a/posthog/temporal/session_replay/import_recording/workflow.py+++ /dev/null@@ -1,81 +0,0 @@-import asyncio-from datetime import timedelta--from temporalio import common, workflow--from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.session_replay.import_recording.activities import (- build_import_context,- cleanup_import_data,- import_event_clickhouse_rows,- import_recording_data,- import_replay_clickhouse_rows,-)-from posthog.temporal.session_replay.import_recording.types import ImportRecordingInput--[email protected](name="import-recording")-class ImportRecordingWorkflow(PostHogWorkflow):- inputs_cls = ImportRecordingInput-- @workflow.run- async def run(self, input: ImportRecordingInput) -> None:- import_context = await workflow.execute_activity(- build_import_context,- input,- 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),- ),- )-- async with asyncio.TaskGroup() as import_tasks:- import_tasks.create_task(- workflow.execute_activity(- import_replay_clickhouse_rows,- import_context,- start_to_close_timeout=timedelta(minutes=30),- schedule_to_close_timeout=timedelta(hours=3),- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )- )- import_tasks.create_task(- workflow.execute_activity(- import_event_clickhouse_rows,- import_context,- start_to_close_timeout=timedelta(minutes=30),- schedule_to_close_timeout=timedelta(hours=3),- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )- )- import_tasks.create_task(- workflow.execute_activity(- import_recording_data,- import_context,- start_to_close_timeout=timedelta(minutes=30),- schedule_to_close_timeout=timedelta(hours=3),- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )- )-- await workflow.execute_activity(- cleanup_import_data,- import_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),- ),- )diff --git a/posthog/temporal/tests/session_replay/export_recording/__init__.py b/posthog/temporal/tests/session_replay/export_recording/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/posthog/temporal/tests/session_replay/export_recording/test_activities.py b/posthog/temporal/tests/session_replay/export_recording/test_activities.pydeleted file mode 100644index 4568f28d2e49..000000000000--- a/posthog/temporal/tests/session_replay/export_recording/test_activities.py+++ /dev/null@@ -1,654 +0,0 @@-import json-import base64-from datetime import timedelta-from uuid import UUID, uuid4--import pytest-from unittest.mock import AsyncMock, MagicMock, patch--from django.utils import timezone--from posthog.session_recordings.recordings.errors import BlockFetchError-from posthog.session_recordings.session_recording_v2_service import RecordingBlock-from posthog.temporal.session_replay.export_recording.activities import (- _mark_stale_exports_failed,- _redis_key,- _redis_url,- build_recording_export_context,- cleanup_export_data,- export_event_clickhouse_rows,- 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,- MarkExportFailedInput,- RedisConfig,-)--from products.replay.backend.models.exported_recording import ExportedRecording--TEST_RECORDING_ID = UUID("01938a67-1234-7000-8000-000000000001")-TEST_REDIS_CONFIG = RedisConfig(redis_url="redis://test-redis:6379", redis_ttl=3600)---def test_redis_url_with_custom_url():- config = RedisConfig(redis_url="redis://my-redis:6380")- assert _redis_url(config) == "redis://my-redis:6380"---def test_redis_url_with_default_uses_settings():- config = RedisConfig()- with patch("posthog.temporal.session_replay.export_recording.activities.settings") as mock_settings:- mock_settings.SESSION_RECORDING_REDIS_URL = "redis://settings-redis:6379"- assert _redis_url(config) == "redis://settings-redis:6379"---def test_redis_key_without_suffix():- export_id = UUID("01938a67-1234-7000-8000-000000000001")- key = _redis_key(export_id, "replay-events")- assert key == f"export-recording:{export_id}:replay-events"---def test_redis_key_with_suffix():- export_id = UUID("01938a67-1234-7000-8000-000000000001")- key = _redis_key(export_id, "block", "file.json")- assert key == f"export-recording:{export_id}:block:file.json"---async def test_build_recording_export_context_success():- TEST_SESSION_ID = "test-session-123"- TEST_TEAM_ID = 67890-- mock_team = MagicMock()- mock_team.id = TEST_TEAM_ID-- mock_record = MagicMock()- mock_record.team = mock_team- mock_record.session_id = TEST_SESSION_ID- mock_record.status = ExportedRecording.Status.PENDING- mock_record.save = MagicMock()-- mock_qs = MagicMock()- mock_qs.select_related.return_value.only.return_value.aget = AsyncMock(return_value=mock_record)-- with (- patch("posthog.temporal.session_replay.export_recording.activities.ExportedRecording.objects", mock_qs),- patch("posthog.temporal.session_replay.export_recording.activities.database_sync_to_async") as mock_db_sync,- ):- mock_db_sync.side_effect = lambda fn: AsyncMock(return_value=fn())- result = await build_recording_export_context(- ExportRecordingInput(exported_recording_id=TEST_RECORDING_ID, redis_config=TEST_REDIS_CONFIG)- )-- assert result.session_id == TEST_SESSION_ID- assert result.team_id == TEST_TEAM_ID- assert result.exported_recording_id == TEST_RECORDING_ID- assert result.redis_config == TEST_REDIS_CONFIG- 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()---async def test_export_replay_clickhouse_rows_success():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- mock_ch_response = MagicMock()- mock_ch_response.content.read = AsyncMock(return_value=b'{"data": []}')-- mock_query_ctx = MagicMock()- mock_query_ctx.__aenter__ = AsyncMock(return_value=mock_ch_response)- mock_query_ctx.__aexit__ = AsyncMock(return_value=None)-- mock_client = MagicMock()- mock_client.aget_query.return_value = mock_query_ctx-- mock_redis = AsyncMock()-- with (- patch("posthog.temporal.session_replay.export_recording.activities.get_client") as mock_get_client,- patch(- "posthog.temporal.session_replay.export_recording.activities.SessionReplayEvents.get_metadata_query"- ) as mock_query,- patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client,- ):- mock_get_client.return_value.__aenter__.return_value = mock_client- mock_query.return_value = "SELECT * FROM session_replay_events"- mock_get_async_client.return_value = mock_redis-- await export_replay_clickhouse_rows(export_context)-- mock_client.aget_query.assert_called_once()- mock_redis.setex.assert_called_once()- call_args = mock_redis.setex.call_args- assert call_args[0][0] == _redis_key(export_id, "replay-events")- assert call_args[0][1] == TEST_REDIS_CONFIG.redis_ttl- assert call_args[0][2] == b'{"data": []}'---async def test_export_event_clickhouse_rows_success():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- mock_ch_response = MagicMock()- mock_ch_response.content.read = AsyncMock(return_value=b'{"data": []}')-- mock_query_ctx = MagicMock()- mock_query_ctx.__aenter__ = AsyncMock(return_value=mock_ch_response)- mock_query_ctx.__aexit__ = AsyncMock(return_value=None)-- mock_client = MagicMock()- mock_client.aget_query.return_value = mock_query_ctx-- mock_redis = AsyncMock()-- with (- patch("posthog.temporal.session_replay.export_recording.activities.get_client") as mock_get_client,- patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client,- ):- mock_get_client.return_value.__aenter__.return_value = mock_client- mock_get_async_client.return_value = mock_redis-- await export_event_clickhouse_rows(export_context)-- mock_client.aget_query.assert_called_once()- # the events SELECT * must exclude the internal materialized columns, including the- # churny properties_group_* maps, otherwise the query breaks whenever the distributed- # and sharded schemas are briefly out of step (e.g. dropping properties_group_ai_large)- executed_query = mock_client.aget_query.call_args.kwargs["query"]- assert "properties_group_.*" in executed_query-- mock_redis.setex.assert_called_once()- call_args = mock_redis.setex.call_args- assert call_args[0][0] == _redis_key(export_id, "events")- 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()---async def test_export_recording_data_prefix_success():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- mock_block = RecordingBlock(- key="team_id/123/session_id/test-session/data/file.json",- start_byte=0,- end_byte=100,- start_timestamp="2024-01-01T00:00:00Z",- end_timestamp="2024-01-01T00:01:00Z",- )-- mock_redis = AsyncMock()-- with (- patch(- "posthog.temporal.session_replay.export_recording.activities.fetch_blocks_from_recording_api",- return_value=[mock_block],- ),- patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client,- ):- mock_get_async_client.return_value = mock_redis-- await export_recording_data_prefix(export_context)-- mock_redis.setex.assert_called_once()- call_args = mock_redis.setex.call_args- assert call_args[0][0] == _redis_key(export_id, "s3-prefix")- assert call_args[0][1] == TEST_REDIS_CONFIG.redis_ttl- assert call_args[0][2] == "team_id/123/session_id/test-session/data"---async def test_export_recording_data_prefix_no_blocks():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- with (- patch(- "posthog.temporal.session_replay.export_recording.activities.fetch_blocks_from_recording_api",- return_value=[],- ),- patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client,- ):- await export_recording_data_prefix(export_context)-- mock_get_async_client.assert_not_called()---async def test_export_recording_data_success():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- mock_block = RecordingBlock(- key="team/123/session/test-session/data/file.json",- start_byte=100,- end_byte=200,- start_timestamp="2024-01-01T00:00:00Z",- end_timestamp="2024-01-01T00:01:00Z",- )-- mock_storage = AsyncMock()- mock_storage.fetch_block = AsyncMock(return_value=b"block data content")- mock_redis = AsyncMock()-- with (- patch(- "posthog.temporal.session_replay.export_recording.activities.fetch_blocks_from_recording_api",- return_value=[mock_block],- ),- patch(- "posthog.temporal.session_replay.export_recording.activities.recording_api_client"- ) as mock_storage_client,- patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client,- ):- mock_storage_client.return_value.__aenter__.return_value = mock_storage- mock_get_async_client.return_value = mock_redis-- await export_recording_data(export_context)-- mock_storage.fetch_block.assert_called_once_with(- mock_block.key,- mock_block.start_byte,- mock_block.end_byte,- export_context.session_id,- export_context.team_id,- )- assert mock_redis.setex.call_count == 2-- block_call = mock_redis.setex.call_args_list[0]- assert block_call[0][0] == _redis_key(export_id, "block", "file.json")- assert block_call[0][2] == base64.b64encode(b"block data content").decode("utf-8")-- manifest_call = mock_redis.setex.call_args_list[1]- assert manifest_call[0][0] == _redis_key(export_id, "block-manifest")- manifest_data = json.loads(manifest_call[0][2])- assert len(manifest_data) == 1- assert manifest_data[0]["filename"] == "file.json"- assert manifest_data[0]["offset"] == 100---async def test_export_recording_data_no_blocks():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- mock_redis = AsyncMock()- mock_storage = AsyncMock()-- with (- patch(- "posthog.temporal.session_replay.export_recording.activities.fetch_blocks_from_recording_api",- return_value=[],- ),- patch(- "posthog.temporal.session_replay.export_recording.activities.recording_api_client"- ) as mock_storage_client,- patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client,- ):- mock_storage_client.return_value.__aenter__.return_value = mock_storage- mock_get_async_client.return_value = mock_redis-- await export_recording_data(export_context)-- mock_redis.setex.assert_called_once()- manifest_call = mock_redis.setex.call_args- assert manifest_call[0][0] == _redis_key(export_id, "block-manifest")- assert json.loads(manifest_call[0][2]) == []---async def test_export_recording_data_block_fetch_error():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- mock_block = RecordingBlock(- key="team/123/session/test-session/data/file.json",- start_byte=100,- end_byte=200,- start_timestamp="2024-01-01T00:00:00Z",- end_timestamp="2024-01-01T00:01:00Z",- )-- mock_storage = AsyncMock()- mock_storage.fetch_block = AsyncMock(side_effect=BlockFetchError("Fetch failed"))- mock_redis = AsyncMock()-- with (- patch(- "posthog.temporal.session_replay.export_recording.activities.fetch_blocks_from_recording_api",- return_value=[mock_block],- ),- patch(- "posthog.temporal.session_replay.export_recording.activities.recording_api_client"- ) as mock_storage_client,- patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client,- ):- mock_storage_client.return_value.__aenter__.return_value = mock_storage- mock_get_async_client.return_value = mock_redis-- await export_recording_data(export_context)-- mock_redis.setex.assert_called_once()- manifest_call = mock_redis.setex.call_args- assert json.loads(manifest_call[0][2]) == []---async def test_store_export_data_success(tmp_path):- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- block_manifest = [- {"filename": "file.json", "offset": 100, "redis_key": f"export-recording:{export_id}:block:file.json"}- ]- block_data_encoded = base64.b64encode(b"block content").decode("utf-8")-- mock_redis = AsyncMock()- mock_redis.get = AsyncMock(- side_effect=lambda key: {- _redis_key(export_id, "replay-events"): b'{"data": []}',- _redis_key(export_id, "events"): b'{"events": []}',- _redis_key(export_id, "s3-prefix"): "team/123/session",- _redis_key(export_id, "block-manifest"): json.dumps(block_manifest),- f"export-recording:{export_id}:block:file.json": block_data_encoded,- }.get(key)- )-- mock_record = MagicMock()- mock_record.save = MagicMock()- mock_storage = AsyncMock()-- with (- patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client,- patch("posthog.temporal.session_replay.export_recording.activities.Path") as mock_path_cls,- patch("posthog.temporal.session_replay.export_recording.activities.shutil.make_archive") as mock_make_archive,- patch("posthog.temporal.session_replay.export_recording.activities.shutil.rmtree"),- patch(- "posthog.temporal.session_replay.export_recording.activities.recording_s3_client.async_recording_s3_client"- ) as mock_export_storage_client,- patch(- "posthog.temporal.session_replay.export_recording.activities.ExportedRecording.objects"- ) as mock_record_qs,- patch("posthog.temporal.session_replay.export_recording.activities.database_sync_to_async") as mock_db_sync,- ):- mock_get_async_client.return_value = mock_redis- mock_export_storage_client.return_value.__aenter__.return_value = mock_storage-- mock_export_dir = MagicMock()- mock_clickhouse_dir = MagicMock()- mock_data_dir = MagicMock()- mock_zip_path = MagicMock()- mock_zip_path.with_suffix.return_value = tmp_path / f"{export_id}"-- def truediv_side_effect(path):- if str(path) == str(export_id):- return mock_export_dir- if ".zip" in str(path):- return mock_zip_path- return MagicMock()-- mock_path_cls.return_value.__truediv__ = MagicMock(side_effect=truediv_side_effect)- mock_export_dir.__truediv__ = MagicMock(- side_effect=lambda p: (- mock_clickhouse_dir if p == "clickhouse" else mock_data_dir if p == "data" else MagicMock()- )- )-- mock_record_qs.aget = AsyncMock(return_value=mock_record)- mock_db_sync.side_effect = lambda fn: AsyncMock(return_value=fn())-- await store_export_data(export_context)-- mock_make_archive.assert_called_once()- mock_storage.upload_file.assert_called_once()- mock_record_qs.aget.assert_called_once_with(id=TEST_RECORDING_ID)---async def test_store_export_data_s3_upload_failure():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- mock_redis = AsyncMock()- mock_redis.get = AsyncMock(return_value=None)-- mock_storage = AsyncMock()- mock_storage.upload_file.side_effect = Exception("Upload failed")-- with (- patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client,- patch("posthog.temporal.session_replay.export_recording.activities.Path") as mock_path_cls,- patch("posthog.temporal.session_replay.export_recording.activities.shutil.make_archive"),- patch(- "posthog.temporal.session_replay.export_recording.activities.recording_s3_client.async_recording_s3_client"- ) as mock_export_storage_client,- ):- mock_get_async_client.return_value = mock_redis- mock_export_storage_client.return_value.__aenter__.return_value = mock_storage-- mock_export_dir = MagicMock()- mock_clickhouse_dir = MagicMock()- mock_zip_path = MagicMock()-- def truediv_side_effect(path):- if str(path) == str(export_id):- return mock_export_dir- if ".zip" in str(path):- return mock_zip_path- return MagicMock()-- mock_path_cls.return_value.__truediv__ = MagicMock(side_effect=truediv_side_effect)- mock_export_dir.__truediv__ = MagicMock(return_value=mock_clickhouse_dir)-- with pytest.raises(Exception, match="Upload failed"):- await store_export_data(export_context)---async def test_cleanup_export_data_success():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- block_manifest = [- {"filename": "file.json", "offset": 100, "redis_key": f"export-recording:{export_id}:block:file.json"}- ]-- mock_redis = AsyncMock()- mock_redis.get = AsyncMock(return_value=json.dumps(block_manifest))- mock_redis.delete = AsyncMock(return_value=5)-- with patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client:- mock_get_async_client.return_value = mock_redis-- await cleanup_export_data(export_context)-- mock_redis.delete.assert_called_once()- delete_args = mock_redis.delete.call_args[0]- assert _redis_key(export_id, "replay-events") in delete_args- assert _redis_key(export_id, "events") in delete_args- assert _redis_key(export_id, "s3-prefix") in delete_args- assert _redis_key(export_id, "block-manifest") in delete_args- assert f"export-recording:{export_id}:block:file.json" in delete_args---async def test_cleanup_export_data_no_manifest():- export_id = uuid4()- export_context = ExportContext(- export_id=export_id,- exported_recording_id=TEST_RECORDING_ID,- session_id="test-session",- team_id=123,- redis_config=TEST_REDIS_CONFIG,- )-- mock_redis = AsyncMock()- mock_redis.get = AsyncMock(return_value=None)- mock_redis.delete = AsyncMock(return_value=4)-- with patch("posthog.temporal.session_replay.export_recording.activities.get_async_client") as mock_get_async_client:- mock_get_async_client.return_value = mock_redis-- await cleanup_export_data(export_context)-- 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_types.py b/posthog/temporal/tests/session_replay/export_recording/test_types.pydeleted file mode 100644index 9e353e6f97a9..000000000000--- a/posthog/temporal/tests/session_replay/export_recording/test_types.py+++ /dev/null@@ -1,71 +0,0 @@-from uuid import UUID, uuid4--from posthog.temporal.session_replay.export_recording.types import ExportContext, ExportRecordingInput, RedisConfig---def test_redis_config_defaults():- config = RedisConfig()- assert config.redis_url is None- assert config.redis_ttl == 3600 * 6---def test_redis_config_custom_values():- config = RedisConfig(redis_url="redis://custom-redis:6380", redis_ttl=7200)- assert config.redis_url == "redis://custom-redis:6380"- assert config.redis_ttl == 7200---def test_export_recording_input_creation():- recording_id = UUID("01938a67-1234-7000-8000-000000000001")- input = ExportRecordingInput(exported_recording_id=recording_id)- assert input.exported_recording_id == recording_id- assert input.redis_config.redis_url is None---def test_export_recording_input_with_custom_redis_config():- recording_id = UUID("01938a67-1234-7000-8000-000000000001")- redis_config = RedisConfig(redis_url="redis://custom-host:6380")- input = ExportRecordingInput(exported_recording_id=recording_id, redis_config=redis_config)- assert input.exported_recording_id == recording_id- assert input.redis_config.redis_url == "redis://custom-host:6380"---def test_export_context_creation():- export_id = uuid4()- recording_id = UUID("01938a67-5678-7000-8000-000000000002")- redis_config = RedisConfig()- context = ExportContext(- export_id=export_id,- exported_recording_id=recording_id,- session_id="test-session-id",- team_id=67890,- redis_config=redis_config,- )- assert context.export_id == export_id- assert context.exported_recording_id == recording_id- assert context.session_id == "test-session-id"- assert context.team_id == 67890- assert context.redis_config == redis_config---def test_export_context_mutability():- export_id = uuid4()- recording_id = UUID("01938a67-9abc-7000-8000-000000000003")- redis_config = RedisConfig()- context = ExportContext(- export_id=export_id,- exported_recording_id=recording_id,- session_id="original-id",- team_id=123,- redis_config=redis_config,- )- context.session_id = "new-id"- assert context.session_id == "new-id"---def test_export_recording_input_mutability():- recording_id = UUID("01938a67-def0-7000-8000-000000000004")- new_recording_id = UUID("01938a67-1111-7000-8000-000000000005")- input = ExportRecordingInput(exported_recording_id=recording_id)- input.exported_recording_id = new_recording_id- assert input.exported_recording_id == new_recording_iddiff --git a/posthog/temporal/tests/session_replay/export_recording/test_workflow.py b/posthog/temporal/tests/session_replay/export_recording/test_workflow.pydeleted file mode 100644index 4bb6ac7d98a2..000000000000--- a/posthog/temporal/tests/session_replay/export_recording/test_workflow.py+++ /dev/null@@ -1,79 +0,0 @@-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, MarkExportFailedInput-from 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"}'])- assert result.exported_recording_id == UUID("01938a67-1234-7000-8000-000000000001")- assert result.redis_config.redis_url is None---def test_export_recording_workflow_parse_inputs_string_uuid():- result = ExportRecordingWorkflow.parse_inputs(['{"exported_recording_id": "01938a67-5678-7000-8000-000000000002"}'])- assert result.exported_recording_id == UUID("01938a67-5678-7000-8000-000000000002")---def test_export_recording_workflow_parse_inputs_with_redis_config():- result = ExportRecordingWorkflow.parse_inputs(- [- '{"exported_recording_id": "01938a67-1234-7000-8000-000000000001", '- '"redis_config": {"redis_url": "redis://custom-redis:6380", "redis_ttl": 7200}}'- ]- )- 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 originaldiff --git a/posthog/temporal/tests/session_replay/import_recording/__init__.py b/posthog/temporal/tests/session_replay/import_recording/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/posthog/temporal/tests/session_replay/import_recording/test_activities.py b/posthog/temporal/tests/session_replay/import_recording/test_activities.pydeleted file mode 100644index 37f0ecce3052..000000000000--- a/posthog/temporal/tests/session_replay/import_recording/test_activities.py+++ /dev/null@@ -1,300 +0,0 @@-import json-import zipfile-from pathlib import Path-from uuid import uuid4--import pytest-from unittest.mock import AsyncMock, MagicMock, patch--from posthog.temporal.session_replay.import_recording.activities import (- build_import_context,- cleanup_import_data,- import_event_clickhouse_rows,- import_recording_data,- import_replay_clickhouse_rows,-)-from posthog.temporal.session_replay.import_recording.types import ImportContext, ImportRecordingInput---async def test_build_import_context_success(tmp_path):- zip_path = tmp_path / "export.zip"- extract_dir = tmp_path / "extract"- extract_dir.mkdir()-- clickhouse_dir = extract_dir / "clickhouse"- clickhouse_dir.mkdir()-- (extract_dir / "s3_prefix.txt").write_text("team/123/session/abc")- (clickhouse_dir / "session-replay-events.json").write_text(- json.dumps({"data": [{"team_id": 123, "session_id": "abc"}]})- )-- with zipfile.ZipFile(zip_path, "w") as zf:- zf.write(extract_dir / "s3_prefix.txt", "s3_prefix.txt")- zf.write(clickhouse_dir / "session-replay-events.json", "clickhouse/session-replay-events.json")-- input = ImportRecordingInput(team_id=123, export_file=str(zip_path))-- result = await build_import_context(input)-- assert result.team_id == 123- assert result.s3_prefix == "team/123/session/abc"- assert result.session_id == "abc"- assert result.import_id is not None---async def test_build_import_context_zip_not_exists():- input = ImportRecordingInput(team_id=123, export_file="/nonexistent/export.zip")-- with pytest.raises(RuntimeError, match="Zip file does not exist"):- await build_import_context(input)---async def test_import_recording_data_success(tmp_path):- import_id = uuid4()- import_dir = tmp_path / str(import_id)- data_dir = import_dir / "data"- data_dir.mkdir(parents=True)-- (data_dir / "file1.json").write_text("content1")- (data_dir / "file2.json").write_text("content2")-- context = ImportContext(- team_id=123,- import_id=import_id,- s3_prefix="team/123/session/abc",- session_id="abc",- )-- mock_storage = AsyncMock()-- with (- patch(- "posthog.temporal.session_replay.import_recording.activities.recording_s3_client.async_recording_s3_client"- ) as mock_async_client,- patch("posthog.temporal.session_replay.import_recording.activities.Path") as mock_path_cls,- ):- mock_async_client.return_value.__aenter__.return_value = mock_storage-- def path_side_effect(p):- if p == "/tmp":- return tmp_path- return Path(p)-- mock_path_cls.side_effect = path_side_effect-- await import_recording_data(context)-- assert mock_storage.upload_file.call_count == 2---async def test_import_replay_clickhouse_rows_success(tmp_path):- import_id = uuid4()- import_dir = tmp_path / str(import_id)- clickhouse_dir = import_dir / "clickhouse"- clickhouse_dir.mkdir(parents=True)-- replay_data = {- "data": [- {- "team_id": 123,- "session_id": "abc",- "distinct_id": "user1",- "start_time": "2024-01-01 00:00:00.000000",- "end_time": "2024-01-01 01:00:00.000000",- "first_url": "https://example.com",- "click_count": 10,- "keypress_count": 5,- "mouse_activity_count": 100,- "active_seconds": 3600,- "console_log_count": 1,- "console_warn_count": 0,- "console_error_count": 0,- "size": 1024,- "event_count": 50,- "message_count": 25,- "snapshot_source": "web",- "retention_period_days": 30,- "block_first_timestamps": [],- "block_last_timestamps": [],- "block_urls": [],- },- ]- }- (clickhouse_dir / "session-replay-events.json").write_text(json.dumps(replay_data))-- context = ImportContext(- team_id=123,- import_id=import_id,- s3_prefix="team/123/session/abc",- session_id="abc",- )-- mock_client = MagicMock()- mock_client.execute_query = AsyncMock()-- with (- patch("posthog.temporal.session_replay.import_recording.activities.get_client") as mock_get_client,- patch("posthog.temporal.session_replay.import_recording.activities.Path") as mock_path_cls,- ):- mock_get_client.return_value.__aenter__.return_value = mock_client-- def path_side_effect(p):- if p == "/tmp":- return tmp_path- return Path(p)-- mock_path_cls.side_effect = path_side_effect-- await import_replay_clickhouse_rows(context)-- mock_client.execute_query.assert_called_once()---async def test_import_event_clickhouse_rows_success(tmp_path):- import_id = uuid4()- import_dir = tmp_path / str(import_id)- clickhouse_dir = import_dir / "clickhouse"- clickhouse_dir.mkdir(parents=True)-- base_event = {- "uuid": "uuid1",- "event": "click",- "properties": "{}",- "timestamp": "2024-01-01 00:00:00.000000",- "team_id": 123,- "distinct_id": "user1",- "elements_chain": "",- "created_at": "2024-01-01 00:00:00.000000",- "person_id": "00000000-0000-0000-0000-000000000000",- "person_created_at": "2024-01-01 00:00:00",- "person_properties": "{}",- "group0_properties": "{}",- "group1_properties": "{}",- "group2_properties": "{}",- "group3_properties": "{}",- "group4_properties": "{}",- "group0_created_at": "1970-01-01 00:00:00",- "group1_created_at": "1970-01-01 00:00:00",- "group2_created_at": "1970-01-01 00:00:00",- "group3_created_at": "1970-01-01 00:00:00",- "group4_created_at": "1970-01-01 00:00:00",- "person_mode": "full",- }- events_data = {- "data": [- base_event,- {**base_event, "uuid": "uuid2", "event": "pageview"},- ]- }- (clickhouse_dir / "events.json").write_text(json.dumps(events_data))-- context = ImportContext(- team_id=123,- import_id=import_id,- s3_prefix="team/123/session/abc",- session_id="abc",- )-- mock_client = MagicMock()- mock_client.execute_query = AsyncMock()-- with (- patch("posthog.temporal.session_replay.import_recording.activities.get_client") as mock_get_client,- patch("posthog.temporal.session_replay.import_recording.activities.Path") as mock_path_cls,- ):- mock_get_client.return_value.__aenter__.return_value = mock_client-- def path_side_effect(p):- if p == "/tmp":- return tmp_path- return Path(p)-- mock_path_cls.side_effect = path_side_effect-- await import_event_clickhouse_rows(context)-- assert mock_client.execute_query.call_count == 2---async def test_import_event_clickhouse_rows_no_file(tmp_path):- import_id = uuid4()- import_dir = tmp_path / str(import_id)- import_dir.mkdir(parents=True)-- context = ImportContext(- team_id=123,- import_id=import_id,- s3_prefix="team/123/session/abc",- session_id="abc",- )-- with patch("posthog.temporal.session_replay.import_recording.activities.Path") as mock_path_cls:-- def path_side_effect(p):- if p == "/tmp":- return tmp_path- return Path(p)-- mock_path_cls.side_effect = path_side_effect-- await import_event_clickhouse_rows(context)---async def test_cleanup_import_data_success(tmp_path):- import_id = uuid4()- import_dir = tmp_path / str(import_id)- import_dir.mkdir(parents=True)- (import_dir / "test_file.json").write_text("test content")-- assert import_dir.exists()-- context = ImportContext(- team_id=123,- import_id=import_id,- s3_prefix="team/123/session/abc",- session_id="abc",- )-- with patch("posthog.temporal.session_replay.import_recording.activities.Path") as mock_path_cls:-- def path_side_effect(p):- if p == "/tmp":- return tmp_path- return Path(p)-- mock_path_cls.side_effect = path_side_effect-- await cleanup_import_data(context)-- assert not import_dir.exists()---async def test_cleanup_import_data_directory_not_exists(tmp_path):- import_id = uuid4()-- context = ImportContext(- team_id=123,- import_id=import_id,- s3_prefix="team/123/session/abc",- session_id="abc",- )-- with patch("posthog.temporal.session_replay.import_recording.activities.Path") as mock_path_cls:-- def path_side_effect(p):- if p == "/tmp":- return tmp_path- return Path(p)-- mock_path_cls.side_effect = path_side_effect-- await cleanup_import_data(context)diff --git a/posthog/temporal/tests/session_replay/import_recording/test_types.py b/posthog/temporal/tests/session_replay/import_recording/test_types.pydeleted file mode 100644index b1656a3ca11a..000000000000--- a/posthog/temporal/tests/session_replay/import_recording/test_types.py+++ /dev/null@@ -1,23 +0,0 @@-from uuid import uuid4--from posthog.temporal.session_replay.import_recording.types import ImportContext, ImportRecordingInput---def test_import_recording_input_creation():- input = ImportRecordingInput(team_id=123, export_file="/tmp/export.zip")- assert input.team_id == 123- assert input.export_file == "/tmp/export.zip"---def test_import_context_creation():- import_id = uuid4()- context = ImportContext(- team_id=123,- import_id=import_id,- s3_prefix="team/123/session/abc",- session_id="abc",- )- assert context.team_id == 123- assert context.import_id == import_id- assert context.s3_prefix == "team/123/session/abc"- assert context.session_id == "abc"diff --git a/posthog/temporal/tests/session_replay/import_recording/test_workflow.py b/posthog/temporal/tests/session_replay/import_recording/test_workflow.pydeleted file mode 100644index 412c70c48404..000000000000--- a/posthog/temporal/tests/session_replay/import_recording/test_workflow.py+++ /dev/null@@ -1,7 +0,0 @@-from posthog.temporal.session_replay.import_recording.workflow import ImportRecordingWorkflow---def test_import_recording_workflow_parse_inputs():- input = ImportRecordingWorkflow.parse_inputs(['{"team_id": 123, "export_file": "/tmp/export.zip"}'])- assert input.team_id == 123- assert input.export_file == "/tmp/export.zip"diff --git a/products/replay/backend/services/__init__.py b/products/replay/backend/services/__init__.pydeleted file mode 100644index ad75f9b5e88e..000000000000--- a/products/replay/backend/services/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-from .export_recording import ReplayActivityContext, trigger_recording_export--__all__ = [- "ReplayActivityContext",- "trigger_recording_export",-]diff --git a/products/replay/backend/services/export_recording.py b/products/replay/backend/services/export_recording.pydeleted file mode 100644index 76be6c0c7a31..000000000000--- a/products/replay/backend/services/export_recording.py+++ /dev/null@@ -1,86 +0,0 @@-import uuid-import asyncio-import dataclasses-from datetime import timedelta--from django.conf import settings--import structlog-from temporalio import common--from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, log_activity-from posthog.models.team.team import Team-from posthog.models.user import User-from posthog.temporal.common.client import sync_connect-from posthog.temporal.session_replay.export_recording.types import ExportRecordingInput--from products.replay.backend.models.exported_recording import ExportedRecording--logger = structlog.get_logger(__name__)--[email protected](frozen=True)-class ReplayActivityContext(ActivityContextBase):- reason: str---def trigger_recording_export(- *,- team: Team,- session_id: str,- reason: str,- user: User,- was_impersonated: bool,-) -> ExportedRecording:- export_record = ExportedRecording.objects.create(- team=team,- session_id=session_id,- reason=reason,- created_by=user,- )-- try:- temporal = sync_connect()- workflow_input = ExportRecordingInput(exported_recording_id=export_record.id)- workflow_id = f"export-recording-{export_record.id}-{uuid.uuid4()}"-- asyncio.run(- temporal.start_workflow(- "export-recording",- workflow_input,- id=workflow_id,- task_queue=settings.SESSION_REPLAY_TASK_QUEUE,- retry_policy=common.RetryPolicy(- maximum_attempts=2,- initial_interval=timedelta(minutes=1),- ),- )- )- except Exception:- export_record.status = ExportedRecording.Status.FAILED- export_record.error_message = "Failed to start the export workflow"- export_record.save(update_fields=["status", "error_message"])- raise-- # The workflow has started; an audit-log write failure must not fail the export- # (which would 502 and prompt a retry that starts a duplicate workflow).- try:- log_activity(- organization_id=team.organization_id,- team_id=team.id,- user=user,- was_impersonated=was_impersonated,- item_id=session_id,- scope="Replay",- activity="exported",- detail=Detail(- name=f"Session replay {session_id}",- short_id=session_id,- type="admin_export",- context=ReplayActivityContext(reason=reason),- ),- )- except Exception:- logger.exception("export_recording_activity_log_failed", team_id=team.id, session_id=session_id)-- return export_recorddiff --git a/products/replay/backend/test/__init__.py b/products/replay/backend/test/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/replay/backend/test/test_export_recording_service.py b/products/replay/backend/test/test_export_recording_service.pydeleted file mode 100644index 8bb0f2d389f3..000000000000--- a/products/replay/backend/test/test_export_recording_service.py+++ /dev/null@@ -1,94 +0,0 @@-from posthog.test.base import BaseTest-from unittest.mock import AsyncMock, MagicMock, patch--from products.replay.backend.models.exported_recording import ExportedRecording-from products.replay.backend.services.export_recording import trigger_recording_export--SERVICE = "products.replay.backend.services.export_recording"---class TestTriggerRecordingExport(BaseTest):- def _run(self, *, was_impersonated: bool = False) -> tuple[ExportedRecording, MagicMock, MagicMock]:- mock_temporal = MagicMock()- mock_temporal.start_workflow = AsyncMock(return_value=None)-- with (- patch(f"{SERVICE}.sync_connect", return_value=mock_temporal),- patch(f"{SERVICE}.log_activity") as mock_log_activity,- ):- record = trigger_recording_export(- team=self.team,- session_id="session-123",- reason="debugging a customer issue",- user=self.user,- was_impersonated=was_impersonated,- )- return record, mock_temporal.start_workflow, mock_log_activity-- def test_creates_exported_recording_row(self) -> None:- record, _, _ = self._run()-- persisted = ExportedRecording.objects.get(id=record.id)- assert persisted.team == self.team- assert persisted.session_id == "session-123"- assert persisted.reason == "debugging a customer issue"- assert persisted.created_by == self.user- assert persisted.status == ExportedRecording.Status.PENDING-- def test_starts_export_workflow_for_the_new_record(self) -> None:- record, start_workflow, _ = self._run()-- start_workflow.assert_called_once()- args, kwargs = start_workflow.call_args- assert args[0] == "export-recording"- assert args[1].exported_recording_id == record.id- assert kwargs["id"].startswith(f"export-recording-{record.id}-")-- def test_forwards_was_impersonated_to_activity_log(self) -> None:- _, _, mock_log_activity = self._run(was_impersonated=True)-- mock_log_activity.assert_called_once()- assert mock_log_activity.call_args.kwargs["was_impersonated"] is True- assert mock_log_activity.call_args.kwargs["scope"] == "Replay"- assert mock_log_activity.call_args.kwargs["activity"] == "exported"-- def test_marks_record_failed_when_workflow_start_fails(self) -> None:- mock_temporal = MagicMock()- mock_temporal.start_workflow = AsyncMock(side_effect=RuntimeError("temporal down"))-- with (- patch(f"{SERVICE}.sync_connect", return_value=mock_temporal),- patch(f"{SERVICE}.log_activity") as mock_log_activity,- ):- with self.assertRaises(RuntimeError):- trigger_recording_export(- team=self.team,- session_id="session-456",- reason="debugging",- user=self.user,- was_impersonated=False,- )-- persisted = ExportedRecording.objects.get(team=self.team, session_id="session-456")- assert persisted.status == ExportedRecording.Status.FAILED- assert persisted.error_message == "Failed to start the export workflow"- mock_log_activity.assert_not_called()-- def test_activity_log_failure_does_not_fail_the_export(self) -> None:- mock_temporal = MagicMock()- mock_temporal.start_workflow = AsyncMock(return_value=None)-- with (- patch(f"{SERVICE}.sync_connect", return_value=mock_temporal),- patch(f"{SERVICE}.log_activity", side_effect=RuntimeError("activity log down")),- ):- record = trigger_recording_export(- team=self.team,- session_id="session-789",- reason="debugging",- user=self.user,- was_impersonated=False,- )-- persisted = ExportedRecording.objects.get(id=record.id)- assert persisted.status == ExportedRecording.Status.PENDINGdiff --git a/products/replay/package.json b/products/replay/package.jsonindex a633124d00f9..58ebdedd00e9 100644--- a/products/replay/package.json+++ b/products/replay/package.json@@ -1,7 +1,7 @@{"name": "@posthog/products-replay","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/test -v --tb=short"+ "backend:test": "echo 'No backend tests'"},"dependencies": {"kea": "catalog:",diff --git a/products/replay/skills/analysing-exported-session-recordings/SKILL.md b/products/replay/skills/analysing-exported-session-recordings/SKILL.mddeleted file mode 100644index 3652e7aca18e..000000000000--- a/products/replay/skills/analysing-exported-session-recordings/SKILL.md+++ /dev/null@@ -1,97 +0,0 @@-----name: analysing-exported-session-recordings-description: >-- Decode and analyse a downloaded session-recording export zip (the `data/` blocks- plus ClickHouse metadata) to understand what is making a recording large or slow:- size composition by DOM mutations vs full snapshots vs network bodies, biggest- payloads, content-type breakdown, churned tags/attributes. Use when asked "why is- this recording so big?", "what's in this export?", "break down replay size for- this session", "analyse the exported recording", or to validate whether a- size-reduction change (e.g. skipping binary network bodies) would actually help a- given session. Pairs with `exporting-session-recordings`, which produces the zip- this skill reads.------# Analysing exported session recordings--An export bundles a recording's raw v2 storage blocks (under `data/`) plus its-ClickHouse metadata (`session-replay-events.json`, `events.json`).-Use this skill to crack those blocks open and measure what the recording is made of,-so size or performance conclusions rest on decoded data — not on raw bytes.--Get the zip first via the `exporting-session-recordings` skill.--## The one thing that will mislead you: the blocks are double-compressed--A `data/` block is **not** readable JSON. It is two layers deep, and skipping either-layer makes the bytes look like binary garbage or "corruption" that isn't there:--1. **Whole block: snappy-compressed.** The exporter fetches blocks with- `decompress=False` (`export_recording/activities.py`), so it writes the raw S3- object. Each block is `snappy`-compressed and written at its byte offset, zero-padded- (so a `data/` file is mostly `\x00` with the real block at the end). Snappy keeps- literal text runs verbatim with binary copy-tokens between them, which is why a raw- block reads as "half JSON, half binary".-2. **Per field: gzip-compressed.** Once snappy-decompressed, a block is JSONL of- `["windowId", {event}]` rows. Events tagged `cv: "2024-10"` have their heavy DOM- fields (full-snapshot `data`; mutation `adds`/`attributes`/`texts`/`removes`)- individually gzip-compressed and stored as a binary-in-JSON string via fflate- `strFromU8(gzipSync(strToU8(json)), true)` — each string char is one gzip byte.--**Do not measure or draw conclusions from the raw block bytes.** Reading them as UTF-8-produces phantom `U+FFFD` runs and wildly wrong size splits (e.g. network bodies look-tiny because they are still snappy-compressed). Always decode both layers first, then-measure. The decoder script below does this; reach for it before hand-rolling anything.--The exporter is lossless — it round-trips the raw S3 block (base64 through Redis, binary-write). Do **not** "fix" the exporter to decompress: export and import are a matched pair-that re-upload the raw blocks, so changing the export format breaks `import_recording`.-The decode belongs on the read side.--## Decoding and the size report--`scripts/decode_recording_export.py` does snappy-then-gzip and reports composition.-It needs a snappy codec (`pip install python-snappy`, or `cramjam`).--```bash-# size + composition report (accepts the zip directly, or an already-extracted dir)-python scripts/decode_recording_export.py export-<session_id>.zip--# also emit fully-decoded events (DOM fields un-gzipped and inlined) for deeper digging-python scripts/decode_recording_export.py export-<session_id>.zip --dump-jsonl decoded.jsonl-```--The report gives you:--- **Decompressed DOM payload** split across full snapshots vs mutation- `adds`/`attributes`/`texts`/`removes` — `adds` and repeated full snapshots are the- usual DOM-side offenders.-- **Network bodies** by response content-type — these are stored **un-gzipped** in the- JSONL, so compare them to DOM on **decoded** size, never on raw bytes.-- **Top tag names and mutated attribute keys**, to see what the DOM churn actually is- (e.g. SVG icon trees, inline `style` animation churn).--## Reading the numbers honestly--- **Compare like with like.** DOM fields are gzip-then-snappy; network bodies are- plaintext-then-snappy. The report's decompressed sizes tell you what is _in_ the- recording (and what the player must hold), which is the right lens for "what should we- cut". For "what does it cost to store/ingest", remember network bodies compress far- better than already-gzipped DOM, so their stored share is smaller than their decoded- share.-- **A handful of blocks may fail to snappy-decompress** (empty/edge blocks). The script- logs and skips them; a few skips do not move the totals.-- **Blocks are sequential byte ranges and should not overlap** — if you write your own- pass, sanity-check for duplicate `(name, timestamp, kind, len)` bodies before trusting- a total.--## Worked example (validated)--A long single-page-app session decoded to ~70 MiB of DOM payload but **~253 MiB of-network bodies**, of which `binary/octet-stream` (136 MiB), `image/webp` (18.5 MiB) and-`image/svg+xml` (3.5 MiB) were binary assets captured as text. The lesson that earned-this skill: measuring those same bodies on the raw (still-snappy) bytes reported only-single-digit MiB and pointed at the wrong culprit. Decoded, the conclusion flips —-skipping binary network bodies (`feat(replay): skip binary/asset bodies in network-capture`, posthog-js #3912) is the dominant lever for a session like this, not a-rounding error. Decode before you conclude.diff --git a/products/replay/skills/analysing-exported-session-recordings/scripts/decode_recording_export.py b/products/replay/skills/analysing-exported-session-recordings/scripts/decode_recording_export.pydeleted file mode 100644index e564c10f682d..000000000000--- a/products/replay/skills/analysing-exported-session-recordings/scripts/decode_recording_export.py+++ /dev/null@@ -1,281 +0,0 @@-#!/usr/bin/env python3-"""Decode and analyse a session-recording export zip.--An export (see the `exporting-session-recordings` skill) bundles the recording's-raw v2 storage blocks under `data/` plus ClickHouse metadata. The blocks are the-RAW S3 objects: each is snappy-compressed, written at its byte offset and-zero-padded (the exporter fetches with decompress=False). Inside, once-snappy-decompressed, each block is JSONL of `["windowId", {event}]` rows; events-tagged `cv: "2024-10"` have their heavy DOM fields individually gzip-compressed-and stored as binary-in-JSON strings (fflate `strFromU8(gzipSync(...), true)`).--So fully decoding is two layers: snappy (whole block) then gzip (per field).--Usage:- python decode_recording_export.py <export.zip|dir> [--report] [--dump-jsonl OUT.jsonl]--Requires a snappy codec: `python-snappy` (preferred) or `cramjam`.-"""--from __future__ import annotations--import argparse-import collections-import gzip-import json-import re-import sys-import zipfile-from pathlib import Path-from typing import Callable, Iterator--EVENT_TYPES = {0: "DomContentLoaded", 1: "Load", 2: "FullSnapshot", 3: "Incremental", 4: "Meta", 5: "Custom", 6: "Plugin"}-INCREMENTAL_SOURCES = {- 0: "Mutation",- 1: "MouseMove",- 2: "MouseInteraction",- 3: "Scroll",- 4: "ViewportResize",- 5: "Input",- 6: "TouchMove",- 7: "MediaInteraction",- 8: "StyleSheetRule",- 9: "CanvasMutation",- 10: "Font",- 11: "Log",- 12: "Drag",- 13: "StyleDeclaration",- 14: "Selection",- 15: "AdoptedStyleSheet",-}-COMPRESSED_MUTATION_FIELDS = ("adds", "attributes", "texts", "removes")-TAG_RE = re.compile(rb'"tagName":"([^"]+)"')-ATTR_KEY_RE = re.compile(rb'"([a-zA-Z_:-]+)":')---def _load_snappy() -> Callable[[bytes], bytes]:- try:- import snappy # noqa: PLC0415 — optional codec, resolved at runtime-- return snappy.decompress- except ImportError:- pass- try:- import cramjam # noqa: PLC0415 — fallback codec, resolved at runtime-- return lambda b: bytes(cramjam.snappy.decompress(b))- except ImportError as err:- raise SystemExit("Need a snappy codec. Install with `pip install python-snappy` (or `cramjam`).") from err---def _strip_null_padding(raw: bytes) -> bytes:- start = 0- while start < len(raw) and raw[start] == 0:- start += 1- end = len(raw)- while end > start and raw[end - 1] == 0:- end -= 1- return raw[start:end]---def _block_to_text(name: str, raw: bytes, snappy_decompress: Callable[[bytes], bytes]) -> str | None:- block = _strip_null_padding(raw)- if not block:- return None- try:- return snappy_decompress(block).decode("utf-8", "replace")- except Exception as err: # noqa: BLE001 — a single bad block shouldn't abort the run- print(f" ! skipped block {name}: {err}", file=sys.stderr)- return None---def iter_block_text(source: Path, snappy_decompress: Callable[[bytes], bytes]) -> Iterator[str]:- """Yield the snappy-decompressed UTF-8 text of every data block, one block in memory at a time."""- if source.is_dir():- block_paths = sorted((source / "data").glob("*")) if (source / "data").is_dir() else sorted(source.glob("*"))- for path in block_paths:- if path.is_file():- text = _block_to_text(path.name, path.read_bytes(), snappy_decompress)- if text is not None:- yield text- else:- # keep a single zip handle open for the whole iteration; read+decode one block at a time- with zipfile.ZipFile(source) as zf:- for name in zf.namelist():- if name.startswith("data/") and not name.endswith("/"):- text = _block_to_text(name, zf.read(name), snappy_decompress)- if text is not None:- yield text---def iter_records(block_text: str) -> Iterator[dict]:- """Yield the event dict from each `["windowId", {event}]` JSONL row."""- for line in block_text.split("\n"):- line = line.strip()- if not line:- continue- try:- row = json.loads(line)- except json.JSONDecodeError:- continue- if isinstance(row, list) and len(row) == 2 and isinstance(row[1], dict):- yield row[1]---def gunzip_field(field: str) -> bytes:- """Reverse fflate `strFromU8(gzipSync(...), true)`: each char is one gzip byte."""- return gzip.decompress(bytes(ord(c) & 0xFF for c in field))---class Report:- def __init__(self) -> None:- self.records = 0- self.gz_ok = 0- self.gz_fail = 0- self.dom_bytes: collections.Counter[str] = collections.Counter()- self.dom_n: collections.Counter[str] = collections.Counter()- self.tags: collections.Counter[str] = collections.Counter()- self.attrs: collections.Counter[str] = collections.Counter()- self.net_body_bytes = 0- self.net_bodies = 0- self.net_bytes_by_content_type: collections.Counter[str] = collections.Counter()-- def add_dom(self, label: str, decompressed: bytes, collect_tags: bool, collect_attrs: bool) -> None:- self.dom_bytes[label] += len(decompressed)- self.dom_n[label] += 1- if collect_tags:- for tag in TAG_RE.findall(decompressed):- self.tags[tag.decode("utf-8", "replace").lower()] += 1- if collect_attrs:- for attr in ATTR_KEY_RE.findall(decompressed):- self.attrs[attr.decode()] += 1---def analyse(source: Path) -> Report:- snappy_decompress = _load_snappy()- report = Report()- for block_text in iter_block_text(source, snappy_decompress):- for event in iter_records(block_text):- report.records += 1- cv = event.get("cv")- data = event.get("data")- event_type = event.get("type")-- if cv == "2024-10" and event_type == 2 and isinstance(data, str):- _decode_into(report, "FullSnapshot", data, collect_tags=True, collect_attrs=False)- elif cv == "2024-10" and event_type == 3 and isinstance(data, dict):- for field in COMPRESSED_MUTATION_FIELDS:- value = data.get(field)- if isinstance(value, str):- _decode_into(- report,- f"mutation.{field}",- value,- collect_tags=(field == "adds"),- collect_attrs=(field == "attributes"),- )- elif event_type == 6 and isinstance(data, dict):- _measure_network(report, data)- return report---def _decode_into(report: Report, label: str, field: str, collect_tags: bool, collect_attrs: bool) -> None:- try:- decompressed = gunzip_field(field)- except Exception: # noqa: BLE001 — count and move on; one field shouldn't abort- report.gz_fail += 1- return- report.gz_ok += 1- report.add_dom(label, decompressed, collect_tags, collect_attrs)---def _measure_network(report: Report, data: dict) -> None:- payload = data.get("payload")- requests = payload.get("requests") if isinstance(payload, dict) else None- for request in requests or []:- content_type = "unknown"- headers = request.get("responseHeaders") or {}- if isinstance(headers, dict):- for header, value in headers.items():- if header.lower() == "content-type" and isinstance(value, str):- content_type = value.split(";")[0].strip()- for key in ("requestBody", "responseBody"):- body = request.get(key)- if isinstance(body, str):- report.net_body_bytes += len(body)- report.net_bodies += 1- report.net_bytes_by_content_type[content_type] += len(body)---def print_report(report: Report) -> None:- dom_total = sum(report.dom_bytes.values())- print(f"records parsed: {report.records:,} gzip fields ok={report.gz_ok:,} fail={report.gz_fail:,}\n")- print(f"=== decompressed DOM payload: {dom_total:,} bytes ({dom_total / 1024 / 1024:.1f} MiB) ===")- for label, by in report.dom_bytes.most_common():- share = 100 * by / dom_total if dom_total else 0- print(f" {label:20} n={report.dom_n[label]:7,} {by:14,} ({by / 1024 / 1024:7.1f} MiB, {share:4.1f}%)")-- net_total = report.net_body_bytes- print(f"\n=== network bodies: {net_total:,} bytes ({net_total / 1024 / 1024:.1f} MiB) across {report.net_bodies:,} bodies ===")- print(" (these are stored UN-gzipped in the JSONL, unlike DOM fields — compare decoded sizes, not raw bytes)")- for ct, by in report.net_bytes_by_content_type.most_common(10):- share = 100 * by / net_total if net_total else 0- print(f" {by / 1024 / 1024:8.1f} MiB ({share:4.1f}%) {ct}")-- print("\n=== top tagNames (FullSnapshot + adds) ===")- for tag, n in report.tags.most_common(20):- print(f" {n:9,} {tag}")-- print("\n=== top mutated attribute keys ===")- for attr, n in report.attrs.most_common(20):- print(f" {n:9,} {attr}")---def dump_jsonl(source: Path, out_path: Path) -> None:- """Write fully-decoded events (DOM fields un-gzipped, inlined) to a JSONL file."""- snappy_decompress = _load_snappy()- written = 0- with out_path.open("w") as out:- for block_text in iter_block_text(source, snappy_decompress):- for event in iter_records(block_text):- cv = event.get("cv")- data = event.get("data")- if cv == "2024-10" and event.get("type") == 2 and isinstance(data, str):- try:- event["data"] = json.loads(gunzip_field(data))- event.pop("cv", None)- except Exception: # noqa: BLE001- pass- elif cv == "2024-10" and event.get("type") == 3 and isinstance(data, dict):- for field in COMPRESSED_MUTATION_FIELDS:- value = data.get(field)- if isinstance(value, str):- try:- data[field] = json.loads(gunzip_field(value))- except Exception: # noqa: BLE001- pass- event.pop("cv", None)- out.write(json.dumps(event, separators=(",", ":")))- out.write("\n")- written += 1- print(f"wrote {written:,} decoded events to {out_path}")---def main() -> None:- parser = argparse.ArgumentParser(description="Decode and analyse a session-recording export zip.")- parser.add_argument("source", type=Path, help="path to export-<id>.zip or an extracted export directory")- parser.add_argument("--report", action="store_true", help="print the size/composition report (default)")- parser.add_argument("--dump-jsonl", type=Path, metavar="OUT", help="write fully-decoded events to a JSONL file")- args = parser.parse_args()-- if not args.source.exists():- raise SystemExit(f"no such path: {args.source}")-- if args.dump_jsonl:- dump_jsonl(args.source, args.dump_jsonl)- if args.report or not args.dump_jsonl:- print_report(analyse(args.source))---if __name__ == "__main__":- main()diff --git a/products/replay/skills/exporting-session-recordings/SKILL.md b/products/replay/skills/exporting-session-recordings/SKILL.mddeleted file mode 100644index f8c10773e6eb..000000000000--- a/products/replay/skills/exporting-session-recordings/SKILL.md+++ /dev/null@@ -1,78 +0,0 @@-----name: exporting-session-recordings-description: >-- Export a single session recording's raw data (recording blocks + ClickHouse- metadata) to a downloadable zip, and download it. Staff-only, via the django- admin portal. Use when asked to "export a session recording", "get the raw- recording data", "download a replay export", "pull a recording for- analysis/support", or to inspect recording block / canvas frame sizes offline.- Explains the team-ownership rule, how to build the admin export / download links- for the owning team, and that there is no export or download API/MCP tool.------# Exporting session recordings--Exporting bundles a recording's storage blocks plus its ClickHouse metadata-(`events.json`, `session-replay-events.json`) into a zip in object storage, for-offline analysis or support. It is **staff-only** and writes nothing back to the-recording.--There is **no export API or MCP tool** — a recording export is a cross-tenant,-token/agent-reachable PII export, which is too dangerous to expose on the-programmatic surface. Exporting (and downloading) is done **only** through the-django admin portal, under interactive staff auth. Your job is to hand the user-the right admin links.--## The one rule that matters: export from the team that owns the recording--The export workflow fetches recording blocks and events **filtered by the team you-run the export for** (block storage is keyed by team; the events query filters-`team_id`). If you run it for the wrong team, the job still reaches-`status: complete` — but the zip is **empty** (zero blocks, empty `events.json`).-"Complete" means "the workflow ran", not "it found data".--So always export from the **owning team's** admin page. The owning `team_id` is-visible in the recording's storage path and in `export_location`-(`session_recording_exports/<team_id>/<session_id>/<uuid>.zip`).--## Exporting via the admin portal (generate these links)--You need the **owning `team_id`** to build the links. If you only have a-`session_id`, get the team from the recording's project (or ask the user). Use the-correct region host — `us.posthog.com` or `eu.posthog.com` — matching where the-recording lives.--- **Trigger the export** (form takes `session_id` + `reason`; `reason` is audited):- `https://<region>.posthog.com/admin/posthog/team/<team_id>/export-replay/`-- **See exports + download buttons** for that team:- `https://<region>.posthog.com/admin/posthog/team/<team_id>/export-history/`-- **Direct download** of one archive once `status` is `complete`:- `https://<region>.posthog.com/admin/posthog/team/<team_id>/download-export/<export_id>/`--Hand the user the export-replay link to start it, then the export-history link to-poll status and download. A small recording takes seconds to a couple of minutes-(it gathers blocks plus ClickHouse metadata); the export-history page shows-`pending` / `running` / `complete` / `failed`.--## Downloading the archive--The download view (export-history / download-export links above) streams the zip-straight from the replay-v2 S3 bucket as `export-<session_id>.zip`. `export_location`-is only a storage key, not a URL. The admin pod holds the prod credentials, so a-local dev or agent session cannot `aws s3 cp` the key itself — the user downloads-from the admin page in their browser.--## Gotchas--- **Empty-but-complete** is the failure mode to watch for — see the team rule. If an- archive is unexpectedly tiny, the export almost certainly ran from the wrong- team's admin page.-- **Expiry:** exports older than 7 days report `is_expired: true` and their data may- be purged. Re-export rather than relying on an old job.-- **Stuck `running`:** a failed export used to sit in `running` forever; a new export- now reaps any export still `pending`/`running` past ~48h to `failed`, so old wedged- rows clear themselves. Don't read a long-stale `running` as "still working".-- **Large recordings:** multi-GB recordings (tab-left-open-for-days outliers) are not- practical to export — the pipeline base64s every block through Redis and zero-pads- to byte offsets on disk. Prefer recordings in the hundreds-of-MB range.-- **Reason is audit-logged** and surfaced in admin — write it for a human reviewer.