: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
feat: add logging around asyncify for better observability (#57740)
ryans-posthogb7b89298e083
diff --git a/posthog/temporal/common/utils.py b/posthog/temporal/common/utils.pyindex 2b0124b1cdb3..03cf8358b641 100644--- a/posthog/temporal/common/utils.py+++ b/posthog/temporal/common/utils.py@@ -1,15 +1,16 @@import timeimport inspect+import threadingfrom collections.abc import Callable, Coroutinefrom datetime import datetimefrom functools import wrapsfrom typing import Any, ParamSpec, TypeVar, cast+import django.dbfrom django.conf import settings-from django.db import close_old_connectionsfrom asgiref.sync import sync_to_async-from temporalio import workflow+from temporalio import activity, workflowP = ParamSpec("P")T = TypeVar("T")@@ -65,15 +66,42 @@ def asyncify(fn: Callable[P, T]) -> Callable[P, Coroutine[Any, Any, T]]:@wraps(fn)async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:- return await sync_to_async(fn)(*args, **kwargs)+ submit_time = time.monotonic()++ def instrumented() -> T:+ start_time = time.monotonic()+ try:+ return fn(*args, **kwargs)+ finally:+ now = time.monotonic()+ thread_wait = start_time - submit_time+ execution_time = now - start_time+ if activity.in_activity():+ activity.logger.warning(+ "asyncify_slow",+ extra={+ "function": fn.__name__,+ "thread_wait_seconds": round(thread_wait, 3),+ "execution_seconds": round(execution_time, 3),+ "thread_name": threading.current_thread().name,+ "activity_id": activity.info().activity_id,+ },+ )++ return await sync_to_async(thread_sensitive=False)(close_db_connections(instrumented))()return wrapper+def _close_initialized_connections() -> None:+ for conn in django.db.connections.all(initialized_only=True):+ conn.close()++def _close_db_connections() -> None:"""Close old database connections to prevent usage of stale connections in long-running Temporal workers."""if not settings.TEST:- close_old_connections()+ _close_initialized_connections()def close_db_connections(fn: Callable[P, T]) -> Callable[P, T]:@@ -89,18 +117,11 @@ def close_db_connections(fn: Callable[P, T]) -> Callable[P, T]:Skipped under ``settings.TEST`` to avoid tearing down the test DB connectionthat ``transaction=True`` fixtures rely on.- Stack below ``@activity.defn``. For sync activities wrapped in ``@asyncify``,- place ``@close_db_connections`` *innermost* so connection cleanup runs on the- same ``sync_to_async`` thread as the ORM work::-+ Stack below ``@activity.defn``. Asyncified activities should use the ``@asyncify`` decorator instead,+ which preserves type hints for Temporal's serialization while allowing sync Django ORM code.@activity.defn@close_db_connectionsasync def my_activity(...): ...-- @activity.defn- @asyncify- @close_db_connections- def my_sync_activity(...): ..."""if inspect.iscoroutinefunction(fn):diff --git a/posthog/temporal/tests/common/test_utils.py b/posthog/temporal/tests/common/test_utils.pyindex 198280708d73..e52823571b8a 100644--- a/posthog/temporal/tests/common/test_utils.py+++ b/posthog/temporal/tests/common/test_utils.py@@ -78,7 +78,7 @@ def test_make_sync_retryable_with_exponential_backoff_raises_if_not_retryable():assert counter == 1-CLOSE_OLD_CONNECTIONS_TARGET = "posthog.temporal.common.utils.close_old_connections"+CLOSE_OLD_CONNECTIONS_TARGET = "posthog.temporal.common.utils._close_initialized_connections"@pytest.mark.parametrize(diff --git a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.pyindex 280a4c478f67..1818f0fbe185 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py@@ -37,7 +37,7 @@ class TestCreateSnapshotActivity:team_id=github_integration.team_id,)- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_create_snapshot_success(self, activity_environment, github_integration):config = SandboxConfig(name="test-create-snapshot",@@ -74,7 +74,7 @@ class TestCreateSnapshotActivity:if created_snapshot_external_id:Sandbox.delete_snapshot(created_snapshot_external_id)- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_create_snapshot_contains_only_current_repo(self, activity_environment, github_integration):"""Verify that snapshots only contain the current repository, not accumulated repos from base."""base_snapshot = SandboxSnapshot.objects.create(@@ -115,7 +115,7 @@ class TestCreateSnapshotActivity:if created_snapshot_external_id:Sandbox.delete_snapshot(created_snapshot_external_id)- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_create_snapshot_sandbox_not_found(self, activity_environment, github_integration):context = self._create_context(github_integration, "test-owner/test-repo")input_data = CreateSnapshotInput(context=context, sandbox_id="non-existent-sandbox-id")diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.pyindex 1304615b20f2..74c231ca77a0 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py@@ -32,7 +32,7 @@ class TestGetSandboxForRepositoryActivity:task_created_by_id=test_task.created_by_id,)- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_sandbox_with_existing_snapshot(self, activity_environment, github_integration, test_task, test_task_run):@@ -65,7 +65,7 @@ class TestGetSandboxForRepositoryActivity:except Exception:pass- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_sandbox_without_snapshot_returns_should_create_snapshot(self, activity_environment, github_integration, test_task, test_task_run):@@ -90,7 +90,7 @@ class TestGetSandboxForRepositoryActivity:except Exception:pass- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_sandbox_creates_sandbox_from_base_when_no_snapshot(self, activity_environment, github_integration, test_task, test_task_run):@@ -118,7 +118,7 @@ class TestGetSandboxForRepositoryActivity:except Exception:pass- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_sandbox_includes_environment_variables(self, activity_environment, github_integration, test_task, test_task_run):diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.pyindex d1e91e77bbd8..9f9bd3918245 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py@@ -33,7 +33,7 @@ class TestGetTaskProcessingContextActivity:def _cleanup_task(self, task):task.soft_delete()- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_success(self, activity_environment, test_task):task_run = test_task.create_run()input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))@@ -48,7 +48,7 @@ class TestGetTaskProcessingContextActivity:assert result.repository == "posthog/posthog-js"assert result.create_pr is True- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_task_not_found(self, activity_environment):non_existent_run_id = "550e8400-e29b-41d4-a716-446655440000"input_data = GetTaskProcessingContextInput(run_id=non_existent_run_id)@@ -56,7 +56,7 @@ class TestGetTaskProcessingContextActivity:with pytest.raises(TaskNotFoundError):async_to_sync(activity_environment.run)(get_task_processing_context, input_data)- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_invalid_uuid(self, activity_environment):invalid_run_id = "not-a-uuid"input_data = GetTaskProcessingContextInput(run_id=invalid_run_id)@@ -64,7 +64,7 @@ class TestGetTaskProcessingContextActivity:with pytest.raises(ValidationError):async_to_sync(activity_environment.run)(get_task_processing_context, input_data)- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_with_different_repository(self, activity_environment, team, user, github_integration):@@ -83,7 +83,7 @@ class TestGetTaskProcessingContextActivity:finally:self._cleanup_task(task)- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_with_create_pr_false(self, activity_environment, test_task):task_run = test_task.create_run()input_data = GetTaskProcessingContextInput(run_id=str(task_run.id), create_pr=False)@@ -92,7 +92,7 @@ class TestGetTaskProcessingContextActivity:assert isinstance(result, TaskProcessingContext)assert result.create_pr is False- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_resolves_user_github_integration_without_repository(self, activity_environment, team, user):@@ -122,7 +122,7 @@ class TestGetTaskProcessingContextActivity:assert result.github_user_integration_id == str(user_integration.id)assert result.has_github_credentials is True- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_uses_team_integration_without_repository(self, activity_environment, team, user, github_integration):@@ -146,7 +146,7 @@ class TestGetTaskProcessingContextActivity:assert result.github_user_integration_id is Noneassert result.has_github_credentials is True- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_resolves_allowed_domains(self, activity_environment, test_task):sandbox_environment = SandboxEnvironment.objects.create(team=test_task.team,@@ -164,7 +164,7 @@ class TestGetTaskProcessingContextActivity:assert result.sandbox_environment_name == "Restricted env"assert result.allowed_domains == ["example.com"]- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_preserves_empty_restricted_domains(self, activity_environment, test_task):sandbox_environment = SandboxEnvironment.objects.create(team=test_task.team,@@ -181,7 +181,7 @@ class TestGetTaskProcessingContextActivity:assert result.sandbox_environment_id == str(sandbox_environment.id)assert result.allowed_domains == []- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_keeps_full_access_unrestricted(self, activity_environment, test_task):sandbox_environment = SandboxEnvironment.objects.create(team=test_task.team,@@ -198,7 +198,7 @@ class TestGetTaskProcessingContextActivity:assert result.sandbox_environment_id == str(sandbox_environment.id)assert result.allowed_domains is None- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_rejects_other_users_private_sandbox_environment(self, activity_environment, test_task):@@ -225,7 +225,7 @@ class TestGetTaskProcessingContextActivity:with pytest.raises(TaskInvalidStateError):async_to_sync(activity_environment.run)(get_task_processing_context, input_data)- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)@pytest.mark.parametrize("flag_value, expected",[@@ -253,7 +253,7 @@ class TestGetTaskProcessingContextActivity:assert kwargs["groups"] == {"organization": org_id}assert kwargs["group_properties"] == {"organization": {"id": org_id}}- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_exposes_ci_prompt(self, activity_environment, test_task):custom_prompt = "Re-run the failed mypy checks and push a fix."test_task.ci_prompt = custom_prompt@@ -265,7 +265,7 @@ class TestGetTaskProcessingContextActivity:assert result.ci_prompt == custom_prompt- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_get_task_processing_context_exposes_runtime_metadata(self, activity_environment, test_task):task_run = test_task.create_run(extra_state={diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py b/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.pyindex 9e2448e5a27e..013efc2e3570 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py@@ -18,7 +18,7 @@ from products.tasks.backend.temporal.process_task.activities.provision_sandbox i)[email protected]_db(transaction=True)class TestInjectFreshTokensOnResumeActivity:@pytest.fixturedef sandbox(self):diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.pyindex 983a7bbee95a..6062277332b5 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py@@ -12,7 +12,7 @@ from products.tasks.backend.temporal.process_task.activities.update_task_run_sta@pytest.mark.requires_secretsclass TestUpdateTaskRunStatusActivity:- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)@pytest.mark.parametrize("status,sets_completed_at",[@@ -33,7 +33,7 @@ class TestUpdateTaskRunStatusActivity:else:assert test_task_run.completed_at is None- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_updates_error_message(self, activity_environment, test_task_run):error_msg = "Something went wrong"input_data = UpdateTaskRunStatusInput(@@ -46,7 +46,7 @@ class TestUpdateTaskRunStatusActivity:test_task_run.refresh_from_db()assert test_task_run.error_message == error_msg- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")def test_publishes_stream_state_event(self, mock_publish_stream_state_event, activity_environment, test_task_run):input_data = UpdateTaskRunStatusInput(run_id=str(test_task_run.id), status=TaskRun.Status.IN_PROGRESS)@@ -55,7 +55,7 @@ class TestUpdateTaskRunStatusActivity:mock_publish_stream_state_event.assert_called_once()- @pytest.mark.django_db+ @pytest.mark.django_db(transaction=True)def test_handles_non_existent_task_run(self, activity_environment):non_existent_run_id = "550e8400-e29b-41d4-a716-446655440000"input_data = UpdateTaskRunStatusInput(