:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(session-replay): bound score export concurrency (#71121)
Nicholas Waltzbbf07a338b2c
diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.pyindex 27c807ed84e8..c4dd6bb78cde 100644--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py@@ -23,6 +23,9 @@ REEXPORT_WINDOW_DAYS = SCORE_LOOKBACK_DAYS + 1# `cityHash64(session_id) % OF_CHUNKS` partitioning, same scheme as the scoring sweep.DEFAULT_OF_CHUNKS = 8+# Keep this background export within a small share of the shared ClickHouse query capacity.+MAX_CONCURRENT_EXPORT_PARTITIONS = 4+SCORE_EXPORT_PREFIX_ENV_VAR = "SESSION_RECORDING_ML_SCORE_EXPORT_PREFIX"DEFAULT_SCORE_EXPORT_PREFIX = "score"@@ -36,7 +39,17 @@ EXPORT_PAGE_MAX_ROWS = 500_000LIST_PARTITIONS_ACTIVITY_TIMEOUT = timedelta(seconds=30)EXPORT_PARTITION_ACTIVITY_TIMEOUT = timedelta(minutes=20)+EXPORT_PARTITION_MAX_ATTEMPTS = 3+# > CH_EXPORT_QUERY_TIMEOUT_S — heartbeats fire between page fetches, not during a SELECT.EXPORT_PARTITION_HEARTBEAT_TIMEOUT = timedelta(minutes=3)-WORKFLOW_EXECUTION_TIMEOUT = timedelta(hours=1)+# Leave enough time for every bounded wave to exhaust its activity retry budget,+# plus headroom for planning, retry backoff, and workflow task scheduling.+_MAX_PARTITIONS_PER_SWEEP = REEXPORT_WINDOW_DAYS * DEFAULT_OF_CHUNKS+_MAX_PARTITION_WAVES = (+ _MAX_PARTITIONS_PER_SWEEP + MAX_CONCURRENT_EXPORT_PARTITIONS - 1+) // MAX_CONCURRENT_EXPORT_PARTITIONS+WORKFLOW_EXECUTION_TIMEOUT = (+ _MAX_PARTITION_WAVES * EXPORT_PARTITION_ACTIVITY_TIMEOUT * EXPORT_PARTITION_MAX_ATTEMPTS + timedelta(hours=1)+)diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.pyindex 41ad60d17b6c..9378b86ce56d 100644--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py@@ -12,7 +12,9 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.session_replay.surfacing_score_export_sweep.constants import (EXPORT_PARTITION_ACTIVITY_TIMEOUT,EXPORT_PARTITION_HEARTBEAT_TIMEOUT,+ EXPORT_PARTITION_MAX_ATTEMPTS,LIST_PARTITIONS_ACTIVITY_TIMEOUT,+ MAX_CONCURRENT_EXPORT_PARTITIONS,WORKFLOW_NAME,)from posthog.temporal.session_replay.surfacing_score_export_sweep.types import (@@ -29,6 +31,9 @@ with workflow.unsafe.imports_passed_through():)+_PATCH_BOUNDED_PARTITION_FANOUT = "surfacing-score-export-bounded-partition-fanout"++@workflow.defn(name=WORKFLOW_NAME)class ExportSurfacingScoresWorkflow(PostHogWorkflow):inputs_cls = ExportScoresSweepInputs@@ -51,8 +56,20 @@ class ExportSurfacingScoresWorkflow(PostHogWorkflow):workflow.logger.info("surfacing_score_export_sweep.no_work")return ExportScoresSweepResult()+ # Activity dispatch is recorded in Temporal history, so gate this change for deterministic replay.+ # The schedule timeout covers the retry budget for every bounded wave.+ concurrency = len(plan.partitions)+ if workflow.patched(_PATCH_BOUNDED_PARTITION_FANOUT):+ concurrency = min(MAX_CONCURRENT_EXPORT_PARTITIONS, concurrency)++ semaphore = asyncio.Semaphore(concurrency)++ async def _export_with_semaphore(spec: ExportPartitionSpec) -> ExportPartitionResult:+ async with semaphore:+ return await self._export_partition(spec)+results = await asyncio.gather(- *(self._export_partition(spec) for spec in plan.partitions),+ *(_export_with_semaphore(spec) for spec in plan.partitions),return_exceptions=True,)return _summarize(plan.partitions, results)@@ -64,7 +81,7 @@ class ExportSurfacingScoresWorkflow(PostHogWorkflow):start_to_close_timeout=EXPORT_PARTITION_ACTIVITY_TIMEOUT,heartbeat_timeout=EXPORT_PARTITION_HEARTBEAT_TIMEOUT,retry_policy=RetryPolicy(- maximum_attempts=3,+ maximum_attempts=EXPORT_PARTITION_MAX_ATTEMPTS,non_retryable_error_types=["PseudonymKeyNotConfiguredError","PseudonymKeyFingerprintMismatchError",diff --git a/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_workflow.py b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_workflow.pynew file mode 100644index 000000000000..afedaf8ba46b--- /dev/null+++ b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_workflow.py@@ -0,0 +1,57 @@+import asyncio++import pytest+from unittest.mock import MagicMock, patch++from posthog.temporal.session_replay.surfacing_score_export_sweep.activities import (+ export_scores_partition_activity,+ list_export_partitions_activity,+)+from posthog.temporal.session_replay.surfacing_score_export_sweep.constants import MAX_CONCURRENT_EXPORT_PARTITIONS+from posthog.temporal.session_replay.surfacing_score_export_sweep.types import (+ ExportPartitionResult,+ ExportPartitionSpec,+ ExportScoresSweepInputs,+ ListExportPartitionsResult,+)+from posthog.temporal.session_replay.surfacing_score_export_sweep.workflow import ExportSurfacingScoresWorkflow+++async def test_bounds_concurrent_partition_activities() -> None:+ partition_count = MAX_CONCURRENT_EXPORT_PARTITIONS + 3+ partitions = [+ ExportPartitionSpec(day="2026-07-14", chunk_id=chunk_id, of_chunks=partition_count)+ for chunk_id in range(partition_count)+ ]+ active = 0+ peak_active = 0++ async def execute_activity(+ activity: object, activity_input: object, **_: object+ ) -> ListExportPartitionsResult | ExportPartitionResult:+ nonlocal active, peak_active++ if activity is list_export_partitions_activity:+ return ListExportPartitionsResult(partitions=partitions)++ assert activity is export_scores_partition_activity+ assert isinstance(activity_input, ExportPartitionSpec)+ active += 1+ peak_active = max(peak_active, active)+ try:+ await asyncio.sleep(0)+ return ExportPartitionResult(day=activity_input.day, chunk_id=activity_input.chunk_id, rows=1)+ finally:+ active -= 1++ with (+ patch("temporalio.workflow.execute_activity", side_effect=execute_activity),+ patch("temporalio.workflow.patched", return_value=True),+ patch("temporalio.workflow.logger", MagicMock()),+ ):+ result = await ExportSurfacingScoresWorkflow().run(ExportScoresSweepInputs())++ assert peak_active == MAX_CONCURRENT_EXPORT_PARTITIONS+ assert result.partitions_dispatched == partition_count+ assert result.total_rows == partition_count