: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): stop the scoring sweep exhausting ClickHouse query slots (#92118)
Tue Haulundf8212263627b
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex d5c0a414347e..fb3b9009a262 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -95,6 +95,8 @@ class ClickHouseUser(StrEnum):ENDPOINTS = "endpoints"BILLING = "billing"REPLAY_VISION = "replay_vision"+ # Session replay surfacing scoring sweep+ SURFACING_SCORING = "surfacing_scoring"# Backups - used by Dagster backup jobsBACKUPS = "backups"diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.pyindex cd56598f8c8b..049287e7bafe 100644--- a/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py@@ -40,6 +40,7 @@ from temporalio import activityfrom temporalio.exceptions import ApplicationErrorfrom posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTSfrom posthog.models.event.util import format_clickhouse_timestamp@@ -82,6 +83,7 @@ def _count_unscored_in_one_bucket(lookback_days: int, of_chunks: int) -> int:sync_execute(surfacing_scoring_sweep_sql.count_unscored_sql(),{"lookback_days": lookback_days, "of_chunks": of_chunks},+ ch_user=ClickHouseUser.SURFACING_SCORING,settings={"max_execution_time": CH_FEATURE_QUERY_TIMEOUT_S,"max_memory_usage": CH_FEATURE_QUERY_MAX_MEMORY_BYTES,@@ -145,6 +147,7 @@ def _fetch_features_dataframe(spec: ChunkSpec) -> pd.DataFrame:"chunk_id": spec.chunk_id,"chunk_size": spec.chunk_size,},+ ch_user=ClickHouseUser.SURFACING_SCORING,settings={"max_execution_time": CH_FEATURE_QUERY_TIMEOUT_S,"max_memory_usage": CH_FEATURE_QUERY_MAX_MEMORY_BYTES,diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/constants.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/constants.pyindex 52cdab7c5860..a050d56ea88c 100644--- a/posthog/temporal/session_replay/surfacing_scoring_sweep/constants.py+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/constants.py@@ -29,6 +29,11 @@ TARGET_SESSIONS_PER_TICK = 200_000DEFAULT_OF_CHUNKS = 20TARGET_CHUNK_SIZE = TARGET_SESSIONS_PER_TICK // DEFAULT_OF_CHUNKS+# Fanning all DEFAULT_OF_CHUNKS out at once exceeds ClickHouse's per-user concurrent query+# limit (max_concurrent_queries_for_user, set per user in posthog-cloud-infra), and ClickHouse+# rejects the excess outright, so those chunks score nothing until the next tick.+MAX_CONCURRENT_SCORE_CHUNKS = 8+# Window for "score eligible" rows. Older sessions are intentionally left# unscored — if a session hasn't been scored within this window its features# are no longer useful for downstream summarization.@@ -58,6 +63,9 @@ SCORE_CHUNK_ACTIVITY_TIMEOUT = timedelta(minutes=4)SCORE_CHUNK_HEARTBEAT_TIMEOUT = timedelta(seconds=90)LIST_CHUNKS_ACTIVITY_TIMEOUT = timedelta(seconds=30)-# Parent workflow has to outlive its longest in-flight chunk activity, but-# must not stretch into the next 5-min tick.+# Parent workflow has to outlive its longest in-flight chunk activity, but must not stretch+# into the next 5-min tick. MAX_CONCURRENT_SCORE_CHUNKS makes this a throughput bound as well:+# the tick fits while the mean chunk stays under+# WORKFLOW_EXECUTION_TIMEOUT * MAX_CONCURRENT_SCORE_CHUNKS / DEFAULT_OF_CHUNKS. Past that the+# workflow expires with chunks undispatched, and those sessions wait for the next tick.WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=4, seconds=30)diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.pyindex e753fb7b8221..9fb8169eca51 100644--- a/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py@@ -3,9 +3,10 @@Per tick (driven by `schedule.py`):1. `list_chunks_activity` plans the fan-out — N deterministic hash-partitionedchunks, each carrying a `(chunk_id, of_chunks, chunk_size)` spec only.- 2. All chunks are dispatched via `asyncio.gather` so they run in parallel- across the worker pool. Each `score_chunk_activity` is fully self-- contained (fetch + predict + write happen inside one activity).+ 2. Chunks are dispatched via `asyncio.gather` behind a semaphore, so at most+ `MAX_CONCURRENT_SCORE_CHUNKS` run at once and the rest start as slots free.+ Each `score_chunk_activity` is fully self-contained (fetch + predict ++ write happen inside one activity).The workflow stays tiny on purpose:* No per-session work in the workflow code path (workflow CPU is precious).@@ -27,6 +28,7 @@ from temporalio.exceptions import ActivityErrorfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.session_replay.surfacing_scoring_sweep.constants import (LIST_CHUNKS_ACTIVITY_TIMEOUT,+ MAX_CONCURRENT_SCORE_CHUNKS,SCORE_CHUNK_ACTIVITY_TIMEOUT,SCORE_CHUNK_HEARTBEAT_TIMEOUT,WORKFLOW_NAME,@@ -48,6 +50,9 @@ with workflow.unsafe.imports_passed_through():from posthog.temporal.session_replay.surfacing_scoring_sweep.metrics import record_tick_summary+_PATCH_BOUNDED_CHUNK_FANOUT = "surfacing-scoring-bounded-chunk-fanout"++@workflow.defn(name=WORKFLOW_NAME)class ScoreSessionsBatchWorkflow(PostHogWorkflow):"""One tick of the scoring pipeline."""@@ -73,8 +78,18 @@ class ScoreSessionsBatchWorkflow(PostHogWorkflow):)return ScoreSessionsBatchResult()+ # Activity dispatch order is recorded in Temporal history, so gate the bound for+ # deterministic replay of runs that started before it.+ semaphore = asyncio.Semaphore(+ MAX_CONCURRENT_SCORE_CHUNKS if workflow.patched(_PATCH_BOUNDED_CHUNK_FANOUT) else len(plan.chunks)+ )++ async def _score_with_semaphore(spec: ChunkSpec) -> ChunkResult:+ async with semaphore:+ return await self._score_chunk(spec)+results = await asyncio.gather(- *(self._score_chunk(spec) for spec in plan.chunks),+ *(_score_with_semaphore(spec) for spec in plan.chunks),return_exceptions=True,)diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.pyindex 8d518bac0e21..7d6850318477 100644--- a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py@@ -1,6 +1,7 @@from __future__ import annotationsimport uuid+import asynciofrom datetime import timedeltaimport pytest@@ -11,7 +12,11 @@ from temporalio import activityfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Worker-from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import WORKFLOW_NAME+from posthog.temporal.session_replay.surfacing_scoring_sweep.activities import (+ list_chunks_activity,+ score_chunk_activity,+)+from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import MAX_CONCURRENT_SCORE_CHUNKS, WORKFLOW_NAMEfrom posthog.temporal.session_replay.surfacing_scoring_sweep.types import (ChunkResult,ChunkSpec,@@ -217,3 +222,42 @@ async def test_workflow_survives_empty_chunk_results() -> None:assert parsed.total_scored == 0assert parsed.chunks_failed == 0assert parsed.chunks_dispatched == 2++[email protected]("patched", [True, False])+async def test_bounds_concurrent_score_chunk_activities(patched: bool) -> None:+ # ClickHouse rejects queries past the per-user concurrency limit outright, and a rejected+ # chunk scores nothing until the next tick, so the sweep must not dispatch every chunk at once.+ # Unpatched runs keep dispatching everything, which is what makes replay deterministic.+ chunk_count = MAX_CONCURRENT_SCORE_CHUNKS + 3+ chunks = [_chunk(chunk_id, of_chunks=chunk_count) for chunk_id in range(chunk_count)]+ active = 0+ peak_active = 0++ async def execute_activity(activity_fn: object, activity_input: object, **_: object) -> object:+ nonlocal active, peak_active++ if activity_fn is list_chunks_activity:+ return _plan(chunks)++ assert activity_fn is score_chunk_activity+ assert isinstance(activity_input, ChunkSpec)+ active += 1+ peak_active = max(peak_active, active)+ try:+ await asyncio.sleep(0)+ return ChunkResult(chunk_id=activity_input.chunk_id, scored=1, fetched=1)+ finally:+ active -= 1++ with (+ mock.patch("temporalio.workflow.execute_activity", side_effect=execute_activity),+ mock.patch("temporalio.workflow.patched", return_value=patched),+ mock.patch("temporalio.workflow.logger", mock.MagicMock()),+ mock.patch("posthog.temporal.session_replay.surfacing_scoring_sweep.workflow.record_tick_summary"),+ ):+ result = await ScoreSessionsBatchWorkflow().run(ScoreSessionsBatchInputs())++ assert peak_active == (MAX_CONCURRENT_SCORE_CHUNKS if patched else chunk_count)+ assert _as_batch_result(result).chunks_dispatched == chunk_count