Skip to content

: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.

fix(notebooks): Add strict LIMIT into sql_v2 queries on AST level instead of wrapping the query (#73631)

Sinan Kucukkoseler78cb8da75f7f
diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.py
index 78895e78d7fa..885fecd7c456 100644
--- a/products/notebooks/backend/sql_v2_data_plane.py
+++ b/products/notebooks/backend/sql_v2_data_plane.py
@@ -37,7 +37,7 @@ from posthog.models import Team, User
from products.notebooks.backend import frame_store
from products.notebooks.backend.models import Notebook
from products.notebooks.backend.sql_v2 import verify_data_plane_token
-from products.notebooks.backend.sql_v2_direct import wrap_hogql_page_query
+from products.notebooks.backend.sql_v2_direct import apply_page_bounds
from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2DataPlaneRequestSerializer
logger = structlog.get_logger(__name__)
@@ -139,7 +139,7 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:
except ExposedHogQLError as exc:
return JsonResponse({"error": str(exc)}, status=400)
- wrapped = wrap_hogql_page_query(data["query"], limit=data["limit"], offset=data["offset"])
+ bounded = apply_page_bounds(data["query"], limit=data["limit"], offset=data["offset"])
if data["delivery"] == "object":
if frame_store.is_enabled():
@@ -157,7 +157,7 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:
team=team,
user_id=user.id if user else None,
notebook_short_id=notebook_short_id,
- query=wrapped,
+ query=bounded,
_test_only_inline=settings.TEST,
)
except Exception:
@@ -180,7 +180,7 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:
status = enqueue_process_query_task(
team=team,
user_id=user.id if user else None,
- query_json={"kind": "HogQLQuery", "query": wrapped},
+ query_json={"kind": "HogQLQuery", "query": bounded},
# Dispatch normally rides transaction.on_commit, which never fires inside
# a test transaction — run inline there, like the manager's own tests do.
_test_only_bypass_celery=settings.TEST,
diff --git a/products/notebooks/backend/sql_v2_direct.py b/products/notebooks/backend/sql_v2_direct.py
index cf02887e4cb4..6f34bc070ff4 100644
--- a/products/notebooks/backend/sql_v2_direct.py
+++ b/products/notebooks/backend/sql_v2_direct.py
@@ -19,6 +19,10 @@ from django.utils import timezone
import structlog
+from posthog.hogql import ast
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.parser import parse_select
+
from posthog.clickhouse.client.execute_async import QueryNotFoundError, enqueue_process_query_task, get_query_status
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
@@ -59,19 +63,65 @@ def notebook_direct_query_id(run_id: str) -> str:
).hexdigest()
-def wrap_hogql_page_query(query: str, limit: int, offset: int) -> str:
- """Cap a HogQL query with an outer LIMIT/OFFSET, without mutating it.
+def _wrap_hogql_page_query(query: str, limit: int, offset: int) -> str:
+ """Cap a page by wrapping the query in an outer ``select * from (...) limit/offset``.
+
+ The fallback for shapes where setting the bound on the query itself would change its
+ meaning: a paged offset or a query with its own OFFSET (both need result-set pagination
+ over the query's output), a set query (no single outer LIMIT), or a non-constant LIMIT.
+ The outer LIMIT does not push into an aggregated view, so prefer `apply_page_bounds`,
+ which does.
- Wrapping caps the page regardless of the query's own shape (set queries, its own
- LIMIT, etc.). The inner query is validated HogQL and the wrapper is re-parsed as
- HogQL downstream, so there is no raw-SQL injection; limit/offset are int()-cast.
- The newline before the closing paren keeps a trailing line comment (`-- …`) in the
- user's query from swallowing the wrapper.
+ The inner query is validated HogQL and the wrapper is re-parsed as HogQL downstream, so
+ there is no raw-SQL injection; limit/offset are int()-cast. The newline before the closing
+ paren keeps a trailing line comment (`-- …`) in the user's query from swallowing the wrapper.
"""
# nosemgrep: semgrep.rules.security.hogql-fstring-audit
return f"select * from ({query}\n) limit {int(limit)} offset {int(offset)}"
+def apply_page_bounds(query: str, limit: int, offset: int) -> str:
+ """Bound a HogQL query to `limit` rows at `offset`, preserving ClickHouse limit pushdown.
+
+ A query with no LIMIT of its own gets one appended to its own outermost SELECT, so
+ ClickHouse can push it into an aggregated view like `persons`: an unbounded
+ `select * from persons` then reads ~limit rows' worth instead of deduplicating the whole
+ table (prod: 6.8M rows / 0.35s vs 226M / 73s). We append to the source text rather than
+ re-print a parsed AST, which drops table-function arguments (`numbers(50001)`); a trailing
+ `;` is stripped first, since it parses but breaks once a LIMIT is appended or wrapped.
+
+ Everything else falls back to `_wrap_hogql_page_query`: a query with its own LIMIT already
+ pushes down through the wrapper's inner subquery, and a paged offset, a query with its own
+ OFFSET, a set query, or an unparseable query all need the wrapper's outer bound.
+ """
+ # A trailing `;` parses cleanly but breaks once we append LIMIT (or wrap the query as a
+ # subquery), so normalize it away for both lanes. HogQL is single-statement, so this only
+ # ever drops the terminator, never a second statement.
+ query = query.rstrip()
+ if query.endswith(";"):
+ query = query[:-1].rstrip()
+
+ try:
+ parsed = parse_select(query)
+ except ExposedHogQLError:
+ return _wrap_hogql_page_query(query, limit, offset)
+
+ if (
+ offset == 0
+ and isinstance(parsed, ast.SelectQuery)
+ and parsed.limit is None
+ and parsed.offset is None
+ and parsed.settings is None
+ ):
+ # With the terminator stripped, LIMIT is the query's last clause (SETTINGS does not
+ # parse), so appending is valid and keeps its table functions intact (re-printing the
+ # AST would drop them). `query` parsed cleanly above and `limit` is int()-cast.
+ # nosemgrep: semgrep.rules.security.hogql-fstring-audit
+ return f"{query}\nlimit {int(limit)}"
+
+ return _wrap_hogql_page_query(query, limit, offset)
+
+
def enqueue_direct_run(team: "Team", user: "User | None", run: NotebookNodeRun) -> None:
"""Enqueue a direct (hogql) run on the async query manager.
@@ -80,12 +130,12 @@ def enqueue_direct_run(team: "Team", user: "User | None", run: NotebookNodeRun)
store all come with it. Fetches one extra row past the cache ceiling so
`sync_direct_run` can detect has_more, mirroring the kernel's capped fetch.
"""
- wrapped = wrap_hogql_page_query(run.code, limit=RESULT_CACHE_ROWS + 1, offset=0)
+ bounded = apply_page_bounds(run.code, limit=RESULT_CACHE_ROWS + 1, offset=0)
with tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, team_id=team.id):
enqueue_process_query_task(
team=team,
user_id=user.id if user else None,
- query_json={"kind": "HogQLQuery", "query": wrapped},
+ query_json={"kind": "HogQLQuery", "query": bounded},
query_id=notebook_direct_query_id(str(run.id)),
# A Run click always executes; never serve a stale cached result.
refresh_requested=True,
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 937e356046c5..5e339276ff4b 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -20,6 +20,9 @@ from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+
from posthog.clickhouse.client.execute_async import QueryNotFoundError
from posthog.constants import AvailableFeature
from posthog.models.organization import OrganizationMembership
@@ -39,6 +42,7 @@ from products.notebooks.backend.sandbox.kernel.data_plane import (
decode_arrow_stream,
)
from products.notebooks.backend.sql_v2 import (
+ RESULT_CACHE_ROWS,
SQLV2KernelNotRunning,
SQLV2PageError,
build_callback_url,
@@ -54,7 +58,7 @@ from products.notebooks.backend.sql_v2 import (
)
from products.notebooks.backend.sql_v2_callback import MAX_ENVELOPE_BYTES
from products.notebooks.backend.sql_v2_data_plane import _rows_to_arrow_bytes
-from products.notebooks.backend.sql_v2_direct import notebook_direct_query_id, sync_direct_run
+from products.notebooks.backend.sql_v2_direct import apply_page_bounds, notebook_direct_query_id, sync_direct_run
from products.notebooks.backend.temporal.sql_v2 import (
SQLV2RunInput,
dispatch_sql_v2_run_activity,
@@ -96,6 +100,57 @@ class TestSQLV2BackendBaseURL(SimpleTestCase):
assert build_callback_url("run-1") == f"{expected_base}/internal/notebooks/runs/run-1/result/"
+class TestSQLV2ApplyPageBounds(SimpleTestCase):
+ def test_naked_scan_is_bounded_in_place_not_wrapped(self) -> None:
+ # The fix: a query with no LIMIT of its own gets the window on its own SELECT so
+ # ClickHouse pushes it into an aggregated view instead of scanning the whole table.
+ parsed = parse_select(apply_page_bounds("select * from persons", limit=301, offset=0))
+ assert isinstance(parsed, ast.SelectQuery)
+ assert isinstance(parsed.limit, ast.Constant) and parsed.limit.value == 301
+ assert parsed.select_from is not None and isinstance(parsed.select_from.table, ast.Field)
+
+ def test_bounding_keeps_the_exact_query_text(self) -> None:
+ # Bounding appends to the source, never re-prints the AST, because re-printing drops
+ # table-function args (numbers(50001) -> numbers), which then fails on ClickHouse.
+ out = apply_page_bounds("select number from numbers(50001)", limit=301, offset=0)
+ assert "numbers(50001)" in out
+ bounded_limit = parse_select(out).limit
+ assert isinstance(bounded_limit, ast.Constant) and bounded_limit.value == 301
+
+ @parameterized.expand(
+ [
+ ("naked_append_path", "select * from persons;"),
+ ("own_limit_wrapper_path", "select * from persons limit 5;"),
+ ("set_query_wrapper_path", "select 1 union all select 2;"),
+ ]
+ )
+ def test_trailing_semicolon_is_stripped_so_the_bound_stays_valid(self, _name: str, query: str) -> None:
+ # A trailing ';' parses fine but breaks once a LIMIT is appended or the query is wrapped
+ # as a subquery. The top-level strip normalizes it for both lanes, so the bounded result
+ # re-parses cleanly instead of failing downstream as `...;\nlimit 301`.
+ parsed = parse_select(apply_page_bounds(query, limit=301, offset=0))
+ assert isinstance(parsed, ast.SelectQuery)
+ assert isinstance(parsed.limit, ast.Constant) and parsed.limit.value == 301
+
+ @parameterized.expand(
+ [
+ ("own_limit_already_pushes_down_via_wrapper", "select * from persons limit 5", 301, 0),
+ ("own_offset_must_not_be_clobbered", "select * from persons offset 10", 301, 0),
+ ("paged_offset_needs_result_set_pagination", "select * from persons", 301, 50),
+ ("set_query_has_no_single_outer_limit", "select 1 union all select 2", 301, 0),
+ ]
+ )
+ def test_other_shapes_fall_back_to_a_valid_wrapped_bound(
+ self, _name: str, query: str, limit: int, offset: int
+ ) -> None:
+ parsed = parse_select(apply_page_bounds(query, limit=limit, offset=offset))
+ assert isinstance(parsed, ast.SelectQuery)
+ # Wrapped: the original query becomes a subquery under the outer window bound.
+ assert parsed.select_from is not None
+ assert isinstance(parsed.select_from.table, ast.SelectQuery | ast.SelectSetQuery)
+ assert isinstance(parsed.limit, ast.Constant) and parsed.limit.value == limit
+
+
class TestSQLV2Callback(APIBaseTest):
def setUp(self):
super().setUp()
@@ -345,7 +400,11 @@ class TestSQLV2Run(APIBaseTest):
self.assertNotEqual(kwargs["query_id"], run_id)
self.assertEqual(kwargs["query_id"], notebook_direct_query_id(run_id))
self.assertTrue(kwargs["refresh_requested"])
- self.assertIn("select 1", kwargs["query_json"]["query"])
+ # The run's code is enqueued bounded to the prefetch window, so an unbounded scan
+ # never ships without a LIMIT (the direct lane's only cap before the FE pages).
+ enqueued_limit = parse_select(kwargs["query_json"]["query"]).limit
+ assert isinstance(enqueued_limit, ast.Constant)
+ self.assertEqual(enqueued_limit.value, RESULT_CACHE_ROWS + 1)
@patch("products.notebooks.backend.sql_v2_direct.get_query_status", side_effect=QueryNotFoundError())
def test_a_query_status_under_the_run_id_cannot_poison_the_run(self, mock_status):