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(data-modeling): check saved query bodies for incremental eligibility (#113985)

Jovan Sakovic2b42af945066
diff --git a/products/data_modeling/backend/logic/incremental_eligibility.py b/products/data_modeling/backend/logic/incremental_eligibility.py
index 1d29d8522b8c..45da651dc4fd 100644
--- a/products/data_modeling/backend/logic/incremental_eligibility.py
+++ b/products/data_modeling/backend/logic/incremental_eligibility.py
@@ -156,6 +156,9 @@ def check_incremental_eligibility(
# Shape is purely structural, so the raw AST is enough — no need for the resolved copy.
for select in raw_selects:
_check_shape(select, blockers)
+ # The resolved copy has every saved query this one reads inlined as a subquery, so the nested
+ # walk sees view bodies too. A LIMIT in a view moves rows under the watermark like an inline one.
+ for select in selects:
_check_nested_shapes(select, blockers)
if config is None:
@@ -357,15 +360,21 @@ def _check_set_operators(node: ast.SelectQuery | ast.SelectSetQuery, blockers: l
_check_set_operators(branch, blockers)
-def _check_shape(select: ast.SelectQuery, blockers: list[str], *, nested: bool = False) -> None:
+def _check_shape(
+ select: ast.SelectQuery, blockers: list[str], *, nested: bool = False, location: str = "a subquery or CTE"
+) -> None:
if select.limit is not None:
- blockers.append(_row_slice_blocker("LIMIT", "A top-N within one window is not a top-N overall.", nested))
+ blockers.append(
+ _row_slice_blocker("LIMIT", "A top-N within one window is not a top-N overall.", nested, location)
+ )
if select.offset is not None:
blockers.append(
- _row_slice_blocker("OFFSET", "The rows skipped within one window are not the rows skipped overall.", nested)
+ _row_slice_blocker(
+ "OFFSET", "The rows skipped within one window are not the rows skipped overall.", nested, location
+ )
)
if select.limit_by is not None:
- blockers.append(_row_slice_blocker("LIMIT BY", "A per-window limit is not a limit overall.", nested))
+ blockers.append(_row_slice_blocker("LIMIT BY", "A per-window limit is not a limit overall.", nested, location))
if not nested:
# Only outer concerns. Nested, an ORDER BY without a LIMIT changes nothing (and with one,
# the LIMIT blocker already fires); a nested DISTINCT commutes with the window filter, so
@@ -398,11 +407,11 @@ def _check_shape(select: ast.SelectQuery, blockers: list[str], *, nested: bool =
)
-def _row_slice_blocker(construct: str, outer_reason: str, nested: bool) -> str:
+def _row_slice_blocker(construct: str, outer_reason: str, nested: bool, location: str) -> str:
if nested:
article = "An" if construct[0] in "AEIOU" else "A"
return (
- f"{article} {construct} inside a subquery or CTE cannot be incremental. Which rows it "
+ f"{article} {construct} inside {location} cannot be incremental. Which rows it "
"lets through changes as data arrives, so a window cannot be recomputed to the same result."
)
return f"{construct} cannot be incremental. {outer_reason}"
@@ -416,7 +425,8 @@ def _check_nested_shapes(select: ast.SelectQuery, blockers: list[str]) -> None:
for source in _source_nodes(select):
_check_set_operators(source, blockers)
for leaf in _leaf_selects(source):
- _check_shape(leaf, blockers, nested=True)
+ location = f'the view "{leaf.view_name}"' if leaf.view_name else "a subquery or CTE"
+ _check_shape(leaf, blockers, nested=True, location=location)
_check_nested_shapes(leaf, blockers)
diff --git a/products/data_modeling/backend/test/test_incremental_eligibility.py b/products/data_modeling/backend/test/test_incremental_eligibility.py
index 9b0cd44e3493..c4807fec4bd5 100644
--- a/products/data_modeling/backend/test/test_incremental_eligibility.py
+++ b/products/data_modeling/backend/test/test_incremental_eligibility.py
@@ -5,6 +5,7 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
from posthog.hogql.database.database import Database
+from posthog.hogql.database.models import IntegerDatabaseField, SavedQuery, TableNode
from products.data_modeling.backend.logic.incremental import IncrementalConfig
from products.data_modeling.backend.logic.incremental_eligibility import check_incremental_eligibility
@@ -429,3 +430,46 @@ class TestStarExpansion:
assert result.eligible
assert any("cannot be pushed down" in warning for warning in result.warnings), result.warnings
+
+ @parameterized.expand(
+ [
+ ("limit", "SELECT id AS team_id_, 1 AS has_views FROM events LIMIT 50000", "LIMIT"),
+ (
+ "having",
+ "SELECT toStartOfDay(timestamp) AS team_id_, count() AS has_views FROM events "
+ "GROUP BY team_id_ HAVING count() > 0",
+ "HAVING",
+ ),
+ ]
+ )
+ def test_a_blocked_shape_behind_a_saved_query_reference_still_blocks(
+ self, _name: str, view_query: str, expected: str
+ ) -> None:
+ database = Database()
+ database._add_views(
+ TableNode(
+ children={
+ "upstream_view": TableNode(
+ name="upstream_view",
+ table=SavedQuery(
+ id="upstream_view",
+ name="upstream_view",
+ query=view_query,
+ fields={
+ "team_id_": IntegerDatabaseField(name="team_id_"),
+ "has_views": IntegerDatabaseField(name="has_views"),
+ },
+ ),
+ )
+ }
+ )
+ )
+
+ result = self._check(
+ "SELECT coalesce(team_id_, 0) AS new_team_id, has_views FROM upstream_view WHERE team_id_ < 100000",
+ IncrementalConfig(incremental_key="new_team_id", unique_key=("new_team_id",)),
+ database=database,
+ )
+
+ assert not result.eligible
+ assert any(expected in blocker for blocker in result.blockers), result.blockers