: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(hogql): stop jev cleanly when a team is out of AI credits (#109341)
Jovan Sakovic254f9c4c7059
diff --git a/posthog/hogql/test/test_prompt_jev.py b/posthog/hogql/test/test_prompt_jev.pyindex 1ef9657595f0..217623cd435a 100644--- a/posthog/hogql/test/test_prompt_jev.py+++ b/posthog/hogql/test/test_prompt_jev.py@@ -110,12 +110,13 @@ class TestPromptJev(SimpleTestCase):PromptJevRunner(team_id=1, distinct_id=None).evaluate(PromptJevCall.parse(node), [value])post.assert_not_called()- def test_gateway_failure_does_not_return_a_decision(self) -> None:+ @parameterized.expand([(429, "could not evaluate"), (402, "used all its AI credits")])+ def test_gateway_failure_does_not_return_a_decision(self, status: int, message: str) -> None:node = parse_expr("jev('refund', 'Refund?')")assert isinstance(node, ast.Call)with (- patch("httpx.AsyncClient.post", return_value=httpx.Response(429)),- self.assertRaisesRegex(QueryError, "could not evaluate"),+ patch("httpx.AsyncClient.post", return_value=httpx.Response(status)),+ self.assertRaisesRegex(QueryError, message),):PromptJevRunner(team_id=1, distinct_id=None).evaluate(PromptJevCall.parse(node), ["refund"])@@ -208,6 +209,26 @@ class TestPromptJevQuery(ClickhouseTestMixin, APIBaseTest):post.assert_not_called()self.assertEqual(self.feature_enabled.call_args.kwargs["groups"]["project"], str(self.team.pk))+ def test_team_out_of_ai_credits_cannot_start_inference(self) -> None:+ with (+ patch("ee.billing.quota_limiting.is_team_over_ai_credit_budget", return_value=True) as limited,+ patch("posthog.hogql.query.sync_execute") as execute,+ patch("httpx.AsyncClient.post") as post,+ self.assertRaisesRegex(QueryError, "used all its AI credits"),+ ):+ execute_hogql_query("SELECT jev('refund', 'Refund?') AS p", self.team, user=self.user)+ execute.assert_not_called()+ post.assert_not_called()+ limited.assert_called_once_with(self.team.api_token)++ def test_credit_lookup_failure_does_not_block_the_query(self) -> None:+ with (+ patch("ee.billing.quota_limiting.is_team_over_ai_credit_budget", side_effect=RuntimeError("redis down")),+ patch("httpx.AsyncClient.post", side_effect=gateway_response),+ ):+ response = execute_hogql_query("SELECT jev('refund', 'Refund?') AS p", self.team, user=self.user)+ self.assertEqual(response.results, [(0.9,)])+@parameterized.expand([("global",), ("team",)])def test_http_route_is_rejected_before_query_or_inference(self, mode: str) -> None:with (diff --git a/posthog/hogql/transforms/prompt_jev.py b/posthog/hogql/transforms/prompt_jev.pyindex be9d1cb50475..916e93454701 100644--- a/posthog/hogql/transforms/prompt_jev.py+++ b/posthog/hogql/transforms/prompt_jev.py@@ -117,6 +117,12 @@ class PromptJevTable:)+OUT_OF_AI_CREDITS_MESSAGE = (+ "jev can't run because your organization has used all its AI credits. "+ "Add credits in billing settings, then try again."+)++@frozenclass _DecisionKey:question: str@@ -163,6 +169,8 @@ class PromptJevRunner:status_code=error.status_code,reason=type(error).__name__,)+ if error.status_code == 402:+ raise QueryError(OUT_OF_AI_CREDITS_MESSAGE) from errorraise QueryError("Jev could not evaluate this query. Try again or select fewer rows.") from errordecisions: dict[str, object] = {}for key, text in state.items():@@ -485,3 +493,19 @@ def validate_prompt_jev_access(team: "Team") -> None:send_feature_flag_events=False,):raise QueryError("jev is not enabled for this project. Contact support to request access.")+ if _is_over_ai_credit_budget(team):+ raise QueryError(OUT_OF_AI_CREDITS_MESSAGE)+++def _is_over_ai_credit_budget(team: "Team") -> bool:+ from ee.billing.quota_limiting import ( # noqa: PLC0415 — keeps the billing query stack off the HogQL import path+ is_team_over_ai_credit_budget,+ )++ try:+ return is_team_over_ai_credit_budget(team.api_token)+ except Exception:+ # The quota cache reads Redis. An outage must not stop a team that has credits, and a team+ # that is really out of them still gets the same message from the gateway's 402.+ logger.warning("prompt_jev_ai_credit_lookup_failed", team_id=team.pk, exc_info=True)+ return False