: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): make the jev row and decision limits settings (#109877)
Jovan Sakovic6539ac05a670
diff --git a/posthog/hogql/test/test_prompt_jev.py b/posthog/hogql/test/test_prompt_jev.pyindex a7197bfd082a..58d29041bd6a 100644--- a/posthog/hogql/test/test_prompt_jev.py+++ b/posthog/hogql/test/test_prompt_jev.py@@ -65,6 +65,14 @@ class TestPromptJev(SimpleTestCase):budget.visit(parse_select(query))self.assertEqual(budget.decisions, expected)+ @override_settings(HOGQL_JEV_MAX_ROWS=5000, HOGQL_JEV_MAX_DECISIONS=10000)+ def test_raised_limits_reserve_and_allow_more_decisions(self) -> None:+ budget = PromptJevBudget()+ budget.visit(parse_select("SELECT jev('a', 'q') AS p, jev('b', 'q') AS q LIMIT 5000"))+ self.assertEqual(budget.decisions, 10000)+ with self.assertRaisesRegex(QueryError, "query budget of 10000"):+ PromptJevBudget().visit(parse_select("SELECT jev('a', 'q') AS p, jev('b', 'q') AS q, jev('c', 'q') AS r"))+def test_unused_ctes_do_not_reserve_budget(self) -> None:budget = PromptJevBudget()budget.visit(parse_select("WITH a AS (SELECT jev('a', 'q') AS p), b AS (SELECT jev('b', 'q') AS p) SELECT 1"))@@ -339,14 +347,18 @@ class TestPromptJevQuery(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.results, [(1,)])post.assert_not_called()- def test_explicit_limit_above_the_default_keeps_every_row(self) -> None:- with patch("httpx.AsyncClient.post", side_effect=gateway_response):+ @parameterized.expand([(150, 1000), (1200, 2000)])+ def test_explicit_limit_above_the_default_keeps_every_row(self, rows: int, limit: int) -> None:+ with (+ override_settings(HOGQL_JEV_MAX_ROWS=limit, HOGQL_JEV_MAX_DECISIONS=limit),+ patch("httpx.AsyncClient.post", side_effect=gateway_response),+ ):response = execute_hogql_query(- "SELECT jev(toString(number), 'Refund?') AS p FROM numbers(150) LIMIT 150",+ f"SELECT jev(toString(number), 'Refund?') AS p FROM numbers({rows}) LIMIT {rows}",self.team,user=self.user,)- self.assertEqual(len(response.results or []), 150)+ self.assertEqual(len(response.results or []), rows)def test_outer_query_reads_properties_off_a_passthrough_column(self) -> None:_create_event(diff --git a/posthog/hogql/transforms/prompt_jev.py b/posthog/hogql/transforms/prompt_jev.pyindex 7ac3a76108ed..15ebb32bf35b 100644--- a/posthog/hogql/transforms/prompt_jev.py+++ b/posthog/hogql/transforms/prompt_jev.py@@ -41,8 +41,6 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)-MAX_ROWS = 1000-MAX_DECISIONS = 1000MAX_INPUT_BYTES = 8192MAX_TOTAL_BYTES = 2 * 1024 * 1024MAX_BATCH_BYTES = 32768@@ -223,7 +221,7 @@ class PromptJevRunner:if key not in self.cache:missing[key] = Noneinput_bytes = self.input_bytes + sum(len(key.text.encode()) for key in missing)- if len(self.cache) + len(missing) > MAX_DECISIONS or input_bytes > MAX_TOTAL_BYTES:+ if len(self.cache) + len(missing) > settings.HOGQL_JEV_MAX_DECISIONS or input_bytes > MAX_TOTAL_BYTES:raise QueryError("jev exceeds the query budget. Select fewer or shorter inputs.")return missing@@ -300,22 +298,24 @@ class PromptJevBudget(TraversingVisitor):for column in node.select:finder.visit(column)if finder.calls:- rows = MAX_ROWS+ max_rows = settings.HOGQL_JEV_MAX_ROWS+ max_decisions = settings.HOGQL_JEV_MAX_DECISIONS+ rows = max_rowsif node.limit is not None:if (not isinstance(node.limit, ast.Constant)or type(node.limit.value) is not int- or not 0 <= node.limit.value <= MAX_ROWS+ or not 0 <= node.limit.value <= max_rows):- raise QueryError(f"jev LIMIT must be an integer literal between 0 and {MAX_ROWS}.")+ raise QueryError(f"jev LIMIT must be an integer literal between 0 and {max_rows}.")rows = node.limit.value# Reserve the worst case before any stage runs, including stages that depend on earlier decisions.self.decisions += rows * len(finder.calls)- if self.decisions > MAX_DECISIONS:+ if self.decisions > max_decisions:raise QueryError(- f"jev exceeds the query budget of {MAX_DECISIONS} row evaluations across all columns and SELECTs. "+ f"jev exceeds the query budget of {max_decisions} row evaluations across all columns and SELECTs. "f"This query reserves {self.decisions}. Add smaller LIMITs to the SELECTs containing Jev calls, "- "or use fewer Jev columns. A SELECT without LIMIT reserves 1000 rows per Jev column."+ f"or use fewer Jev columns. A SELECT without LIMIT reserves {max_rows} rows per Jev column.")super().visit_select_query(node)@@ -435,21 +435,22 @@ class PromptJevPlanner(CloningVisitor):if PromptJevFinder.contains(source):raise QueryError("Use jev only in SELECT columns. Filter its results in an outer query.")_AliasReferences(aliases).visit(source)+ max_rows = settings.HOGQL_JEV_MAX_ROWSif source.limit is None:- source.limit = ast.Constant(value=MAX_ROWS + 1)+ source.limit = ast.Constant(value=max_rows + 1)elif (not isinstance(source.limit, ast.Constant)or type(source.limit.value) is not int- or not 0 <= source.limit.value <= MAX_ROWS+ or not 0 <= source.limit.value <= max_rows):- raise QueryError(f"jev LIMIT must be an integer literal between 0 and {MAX_ROWS}.")+ raise QueryError(f"jev LIMIT must be an integer literal between 0 and {max_rows}.")result = self.execute(source)response = result.responseif response.error:raise QueryError(response.error)rows: list[list[object]] = [list(row) for row in response.results or []]- if len(rows) > MAX_ROWS:- raise QueryError(f"jev reads at most {MAX_ROWS} rows. Add a LIMIT to its SELECT.")+ if len(rows) > max_rows:+ raise QueryError(f"jev reads at most {max_rows} rows. Add a LIMIT to its SELECT.")names = response.columns or []if len(names) != len(query.select) or len(set(names)) != len(names):raise QueryError("Give each column in the jev SELECT a unique name.")diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex d8dc26430e7e..ae11551b4264 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1327,6 +1327,10 @@ AI_GATEWAY_API_KEY = get_from_env("AI_GATEWAY_API_KEY", "")# Decision model behind the HogQL `jev` function. Per environment, so a# different model can be measured without a code change.HOGQL_PROMPT_JEV_MODEL = get_from_env("HOGQL_PROMPT_JEV_MODEL", "posthog/hogference/jeeves-0.1")+# Limits for one `jev`/`decide` query: rows read per SELECT, and model decisions across the whole query.+# Each decision is a billed gateway call, so these bound the cost of one query.+HOGQL_JEV_MAX_ROWS = get_from_env("HOGQL_JEV_MAX_ROWS", 1000, type_cast=int)+HOGQL_JEV_MAX_DECISIONS = get_from_env("HOGQL_JEV_MAX_DECISIONS", 1000, type_cast=int)# Projected into gateway_credential.json: a JSON team_id -> tier map# ("free"/"pro"/"enterprise") for the gateway's rate-limit bucket.