: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(product-analytics): drain the presentation wave and skip its Django suite (#86275)
Thomas Obermüllere2660188d9c9
diff --git a/posthog/api/test/test_search_match_type_mixin.py b/posthog/api/test/test_search_match_type_mixin.pyindex 5e6f687e1097..e828817c8e7a 100644--- a/posthog/api/test/test_search_match_type_mixin.py+++ b/posthog/api/test/test_search_match_type_mixin.py@@ -5,7 +5,7 @@ from posthog.api.cohort import CohortSerializerfrom posthog.api.organization_member import OrganizationMemberSerializerfrom posthog.api.shared import SearchMatchTypeSerializerMixin-from products.alerts.backend.api.alert import AlertSerializer+from products.alerts.backend.presentation.views.alert import AlertSerializerfrom products.cdp.backend.api.hog_function import HogFunctionMinimalSerializer, HogFunctionSerializerfrom products.dashboards.backend.api.dashboard import DashboardBasicSerializerfrom products.product_analytics.backend.presentation.insight import InsightBasicSerializer, InsightSerializerdiff --git a/posthog/tasks/alerts/test/test_metrics_alerts.py b/posthog/tasks/alerts/test/test_metrics_alerts.pyindex ddccb4255043..277c855a5a61 100644--- a/posthog/tasks/alerts/test/test_metrics_alerts.py+++ b/posthog/tasks/alerts/test/test_metrics_alerts.py@@ -71,7 +71,9 @@ def _stub_investigation_result(metric_name: str, mover_label: str = "pod-1") ->@freeze_time(FROZEN_TIME)-@patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", side_effect=_metrics_flag_only)+@patch(+ "products.alerts.backend.presentation.views.alert.posthoganalytics.feature_enabled", side_effect=_metrics_flag_only+)@patch("posthog.tasks.alerts.utils.send_notifications_for_errors", return_value=[])@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.pyindex f7af573d4b88..5fda0c7efffe 100644--- a/products/alerts/backend/facade/api.py+++ b/products/alerts/backend/facade/api.py@@ -1,7 +1,7 @@import uuidfrom collections.abc import Collectionfrom datetime import datetime, timedelta-from typing import Literal+from typing import Any, Literal, castfrom zoneinfo import ZoneInfofrom django.db import transaction@@ -15,7 +15,6 @@ from posthog.rbac.user_access_control import UserAccessControlfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import relative_date_parse-from products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestrictionfrom products.alerts.backend.destination_configs import (DESTINATION_TEMPLATE_IDS,AlertDestinationData,@@ -33,6 +32,7 @@ from products.alerts.backend.destinations import (from products.alerts.backend.email_notifications import send_alert_emailfrom products.alerts.backend.insight_alert_state_machine import apply_snoozefrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration+from products.alerts.backend.presentation.views.alert_schedule_restriction import AlertScheduleRestrictionfrom products.alerts.backend.scheduling import validate_and_normalize_schedule_restrictionlogger = structlog.get_logger(__name__)@@ -70,6 +70,20 @@ def insight_ids_with_alerts(insight_ids: Collection[int]) -> set[int]:return set(AlertConfiguration.objects.filter(insight_id__in=insight_ids).values_list("insight_id", flat=True))+def serialize_insight_alerts(alerts: Collection[AlertConfiguration], context: dict[str, Any]) -> list[dict[str, Any]]:+ """Render an insight's alerts for the insight API response.++ The insight API prefetches the alerts so the render costs no extra query, then hands them+ back here — the alert JSON shape is this product's to define, not product_analytics'.+ ``context`` is the calling serializer's DRF context.+ """+ # Deferred so the facade does not pull DRF onto its import path.+ from products.alerts.backend.presentation.views.alert import AlertSerializer # noqa: PLC0415++ # `many=True` yields a ReturnList; the DRF stubs type `.data` as ReturnDict either way.+ return cast(list[dict[str, Any]], AlertSerializer(alerts, many=True, context=context).data)++def snooze_alert_from_slack(alert_id: uuid.UUID, *, user: User, duration: str | None = None, until: datetime | None = None) -> SlackSnoozeOutcome:@@ -169,6 +183,7 @@ __all__ = ["create_alert_destination_hog_functions","get_alert_team_id","insight_ids_with_alerts",+ "serialize_insight_alerts","snooze_alert_from_slack","soft_delete_alert_destinations","soft_delete_alert_destinations_for_alerts",diff --git a/products/alerts/backend/facade/models.py b/products/alerts/backend/facade/models.pynew file mode 100644index 000000000000..4c85d73d5331--- /dev/null+++ b/products/alerts/backend/facade/models.py@@ -0,0 +1,14 @@+"""+Model-class wiring for alerts.++Re-exports the ``AlertConfiguration``, ``AlertSubscription`` and ``Threshold`` model classes+under the watched-models allowance (MODEL_CROSSINGS). The insight API prefetches an insight's+alerts with a ``Prefetch`` queryset so rendering them costs no extra query, and soft-deletes+them alongside the insight — ORM semantics a frozen contract cannot express. ``Threshold`` and+``AlertSubscription`` hang off ``AlertConfiguration`` and cross with it, because the rendered+alert carries its threshold and its subscribers.+"""++from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold++__all__ = ["AlertConfiguration", "AlertSubscription", "Threshold"]diff --git a/products/alerts/backend/presentation/__init__.py b/products/alerts/backend/presentation/__init__.pynew file mode 100644index 000000000000..e6658575bf9d--- /dev/null+++ b/products/alerts/backend/presentation/__init__.py@@ -0,0 +1 @@+"""HTTP presentation layer of the alerts product (DRF viewsets and serializers)."""diff --git a/products/alerts/backend/api/__init__.py b/products/alerts/backend/presentation/views/__init__.pysimilarity index 100%rename from products/alerts/backend/api/__init__.pyrename to products/alerts/backend/presentation/views/__init__.pydiff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/presentation/views/alert.pysimilarity index 99%rename from products/alerts/backend/api/alert.pyrename to products/alerts/backend/presentation/views/alert.pyindex 91680ffbbe47..3fa493ee01e9 100644--- a/products/alerts/backend/api/alert.py+++ b/products/alerts/backend/presentation/views/alert.py@@ -57,7 +57,6 @@ from posthog.tasks.alerts.utils import ()from posthog.utils import relative_date_parse-from products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestrictionfrom products.alerts.backend.destination_configs import DestinationTypefrom products.alerts.backend.destinations import count_active_alert_destinationsfrom products.alerts.backend.evaluation.contract import AlertExtractionError@@ -75,6 +74,7 @@ from products.alerts.backend.insight_alert_state_machine import (apply_unsnooze,)from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold+from products.alerts.backend.presentation.views.alert_schedule_restriction import AlertScheduleRestrictionfrom products.product_analytics.backend.facade.models import InsightINSIGHT_ALERT_FIRING_EVENT = "$insight_alert_firing"diff --git a/products/alerts/backend/api/alert_schedule_restriction.py b/products/alerts/backend/presentation/views/alert_schedule_restriction.pysimilarity index 100%rename from products/alerts/backend/api/alert_schedule_restriction.pyrename to products/alerts/backend/presentation/views/alert_schedule_restriction.pydiff --git a/products/alerts/backend/routes.py b/products/alerts/backend/routes.pyindex 6adaf39debc3..ed84bd386fa1 100644--- a/products/alerts/backend/routes.py+++ b/products/alerts/backend/routes.py@@ -1,6 +1,6 @@from posthog.api.routing import RouterRegistry-import products.alerts.backend.api.alert as alert+import products.alerts.backend.presentation.views.alert as alertdef register_routes(routers: RouterRegistry) -> None:diff --git a/products/alerts/backend/api/test/__init__.py b/products/alerts/backend/tests/api/__init__.pysimilarity index 100%rename from products/alerts/backend/api/test/__init__.pyrename to products/alerts/backend/tests/api/__init__.pydiff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/tests/api/test_alert.pysimilarity index 99%rename from products/alerts/backend/api/test/test_alert.pyrename to products/alerts/backend/tests/api/test_alert.pyindex 2148153f98c0..f17aa652c74e 100644--- a/products/alerts/backend/api/test/test_alert.py+++ b/products/alerts/backend/tests/api/test_alert.py@@ -688,7 +688,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):def test_alert_limit(self) -> None:with mock.patch(- "products.alerts.backend.api.alert.AlertConfiguration.ALERTS_ALLOWED_ON_FREE_TIER"+ "products.alerts.backend.presentation.views.alert.AlertConfiguration.ALERTS_ALLOWED_ON_FREE_TIER") as alert_limit:alert_limit.__get__ = mock.Mock(return_value=1)@@ -1687,7 +1687,7 @@ class TestAlertTestDelivery(APIBaseTest):},)- @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions")+ @mock.patch("products.alerts.backend.presentation.views.alert.trigger_alert_hog_functions")def test_queues_test_delivery_for_active_destinations_without_changing_alert(self, mock_trigger) -> None:mock_trigger.return_value = [TEST_DESTINATION_DELIVERY]self._create_destination()@@ -1717,7 +1717,7 @@ class TestAlertTestDelivery(APIBaseTest):assert alert_after.last_notified_at == alert_before.last_notified_atassert AlertCheck.objects.filter(alert_configuration_id=self.alert["id"]).count() == 0- @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions")+ @mock.patch("products.alerts.backend.presentation.views.alert.trigger_alert_hog_functions")@mock.patch("products.alerts.backend.email_notifications.EmailMessage")def test_sends_test_delivery_to_subscribed_users_without_a_destination(self, mock_email_message, mock_trigger@@ -1739,9 +1739,13 @@ class TestAlertTestDelivery(APIBaseTest):mock_email_message.return_value.send.assert_called_once_with()mock_trigger.assert_not_called()- @mock.patch("products.alerts.backend.api.alert.send_test_alert_email", side_effect=RuntimeError("email failed"))@mock.patch(- "products.alerts.backend.api.alert.trigger_alert_hog_functions", return_value=[TEST_DESTINATION_DELIVERY]+ "products.alerts.backend.presentation.views.alert.send_test_alert_email",+ side_effect=RuntimeError("email failed"),+ )+ @mock.patch(+ "products.alerts.backend.presentation.views.alert.trigger_alert_hog_functions",+ return_value=[TEST_DESTINATION_DELIVERY],)def test_destination_still_queues_when_email_fails(self, mock_trigger, _mock_email) -> None:alert = AlertConfiguration.objects.get(id=self.alert["id"])@@ -1758,7 +1762,7 @@ class TestAlertTestDelivery(APIBaseTest):}mock_trigger.assert_called_once()- @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions", return_value=[])+ @mock.patch("products.alerts.backend.presentation.views.alert.trigger_alert_hog_functions", return_value=[])def test_returns_service_unavailable_when_destination_fails_to_queue(self, mock_trigger) -> None:self._create_destination()@@ -1770,7 +1774,7 @@ class TestAlertTestDelivery(APIBaseTest):}mock_trigger.assert_called_once()- @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions")+ @mock.patch("products.alerts.backend.presentation.views.alert.trigger_alert_hog_functions")def test_rejects_test_delivery_without_active_destinations(self, mock_trigger) -> None:self._create_destination(enabled=False)@@ -1782,7 +1786,7 @@ class TestAlertTestDelivery(APIBaseTest):@mock.patch("posthog.rate_limit.AlertTestDeliveryThrottle.rate", new="2/minute")@mock.patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)- @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions")+ @mock.patch("products.alerts.backend.presentation.views.alert.trigger_alert_hog_functions")def test_rate_limits_test_delivery_per_team(self, _mock_trigger, _rate_limit_enabled) -> None:cache.clear()self._create_destination()diff --git a/products/annotations/backend/facade/ai_context.py b/products/annotations/backend/facade/ai_context.pynew file mode 100644index 000000000000..97ab5def9a2d--- /dev/null+++ b/products/annotations/backend/facade/ai_context.py@@ -0,0 +1,15 @@+"""+Facade re-exports for the annotation context AI surfaces embed in their prompts.++An insight summary, a dashboard summary and a subscription snapshot each resolve their own+date window and then ask for the annotations in it. Callers outside this product import the+two helpers from here rather than reaching the internal ``annotation_context`` module.+"""++from products.annotations.backend.api.annotation_context import (+ build_annotations_block,+ resolve_query_date_range,+ resolve_snapshot_date_range,+)++__all__ = ["build_annotations_block", "resolve_query_date_range", "resolve_snapshot_date_range"]diff --git a/products/architecture.md b/products/architecture.mdindex 10928fc71102..ee382b35b283 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -106,12 +106,20 @@ Two core registries are keyed by model class identity and are explicit, sanctionThere the class crosses for registration only, core drives only the registry's mixin methods, and the model's module must stay in the product's contract-check inputs.**The watched-models allowance** is the one further, deliberately temporary exception, for products whose models are load-bearing substrate that core and sibling products consume and cannot yet stop consuming.-Two products hold entries.+Five products hold entries.`warehouse_sources`: core HogQL reads its warehouse table/schema/source models to build queryable tables.`product_analytics`: `Insight`, `InsightVariable` and `InsightViewed`.Core and seven products (alerts, dashboards, surveys, annotations, exports, customer_analytics, pulse) hold ForeignKeys or M2Ms into `Insight` — dashboard tiles, subscriptions and exported assets, sharing configurations, tagged items — and rely on cascade deletes, relation traversal, reverse relations, and queryset-typed access-control filtering that a frozen contract cannot express.`InsightViewed` crosses for the view-tracking upsert (`update_or_create`) that shared-insight rendering and the demo generator perform.The dashboards→product_analytics `DashboardTile.insight` FK and `Dashboard.insights` M2M-through cross into the product against §8's direction rule; that coupling is accepted under this entry until dashboards pursues its own isolation.++`dashboards` (`Dashboard`, `DashboardTile`, `Text`), `alerts` (`AlertConfiguration`, `Threshold`, `AlertSubscription`) and `cohorts` (`Cohort`) are the same coupling read from the other side.+An insight's API representation includes the dashboards it sits on and the alerts watching it, so the insight viewset resolves target dashboards through querysets, compares `Dashboard.PrivilegeLevel` off the model, serializes tiles with a `ModelSerializer`, and creates, soft-deletes and restores tiles through the soft-delete manager.+It prefetches alerts with a `Prefetch` queryset so the render costs no extra query, and soft-deletes them when the insight goes; `Threshold` and `AlertSubscription` hang off `AlertConfiguration` and are rendered with it.+`Cohort` crosses for its `DoesNotExist`, which the legacy query path raises from inside filter resolution and the viewset turns into a 400.+None of the three products is narrowed today, so the allowance costs them nothing yet; it binds when they narrow, and it keeps each crossing named rather than hidden behind an unlinted facade re-export.+Retiring them means moving the dashboard-membership and alert rendering out of `product_analytics`' presentation, which is a larger change than sealing the product was.+An allowance product's facade may hand out model classes defined under `backend/models/`, provided the whole model surface — `backend/models/` and `backend/migrations/` — stays in the `backend:contract-check` inputs, so any model or migration change still re-runs the full suite.That is the same soundness contract wiring locations have; what it does not buy is isolation — the coupling to core remains, `hogli product:lint` keeps a standing warning on it, and the direction of travel is still facade functions returning contracts.The list lives in `MODEL_CROSSINGS` (`tools/hogli-commands/hogli_commands/product/isolation.py`) and is keyed `(product, class)`, like the carve-outs above: a class that is not listed is a leak and blocks narrowing, so a product already on the list cannot grow a new crossing without a doctrine change.diff --git a/products/cohorts/backend/facade/__init__.py b/products/cohorts/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cohorts/backend/facade/models.py b/products/cohorts/backend/facade/models.pynew file mode 100644index 000000000000..bc3a45726f62--- /dev/null+++ b/products/cohorts/backend/facade/models.py@@ -0,0 +1,12 @@+"""+Model-class wiring for cohorts.++Re-exports the ``Cohort`` model class under the watched-models allowance (MODEL_CROSSINGS).+The insight API's legacy query path raises ``Cohort.DoesNotExist`` from inside filter+resolution and turns it into a 400 — catching a model's own exception needs the class, and+the tests that cover that path build cohort rows through the manager.+"""++from products.cohorts.backend.models.cohort import Cohort++__all__ = ["Cohort"]diff --git a/products/dashboards/backend/access.py b/products/dashboards/backend/access.pyindex 9b29aec90935..a5aa33a96354 100644--- a/products/dashboards/backend/access.py+++ b/products/dashboards/backend/access.py@@ -1,5 +1,3 @@-from enum import StrEnum-from django.utils.timezone import nowfrom prometheus_client import Counter@@ -8,18 +6,11 @@ from rest_framework.request import Requestfrom posthog.event_usage import EventSource, get_event_sourcefrom posthog.otel_metrics import OtelInstrumentFactory+from products.dashboards.backend.facade.enums import DashboardAccessMethodfrom products.dashboards.backend.models.dashboard import Dashboard_otel = OtelInstrumentFactory("dashboards")--class DashboardAccessMethod(StrEnum):- HUMAN = "human"- SHARED = "shared"- EMBEDDED = "embedded"- API = "api"--DASHBOARD_ACCESS_COUNTER = Counter("posthog_dashboard_access_total","Dashboard accesses by source",diff --git a/products/dashboards/backend/facade/__init__.py b/products/dashboards/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/dashboards/backend/facade/access.py b/products/dashboards/backend/facade/access.pynew file mode 100644index 000000000000..2af811e5861c--- /dev/null+++ b/products/dashboards/backend/facade/access.py@@ -0,0 +1,12 @@+"""+Facade re-exports for dashboard access classification and cache telemetry.++Insights render inside dashboards, so the insight API classifies how a render was reached and+records the cache outcome under the dashboards metrics. It imports both from here rather than+reaching the internal ``access`` module.+"""++from products.dashboards.backend.access import dashboard_access_method, record_dashboard_cache_outcome+from products.dashboards.backend.facade.enums import DashboardAccessMethod++__all__ = ["DashboardAccessMethod", "dashboard_access_method", "record_dashboard_cache_outcome"]diff --git a/products/dashboards/backend/facade/enums.py b/products/dashboards/backend/facade/enums.pynew file mode 100644index 000000000000..7b9f7d4d2e07--- /dev/null+++ b/products/dashboards/backend/facade/enums.py@@ -0,0 +1,16 @@+"""+Shared enums for the dashboards product.++``DashboardAccessMethod`` labels how a dashboard render was reached. It lives in the facade+rather than in ``backend/access.py`` because the insight API tags its own cache metrics with+it, and a data type that crosses the product boundary belongs here.+"""++from enum import StrEnum+++class DashboardAccessMethod(StrEnum):+ HUMAN = "human"+ SHARED = "shared"+ EMBEDDED = "embedded"+ API = "api"diff --git a/products/dashboards/backend/facade/models.py b/products/dashboards/backend/facade/models.pynew file mode 100644index 000000000000..a81423d8ac37--- /dev/null+++ b/products/dashboards/backend/facade/models.py@@ -0,0 +1,15 @@+"""+Model-class wiring for dashboards.++Re-exports the ``Dashboard``, ``DashboardTile`` and ``Text`` model classes for cross-product+consumers under the watched-models allowance (MODEL_CROSSINGS). The insight API renders an+insight's dashboard membership: it resolves target dashboards through querysets, reads+privilege levels off the model, serializes tiles with a ``ModelSerializer``, and creates,+soft-deletes and restores tiles — ORM semantics a frozen contract cannot express. ``Text``+crosses with ``DashboardTile`` because a tile carries either an insight or a text block.+"""++from products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text++__all__ = ["Dashboard", "DashboardTile", "Text"]diff --git a/products/isolation_baseline.txt b/products/isolation_baseline.txtindex 16517ba05ca2..a5a4cad01e87 100644--- a/products/isolation_baseline.txt+++ b/products/isolation_baseline.txt@@ -60,7 +60,6 @@ notebooksnotificationsplatform_featuresposthog_ai-product_analyticsproduct_tourspulseremindersdiff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex 3c45e42a1d6d..1b0f71b6bdfe 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -143,15 +143,15 @@ from posthog.utils import (variables_override_requested_by_client,)-from products.alerts.backend.models.alert import AlertConfiguration-from products.cohorts.backend.models.cohort import Cohort-from products.dashboards.backend.access import (+from products.alerts.backend.facade.api import serialize_insight_alerts+from products.alerts.backend.facade.models import AlertConfiguration+from products.cohorts.backend.facade.models import Cohort+from products.dashboards.backend.facade.access import (DashboardAccessMethod,dashboard_access_method,record_dashboard_cache_outcome,)-from products.dashboards.backend.models.dashboard import Dashboard-from products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.dashboards.backend.facade.models import Dashboard, DashboardTilefrom products.product_analytics.backend.facade.api import map_stale_to_latest, plan_test_account_filter_updatefrom products.product_analytics.backend.facade.models import Insight, InsightVariable, InsightViewedfrom products.product_analytics.backend.presentation.insight_metadata import (@@ -1155,9 +1155,7 @@ class InsightSerializer(InsightBasicSerializer):# Use prefetched alerts dataalerts = getattr(insight, "_prefetched_alerts", [])- from products.alerts.backend.api.alert import AlertSerializer-- return AlertSerializer(alerts, many=True, context=self.context).data+ return serialize_insight_alerts(alerts, self.context)@extend_schema_field(InsightFilterOverrideContext) # type: ignore[arg-type]def get_filter_override_context(self, insight: Insight) -> dict[str, object] | None:diff --git a/products/product_analytics/backend/presentation/insight_ee.py b/products/product_analytics/backend/presentation/insight_ee.pyindex c16b22bd60bd..318033163290 100644--- a/products/product_analytics/backend/presentation/insight_ee.py+++ b/products/product_analytics/backend/presentation/insight_ee.py@@ -3,7 +3,7 @@from rest_framework.permissions import SAFE_METHODS, BasePermissionfrom rest_framework.request import Request-from products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.facade.models import Dashboardfrom products.product_analytics.backend.facade.models import Insightfrom products.product_analytics.backend.presentation.insight import InsightViewSetdiff --git a/products/product_analytics/backend/presentation/insight_suggestions.py b/products/product_analytics/backend/presentation/insight_suggestions.pyindex 6ee82abc2cb7..e471393c40f3 100644--- a/products/product_analytics/backend/presentation/insight_suggestions.py+++ b/products/product_analytics/backend/presentation/insight_suggestions.py@@ -21,7 +21,7 @@ from posthog.event_usage import groupsfrom posthog.llm.completions import hit_openaifrom posthog.models import Team-from products.annotations.backend.api.annotation_context import build_annotations_block, resolve_query_date_range+from products.annotations.backend.facade.ai_context import build_annotations_block, resolve_query_date_rangefrom products.product_analytics.backend.facade.api import get_query_specific_instructionsfrom products.product_analytics.backend.presentation.ai_billing import billable_ai_propertiesdiff --git a/products/product_analytics/backend/presentation/test/test_deprecated_dashboards_field.py b/products/product_analytics/backend/presentation/test/test_deprecated_dashboards_field.pyindex 92d52a8fb67c..02f4b19ff90e 100644--- a/products/product_analytics/backend/presentation/test/test_deprecated_dashboards_field.py+++ b/products/product_analytics/backend/presentation/test/test_deprecated_dashboards_field.py@@ -10,8 +10,7 @@ from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication, Shfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from products.dashboards.backend.models.dashboard import Dashboard-from products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.dashboards.backend.facade.models import Dashboard, DashboardTilefrom products.product_analytics.backend.facade.models import Insightfrom products.product_analytics.backend.presentation.insight import should_serve_deprecated_dashboards_fielddiff --git a/products/product_analytics/backend/presentation/test/test_insight.py b/products/product_analytics/backend/presentation/test/test_insight.pyindex 6af5610d5259..3fbddf46d624 100644--- a/products/product_analytics/backend/presentation/test/test_insight.py+++ b/products/product_analytics/backend/presentation/test/test_insight.py@@ -55,11 +55,10 @@ from posthog.models.project import Projectfrom posthog.test.db_context_capturing import capture_db_queriesfrom posthog.test.persons import create_person-from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold-from products.cohorts.backend.models.cohort import Cohort-from products.dashboards.backend.access import DashboardAccessMethod-from products.dashboards.backend.models.dashboard import Dashboard-from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+from products.alerts.backend.facade.models import AlertConfiguration, AlertSubscription, Threshold+from products.cohorts.backend.facade.models import Cohort+from products.dashboards.backend.facade.access import DashboardAccessMethod+from products.dashboards.backend.facade.models import Dashboard, DashboardTile, Textfrom products.product_analytics.backend.facade.models import Insight, InsightVariable, InsightViewedfrom ee.models.rbac.access_control import AccessControldiff --git a/products/product_analytics/backend/routes.py b/products/product_analytics/backend/routes.pyindex 66a133b26896..da55012c7d47 100644--- a/products/product_analytics/backend/routes.py+++ b/products/product_analytics/backend/routes.py@@ -2,7 +2,7 @@ from posthog.api import sharingfrom posthog.api.routing import RouterRegistryfrom posthog.settings import EE_AVAILABLE-import products.alerts.backend.api.alert as alert+import products.alerts.backend.presentation.views.alert as alertfrom products.product_analytics.backend.presentation.insight import InsightViewSetfrom products.product_analytics.backend.presentation.insight_ee import EnterpriseInsightsViewSetfrom products.product_analytics.backend.presentation.insight_variable import InsightVariableViewSetdiff --git a/products/product_analytics/package.json b/products/product_analytics/package.jsonindex d0010dd4ab26..ae0079db4a32 100644--- a/products/product_analytics/package.json+++ b/products/product_analytics/package.json@@ -1,7 +1,8 @@{"name": "@posthog/products-product-analytics","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short",+ "backend:contract-check": "echo 'Contract files unchanged'"},"dependencies": {"@posthog/quill-charts": "workspace:*",diff --git a/products/product_analytics/turbo.json b/products/product_analytics/turbo.jsonnew file mode 100644index 000000000000..d9ed4a52f28a--- /dev/null+++ b/products/product_analytics/turbo.json@@ -0,0 +1,19 @@+{+ "extends": ["//"],+ "tasks": {+ "backend:contract-check": {+ "inputs": [+ "backend/facade/**",+ "backend/presentation/**",+ "!backend/presentation/test/**",+ "backend/routes.py",+ "backend/models/**",+ "backend/migrations/**",+ "backend/hogql_queries/**",+ "!backend/hogql_queries/*/test/**"+ ],+ "outputs": [],+ "cache": true+ }+ }+}diff --git a/pyproject.toml b/pyproject.tomlindex 849ae5ad39fa..a1af16b446af 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -527,6 +527,13 @@ ignore_imports = ["products.**.backend.presentation.** -> products.**.backend.facade.**","products.**.backend.presentation.** -> products.**.backend.presentation.**",# TODO: existing violations — fix by routing through facade+ "products.alerts.backend.presentation.views.alert -> products.alerts.backend.destination_configs",+ "products.alerts.backend.presentation.views.alert -> products.alerts.backend.destinations",+ "products.alerts.backend.presentation.views.alert -> products.alerts.backend.evaluation.contract",+ "products.alerts.backend.presentation.views.alert -> products.alerts.backend.evaluation.detector",+ "products.alerts.backend.presentation.views.alert -> products.alerts.backend.evaluation.validation",+ "products.alerts.backend.presentation.views.alert -> products.alerts.backend.insight_alert_state_machine",+ "products.alerts.backend.presentation.views.alert -> products.alerts.backend.models.alert","products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.logic","products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.models","products.mcp_analytics.backend.presentation.serializers -> products.mcp_analytics.backend.models",@@ -620,26 +627,6 @@ ignore_imports = ["products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_state","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.client","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.sql_v2",- # TODO: product_analytics presentation wave — newly surfaced debt from the backend/api/ →- # backend/presentation/ rename (same situation as experiments below), not new coupling. The- # insight viewset renders dashboard tiles, alert state, cohort filters and annotation context- # in-process; these drain as those products expose facades (or the rendering moves behind- # product_analytics' own facade). backend:contract-check stays off until this list is empty.- "products.product_analytics.backend.presentation.insight -> products.alerts.backend.api.alert",- "products.product_analytics.backend.presentation.insight -> products.alerts.backend.models.alert",- "products.product_analytics.backend.presentation.insight -> products.cohorts.backend.models.cohort",- "products.product_analytics.backend.presentation.insight -> products.dashboards.backend.access",- "products.product_analytics.backend.presentation.insight -> products.dashboards.backend.models.dashboard",- "products.product_analytics.backend.presentation.insight -> products.dashboards.backend.models.dashboard_tile",- "products.product_analytics.backend.presentation.insight_ee -> products.dashboards.backend.models.dashboard",- "products.product_analytics.backend.presentation.insight_suggestions -> products.annotations.backend.api.annotation_context",- "products.product_analytics.backend.presentation.test.test_insight -> products.alerts.backend.models.alert",- "products.product_analytics.backend.presentation.test.test_insight -> products.cohorts.backend.models.cohort",- "products.product_analytics.backend.presentation.test.test_insight -> products.dashboards.backend.access",- "products.product_analytics.backend.presentation.test.test_insight -> products.dashboards.backend.models.dashboard",- "products.product_analytics.backend.presentation.test.test_insight -> products.dashboards.backend.models.dashboard_tile",- "products.product_analytics.backend.presentation.test.test_deprecated_dashboards_field -> products.dashboards.backend.models.dashboard",- "products.product_analytics.backend.presentation.test.test_deprecated_dashboards_field -> products.dashboards.backend.models.dashboard_tile",# TODO: experiments presentation wave — these were invisible to import-linter until# backend/presentation/ got its package marker, so they are newly surfaced debt, not new# coupling. experiments is not isolated, so nothing was being skipped on their account.@@ -697,7 +684,6 @@ ignore_imports = [# TODO: views still registered from backend/api/ — move them into presentation/ and drop the line"products.actions.backend.routes -> products.actions.backend.api.action","products.ai_observability.backend.routes -> products.ai_observability.backend.api",- "products.alerts.backend.routes -> products.alerts.backend.api.alert","products.annotations.backend.routes -> products.annotations.backend.api.annotation","products.approvals.backend.routes -> products.approvals.backend.api","products.batch_exports.backend.routes -> products.batch_exports.backend.api.batch_export",@@ -734,9 +720,6 @@ ignore_imports = ["products.messaging.backend.routes -> products.messaging.backend.api.message_suppression","products.messaging.backend.routes -> products.messaging.backend.api.message_templates","products.posthog_ai.backend.routes -> products.posthog_ai.backend.api",- # product_analytics registers the alerts viewset under insights; that moves with alerts'- # own routes.py and presentation/ (cross-product ownership is tach's concern, not this one)- "products.product_analytics.backend.routes -> products.alerts.backend.api.alert","products.product_tours.backend.routes -> products.product_tours.backend.api","products.pulse.backend.routes -> products.pulse.backend.api.brief","products.reminders.backend.routes -> products.reminders.backend.api.reminder",diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex 672e318b4013..b311a61dd8a0 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -506,6 +506,13 @@ CARVE_OUTS: frozenset[tuple[str, str]] = frozenset(# products/architecture.md § Wiring couplings.MODEL_CROSSINGS: frozenset[tuple[str, str]] = frozenset({+ ("alerts", "AlertConfiguration"),+ ("alerts", "AlertSubscription"),+ ("alerts", "Threshold"),+ ("cohorts", "Cohort"),+ ("dashboards", "Dashboard"),+ ("dashboards", "DashboardTile"),+ ("dashboards", "Text"),("product_analytics", "Insight"),("product_analytics", "InsightVariable"),("product_analytics", "InsightViewed"),