: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(endpoints): materialize compare mode trends (#110759)
Jovan Sakovicdfb0ca82c12e
diff --git a/products/endpoints/backend/insight_transformers.py b/products/endpoints/backend/insight_transformers.pyindex 65598426492c..37ecffd2494b 100644--- a/products/endpoints/backend/insight_transformers.py+++ b/products/endpoints/backend/insight_transformers.py@@ -84,6 +84,12 @@ def _make_runner(original_query: dict, team: Team, now: datetime | None = None)# Pin the date range to materialization time so response labels reflect# when the data was snapshotted, not when the request was served.runner.query_date_range.pin_now(now)+ if (+ original_query.get("kind") == "TrendsQuery"+ and runner.query.compareFilter is not None+ and runner.query.compareFilter.compare+ ):+ runner.query_previous_date_range.pin_now(now)return runner@@ -185,6 +191,12 @@ def _transform_trends(result: dict, original_query: dict, team: Team, now: datetcolumns = result.get("columns", [])rows = result.get("results", [])+ if runner.query.compareFilter is not None and runner.query.compareFilter.compare:+ result["resolved_compare_date_range"] = {+ "date_from": runner.query_previous_date_range.date_from(),+ "date_to": runner.query_previous_date_range.date_to(),+ }+if not rows:result["results"] = []_strip_hogql_fields(result)diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.pyindex 2dd6a442bff0..4930e84da2bb 100644--- a/products/endpoints/backend/logic/execution.py+++ b/products/endpoints/backend/logic/execution.py@@ -38,6 +38,7 @@ from posthog.schema import (RefreshType,)+from posthog.hogql.constants import LimitContextfrom posthog.hogql.errors import ExposedHogQLError, ResolutionErrorfrom posthog.api.mixins import PydanticModelMixin@@ -832,6 +833,7 @@ class EndpointExecutionService(PydanticModelMixin):debug=debug,headers=deprecation_headers,pagination=pagination,+ limit_context=strategy.materialized_limit_context,)if self._is_cache_stale(result, materialized_at):@@ -843,6 +845,7 @@ class EndpointExecutionService(PydanticModelMixin):debug=debug,headers=deprecation_headers,pagination=pagination,+ limit_context=strategy.materialized_limit_context,)if isinstance(result.data, dict):@@ -1042,6 +1045,7 @@ class EndpointExecutionService(PydanticModelMixin):debug: bool = False,headers: dict[str, str] | None = None,pagination: EndpointPagination | None = None,+ limit_context: LimitContext | None = None,) -> Response:"""Shared query execution logic."""merged_data = self.get_model(query_request_data, QueryRequest)@@ -1057,6 +1061,7 @@ class EndpointExecutionService(PydanticModelMixin):self.team,query,variables_override=variables_override,+ limit_context=limit_context,execution_mode=execution_mode,query_id=client_query_id,user=cast(User, self.request.user),diff --git a/products/endpoints/backend/logic/strategies.py b/products/endpoints/backend/logic/strategies.pyindex a898919b16bd..dffeddb87697 100644--- a/products/endpoints/backend/logic/strategies.py+++ b/products/endpoints/backend/logic/strategies.py@@ -25,6 +25,7 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.schema import DashboardFilter, EndpointRunRequest, HogQLVariable, PropertyOperatorfrom posthog.hogql import ast+from posthog.hogql.constants import LimitContextfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.errors import QueryErrorfrom posthog.hogql.parser import parse_expr, parse_select@@ -310,6 +311,7 @@ class EndpointQueryStrategy(abc.ABC):supports_pagination: ClassVar[bool] = Falsesupports_ducklake: ClassVar[bool] = False+ materialized_limit_context: ClassVar[LimitContext | None] = Nonedef __init__(self, endpoint: Endpoint, version: EndpointVersion, team: Team):self.endpoint = endpoint@@ -609,6 +611,7 @@ class InsightEndpointStrategy(EndpointQueryStrategy):"""BREAKDOWN_SUPPORTED_QUERY_TYPES: ClassVar[frozenset[str]] = BREAKDOWN_SUPPORTED_QUERY_TYPES+ materialized_limit_context = LimitContext.SAVED_QUERY# Query types with a materialized-response transformerINSIGHT_TRANSFORM_TYPES: ClassVar[set[str]] = {"TrendsQuery", "LifecycleQuery", "RetentionQuery"}diff --git a/products/endpoints/backend/logic/validation.py b/products/endpoints/backend/logic/validation.pyindex e88dfb1cc972..c2e73a77c84e 100644--- a/products/endpoints/backend/logic/validation.py+++ b/products/endpoints/backend/logic/validation.py@@ -325,7 +325,7 @@ def validate_update_request(data.query.model_dump() if data.query is not None else (endpoint.get_version().query if endpoint else None))if effective_query is not None:- can_materialize, reason = can_materialize_query(effective_query)+ can_materialize, reason = can_materialize_query(effective_query, team)if not can_materialize:raise ValidationError(f"Cannot materialize endpoint. Reason: {reason}")diff --git a/products/endpoints/backend/models.py b/products/endpoints/backend/models.pyindex 5db3054c9b05..a9ee20bfa310 100644--- a/products/endpoints/backend/models.py+++ b/products/endpoints/backend/models.py@@ -10,6 +10,8 @@ from django.db import modelsfrom django.db.models import Qfrom django.utils import timezone+import posthoganalytics+from posthog.hogql import astfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.visitor import CloningVisitor@@ -24,6 +26,28 @@ from posthog.schema_enums import ProductKeylogger = logging.getLogger(__name__)+COMPARE_MODE_MATERIALIZATION_FLAG = "endpoints-materialized-compare-mode"+++def compare_mode_materialization_enabled(team: Team) -> bool:+ try:+ return bool(+ posthoganalytics.feature_enabled(+ COMPARE_MODE_MATERIALIZATION_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )+ except Exception as error:+ capture_exception(error)+ return False+class _ReplacePlaceholdersWithDummies(CloningVisitor):"""Replace all {variables.foo} placeholders with empty string constants."""@@ -74,7 +98,7 @@ def _clickhouse_type_to_serialized_type(ch_type: str) -> str:return "unknown"-def can_materialize_query(query: dict | None) -> tuple[bool, str]:+def can_materialize_query(query: dict | None, team: Team | None = None) -> tuple[bool, str]:"""Check whether an endpoint query can be materialized.Returns: (can_materialize: bool, reason: str)@@ -97,10 +121,13 @@ def can_materialize_query(query: dict | None) -> tuple[bool, str]:assert query is not None- # Block compare mode — materialization can't reconstruct doubled seriescompare_filter = query.get("compareFilter") or {}if compare_filter.get("compare"):- return False, "Compare mode is not supported for materialized endpoints."+ compare_mode_supported = (+ query_kind == "TrendsQuery" and team is not None and compare_mode_materialization_enabled(team)+ )+ if not compare_mode_supported:+ return False, "Compare mode is not supported for materialized endpoints."# Block cohort breakdowns — they produce a UNION ALL across cohorts, which# inject_series_index tags as separate series, causing a mismatch at read time.@@ -314,7 +341,7 @@ class EndpointVersion(UpdatedMetaFields, models.Model):Returns: (can_materialize: bool, reason: str)"""- return can_materialize_query(self.query)+ return can_materialize_query(self.query, self.team)@staticmethoddef extract_columns(query: dict, team_id: int) -> list[dict]:diff --git a/products/endpoints/backend/presentation/views/api.py b/products/endpoints/backend/presentation/views/api.pyindex e5892a0541bf..da5f7faeeb65 100644--- a/products/endpoints/backend/presentation/views/api.py+++ b/products/endpoints/backend/presentation/views/api.py@@ -335,7 +335,7 @@ class EndpointViewSet(def _with_materialization_job_prefetches(queryset):latest_jobs = DataModelingJob.objects.filter(engine=DataModelingJob.Engine.CLICKHOUSE).order_by("-last_run_at")latest_completed_jobs = latest_jobs.filter(status=DataModelingJob.Status.COMPLETED)- return queryset.select_related("saved_query").prefetch_related(+ return queryset.select_related("saved_query", "team").prefetch_related(Prefetch("saved_query__datamodelingjob_set", queryset=latest_jobs[:1], to_attr="prefetched_latest_jobs"),Prefetch("saved_query__datamodelingjob_set",diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.pyindex cd078f3df34b..19e8867694eb 100644--- a/products/endpoints/backend/tests/test_endpoint.py+++ b/products/endpoints/backend/tests/test_endpoint.py@@ -1916,7 +1916,7 @@ class TestOptionalBreakdownProperties(ClickhouseTestMixin, APIBaseTest):class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):ENDPOINT = "endpoints"- def _create_endpoints(self, count: int) -> None:+ def _create_endpoints(self, count: int, materialized: bool) -> None:for i in range(count):endpoint_name = f"list_perf_{count}_{i}"endpoint = create_endpoint_with_version(@@ -1929,6 +1929,8 @@ class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):},created_by=self.user,)+ if not materialized:+ continuesaved_query = DataWarehouseSavedQuery.objects.create(team=self.team,name=endpoint_name,@@ -1957,9 +1959,9 @@ class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):last_run_at=timezone.now(),)- def _list_query_count(self, endpoint_count: int) -> int:+ def _list_query_count(self, endpoint_count: int, materialized: bool) -> int:Endpoint.objects.all().delete()- self._create_endpoints(endpoint_count)+ self._create_endpoints(endpoint_count, materialized)url = f"/api/environments/{self.team.id}/endpoints/"self.client.get(url)with CaptureQueriesContext(connection) as ctx:@@ -1968,13 +1970,14 @@ class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):self.assertEqual(endpoint_count, len(response.json()["results"]))return len(ctx.captured_queries)- def test_list_query_count_does_not_grow_with_endpoint_count(self):- few = self._list_query_count(2)- many = self._list_query_count(8)+ @parameterized.expand([("materialized", True), ("unmaterialized", False)])+ def test_list_query_count_does_not_grow_with_endpoint_count(self, _name: str, materialized: bool):+ few = self._list_query_count(2, materialized)+ many = self._list_query_count(8, materialized)self.assertEqual(few, many, f"listing 8 endpoints cost {many} queries vs {few} for 2, so something N+1s")- def _versions_query_count(self, version_count: int) -> int:+ def _versions_query_count(self, version_count: int, materialized: bool) -> int:Endpoint.objects.all().delete()endpoint = create_endpoint_with_version(name=f"versions_perf_{version_count}",@@ -1996,6 +1999,8 @@ class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):columns=[{"name": "result", "type": "integer"}],))+ if not materialized:+ continuesaved_query = DataWarehouseSavedQuery.objects.create(team=self.team,name=f"versions_perf_{version_count}_v{version_number}",@@ -2023,9 +2028,10 @@ class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):self.assertEqual(version_count, len(response.json()["results"]))return len(ctx.captured_queries)- def test_versions_query_count_does_not_grow_with_version_count(self):- few = self._versions_query_count(2)- many = self._versions_query_count(8)+ @parameterized.expand([("materialized", True), ("unmaterialized", False)])+ def test_versions_query_count_does_not_grow_with_version_count(self, _name: str, materialized: bool):+ few = self._versions_query_count(2, materialized)+ many = self._versions_query_count(8, materialized)self.assertEqual(few, many, f"listing 8 versions cost {many} queries vs {few} for 2, so something N+1s")diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.pyindex 50a2dfb26951..5047a1840f74 100644--- a/products/endpoints/backend/tests/test_endpoint_execution.py+++ b/products/endpoints/backend/tests/test_endpoint_execution.py@@ -13,6 +13,7 @@ from rest_framework.response import Responsefrom posthog.schema import EventsNode, TrendsQuery+from posthog.hogql.constants import LimitContextfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.errors import CHQueryErrorNoCommonType@@ -1103,6 +1104,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):# Must use has() for array containment, not = for string equalityself.assertIn("has(breakdown_value", query_sql)self.assertIn("chrome", query_sql)+ # Insight reads are nested on return, so a default row cap would silently drop+ # breakdown values or a compare period instead of reporting hasMore.+ self.assertEqual(mock_exec.call_args.kwargs["limit_context"], LimitContext.SAVED_QUERY)def test_materialized_insight_endpoint_filters_by_multiple_breakdowns(self):endpoint = create_endpoint_with_version(diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.pyindex 0672a398a10f..e131b98a8c0b 100644--- a/products/endpoints/backend/tests/test_endpoint_materialization.py+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py@@ -28,6 +28,7 @@ from posthog.sync import database_sync_to_asyncfrom products.data_modeling.backend.facade.api import UnsatisfiableFrequencyError, get_declared_targetfrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPathfrom products.data_modeling.backend.facade.models import DAG, DataModelingJob, DataWarehouseSavedQuery, Node+from products.endpoints.backend.insight_transformers import transform_materialized_insight_responsefrom products.endpoints.backend.logic.execution import EndpointExecutionServicefrom products.endpoints.backend.logic.materialization import (EndpointMaterializationService,@@ -65,6 +66,15 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):self.v2_dag_ids_patcher.stop()super().tearDown()+ def _trends_query(self, **overrides: Any) -> dict[str, Any]:+ query: dict[str, Any] = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ "dateRange": {"date_from": "-7d"},+ }+ query.update(overrides)+ return query+def test_enable_materialization_creates_saved_query(self):"""Test that enabling materialization creates a SavedQuery."""# Create an endpoint with version@@ -479,6 +489,29 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())self.assertIn("Unresolved placeholder", str(response.json()))+ def test_compare_mode_materialization_requires_rollout_flag(self):+ endpoint = create_endpoint_with_version(+ name="test_compare_mode_rollout",+ team=self.team,+ query=self._trends_query(compareFilter={"compare": True}),+ created_by=self.user,+ )++ with mock.patch(+ "products.endpoints.backend.models.posthoganalytics.feature_enabled",+ return_value=False,+ ) as feature_enabled_mock:+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"is_materialized": True, "data_freshness_seconds": 86400},+ format="json",+ )++ feature_enabled_mock.assert_called_once()+ self.assertEqual(feature_enabled_mock.call_args.args[0], "endpoints-materialized-compare-mode")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("Compare mode is not supported", response.json()["detail"])+@parameterized.expand([(@@ -567,6 +600,21 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):can_materialize, reason = version.can_materialize()self.assertTrue(can_materialize, reason)+ runner = mock.Mock()+ runner.query = object()+ materialized_result: dict[str, Any] = {"results": []}+ with mock.patch(+ "products.endpoints.backend.insight_transformers.get_query_runner",+ return_value=runner,+ ):+ transform_materialized_insight_response(+ materialized_result,+ query,+ self.team,+ now=timezone.now(),+ )+ self.assertEqual(materialized_result["results"], [])+@parameterized.expand([(@@ -1859,12 +1907,11 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):_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",- }+ trends_query = self._trends_query(+ series=[{"kind": "EventsNode", "event": "$pageview", "math": "total"}],+ dateRange={"date_from": "-30d"},+ interval="day",+ )with time_machine.travel("2026-04-20T12:00:00Z", tick=False):endpoint = create_endpoint_with_version(diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.pyindex 0b455d46c676..957caff40079 100644--- a/products/endpoints/backend/tests/test_insight_response_parity.py+++ b/products/endpoints/backend/tests/test_insight_response_parity.py@@ -4,10 +4,11 @@ These tests are written TDD-style: they define the expected contract and initialmaterialized path currently returns flat HogQL data instead of rich insight-specific responses."""-from datetime import UTC, date, datetime+from datetime import UTC, date, datetime, timedeltafrom typing import Anyimport pytest+import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest import mock@@ -16,7 +17,20 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.schema import Breakdown, BreakdownFilter, BreakdownType, EventsNode, HogQLQueryResponse, TrendsQuery+from posthog.schema import (+ Breakdown,+ BreakdownFilter,+ BreakdownType,+ CachedHogQLQueryResponse,+ CompareFilter,+ EventsNode,+ HogQLQuery,+ HogQLQueryResponse,+ TrendsFilter,+ TrendsQuery,+)++from posthog.api.services.query import process_query_modelfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.endpoints.backend.insight_transformers import (@@ -60,11 +74,11 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):self.v2_dag_ids_patcher.stop()super().tearDown()- def _materialize_endpoint(self, endpoint):+ def _materialize_endpoint(self, endpoint, data_freshness_seconds=86400):"""Enable materialization and set up a completed saved query with table."""response = self.client.patch(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",- {"is_materialized": True, "data_freshness_seconds": 86400},+ {"is_materialized": True, "data_freshness_seconds": data_freshness_seconds},format="json",)assert response.status_code == status.HTTP_200_OK, response.json()@@ -93,6 +107,16 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):format="json",)+ def _trends_query(self, **kwargs: Any) -> dict[str, Any]:+ return TrendsQuery(**kwargs).model_dump()++ def _compare_mode_rollout(self):+ """Eligibility is re-checked on every materialized read, not just when materializing."""+ return mock.patch(+ "products.endpoints.backend.models.posthoganalytics.feature_enabled",+ return_value=True,+ )+# =========================================================================# TRENDS# =========================================================================@@ -101,10 +125,10 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):endpoint = create_endpoint_with_version(name="trends_parity",team=self.team,- query=TrendsQuery(+ query=self._trends_query(series=[EventsNode(event="$pageview")],dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},- ).model_dump(),+ ),created_by=self.user,is_active=True,)@@ -301,6 +325,23 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):assert series["days"] == ["2026-05-04", "2026-05-05", "2026-05-06"]assert series["labels"] == ["4-May-2026", "5-May-2026", "6-May-2026"]+ def test_transform_empty_compare_result_preserves_resolved_date_range(self):+ materialized_at = datetime(2026, 9, 26, 12, tzinfo=UTC)+ original_query = self._trends_query(+ series=[EventsNode(event="$pageview")],+ dateRange={"date_from": "-7d"},+ compareFilter=CompareFilter(compare=True, compare_to="-1w"),+ )+ result: dict[str, Any] = {"results": [], "columns": ["__series_index", "date", "total"]}++ _transform_trends(result, original_query, self.team, materialized_at)++ assert result["results"] == []+ assert result["resolved_compare_date_range"] == {+ "date_from": datetime(2026, 9, 12, tzinfo=UTC),+ "date_to": datetime(2026, 9, 19, 23, 59, 59, 999999, tzinfo=UTC),+ }+# =========================================================================# MULTI-SERIES TRENDS# =========================================================================@@ -362,6 +403,77 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):assert result["data"] == [1.0] * 10, f"Series {i}: unexpected data values: {result['data']}"assert result["count"] == 10.0, f"Series {i}: unexpected count: {result['count']}"+ def test_materialized_compare_formula_matches_inline_response_contract(self):+ materialized_at = datetime(2026, 9, 26, 12, tzinfo=UTC)+ event_counts = [+ ("2026-09-20", "$pageview", 1),+ ("2026-09-21", "$pageview", 2),+ ("2026-09-20", "$pageleave", 3),+ ("2026-09-21", "$pageleave", 4),+ ("2026-09-13", "$pageview", 5),+ ("2026-09-14", "$pageview", 6),+ ("2026-09-13", "$pageleave", 7),+ ("2026-09-14", "$pageleave", 8),+ ]+ for event_date, event_name, count in event_counts:+ for index in range(count):+ _create_event(+ event=event_name,+ distinct_id=f"{event_name}-{event_date}-{index}",+ team=self.team,+ timestamp=f"{event_date} 12:{index:02d}:00",+ )+ flush_persons_and_events()++ endpoint = create_endpoint_with_version(+ name="compare_formula_parity",+ team=self.team,+ query=self._trends_query(+ series=[EventsNode(event="$pageview"), EventsNode(event="$pageleave")],+ dateRange={"date_from": "-7d"},+ trendsFilter=TrendsFilter(formula="A+2*B"),+ compareFilter=CompareFilter(compare=True, compare_to="-1w"),+ ),+ created_by=self.user,+ is_active=True,+ data_freshness_seconds=604800,+ )++ with time_machine.travel(materialized_at, tick=False):+ inline_response = self._run_endpoint(endpoint)+ assert inline_response.status_code == status.HTTP_200_OK+ inline_compare_range = inline_response.json()["resolved_compare_date_range"]+ with self._compare_mode_rollout():+ saved_query = self._materialize_endpoint(endpoint, data_freshness_seconds=604800)++ flat_response = process_query_model(+ self.team,+ HogQLQuery.model_validate(saved_query.query),+ user=self.user,+ )+ assert isinstance(flat_response, HogQLQueryResponse | CachedHogQLQueryResponse)++ with (+ time_machine.travel(materialized_at + timedelta(days=6), tick=False),+ self._compare_mode_rollout(),+ mock.patch(+ "products.endpoints.backend.logic.execution.process_query_model",+ return_value=flat_response,+ ),+ ):+ materialized_response = self._run_endpoint(endpoint)++ assert materialized_response.status_code == status.HTTP_200_OK, materialized_response.json()+ response_data = materialized_response.json()+ assert response_data["resolved_compare_date_range"] == inline_compare_range+ response_series = response_data["results"]+ inline_series = inline_response.json()["results"]+ fields = ("compare_label", "data", "days", "labels", "count")+ assert [{field: series[field] for field in fields} for series in response_series] == [+ {field: series[field] for field in fields} for series in inline_series+ ]+ assert response_series[0]["days"] != response_series[1]["days"]+# =========================================================================# DATE STRING COERCION (materialized tables return Array(Date) as strings)# =========================================================================diff --git a/products/endpoints/skills/creating-an-endpoint/SKILL.md b/products/endpoints/skills/creating-an-endpoint/SKILL.mdindex 2ae4ba087e0e..470753ace375 100644--- a/products/endpoints/skills/creating-an-endpoint/SKILL.md+++ b/products/endpoints/skills/creating-an-endpoint/SKILL.md@@ -5,9 +5,9 @@ description: >conventions, what to expose as variables (HogQL code_name vs insight breakdown),data_freshness_seconds, and whether to materialise on day one. Use when the user says "create an endpoint", "expose thisquery as an API", "turn this insight into an endpoint", or asks for help structuring a new- endpoint. Steers away from common mistakes: materialising a query with cohort breakdowns or- compare mode, inline-only variables on a materialised endpoint, unbounded date ranges, ambiguous- names.+ endpoint. Steers away from common mistakes: materialising a query with cohort breakdowns or an+ ineligible compare query, inline-only variables on a materialised endpoint, unbounded date+ ranges, ambiguous names.---# Creating an endpointdiff --git a/products/endpoints/skills/creating-an-endpoint/references/materializing.md b/products/endpoints/skills/creating-an-endpoint/references/materializing.mdindex 2c8a84338a9d..e7f1e3d5dd89 100644--- a/products/endpoints/skills/creating-an-endpoint/references/materializing.md+++ b/products/endpoints/skills/creating-an-endpoint/references/materializing.md@@ -24,9 +24,10 @@ If two or more of these apply, materialise. If none apply, don't.bucket is tiny and the refresh churn outweighs the read savings.- **Low-traffic endpoint.** If it's called once a day, the materialisation refresh costs morethan the inline reads would.-- **Cohort breakdowns or compare mode (insight endpoints).** Regular property breakdowns- materialise fine; only cohort breakdowns and compare mode are rejected. Use- `endpoints-materialization-preview` to confirm.+- **Cohort breakdowns (insight endpoints).** Regular property breakdowns materialise fine, but+ cohort breakdowns are rejected. Compare mode can materialise for eligible Trends endpoints+ during its controlled rollout. It stores and computes both periods, so expect about twice the+ storage and refresh work. Use `endpoints-materialization-preview` to confirm eligibility.- **Query reads `now()` / `today()` directly.** Replace with a variable; otherwise thematerialised result is anchored to the refresh time, not the call time.@@ -38,7 +39,7 @@ rejection reasons:| Reason | What it means | Fix || ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- || `Cohort breakdowns are not supported` | Cohort breakdowns produce a UNION ALL the transform can't tag by series | Use a property breakdown, or split into separate endpoints, one per cohort |-| `Compare mode is not supported` | Compare mode doubles the series, which the transform can't reconstruct | Drop compare mode, or expose the comparison window as a variable |+| `Compare mode is not supported` | The query is not a Trends query, or the project is not in the compare-mode materialisation rollout | Keep it inline, drop compare mode, or expose the comparison window as a variable || `Query has unresolved variables` | A variable in the query has no default and the materialisation can't pick a value | Set defaults for all variables || `Query references non-deterministic functions` | `now()`, `today()`, `rand()` change between refresh runs | Replace with a `date_from` / `date_to` variable || `CTE variables with JOINs … not supported` | A variable filter combined with a top-level `JOIN` changes joined-row cardinality, silently producing wrong results (e.g. `LEFT JOIN` non-matches lose the variable column) | Filter inside a subquery/CTE, then join the result — don't apply the variable across the JOIN |