: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(python): prep for 3.13 - asyncio and ast deprecations (#59438)
Raúl Negrón-Oterob08050993ebc
diff --git a/ee/hogai/stream/redis_stream.py b/ee/hogai/stream/redis_stream.pyindex f62fe9e907ce..8358d81d7c38 100644--- a/ee/hogai/stream/redis_stream.py+++ b/ee/hogai/stream/redis_stream.py@@ -236,7 +236,7 @@ class ConversationRedisStream:delay_increment = 0.15 # Increment by 150ms each attemptmax_delay = 2.0 # Cap at 2 secondstimeout = 60.0 # 60 seconds timeout- start_time = asyncio.get_event_loop().time()+ start_time = asyncio.get_running_loop().time()last_iteration_time = Noneattempts = 0@@ -252,7 +252,7 @@ class ConversationRedisStream:last_iteration_time = current_timeattempts += 1- elapsed_time = asyncio.get_event_loop().time() - start_time+ elapsed_time = asyncio.get_running_loop().time() - start_timeif elapsed_time >= timeout:logger.debug(f"Stream creation timeout after {elapsed_time:.2f}s",@@ -294,7 +294,7 @@ class ConversationRedisStream:RedisStreamEvent"""current_id = start_id- start_time = asyncio.get_event_loop().time()+ start_time = asyncio.get_running_loop().time()last_iteration_time = Nonewhile True:@@ -304,7 +304,7 @@ class ConversationRedisStream:REDIS_READ_ITERATION_LATENCY_HISTOGRAM.observe(iteration_duration)last_iteration_time = current_time- if asyncio.get_event_loop().time() - start_time > self._timeout:+ if asyncio.get_running_loop().time() - start_time > self._timeout:raise StreamError("Stream timeout - conversation took too long to complete")try:diff --git a/ee/hogai/stream/test/test_redis_stream.py b/ee/hogai/stream/test/test_redis_stream.pyindex 0ed37c42e09f..b93c25bdc54e 100644--- a/ee/hogai/stream/test/test_redis_stream.py+++ b/ee/hogai/stream/test/test_redis_stream.py@@ -62,7 +62,7 @@ class TestRedisStream(BaseTest):mock_client.exists = AsyncMock(return_value=False)with patch("asyncio.sleep", new_callable=AsyncMock):- with patch("ee.hogai.stream.redis_stream.asyncio.get_event_loop") as mock_get_loop:+ with patch("ee.hogai.stream.redis_stream.asyncio.get_running_loop") as mock_get_loop:from unittest.mock import MagicMockmock_loop = MagicMock()@@ -135,7 +135,7 @@ class TestRedisStream(BaseTest):# Mock xread to return no messages indefinitelymock_client.xread = AsyncMock(return_value=[])- with patch("asyncio.get_event_loop") as mock_loop:+ with patch("ee.hogai.stream.redis_stream.asyncio.get_running_loop") as mock_loop:mock_loop.return_value.time.side_effect = [0, CONVERSATION_STREAM_TIMEOUT + 1]with self.assertRaises(StreamError) as context:diff --git a/posthog/hogql_queries/utils/formula_ast.py b/posthog/hogql_queries/utils/formula_ast.pyindex 2645845d2a0a..3d1f7fe1126c 100644--- a/posthog/hogql_queries/utils/formula_ast.py+++ b/posthog/hogql_queries/utils/formula_ast.py@@ -75,8 +75,10 @@ class FormulaAST:return operandraise ValueError(f"Operator {unary_op.__class__.__name__} not supported")- elif isinstance(node, ast.Num):- return node.n+ elif (+ isinstance(node, ast.Constant) and isinstance(node.value, int | float) and not isinstance(node.value, bool)+ ):+ return node.valueelif isinstance(node, ast.Name):try:diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_copy_activity.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_copy_activity.pyindex dc9d8596a3cc..831bb72923f1 100644--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_copy_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_copy_activity.py@@ -28,8 +28,8 @@ from products.batch_exports.backend.tests.temporal.destinations.redshift.utils iMISSING_REQUIRED_ENV_VARS,TEST_MODELS,assert_clickhouse_records_in_redshift,- has_valid_credentials,)+from products.batch_exports.backend.tests.temporal.destinations.s3.utils import has_valid_credentialsfrom products.batch_exports.backend.tests.temporal.utils.persons import (generate_test_person_distinct_id2_in_clickhouse,generate_test_persons_in_clickhouse,diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.pyindex ce47e36e733c..5e7d16ad5f0a 100644--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py@@ -1,12 +1,9 @@import osimport json-import asyncioimport datetime as dtimport operatorimport collections.abc-import aioboto3-import botocore.exceptionsfrom psycopg import sqlfrom posthog.temporal.common.clickhouse import ClickHouseClient@@ -248,21 +245,3 @@ async def assert_clickhouse_records_in_redshift(assert inserted_records[0] == expected_records[0]assert inserted_records == expected_recordsassert len(inserted_records) == len(expected_records)---async def check_valid_credentials() -> bool:- """Check if there are valid AWS credentials in the environment."""- session = aioboto3.Session()- async with session.client("sts") as sts:- try:- await sts.get_caller_identity()- except botocore.exceptions.ClientError:- return False- else:- return True---def has_valid_credentials() -> bool:- """Synchronous wrapper around check_valid_credentials."""- loop = asyncio.get_event_loop()- return loop.run_until_complete(check_valid_credentials())diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.pyindex 2d80a04ccf5b..b5f1ab3f6990 100644--- a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py@@ -93,8 +93,7 @@ async def check_valid_credentials() -> bool:def has_valid_credentials() -> bool:"""Synchronous wrapper around check_valid_credentials."""- loop = asyncio.get_event_loop()- return loop.run_until_complete(check_valid_credentials())+ return asyncio.run(check_valid_credentials())MetricKind = t.Literal["success", "cancellation", "failure", "rows"]diff --git a/services/llm-gateway/tests/test_anthropic.py b/services/llm-gateway/tests/test_anthropic.pyindex 844110d07204..8dd148d7629c 100644--- a/services/llm-gateway/tests/test_anthropic.py+++ b/services/llm-gateway/tests/test_anthropic.py@@ -1,3 +1,4 @@+import asyncioimport osfrom collections.abc import AsyncIteratorfrom typing import Any@@ -1187,9 +1188,7 @@ class TestAnthropicCircuitBreakerIntegration:async def consume() -> list[bytes]:return [chunk async for chunk in wrapped.body_iterator]- import asyncio as _asyncio-- chunks = _asyncio.get_event_loop().run_until_complete(consume())+ chunks = asyncio.run(consume())assert len(chunks) == 2breaker.record_outcome.assert_awaited_with(success=True)@@ -1219,7 +1218,5 @@ class TestAnthropicCircuitBreakerIntegration:except RuntimeError:pass- import asyncio as _asyncio-- _asyncio.get_event_loop().run_until_complete(consume())+ asyncio.run(consume())breaker.record_outcome.assert_awaited_with(success=False)