: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(endpoints): bill materialized fallback runs to the inline rate budget (#129444)
Jovan Sakovic37c915728c91
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.pyindex 92bb3db80370..8fb8e0114f54 100644--- a/products/endpoints/backend/logic/execution.py+++ b/products/endpoints/backend/logic/execution.py@@ -11,6 +11,7 @@ response post-processing, metrics, and failure signals. Kind-specific behaviorimport reimport timeimport uuid+from collections.abc import Callablefrom datetime import datetime, timedeltafrom typing import Literal, Union, cast@@ -518,6 +519,7 @@ class EndpointExecutionService(PydanticModelMixin):version_obj: EndpointVersion | None,limit: int | None = None,offset: int | None = None,+ before_inline_fallback: Callable[[], None] | None = None,) -> Response:"""Run an endpoint version and return the HTTP response.@@ -605,6 +607,8 @@ class EndpointExecutionService(PydanticModelMixin):result = Noneif result is None:+ if materialized_failed and before_inline_fallback is not None:+ before_inline_fallback()result = self._execute_inline_endpoint(endpoint,data,@@ -677,6 +681,8 @@ class EndpointExecutionService(PydanticModelMixin):code, detail = _query_performance_code_and_detail(e)logger.warning("Endpoint query hit a performance limit", endpoint_name=endpoint.name, reason=error_label)raise EndpointQueryTooExpensive(detail, code=code)+ except Throttled:+ raiseexcept ClickHouseAtCapacity as e:execution_status = "capacity"error_label = "ClickHouseAtCapacity"diff --git a/products/endpoints/backend/presentation/throttles.py b/products/endpoints/backend/presentation/throttles.pyindex 8a09534f1746..84dc8f7aad65 100644--- a/products/endpoints/backend/presentation/throttles.py+++ b/products/endpoints/backend/presentation/throttles.py@@ -5,6 +5,7 @@ ones. That classification is resolved through the facade; the throttle classesand their request-parsing helpers are pure HTTP concerns and live here."""+from rest_framework.exceptions import Throttledfrom rest_framework.throttling import SimpleRateThrottlefrom posthog.rate_limit import (@@ -55,6 +56,14 @@ def _is_materialized_endpoint_request(request, view) -> bool:return is_materialized_request(team_id, endpoint_name, version, body)+def _materialized_throttles(request) -> set[type]:+ granted = getattr(request, "endpoint_materialized_throttles", None)+ if granted is None:+ granted = set()+ request.endpoint_materialized_throttles = granted+ return granted++class _MaterializedRateMixin(SimpleRateThrottle):"""Swaps in the higher materialized-endpoint rate and records 429s, on top of any base throttle.@@ -65,10 +74,12 @@ class _MaterializedRateMixin(SimpleRateThrottle):materialized_rate: strmaterialized_scope: str+ inline_only = Falsedef allow_request(self, request, view):- materialized = _is_materialized_endpoint_request(request, view)+ materialized = not self.inline_only and _is_materialized_endpoint_request(request, view)if materialized:+ _materialized_throttles(request).add(type(self))self.rate = self.materialized_rateself.scope = self.materialized_scopeself.num_requests, self.duration = self.parse_rate(self.rate)@@ -124,3 +135,20 @@ class EndpointProjectSecretApiKeyTeamSustainedThrottle(_MaterializedRateMixin, Prate = APIQueriesSustainedThrottle.ratematerialized_rate = EndpointSustainedThrottle.materialized_ratematerialized_scope = "materialized_endpoint_psak_team_sustained"+++def charge_inline_rate(request, view) -> None:+ """Bill a run that fell back to inline to the inline budget, or refuse it with a 429.++ A throttle that already charged the inline budget for this request is skipped.+ """+ waits = []+ granted = _materialized_throttles(request)+ for throttle in view.get_throttles():+ if type(throttle) not in granted:+ continue+ throttle.inline_only = True+ if not throttle.allow_request(request, view):+ waits.append(throttle.wait())+ if waits:+ raise Throttled(wait=max((wait for wait in waits if wait is not None), default=None))diff --git a/products/endpoints/backend/presentation/views/api.py b/products/endpoints/backend/presentation/views/api.pyindex e94588ffb23c..f00dcab05194 100644--- a/products/endpoints/backend/presentation/views/api.py+++ b/products/endpoints/backend/presentation/views/api.py@@ -90,6 +90,7 @@ from products.endpoints.backend.presentation.throttles import (EndpointProjectSecretApiKeyTeamBurstThrottle,EndpointProjectSecretApiKeyTeamSustainedThrottle,EndpointSustainedThrottle,+ charge_inline_rate,)@@ -731,7 +732,14 @@ class EndpointViewSet(service.log_rejected_run(endpoint, self._rejection_reason(response))return response- return service.execute(endpoint, data, version_obj, limit=limit, offset=offset)+ return service.execute(+ endpoint,+ data,+ version_obj,+ limit=limit,+ offset=offset,+ before_inline_fallback=lambda: charge_inline_rate(request, self),+ )@extend_schema(description=(diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.pyindex 8413c5d2d483..5a08bdf3f6c6 100644--- a/products/endpoints/backend/tests/test_endpoint_execution.py+++ b/products/endpoints/backend/tests/test_endpoint_execution.py@@ -2876,6 +2876,31 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(inline_after - inline_before, 1.0)+ def test_exhausted_inline_budget_refuses_the_fallback_run(self):+ from rest_framework.exceptions import Throttled++ endpoint = self._make_fresh_materialized_endpoint(+ "mat-fallback-throttled", {"kind": "HogQLQuery", "query": "SELECT count() FROM events"}+ )++ with (+ mock.patch.object(+ EndpointExecutionService,+ "_execute_query_and_respond",+ side_effect=RuntimeError("materialized table exploded"),+ ) as mock_exec,+ mock.patch(+ "products.endpoints.backend.presentation.views.api.charge_inline_rate",+ side_effect=Throttled(wait=5),+ ),+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertEqual(mock_exec.call_count, 1, "the inline retry must not run once the inline budget is spent")+def test_paginating_union_query_counts_as_user_error(self):from prometheus_client import REGISTRYdiff --git a/products/endpoints/backend/tests/test_rate_limit.py b/products/endpoints/backend/tests/test_rate_limit.pyindex 587eba076803..044f79af0ec6 100644--- a/products/endpoints/backend/tests/test_rate_limit.py+++ b/products/endpoints/backend/tests/test_rate_limit.py@@ -1,4 +1,5 @@from datetime import timedelta+from types import SimpleNamespacefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -9,6 +10,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom prometheus_client import REGISTRY+from rest_framework.exceptions import Throttledfrom rest_framework.parsers import JSONParserfrom rest_framework.request import Requestfrom rest_framework.test import APIRequestFactory@@ -19,6 +21,7 @@ from products.endpoints.backend.presentation.throttles import (EndpointBurstThrottle,EndpointSustainedThrottle,_is_materialized_endpoint_request,+ charge_inline_rate,)from products.endpoints.backend.rate_limit import (MATERIALIZED_ENDPOINT_CACHE_TTL,@@ -552,6 +555,37 @@ class TestEndpointThrottles(APIBaseTest):{"team_id": self.team.id, "endpoint_name": "refused", "reason": expected_reason},)+ @parameterized.expand(+ [+ ("materialized_run_is_billed_inline", True, True),+ ("inline_run_is_not_billed_twice", False, False),+ ]+ )+ def test_fallback_charge(self, _name, materialized, expect_refusal):+ if materialized:+ _create_ready_materialized_endpoint(self.team, self.user, "fell_back", timezone.now())+ request = SimpleNamespace(data={}, query_params={})+ view = MagicMock()+ view.team_id = self.team.id+ view.kwargs = {"name": "fell_back"}+ view.get_throttles.side_effect = lambda: [EndpointBurstThrottle()]+ inline_labels = {"scope": "api_queries_burst", "reason": "inline_rate"}+ before = REGISTRY.get_sample_value("posthog_endpoint_rate_limited_total", inline_labels) or 0++ with patch("posthog.rate_limit.PersonalOrProjectSecretApiKeyRateThrottle.allow_request", return_value=True):+ for throttle in view.get_throttles():+ self.assertTrue(throttle.allow_request(request, view))++ with patch("posthog.rate_limit.PersonalOrProjectSecretApiKeyRateThrottle.allow_request", return_value=False):+ if expect_refusal:+ with patch.object(EndpointBurstThrottle, "wait", return_value=1), self.assertRaises(Throttled):+ charge_inline_rate(request, view)+ else:+ charge_inline_rate(request, view)++ after = REGISTRY.get_sample_value("posthog_endpoint_rate_limited_total", inline_labels) or 0+ self.assertEqual(after - before, 1 if expect_refusal else 0)+class TestMaterializationStateCacheTimeout(APIBaseTest):def setUp(self):