: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(temporal): deliver heartbeats from asyncify activity threads (#107686)
Rafael Audibert0670c81e1872
diff --git a/posthog/temporal/common/heartbeat_sync.py b/posthog/temporal/common/heartbeat_sync.pyindex fd825be74644..566a0bf34c29 100644--- a/posthog/temporal/common/heartbeat_sync.py+++ b/posthog/temporal/common/heartbeat_sync.py@@ -1,37 +1,75 @@import timeimport socket+import asyncioimport threading-from contextvars import copy_context+from collections.abc import Callable, Iterator+from concurrent.futures import Future+from contextlib import contextmanager+from contextvars import ContextVar, copy_contextfrom typing import Any+from structlog import get_loggerfrom structlog.types import FilteringBoundLoggerfrom temporalio import activityfrom posthog.temporal.common.liveness_tracker import get_liveness_tracker+LOGGER = get_logger(__name__)++HEARTBEAT_ACCEPT_TIMEOUT_SECONDS = 10++# An async activity's `activity.heartbeat` only works on the event loop thread.+_loop_heartbeat: ContextVar[Callable[..., None] | None] = ContextVar("loop_heartbeat", default=None)+++@contextmanager+def heartbeat_through_loop(loop: asyncio.AbstractEventLoop) -> Iterator[None]:+ """Make `HeartbeaterSync` send heartbeats through `loop`, for an async activity whose sync body runs on another thread."""+ activity_context = copy_context()++ def heartbeat(*details: Any) -> None:+ accepted: Future[None] = Future()++ def send() -> None:+ try:+ activity.heartbeat(*details)+ except Exception as e:+ accepted.set_exception(e)+ else:+ accepted.set_result(None)++ loop.call_soon_threadsafe(send, context=activity_context)+ accepted.result(timeout=HEARTBEAT_ACCEPT_TIMEOUT_SECONDS)++ token = _loop_heartbeat.set(heartbeat)+ try:+ yield+ finally:+ _loop_heartbeat.reset(token)+class HeartbeaterSync:def __init__(self, details: tuple[Any, ...] = (), factor: int = 12, logger: FilteringBoundLogger | None = None):self.details: tuple[Any, ...] = detailsself.factor = factor- self.logger = logger+ self.logger = logger or LOGGER.bind()self.stop_event: threading.Event | None = Noneself.heartbeat_thread: threading.Thread | None = None- def log_debug(self, message: str, exc_info: Any | None = None) -> None:- if self.logger:- self.logger.debug(message, exc_info=exc_info)+ def log_debug(self, message: str) -> None:+ self.logger.debug(message)def heartbeat_regularly(self, stop_event: threading.Event, interval: int, details: tuple[Any, ...]):tracker = get_liveness_tracker()+ send_heartbeat = _loop_heartbeat.get() or activity.heartbeatwhile not stop_event.is_set():try:extra_payload = {"host": socket.gethostname(), "ts": time.time()}- activity.heartbeat(*details, extra_payload)+ send_heartbeat(*details, extra_payload)tracker.record_heartbeat()self.log_debug("Heartbeat")except Exception as e:- self.log_debug(f"Heartbeat failed {e}", exc_info=e)+ self.logger.warning("Heartbeat failed", error=str(e), exc_info=e)stop_event.wait(interval)def __enter__(self):diff --git a/posthog/temporal/common/utils.py b/posthog/temporal/common/utils.pyindex 8352bb5799da..88625a95c6e4 100644--- a/posthog/temporal/common/utils.py+++ b/posthog/temporal/common/utils.py@@ -1,4 +1,5 @@import time+import asyncioimport inspectimport threadingfrom collections.abc import Callable, Coroutine@@ -13,6 +14,8 @@ from django.conf import settingsfrom asgiref.sync import sync_to_asyncfrom temporalio import activity, workflow+from posthog.temporal.common.heartbeat_sync import heartbeat_through_loop+P = ParamSpec("P")T = TypeVar("T")@@ -137,9 +140,13 @@ def asyncify(fn: Callable[P, T]) -> Callable[P, Coroutine[Any, Any, T]]:f"thread_name={threading.current_thread().name}")- return await sync_to_async(thread_sensitive=False, executor=get_asyncify_executor())(+ run_on_thread = sync_to_async(thread_sensitive=False, executor=get_asyncify_executor())(close_db_connections(instrumented)- )()+ )+ if not activity.in_activity():+ return await run_on_thread()+ with heartbeat_through_loop(asyncio.get_running_loop()):+ return await run_on_thread()return wrapperdiff --git a/posthog/temporal/tests/test_asyncify.py b/posthog/temporal/tests/test_asyncify.pyindex e38034b35b4c..19a20d27c4f6 100644--- a/posthog/temporal/tests/test_asyncify.py+++ b/posthog/temporal/tests/test_asyncify.py@@ -1,15 +1,20 @@import asyncioimport threading+import dataclassesfrom collections.abc import Iteratorfrom concurrent.futures import ThreadPoolExecutor-from typing import Protocol+from datetime import timedelta+from typing import Any, Protocolimport pytestfrom unittest import mockfrom django.conf import settings+from temporalio.testing import ActivityEnvironment+from posthog.temporal.common import utils, worker+from posthog.temporal.common.heartbeat_sync import HeartbeaterSyncfrom posthog.temporal.common.utils import asyncify, configure_asyncify_executor, get_asyncify_executorpytestmark = pytest.mark.asyncio@@ -89,6 +94,53 @@ async def test_asyncify_keeps_unrelated_calls_off_a_saturated_pool(asyncify_execawait asyncio.gather(*saturating)+async def test_asyncify_delivers_heartbeater_sync_heartbeats_on_the_event_loop() -> None:+ loop_thread = threading.get_ident()+ heartbeat_threads: list[int] = []+ heartbeat_seen = threading.Event()++ def record_heartbeat(*details: Any) -> None:+ heartbeat_threads.append(threading.get_ident())+ heartbeat_seen.set()++ @asyncify+ def heartbeat_from_a_worker_thread() -> bool:+ with HeartbeaterSync(factor=10):+ return heartbeat_seen.wait(timeout=BARRIER_TIMEOUT_SECONDS)++ env = ActivityEnvironment()+ env.info = dataclasses.replace(env.info, heartbeat_timeout=timedelta(seconds=1))+ env.on_heartbeat = record_heartbeat++ assert await env.run(heartbeat_from_a_worker_thread)+ assert set(heartbeat_threads) == {loop_thread}+++async def test_asyncify_reports_a_heartbeat_the_sdk_rejects_on_the_event_loop() -> None:+ warned = threading.Event()+ logger = mock.MagicMock()+ logger.warning.side_effect = lambda *args, **kwargs: warned.set()+ tracker = mock.MagicMock()++ def reject_heartbeat(*details: Any) -> None:+ raise RuntimeError("heartbeat rejected")++ @asyncify+ def heartbeat_from_a_worker_thread() -> bool:+ with HeartbeaterSync(factor=10, logger=logger):+ return warned.wait(timeout=BARRIER_TIMEOUT_SECONDS)++ env = ActivityEnvironment()+ env.info = dataclasses.replace(env.info, heartbeat_timeout=timedelta(seconds=1))+ env.on_heartbeat = reject_heartbeat++ with mock.patch("posthog.temporal.common.heartbeat_sync.get_liveness_tracker", return_value=tracker):+ assert await env.run(heartbeat_from_a_worker_thread)++ assert logger.warning.call_args.kwargs["error"] == "heartbeat rejected"+ tracker.record_heartbeat.assert_not_called()++async def test_asyncify_falls_back_to_the_default_executor() -> None:previous = get_asyncify_executor()utils._asyncify_executor = Nonediff --git a/posthog/temporal/tests/weekly_digest/test_activities.py b/posthog/temporal/tests/weekly_digest/test_activities.pyindex 08f2919d5dc2..d84812172588 100644--- a/posthog/temporal/tests/weekly_digest/test_activities.py+++ b/posthog/temporal/tests/weekly_digest/test_activities.py@@ -18,6 +18,9 @@ import fakeredisfrom asgiref.sync import sync_to_asyncfrom temporalio import activity+from posthog.schema import HogQLQueryResponse++from posthog.exceptions import ClickHouseAtCapacityfrom posthog.models.messaging import MessagingRecordfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.organization_notification_lock import OrganizationMemberNotificationLock@@ -844,6 +847,43 @@ def test_generate_usage_trends_lookup_queries_only_teams_with_events(assert redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.USAGE_TRENDS, idle_team.id)) is None+def test_generate_usage_trends_lookup_waits_out_a_busy_clickhouse(team, redis_servers, common_input, digest):+ with (+ patch(+ "posthog.temporal.weekly_digest.activities.sync_execute",+ side_effect=[ClickHouseAtCapacity(), [(team.id,)]],+ ),+ patch(+ "posthog.temporal.weekly_digest.activities.execute_hogql_query",+ side_effect=[ClickHouseAtCapacity(), HogQLQueryResponse(results=[[5, 4, 2, 2]])],+ ),+ patch("posthog.temporal.common.utils.time.sleep"),+ ):+ run_sync(generate_usage_trends_lookup, batch_input(team, digest, common_input))++ stored = json.loads(redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.USAGE_TRENDS, team.id)))+ assert [(metric["label"], metric["current"]) for metric in stored["metrics"]] == [+ ("Events", 5),+ ("Active users", 2),+ ]+++def test_generate_recording_lookup_waits_out_a_busy_clickhouse(team, redis_servers, common_input, digest):+ with (+ patch(+ "posthog.temporal.weekly_digest.activities.sync_execute",+ side_effect=[ClickHouseAtCapacity(), [(team.id, 2)]],+ ),+ patch("posthog.temporal.common.utils.time.sleep"),+ ):+ run_sync(generate_recording_lookup, batch_input(team, digest, common_input))++ stored = json.loads(redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.EXPIRING_RECORDINGS, team.id)))+ assert stored == {"recording_count": 2}++@pytest.mark.django_db@pytest.mark.parametrize("side_effects,should_raise",diff --git a/posthog/temporal/weekly_digest/activities.py b/posthog/temporal/weekly_digest/activities.pyindex 3883b2a6bc77..f4c278c5ba67 100644--- a/posthog/temporal/weekly_digest/activities.py+++ b/posthog/temporal/weekly_digest/activities.py@@ -4,7 +4,7 @@ import timefrom collections import defaultdictfrom collections.abc import Callable, Iterable, Sequencefrom datetime import UTC, datetime-from typing import Any, TypeVar+from typing import Any, ParamSpec, TypeVarfrom uuid import UUIDfrom django.conf import settings@@ -29,6 +29,7 @@ from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.constants import AvailableFeature+from posthog.exceptions import ClickHouseAtCapacityfrom posthog.models.messaging import MessagingRecordfrom posthog.models.organization_notification_lock import GovernedSetting, notification_locks_for_usersfrom posthog.models.team import Team@@ -40,7 +41,7 @@ from posthog.tasks.email import NotificationSetting, should_send_notificationfrom posthog.tasks.email_utils import compute_week_over_week_changefrom posthog.temporal.common.heartbeat_sync import HeartbeaterSyncfrom posthog.temporal.common.logger import get_write_only_logger-from posthog.temporal.common.utils import asyncify+from posthog.temporal.common.utils import asyncify, make_sync_retryable_with_exponential_backofffrom posthog.temporal.weekly_digest.keys import TeamDataKey, UserDataKey, org_digest_key, team_data_key, user_data_keyfrom posthog.temporal.weekly_digest.queries import (query_experiments_completed,@@ -98,6 +99,12 @@ LOGGER = get_write_only_logger()REDIS_COMMAND_CHUNK_SIZE = 5000T = TypeVar("T")+P = ParamSpec("P")+++def _retry_while_clickhouse_busy(fn: Callable[P, T]) -> Callable[P, T]:+ # Other workloads share the offline cluster's per-user query limit, so a rejection clears within seconds.+ return make_sync_retryable_with_exponential_backoff(fn, retryable_exceptions=(ClickHouseAtCapacity,))def _redis_url(common: CommonInput) -> str:@@ -405,11 +412,8 @@ def generate_filter_lookup(input: GenerateDigestDataBatchInput) -> None:TTL_THRESHOLD = 10 # days-def _generate_recording_lookup(input: GenerateDigestDataBatchInput) -> None:- logger = _bind_batch_logger(input)- logger.info("Generating Replay recording count batch")-- eligible_team_ids = _eligible_team_ids(input)+@_retry_while_clickhouse_busy+def _expiring_session_counts(input: GenerateDigestDataBatchInput) -> dict[int, int]:tag_queries(product=Product.INTERNAL, feature=Feature.DIGEST)rows = sync_execute(SessionReplayEvents.count_soon_to_expire_sessions_by_team_query(),@@ -421,14 +425,23 @@ def _generate_recording_lookup(input: GenerateDigestDataBatchInput) -> None:},workload=Workload.OFFLINE,)+ return {team_id: int(count) for team_id, count in rows}+++def _generate_recording_lookup(input: GenerateDigestDataBatchInput) -> None:+ logger = _bind_batch_logger(input)+ logger.info("Generating Replay recording count batch")++ eligible_team_ids = _eligible_team_ids(input)+ counts_by_team = _expiring_session_counts(input)# Teams without expiring recordings get no key; aggregation defaults the count to zero.payload_by_team: dict[int, str] = {}recording_count = 0- for team_id, count in rows:+ for team_id, count in counts_by_team.items():if team_id not in eligible_team_ids:continue- expiring_recordings = RecordingCount(recording_count=int(count))+ expiring_recordings = RecordingCount(recording_count=count)payload_by_team[team_id] = expiring_recordings.model_dump_json()recording_count += expiring_recordings.recording_count@@ -513,6 +526,7 @@ GROUP BY team_id"""+@_retry_while_clickhouse_busydef _active_team_ids(input: GenerateDigestDataBatchInput) -> set[int]:tag_queries(product=Product.INTERNAL, feature=Feature.DIGEST)rows = sync_execute(@@ -528,6 +542,7 @@ def _active_team_ids(input: GenerateDigestDataBatchInput) -> set[int]:return {int(team_id) for (team_id,) in rows}+@_retry_while_clickhouse_busydef _query_team_usage_trends(team: Team, period_start: datetime, period_end: datetime) -> UsageTrends | None:"""Run the per-team usage snapshot on the offline cluster. Returns None for inactive teams."""window = period_end - period_start