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(endpoints): refresh saved query before materialization (#59048)

Jovan Sakovic23def4648127
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index aadbb1b7a10e..8a0d235ed4f8 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -36,6 +36,7 @@ from products.data_warehouse.backend.models import get_s3_client
from products.data_warehouse.backend.models.data_modeling_job import DataModelingJob
from products.data_warehouse.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.data_warehouse.backend.s3 import ensure_bucket_exists
+from products.endpoints.backend.services.endpoint_materialization_service import prepare_executable_query
LOGGER = get_logger(__name__)
@@ -421,6 +422,9 @@ def _get_matview_input_objects(
.exclude(deleted=True)
.get(id=node.saved_query.id, team_id=inputs.team_id)
)
+ if saved_query.origin == DataWarehouseSavedQuery.Origin.ENDPOINT:
+ prepare_executable_query(saved_query)
+
job = DataModelingJob.objects.get(id=inputs.job_id, team_id=inputs.team_id)
return (team, node, saved_query, job)
diff --git a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
index 71e2f6067cd5..44274a731ba4 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
@@ -16,6 +16,7 @@ from posthog.temporal.common.logger import get_logger
from products.data_modeling.backend.models import Node, NodeType
from products.data_warehouse.backend.models.data_modeling_job import DataModelingJob, DataModelingJobStatus
from products.data_warehouse.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from products.endpoints.backend.services.endpoint_materialization_service import prepare_executable_query
LOGGER = get_logger(__name__)
@@ -102,6 +103,9 @@ def _get_shadow_input_objects(
saved_query = DataWarehouseSavedQuery.objects.exclude(deleted=True).get(
id=node.saved_query.id, team_id=inputs.team_id
)
+ if saved_query.origin == DataWarehouseSavedQuery.Origin.ENDPOINT:
+ prepare_executable_query(saved_query)
+
return (team, node, saved_query)
diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.py
index 1582b9d3d7d8..be60f438612e 100644
--- a/products/endpoints/backend/api.py
+++ b/products/endpoints/backend/api.py
@@ -88,12 +88,15 @@ from products.endpoints.backend.insight_transformers import (
transform_materialized_insight_response,
)
from products.endpoints.backend.materialization import (
+ ENDPOINT_BREAKDOWN_LIMIT,
SUPPORTED_BUCKET_FUNCTIONS,
VariablePlaceholderFinder,
_extract_aggregate_name,
analyze_variables_for_materialization,
+ build_endpoint_hogql,
convert_insight_query_to_hogql,
get_reaggregation,
+ prepare_insight_query_for_endpoint,
transform_query_for_materialization,
transform_select_for_materialized_table,
)
@@ -137,7 +140,6 @@ DATA_FRESHNESS_BUCKETS: dict[int, str] = {
}
VALID_DATA_FRESHNESS_SECONDS: frozenset[int] = frozenset(DATA_FRESHNESS_BUCKETS)
DEFAULT_DATA_FRESHNESS_SECONDS = 86400
-ENDPOINT_BREAKDOWN_LIMIT = 10_000
ENDPOINT_NAME_REGEX = r"^[a-zA-Z][a-zA-Z0-9_-]{0,127}$"
@@ -1131,21 +1133,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
origin=DataWarehouseSavedQuery.Origin.ENDPOINT,
)
- mat_query = _prepare_insight_query_for_endpoint(version.query)
- hogql_query = convert_insight_query_to_hogql(mat_query, self.team)
-
- variable_infos: list = []
- if version.query.get("variables"):
- can_materialize, reason, variable_infos = analyze_variables_for_materialization(
- version.query, bucket_overrides=bucket_overrides
- )
-
- if can_materialize and variable_infos:
- hogql_query = transform_query_for_materialization(
- hogql_query, variable_infos, self.team, bucket_overrides=bucket_overrides
- )
-
- hogql_query = _replace_breakdown_sentinels_in_query(hogql_query)
+ hogql_query = build_endpoint_hogql(version.query, self.team, bucket_overrides=bucket_overrides)
saved_query.query = hogql_query
saved_query.external_tables = saved_query.s3_tables
@@ -2064,7 +2052,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
) -> Response:
"""Execute query directly against ClickHouse."""
try:
- query = _prepare_insight_query_for_endpoint(query)
+ query = prepare_insight_query_for_endpoint(query)
pagination: EndpointPagination | None = None
if limit is not None:
@@ -2666,51 +2654,6 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
return Response(spec, content_type="application/json")
-def _prepare_insight_query_for_endpoint(query: dict) -> dict:
- """Prepare an insight query for endpoint execution.
-
- We override the breakdown_limit to a high value so all values are returned
- (the insight UI default of 25 would silently drop data). We keep
- breakdown_hide_other_aggregation=False (default) so that if the limit IS
- exceeded, the "Other" bucket appears in results and we can detect + alert.
- """
- breakdown_filter = query.get("breakdownFilter")
- if not breakdown_filter:
- return query
-
- return {
- **query,
- "breakdownFilter": {
- **breakdown_filter,
- "breakdown_hide_other_aggregation": False,
- "breakdown_limit": ENDPOINT_BREAKDOWN_LIMIT,
- },
- }
-
-
-def _replace_breakdown_sentinels_in_query(hogql_query: dict) -> dict:
- """Replace breakdown sentinel string literals in HogQL query text.
-
- Runs before the query is stored for materialization, so S3 data
- never contains the internal sentinel strings. The "other" sentinel
- is still embedded in the HogQL by the query builder (in if() and ORDER BY
- expressions) even when breakdown_hide_other_aggregation is set, because
- that flag only affects post-processing in the query runner.
- """
- query_text = hogql_query.get("query")
- if not query_text or not isinstance(query_text, str):
- return hogql_query
-
- replacements = {
- f"'{BREAKDOWN_NULL_STRING_LABEL}'": "''",
- f"'{BREAKDOWN_OTHER_STRING_LABEL}'": "'Other'",
- }
- for old, new in replacements.items():
- query_text = query_text.replace(old, new)
-
- return {**hogql_query, "query": query_text}
-
-
def _clean_breakdown_sentinels(result: dict) -> None:
"""Replace breakdown sentinel strings in API response results in-place.
diff --git a/products/endpoints/backend/materialization.py b/products/endpoints/backend/materialization.py
index a32d27b35c6a..dca275099e34 100644
--- a/products/endpoints/backend/materialization.py
+++ b/products/endpoints/backend/materialization.py
@@ -14,9 +14,12 @@ from posthog.hogql.timings import HogQLTimings
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
from posthog.exceptions_capture import capture_exception
+from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL
from posthog.hogql_queries.query_runner import get_query_runner
from posthog.models.team import Team
+ENDPOINT_BREAKDOWN_LIMIT = 10_000
+
class VariableInHavingClauseError(ValueError):
"""Raised when a variable is used in a HAVING clause, which is not supported for materialization."""
@@ -1357,3 +1360,56 @@ class MaterializationTransformer(CloningVisitor):
if isinstance(node, ast.Call):
return any(self._expr_contains_variable(arg) for arg in node.args)
return False
+
+
+def prepare_insight_query_for_endpoint(query: dict) -> dict:
+ """Override breakdown_limit to surface all values; keep breakdown_hide_other_aggregation=False so the
+ 'Other' bucket appears in results if the limit is ever exceeded."""
+ breakdown_filter = query.get("breakdownFilter")
+ if not breakdown_filter:
+ return query
+
+ return {
+ **query,
+ "breakdownFilter": {
+ **breakdown_filter,
+ "breakdown_hide_other_aggregation": False,
+ "breakdown_limit": ENDPOINT_BREAKDOWN_LIMIT,
+ },
+ }
+
+
+def replace_breakdown_sentinels_in_query(hogql_query: dict) -> dict:
+ """Strip internal sentinel string literals from HogQL so S3-stored data is clean. The 'other' sentinel
+ is embedded in the HogQL by the query builder (in if() and ORDER BY expressions) regardless of
+ breakdown_hide_other_aggregation, which only affects post-processing."""
+ query_text = hogql_query.get("query")
+ if not query_text or not isinstance(query_text, str):
+ return hogql_query
+
+ replacements = {
+ f"'{BREAKDOWN_NULL_STRING_LABEL}'": "''",
+ f"'{BREAKDOWN_OTHER_STRING_LABEL}'": "'Other'",
+ }
+ for old, new in replacements.items():
+ query_text = query_text.replace(old, new)
+
+ return {**hogql_query, "query": query_text}
+
+
+def build_endpoint_hogql(insight_query: dict, team: Team, bucket_overrides: dict[str, str] | None = None) -> dict:
+ """Run the full endpoint conversion pipeline: prepare → convert insight to HogQL → apply variable
+ materialization plan → strip breakdown sentinels. Pure function; no DB side effects."""
+ mat_query = prepare_insight_query_for_endpoint(insight_query)
+ hogql_query = convert_insight_query_to_hogql(mat_query, team)
+
+ if insight_query.get("variables"):
+ can_materialize, _reason, variable_infos = analyze_variables_for_materialization(
+ insight_query, bucket_overrides=bucket_overrides
+ )
+ if can_materialize and variable_infos:
+ hogql_query = transform_query_for_materialization(
+ hogql_query, variable_infos, team, bucket_overrides=bucket_overrides
+ )
+
+ return replace_breakdown_sentinels_in_query(hogql_query)
diff --git a/products/endpoints/backend/services/__init__.py b/products/endpoints/backend/services/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/endpoints/backend/services/endpoint_materialization_service.py b/products/endpoints/backend/services/endpoint_materialization_service.py
new file mode 100644
index 000000000000..628283874de7
--- /dev/null
+++ b/products/endpoints/backend/services/endpoint_materialization_service.py
@@ -0,0 +1,17 @@
+from products.data_warehouse.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from products.endpoints.backend.materialization import build_endpoint_hogql
+
+
+class OrphanedEndpointSavedQueryError(Exception):
+ pass
+
+
+def prepare_executable_query(saved_query: DataWarehouseSavedQuery) -> None:
+ version = saved_query.endpoint_versions.first()
+ if version is None:
+ raise OrphanedEndpointSavedQueryError(
+ f"Saved query {saved_query.id} ({saved_query.name}) has no linked EndpointVersion"
+ )
+
+ saved_query.query = build_endpoint_hogql(version.query, saved_query.team, bucket_overrides=version.bucket_overrides)
+ saved_query.save(update_fields=["query", "updated_at"])
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index 58647961ecde..30555becc028 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -1821,7 +1821,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
# Patch the limit to a low value so the 30 distinct breakdown values exceed it
with (
- mock.patch("products.endpoints.backend.api.ENDPOINT_BREAKDOWN_LIMIT", 5),
+ mock.patch("products.endpoints.backend.materialization.ENDPOINT_BREAKDOWN_LIMIT", 5),
mock.patch("products.endpoints.backend.api.capture_exception") as mock_capture,
):
response = self.client.post(
diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.py
index ae7cca38d0bf..34ad568542f3 100644
--- a/products/endpoints/backend/tests/test_endpoint_materialization.py
+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py
@@ -1,9 +1,12 @@
from datetime import timedelta
import pytest
+from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest import mock
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
import pytest_asyncio
@@ -22,6 +25,11 @@ from products.data_warehouse.backend.data_load.saved_query_service import get_sa
from products.data_warehouse.backend.models import DataWarehouseModelPath, DataWarehouseTable
from products.data_warehouse.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.endpoints.backend.api import EndpointViewSet
+from products.endpoints.backend.materialization import build_endpoint_hogql
+from products.endpoints.backend.services.endpoint_materialization_service import (
+ OrphanedEndpointSavedQueryError,
+ prepare_executable_query,
+)
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
pytestmark = [pytest.mark.django_db]
@@ -1380,6 +1388,75 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ def test_materialized_relative_date_range_advances_on_refresh(self):
+ _create_event(team=self.team, event="$pageview", distinct_id="u1")
+ flush_persons_and_events()
+
+ trends_query = {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview", "math": "total"}],
+ "dateRange": {"date_from": "-30d"},
+ "interval": "day",
+ }
+
+ with freeze_time("2026-04-20T12:00:00Z"):
+ endpoint = create_endpoint_with_version(
+ name="relative_dates_stay_fresh",
+ team=self.team,
+ query=trends_query,
+ created_by=self.user,
+ is_active=True,
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",
+ {"is_materialized": True, "data_freshness_seconds": 86400},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+
+ version = endpoint.versions.first()
+ version.refresh_from_db()
+ saved_query = version.saved_query
+ assert saved_query is not None
+ self.assertIn("2026-04-20", saved_query.query["query"])
+
+ with freeze_time("2026-04-30T12:00:00Z"):
+ prepare_executable_query(saved_query)
+
+ saved_query.refresh_from_db()
+ hogql = saved_query.query["query"]
+ self.assertIn("2026-04-30", hogql)
+ self.assertNotIn("2026-04-20", hogql)
+
+ def test_prepare_executable_query_raises_when_no_linked_version(self):
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ name="orphan_saved_query",
+ team=self.team,
+ query=self.sample_hogql_query,
+ created_by=self.user,
+ )
+
+ with self.assertRaises(OrphanedEndpointSavedQueryError):
+ prepare_executable_query(saved_query)
+
+ def test_build_endpoint_hogql_performs_no_db_writes(self):
+ _create_event(team=self.team, event="$pageview", distinct_id="u1")
+ flush_persons_and_events()
+
+ insight_query = {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview", "math": "total"}],
+ "dateRange": {"date_from": "-7d"},
+ }
+
+ with CaptureQueriesContext(connection) as ctx:
+ build_endpoint_hogql(insight_query, self.team)
+
+ write_prefixes = ("insert", "update", "delete")
+ writes = [q["sql"] for q in ctx.captured_queries if q["sql"].lstrip().lower().startswith(write_prefixes)]
+ self.assertEqual(writes, [], f"build_endpoint_hogql wrote to Postgres: {writes}")
+
@pytest.mark.asyncio
class TestEndpointMaterializationTemporal: