: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
chore(product-analytics): move the endpoint contract cases next to the runners (#92259)
Thomas Obermüllerea5ed9b4db0b
diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.pyindex 6f99e403a56e..2727ef1abf02 100644--- a/products/cohorts/backend/models/test/test_util.py+++ b/products/cohorts/backend/models/test/test_util.py@@ -403,30 +403,13 @@ class TestCohortUtils(BaseTest):def test_print_cohort_hogql_query_includes_settings(self):"""Test that cohort queries include HogQL global settings"""- # Create a cohort with a HogQL query (simulating a funnel-to-cohort conversion)+ # The settings come from the printer, so any actors-shaped cohort query reaches them.cohort = Cohort.objects.create(team=self.team,- name="Test Funnel Cohort",+ name="Test Actors Cohort",query={"kind": "ActorsQuery",- "source": {- "kind": "FunnelsActorsQuery",- "source": {- "kind": "FunnelsQuery",- "series": [- {"kind": "EventsNode", "event": "$pageview"},- {"kind": "EventsNode", "event": "$identify"},- ],- "interval": "day",- "dateRange": {"date_from": "-30d"},- "funnelsFilter": {- "funnelVizType": "steps",- "funnelWindowInterval": 1,- "funnelWindowIntervalUnit": "day",- },- },- "funnelStep": 2,- },+ "source": {"kind": "HogQLQuery", "query": "SELECT id AS actor_id FROM persons"},},)diff --git a/products/endpoints/backend/facade/api.py b/products/endpoints/backend/facade/api.pyindex 22aae3c063b7..524f53258057 100644--- a/products/endpoints/backend/facade/api.py+++ b/products/endpoints/backend/facade/api.py@@ -34,6 +34,7 @@ from products.endpoints.backend.models import Endpoint, EndpointVersionfrom . import contractsif TYPE_CHECKING:+ from products.endpoints.backend.insight_transformers import transform_materialized_insight_responsefrom products.endpoints.backend.logic.ai_materialization_fix import (REWRITE_CONTRACT,live_materialization_conditions_source,@@ -51,6 +52,7 @@ if TYPE_CHECKING:validate_endpoint_request,validate_update_request,)+ from products.endpoints.backend.materialization_transforms import build_endpoint_hogqlfrom products.endpoints.backend.openapi import generate_openapi_spec# symbol -> source module (relative to products.endpoints.backend)@@ -67,6 +69,10 @@ _LAZY = {"validate_endpoint_request": "logic.validation","validate_update_request": "logic.validation","generate_openapi_spec": "openapi",+ # The insight-conversion seam. Product analytics owns the runners these two reach through+ # core's dispatcher, so its tests hold the cases that prove the conversion still works.+ "build_endpoint_hogql": "materialization_transforms",+ "transform_materialized_insight_response": "insight_transformers",}@@ -148,6 +154,7 @@ __all__ = ["EndpointCrudService","EndpointExecutionService","EndpointMaterializationService",+ "build_endpoint_hogql","build_materialization_info","generate_openapi_spec","get_endpoint",@@ -158,6 +165,7 @@ __all__ = ["live_materialization_conditions_source","materialization_fix_enabled","suggest_materialization_fix",+ "transform_materialized_insight_response","validate_bucket_overrides","validate_endpoint_request","validate_update_request",diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.pyindex 918906f19f74..21c760a12ada 100644--- a/products/endpoints/backend/tests/test_endpoint_materialization.py+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py@@ -548,12 +548,6 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):can_materialize, reason = version.can_materialize()self.assertTrue(can_materialize, reason)- # The allowlist only reads the kind, so compile too: this is the step that would break if the- # runner stopped producing a printable AST.- hogql_query = build_endpoint_hogql(version.query, self.team)- self.assertEqual(hogql_query["kind"], "HogQLQuery")- self.assertIsInstance(hogql_query["query"], str)-@parameterized.expand([(diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.pyindex caef37643e0c..da71d33645db 100644--- a/products/endpoints/backend/tests/test_insight_response_parity.py+++ b/products/endpoints/backend/tests/test_insight_response_parity.py@@ -16,17 +16,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.schema import (- Breakdown,- BreakdownFilter,- BreakdownType,- EventsNode,- HogQLQueryResponse,- LifecycleQuery,- RetentionFilter,- RetentionQuery,- TrendsQuery,-)+from posthog.schema import Breakdown, BreakdownFilter, BreakdownType, EventsNode, HogQLQueryResponse, TrendsQueryfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.endpoints.backend.insight_transformers import (@@ -41,10 +31,6 @@ pytestmark = [pytest.mark.django_db]# Fields that every TrendsQuery result dict must haveTRENDS_REQUIRED_FIELDS = {"data", "labels", "days", "count", "label", "action"}-# Fields that every LifecycleQuery result dict must have-LIFECYCLE_REQUIRED_FIELDS = {"data", "labels", "days", "count", "label", "action", "status"}-# Fields that every RetentionQuery result dict must have-RETENTION_REQUIRED_FIELDS = {"values", "label", "date"}class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):@@ -320,73 +306,6 @@ 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"]- # =========================================================================- # LIFECYCLE- # =========================================================================-- def test_materialized_lifecycle_has_insight_shape(self):- original_query = LifecycleQuery(- series=[EventsNode(event="$pageview")],- dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},- ).model_dump()-- # Columns arrive in alphabetical order, the way Delta/Parquet sorts a materialized table.- dates = [date(2026, 1, d) for d in range(1, 11)]- result: dict[str, Any] = {- "results": [- (dates, "new", [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),- (dates, "returning", [0, 1, 1, 1, 1, 1, 1, 1, 1, 1]),- (dates, "resurrecting", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),- (dates, "dormant", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),- ],- "columns": ["date", "status", "total"],- "types": ["Array(Date)", "String", "Array(Int64)"],- }-- transform_materialized_insight_response(result, original_query, self.team)-- rows = result["results"]- assert len(rows) > 0- for field in LIFECYCLE_REQUIRED_FIELDS:- assert field in rows[0], f"Materialized lifecycle response missing '{field}'"- assert {r["status"] for r in rows} == {"new", "returning", "resurrecting", "dormant"}- for r in rows:- assert len(r["data"]) == 10, f"Status {r['status']}: expected 10 data points, got {len(r['data'])}"-- # =========================================================================- # RETENTION- # =========================================================================-- def test_materialized_retention_has_insight_shape(self):- original_query = RetentionQuery(- retentionFilter=RetentionFilter(),- dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},- ).model_dump()-- # Columns arrive in alphabetical order, the way Delta/Parquet sorts a materialized table.- result: dict[str, Any] = {- "results": [- (1, 0, 0),- (1, 1, 0),- (1, 0, 1),- (1, 1, 1),- (0, 0, 2),- (0, 1, 2),- ],- "columns": ["count", "intervals_from_base", "start_event_matching_interval"],- "types": ["UInt64", "Int64", "Int64"],- }-- transform_materialized_insight_response(result, original_query, self.team)-- rows = result["results"]- assert len(rows) >= 3, f"Expected at least 3 cohorts, got {len(rows)}"- for field in RETENTION_REQUIRED_FIELDS:- assert field in rows[0], f"Materialized retention response missing '{field}'"- assert isinstance(rows[0]["values"], list)- assert rows[0]["values"][0]["count"] == 1- assert "label" in rows[0]["values"][0]-# =========================================================================# MULTI-SERIES TRENDS# =========================================================================diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex ae28a52ee98f..245dce8191e8 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -674,12 +674,6 @@ product_analytics.Insight products.reminders.backend.constants in-collection 1product_analytics.Insight products.slack_app.backend.slack_link_unfurl instance-single 1product_analytics.Insight products.surveys.backend.api.survey instance-single 1product_analytics.Insight surveys.Survey.linked_insight reverse-accessor(surveys_linked_insight) 1-product_analytics:backend/hogql_queries/ products.cohorts.backend.models.test.test_util drives(FunnelsQuery) 1-product_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_endpoint_materialization drives(LifecycleQuery) 1-product_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_endpoint_materialization drives(RetentionQuery) 1-product_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_insight_response_parity drives(LifecycleQuery) 1-product_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_insight_response_parity drives(RetentionQuery) 1-product_analytics:backend/hogql_queries/ products.posthog_ai.scripts.hogql_example.test.test_hogql_example drives(FunnelsQuery) 1replay_vision.ReplayScanner posthog.TaggedItem.replay_scanner reverse-accessor(tagged_items) 1signals.SignalReport tasks.Task.signal_report reverse-accessor(task) 1surveys.Survey product_tours.ProductTour.linked_surveys reverse-accessor(product_tours) 1diff --git a/products/posthog_ai/scripts/hogql_example/test/test_hogql_example.py b/products/posthog_ai/scripts/hogql_example/test/test_hogql_example.pyindex 3f2df4fc0234..d2938badad16 100644--- a/products/posthog_ai/scripts/hogql_example/test/test_hogql_example.py+++ b/products/posthog_ai/scripts/hogql_example/test/test_hogql_example.py@@ -2,6 +2,8 @@from __future__ import annotations+from types import SimpleNamespace+import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -56,24 +58,16 @@ class TestRenderHogQLExample(BaseTest):assert "2025-12-10" in resultassert "2025-12-03" in result- @patch("django.conf.settings.DEBUG", True)- def test_funnel_pins_context_now_for_sub_date_ranges(self) -> None:- # FunnelsQuery's sub-helpers read `context.now` rather than the runner's- # query_date_range, so this guards the context-pinning branch of- # `_pin_runner_now`.- result = render_hogql_example(- {- "kind": "FunnelsQuery",- "series": [- {"kind": "EventsNode", "event": "$pageview"},- {"kind": "EventsNode", "event": "user signed up"},- ],- "dateRange": {"date_from": "-7d"},- }- )+ def test_pins_context_now_as_well_as_the_date_range(self) -> None:+ # Some runners resolve sub-ranges off `context.now` rather than off query_date_range, so+ # both surfaces have to be pinned. A stub stands in for the runner because the branch is+ # generic: reaching it through a real query kind ties this suite to whichever product+ # owns that kind, and the trends case above already covers the pipeline end to end.+ runner = SimpleNamespace(context=SimpleNamespace(now=None))- assert "2025-12-10" in result- assert "2025-12-03" in result+ hogql_example_module._pin_runner_now(runner, hogql_example_module._FROZEN_DATETIME)++ assert runner.context.now == hogql_example_module._FROZEN_DATETIME@patch("django.conf.settings.DEBUG", True)def test_render_does_not_use_freezegun(self) -> None:diff --git a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_endpoint_contract.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_endpoint_contract.pynew file mode 100644index 000000000000..2c660aec3b86--- /dev/null+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_endpoint_contract.py@@ -0,0 +1,51 @@+from datetime import date+from typing import Any++from posthog.test.base import BaseTest++from posthog.schema import EventsNode, LifecycleQuery++from products.endpoints.backend.facade.api import build_endpoint_hogql, transform_materialized_insight_response++LIFECYCLE_REQUIRED_FIELDS = {"data", "labels", "days", "count", "label", "action", "status"}+++# What the endpoints product needs from this runner, tested where the runner lives. Both paths+# reach `LifecycleQueryRunner` through core's dispatcher, so an edit here breaks endpoints, and+# keeping the cases beside the runner is what makes them run on that edit.+class TestLifecycleEndpointContract(BaseTest):+ def _query(self) -> dict[str, Any]:+ return LifecycleQuery(+ series=[EventsNode(event="$pageview")],+ dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},+ ).model_dump()++ def test_compiles_to_printable_hogql(self) -> None:+ hogql_query = build_endpoint_hogql(self._query(), self.team)++ assert hogql_query["kind"] == "HogQLQuery"+ assert isinstance(hogql_query["query"], str)++ def test_materialized_rows_take_the_insight_shape(self) -> None:+ # Columns arrive in alphabetical order, the way Delta/Parquet sorts a materialized table.+ dates = [date(2026, 1, day) for day in range(1, 11)]+ result: dict[str, Any] = {+ "results": [+ (dates, "new", [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),+ (dates, "returning", [0, 1, 1, 1, 1, 1, 1, 1, 1, 1]),+ (dates, "resurrecting", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),+ (dates, "dormant", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),+ ],+ "columns": ["date", "status", "total"],+ "types": ["Array(Date)", "String", "Array(Int64)"],+ }++ transform_materialized_insight_response(result, self._query(), self.team)++ rows = result["results"]+ assert len(rows) > 0+ for field in LIFECYCLE_REQUIRED_FIELDS:+ assert field in rows[0], f"Materialized lifecycle response missing '{field}'"+ assert {row["status"] for row in rows} == {"new", "returning", "resurrecting", "dormant"}+ for row in rows:+ assert len(row["data"]) == 10, f"Status {row['status']}: expected 10 data points, got {len(row['data'])}"diff --git a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_endpoint_contract.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_endpoint_contract.pynew file mode 100644index 000000000000..1aa61237a393--- /dev/null+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_endpoint_contract.py@@ -0,0 +1,67 @@+from typing import Any++from posthog.test.base import BaseTest++from posthog.schema import RetentionFilter, RetentionQuery++from posthog.constants import RETENTION_FIRST_EVER_OCCURRENCE, TREND_FILTER_TYPE_EVENTS++from products.endpoints.backend.facade.api import build_endpoint_hogql, transform_materialized_insight_response++RETENTION_REQUIRED_FIELDS = {"values", "label", "date"}+++# What the endpoints product needs from this runner, tested where the runner lives. Both paths+# reach `RetentionQueryRunner` through core's dispatcher, so an edit here breaks endpoints, and+# keeping the cases beside the runner is what makes them run on that edit.+class TestRetentionEndpointContract(BaseTest):+ def test_compiles_to_printable_hogql(self) -> None:+ query = RetentionQuery(+ dateRange={"date_from": "2025-01-01", "date_to": "2025-01-08"},+ retentionFilter=RetentionFilter(+ period="Day",+ totalIntervals=7,+ retentionType=RETENTION_FIRST_EVER_OCCURRENCE,+ targetEntity={+ "id": "$user_signed_up",+ "name": "$user_signed_up",+ "type": TREND_FILTER_TYPE_EVENTS,+ },+ returningEntity={"id": "$pageview", "name": "$pageview", "type": "events"},+ ),+ ).model_dump()++ hogql_query = build_endpoint_hogql(query, self.team)++ assert hogql_query["kind"] == "HogQLQuery"+ assert isinstance(hogql_query["query"], str)++ def test_materialized_rows_take_the_insight_shape(self) -> None:+ original_query = RetentionQuery(+ retentionFilter=RetentionFilter(),+ dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},+ ).model_dump()++ # Columns arrive in alphabetical order, the way Delta/Parquet sorts a materialized table.+ result: dict[str, Any] = {+ "results": [+ (1, 0, 0),+ (1, 1, 0),+ (1, 0, 1),+ (1, 1, 1),+ (0, 0, 2),+ (0, 1, 2),+ ],+ "columns": ["count", "intervals_from_base", "start_event_matching_interval"],+ "types": ["UInt64", "Int64", "Int64"],+ }++ transform_materialized_insight_response(result, original_query, self.team)++ rows = result["results"]+ assert len(rows) >= 3, f"Expected at least 3 cohorts, got {len(rows)}"+ for field in RETENTION_REQUIRED_FIELDS:+ assert field in rows[0], f"Materialized retention response missing '{field}'"+ assert isinstance(rows[0]["values"], list)+ assert rows[0]["values"][0]["count"] == 1+ assert "label" in rows[0]["values"][0]diff --git a/products/product_analytics/turbo.json b/products/product_analytics/turbo.jsonindex c72b121729e4..0be4d6c10996 100644--- a/products/product_analytics/turbo.json+++ b/products/product_analytics/turbo.json@@ -4,7 +4,6 @@"backend:contract-check": {"inputs": ["backend/facade/**",- "backend/hogql_queries/**","backend/presentation/**","backend/routes.py","backend/models/**",