: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(billing): evaluate the api queries quota without API_QUERIES_ENABLED (#87954)
Andy Zhaoc7e13bb652b6
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 481e25f47118..a3fccde0a1f4 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -3,7 +3,7 @@ from collections.abc import Callable, Sequencefrom datetime import UTC, datetime, timedeltafrom enum import StrEnumfrom functools import cache, cached_property-from time import monotonic, perf_counter+from time import perf_counterfrom types import UnionTypefrom typing import Any, Generic, NamedTuple, Optional, Protocol, TypeGuard, TypeVar, Union, cast, get_args, get_originfrom zoneinfo import ZoneInfo@@ -358,13 +358,7 @@ def shared_insights_execution_mode(execution_mode: ExecutionMode) -> SharedExecudef get_api_queries_quota_limited_until(team: Team) -> Optional[datetime]:- """When a free org is over its monthly chargeable-bytes allowance, returns the moment- the counter resets; otherwise None.-- Recomputed live from the synced subscription column and the Redis counter on every- call, so there is no verdict to go stale after an upgrade. Fails open on error.- """- if not django_settings.API_QUERIES_ENABLED or not django_settings.API_QUERIES_FREE_TIER_READ_BYTES_LIMIT:+ if not django_settings.API_QUERIES_FREE_TIER_READ_BYTES_LIMIT:return Nonetry:if team.organization.has_active_subscription is not False:@@ -378,22 +372,10 @@ def get_api_queries_quota_limited_until(team: Team) -> Optional[datetime]:return None-# Flag evaluation is a network call to the flags service, and it runs once per chargeable-# query from an over-quota org, so a runaway API consumer would hammer that service at its-# own query rate. The short per-process cache bounds that load; the TTL also bounds how long-# a flag flip takes to apply on any one worker.-_ENFORCEMENT_FLAG_TTL_SECONDS = 30-_enforcement_flag_cache: dict[str, tuple[bool, float]] = {}--def _api_queries_enforcement_enabled(team: Team) -> bool:org_id = str(team.organization_id)- cached = _enforcement_flag_cache.get(org_id)- now = monotonic()- if cached is not None and cached[1] > now:- return cached[0]try:- enabled = bool(+ return bool(posthoganalytics.feature_enabled(API_QUERIES_QUOTA_ENFORCEMENT_FLAG,org_id,@@ -404,12 +386,7 @@ def _api_queries_enforcement_enabled(team: Team) -> bool:))except Exception:- # Not cached, so enforcement resumes as soon as the flags service recovers.return False- if len(_enforcement_flag_cache) > 1024:- _enforcement_flag_cache.clear()- _enforcement_flag_cache[org_id] = (enabled, now + _ENFORCEMENT_FLAG_TTL_SECONDS)- return enableddef _format_data_size(bytes_count: int) -> str:diff --git a/posthog/hogql_queries/test/test_api_queries_quota.py b/posthog/hogql_queries/test/test_api_queries_quota.pyindex 06f24e194a26..a491fc853438 100644--- a/posthog/hogql_queries/test/test_api_queries_quota.py+++ b/posthog/hogql_queries/test/test_api_queries_quota.py@@ -17,13 +17,12 @@ from posthog.hogql_queries.query_runner import (API_QUERIES_QUOTA_LIMITED_COUNTER,_api_queries_enforcement_enabled,_api_queries_quota_detail,- _enforcement_flag_cache,_format_data_size,get_api_queries_quota_limited_until,)-@override_settings(API_QUERIES_ENABLED=True, API_QUERIES_FREE_TIER_READ_BYTES_LIMIT=1000)+@override_settings(API_QUERIES_FREE_TIER_READ_BYTES_LIMIT=1000)class TestGetApiQueriesQuotaLimitedUntil(BaseTest):def _set(self, has_active_subscription, counter_bytes):self.organization.has_active_subscription = has_active_subscription@@ -66,11 +65,6 @@ class TestGetApiQueriesQuotaLimitedUntil(BaseTest):after = API_QUERIES_QUOTA_ERRORS_COUNTER.labels(op="check")._value.get()assert after == before + 1- @override_settings(API_QUERIES_ENABLED=False)- def test_disabled_setting_returns_none(self):- self._set(False, 2000)- assert get_api_queries_quota_limited_until(self.team) is None-class TestApiQueriesQuotaDetail(SimpleTestCase):def test_detail_includes_usage_limit_and_reset(self):@@ -116,22 +110,10 @@ class TestApiQueriesQuotaDetail(SimpleTestCase):class TestApiQueriesEnforcementEnabled(BaseTest):- def setUp(self):- super().setUp()- _enforcement_flag_cache.clear()-def test_flag_on_returns_true(self):with patch("posthog.hogql_queries.query_runner.posthoganalytics.feature_enabled", return_value=True):assert _api_queries_enforcement_enabled(self.team) is True- def test_flag_result_is_cached_within_ttl(self):- with patch(- "posthog.hogql_queries.query_runner.posthoganalytics.feature_enabled", return_value=True- ) as mock_flag:- assert _api_queries_enforcement_enabled(self.team) is True- assert _api_queries_enforcement_enabled(self.team) is True- assert mock_flag.call_count == 1-def test_flag_service_error_fails_open_to_false(self):with patch("posthog.hogql_queries.query_runner.posthoganalytics.feature_enabled",@@ -140,12 +122,7 @@ class TestApiQueriesEnforcementEnabled(BaseTest):assert _api_queries_enforcement_enabled(self.team) is False-@override_settings(API_QUERIES_ENABLED=True)class TestApiQueriesQuotaEnforcement(BaseTest):- def setUp(self):- super().setUp()- _enforcement_flag_cache.clear()-def _runner(self):runner = HogQLQueryRunner(query=HogQLQuery(query="select 1"), team=self.team)runner.is_query_service = True