: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(clickhouse): return a frozen dataclass from RateLimit.use (#83163)
Arno Hillen6fca5f877e51
diff --git a/posthog/clickhouse/client/limit.py b/posthog/clickhouse/client/limit.pyindex adf9818ff405..17ce7b8fe1dc 100644--- a/posthog/clickhouse/client/limit.py+++ b/posthog/clickhouse/client/limit.py@@ -14,6 +14,7 @@ from posthog import redis, settingsfrom posthog.clickhouse.cluster import ExponentialBackofffrom posthog.clickhouse.query_tagging import Product, add_fallback_query_tags, get_query_tags, tag_queriesfrom posthog.constants import AvailableFeature+from posthog.dataclasses import frozenfrom posthog.schema_enums import ProductKeyfrom posthog.settings import TESTfrom posthog.utils import generate_short_id@@ -74,7 +75,16 @@ def _is_in_temporal() -> bool:return False+@frozen+class ConcurrencySlot:+ """An acquired concurrency slot: the Redis sorted-set key and the member to remove on release."""++ running_tasks_key: str+ task_id: str+++# Mutable by design: tests inject fake clocks by assigning get_time and sleep after construction[email protected](frozen=False)class RateLimit:"""Ensures that only max_concurrency of tasks_name are executed at a given time.@@ -99,18 +109,18 @@ class RateLimit:def run(self, *args, **kwargs):applicable = not self.applicable or self.applicable(*args, **kwargs)- if applicable:- running_task_key, task_id = self.use(*args, **kwargs)+ slot = self.use(*args, **kwargs) if applicable else Nonetry:yieldfinally:- if applicable and running_task_key and task_id:- self.release(running_task_key, task_id)+ if slot is not None:+ self.release(slot)- def use(self, *args, **kwargs) -> tuple[Optional[str], Optional[str]]:+ def use(self, *args, **kwargs) -> Optional[ConcurrencySlot]:"""Acquire the resource before execution or throw exception.+ Returns None when the limiter let the caller through without taking a slot (bypass)."""wait_deadline = self.get_time() + self.retry_timeouttask_name = self.get_task_name(*args, **kwargs)@@ -172,7 +182,7 @@ class RateLimit:result=result,product=product_label,).inc()- return None, None+ return Noneif self.retry and self.get_time() < wait_deadline:CONCURRENT_QUERY_LIMIT_EXCEEDED_COUNTER.labels(@@ -203,13 +213,13 @@ class RateLimit:f"Exceeded maximum concurrency limit: {max_concurrency} for key: {task_name} and task: {task_id}")- return running_tasks_key, task_id+ return ConcurrencySlot(running_tasks_key=running_tasks_key, task_id=task_id)- def release(self, running_task_key, task_id):+ def release(self, slot: ConcurrencySlot) -> None:"""Release the resource, when the execution finishes."""- self.redis_client.zrem(running_task_key, task_id)+ self.redis_client.zrem(slot.running_tasks_key, slot.task_id)def wrap(self, task_func):@wraps(task_func)diff --git a/posthog/clickhouse/client/test/test_execute.py b/posthog/clickhouse/client/test/test_execute.pyindex 8a1935cccf95..9ccbe63abd50 100644--- a/posthog/clickhouse/client/test/test_execute.py+++ b/posthog/clickhouse/client/test/test_execute.py@@ -3,7 +3,7 @@ from unittest.mock import MagicMock, patchfrom posthog.clickhouse.client.connection import ClickHouseUser, Workloadfrom posthog.clickhouse.client.execute import sync_execute-from posthog.clickhouse.client.limit import RateLimit, get_llm_analytics_rate_limiter+from posthog.clickhouse.client.limit import ConcurrencySlot, RateLimit, get_llm_analytics_rate_limiterfrom posthog.clickhouse.query_tagging import AccessMethod, Product, tags_context@@ -21,7 +21,8 @@ def llm_analytics_slots():"""Counts concurrency slots taken per query, with the limiter forced on (it is inert in tests)."""limiter = get_llm_analytics_rate_limiter()with patch.object(limiter, "applicable", lambda *args, **kwargs: True):- with patch.object(RateLimit, "use", return_value=("key", "task")) as use, patch.object(RateLimit, "release"):+ slot = ConcurrencySlot(running_tasks_key="key", task_id="task")+ with patch.object(RateLimit, "use", return_value=slot) as use, patch.object(RateLimit, "release"):yield usediff --git a/posthog/clickhouse/client/test/test_limit.py b/posthog/clickhouse/client/test/test_limit.pyindex 44e22c8d124f..145dd8f9f297 100644--- a/posthog/clickhouse/client/test/test_limit.py+++ b/posthog/clickhouse/client/test/test_limit.py@@ -7,7 +7,7 @@ from unittest.mock import Mock, patchfrom parameterized import parameterized-from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, RateLimit+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, ConcurrencySlot, RateLimitfrom posthog.clickhouse.query_tagging import Product, QueryTags, query_tags, reset_query_tags, tag_queriesfrom posthog.constants import AvailableFeature@@ -24,11 +24,12 @@ class TestRateLimit(BaseTest):get_task_id=lambda *args, **kwargs: f"{kwargs.get('task_id') or args[2]}",ttl=10,)- self.cancels: list[tuple[str | None, str | None]] = []+ self.cancels: list[ConcurrencySlot | None] = []def tearDown(self) -> None:- for a, b in self.cancels:- self.limit.release(a, b)+ for slot in self.cancels:+ if slot is not None:+ self.limit.release(slot)def test_rate_limit(self):args, kwargs = (), {"is_api": True, "team_id": 7, "task_id": 17}@@ -210,11 +211,12 @@ class TestRateLimit(BaseTest):retry_timeout=0.5, # 500ms total timeout)- running_task_key, task_id = retry_limit.use(task_id=1) # consumes the slot+ slot = retry_limit.use(task_id=1) # consumes the slot+ assert slot is not Nonedef on_sleep(duration):if duration > 0.1: # after second sleep, the slot is released- retry_limit.release(running_task_key, task_id)+ retry_limit.release(slot)time_helper = TimeHelper(on_sleep)@@ -417,7 +419,7 @@ class TestMaterializedEndpointsRateLimiter(BaseTest):from posthog.clickhouse.client.limit import get_materialized_endpoints_rate_limiterrate_limiter = get_materialized_endpoints_rate_limiter()- acquired_slots: list[tuple[str | None, str | None]] = []+ acquired_slots: list[ConcurrencySlot | None] = []try:# Acquire all 10 slots@@ -432,9 +434,9 @@ class TestMaterializedEndpointsRateLimiter(BaseTest):rate_limiter.use(team_id=self.team.id, task_id="test-slot-overflow", is_materialized_endpoint=True)finally:# Clean up all acquired slots- for key, task_id in acquired_slots:- if key and task_id:- rate_limiter.release(key, task_id)+ for slot in acquired_slots:+ if slot is not None:+ rate_limiter.release(slot)@patch("posthog.clickhouse.client.limit.TEST", False)def test_rate_limiter_allows_after_release(self):@@ -442,7 +444,7 @@ class TestMaterializedEndpointsRateLimiter(BaseTest):from posthog.clickhouse.client.limit import get_materialized_endpoints_rate_limiterrate_limiter = get_materialized_endpoints_rate_limiter()- acquired_slots: list[tuple[str | None, str | None]] = []+ acquired_slots: list[ConcurrencySlot | None] = []try:# Fill all 10 slots@@ -453,18 +455,18 @@ class TestMaterializedEndpointsRateLimiter(BaseTest):acquired_slots.append(slot)# Release one slot- key, task_id = acquired_slots.pop()- if key and task_id:- rate_limiter.release(key, task_id)+ released = acquired_slots.pop()+ if released is not None:+ rate_limiter.release(released)# Now a new request should succeednew_slot = rate_limiter.use(team_id=self.team.id, task_id="test-release-new", is_materialized_endpoint=True)acquired_slots.append(new_slot)finally:# Clean up- for key, task_id in acquired_slots:- if key and task_id:- rate_limiter.release(key, task_id)+ for slot in acquired_slots:+ if slot is not None:+ rate_limiter.release(slot)class TestAppOrgRateLimiter(BaseTest):diff --git a/posthog/test/dataclass_frozen_baseline.txt b/posthog/test/dataclass_frozen_baseline.txtindex 91a0fd5ad5a2..b877e31fada8 100644--- a/posthog/test/dataclass_frozen_baseline.txt+++ b/posthog/test/dataclass_frozen_baseline.txt@@ -13,7 +13,6 @@1 posthog/api/oauth/toolbar_service.py1 posthog/api/test/test_event_definition.py1 posthog/cache_utils.py-1 posthog/clickhouse/client/limit.py1 posthog/clickhouse/custom_metrics.py1 posthog/clickhouse/explain.py1 posthog/clickhouse/property_groups.pydiff --git a/products/notebooks/backend/temporal/frame_materialize.py b/products/notebooks/backend/temporal/frame_materialize.pyindex 7790133e0d13..66ebf2f90c6b 100644--- a/products/notebooks/backend/temporal/frame_materialize.py+++ b/products/notebooks/backend/temporal/frame_materialize.py@@ -66,7 +66,7 @@ from posthog.clickhouse.client.connection import ()from posthog.clickhouse.client.execute import kill_switch_overridesfrom posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager, get_query_status-from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, RateLimit+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, ConcurrencySlot, RateLimitfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.clickhouse.workload import Workloadfrom posthog.dataclasses import frozen@@ -307,20 +307,20 @@ def _materialize_slots(team_id: int, task_id: str) -> Iterator[None]:"""global_limiter = _get_global_limiter()team_limiter = _get_per_team_limiter()- global_key, global_task = global_limiter.use(task_id=f"{task_id}:global", team_id=team_id)- team_key = team_task = None+ global_slot = global_limiter.use(task_id=f"{task_id}:global", team_id=team_id)+ team_slot: ConcurrencySlot | None = Nonetry:- team_key, team_task = team_limiter.use(task_id=f"{task_id}:team", team_id=team_id)+ team_slot = team_limiter.use(task_id=f"{task_id}:team", team_id=team_id)yieldfinally:# Release each slot independently: a Redis blip releasing the team slot must not# skip the global release and leak a global slot until its 15-minute TTL.- if team_key and team_task:+ if team_slot is not None:with suppress(Exception):- team_limiter.release(team_key, team_task)- if global_key and global_task:+ team_limiter.release(team_slot)+ if global_slot is not None:with suppress(Exception):- global_limiter.release(global_key, global_task)+ global_limiter.release(global_slot)def _capped_settings(team_id: int) -> HogQLGlobalSettings: