: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): add facade and watched-models allowance (#85148)
Thomas Obermüller24bee46ad697
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.pyindex 6e3774356d9e..a5cc39bff843 100644--- a/posthog/test/test_utils.py+++ b/posthog/test/test_utils.py@@ -1104,7 +1104,7 @@ class TestSharingOverrideProtection(TestCase):])@patch(- "products.product_analytics.backend.api.insight_variable.map_stale_to_latest",+ "products.product_analytics.backend.facade.api.map_stale_to_latest",side_effect=lambda variables, _: variables,)def test_variables_override_blocked_for_sharing_authenticators(self, auth_type, _mock):@@ -1125,7 +1125,7 @@ class TestSharingOverrideProtection(TestCase):assert result == {"var1": {"value": "safe"}}@patch(- "products.product_analytics.backend.api.insight_variable.map_stale_to_latest",+ "products.product_analytics.backend.facade.api.map_stale_to_latest",side_effect=lambda variables, _: variables,)def test_variables_override_allowed_for_normal_auth(self, _mock):@@ -1181,7 +1181,7 @@ class TestSharingOverrideProtection(TestCase):assert result == {"date_from": "-30d"}@patch(- "products.product_analytics.backend.api.insight_variable.map_stale_to_latest",+ "products.product_analytics.backend.facade.api.map_stale_to_latest",side_effect=lambda variables, _: variables,)def test_variables_override_blocked_for_shared_context_without_authenticator(self, _mock):diff --git a/posthog/utils.py b/posthog/utils.pyindex e77d3fb24a0c..937f9578b23d 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -1809,7 +1809,7 @@ def variables_override_requested_by_client() -> Optional[dict[str, dict]]:from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication- from products.product_analytics.backend.api.insight_variable import map_stale_to_latest+ from products.product_analytics.backend.facade.api import map_stale_to_latestdashboard_variables = (dashboard and dashboard.variables) or {}raw_override = request.query_params.get("variables_override") if request else Nonediff --git a/products/architecture.md b/products/architecture.mdindex 9786f0245679..2ba23e38102b 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -105,7 +105,12 @@ A model cannot be narrowed: whatever interface it presents, the object still carTwo core registries are keyed by model class identity and are explicit, sanctioned exceptions: the team-extension registry and the file-system unfiled registry (`FileSystemSyncMixin`).There 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 consumes at query time and cannot yet stop consuming (today only `warehouse_sources`, whose warehouse table/schema/source models core HogQL reads to build queryable tables).+**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.+`warehouse_sources`: core HogQL reads its warehouse table/schema/source models to build queryable tables.+`product_analytics`: `Insight` and `InsightVariable`.+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.+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.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/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex c8dab626b45d..177494926487 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -156,7 +156,7 @@ from products.product_analytics.backend.api.insight import (InsightBasicSerializer,InsightSerializer,InsightViewSet,- _get_insight_type,+ get_insight_type,)from products.product_analytics.backend.models.insight import Insightfrom products.product_analytics.backend.models.insight_variable import InsightVariable@@ -1329,7 +1329,7 @@ def _report_dashboard_tile_removed(request: Request | None = None,) -> None:tile_type, widget_type = _tile_type_and_widget_type(tile)- insight_type = _get_insight_type(tile.insight) if tile.insight is not None else None+ insight_type = get_insight_type(tile.insight) if tile.insight is not None else Noneproperties: dict[str, Any] = {"tile_type": tile_type,"insight_type": insight_type,diff --git a/products/exports/backend/tasks/image_exporter.py b/products/exports/backend/tasks/image_exporter.pyindex e1ecfad21e9e..c1226607f593 100644--- a/products/exports/backend/tasks/image_exporter.py+++ b/products/exports/backend/tasks/image_exporter.py@@ -41,7 +41,7 @@ from products.exports.backend.tasks.failure_handler import (InvalidExportContext,classify_failure_type,)-from products.product_analytics.backend.api.insight_variable import map_stale_to_latest+from products.product_analytics.backend.facade.api import map_stale_to_latestfrom products.product_analytics.backend.models.insight_variable import InsightVariablelogger = structlog.get_logger(__name__)diff --git a/products/exports/backend/tasks/test/test_image_exporter.py b/products/exports/backend/tasks/test/test_image_exporter.pyindex 0ba37577481f..cfda8b336934 100644--- a/products/exports/backend/tasks/test/test_image_exporter.py+++ b/products/exports/backend/tasks/test/test_image_exporter.py@@ -35,7 +35,7 @@ from products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.tasks import image_exporterfrom products.exports.backend.tasks.failure_handler import BrowserlessUnavailable, InvalidExportContext-from products.product_analytics.backend.api.insight_variable import map_stale_to_latest+from products.product_analytics.backend.facade.api import map_stale_to_latestfrom products.product_analytics.backend.models.insight import Insightfrom products.product_analytics.backend.models.insight_variable import InsightVariablediff --git a/products/exports/backend/temporal/subscriptions/llm_change_summary.py b/products/exports/backend/temporal/subscriptions/llm_change_summary.pyindex 50b10154ea7f..37f3e6f561f6 100644--- a/products/exports/backend/temporal/subscriptions/llm_change_summary.py+++ b/products/exports/backend/temporal/subscriptions/llm_change_summary.py@@ -28,7 +28,7 @@ from posthog.security.llm_prompt_sanitization import ()from posthog.utils import get_instance_region-from products.product_analytics.backend.api.insight_suggestions import get_query_specific_instructions+from products.product_analytics.backend.facade.api import get_query_specific_instructionslogger = structlog.get_logger(__name__)diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex 9b8837b31e82..2642b48a1b61 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -156,7 +156,7 @@ from products.product_analytics.backend.api.insight_metadata import (generate_insight_metadata,)from products.product_analytics.backend.api.insight_suggestions import get_insight_analysis, get_insight_suggestions-from products.product_analytics.backend.api.insight_variable import map_stale_to_latest+from products.product_analytics.backend.logic import map_stale_to_latestfrom products.product_analytics.backend.models.insight import Insight, InsightViewedfrom products.product_analytics.backend.models.insight_variable import InsightVariable@@ -175,7 +175,7 @@ EXPORT_QUERY_CACHE_MISS = Counter()-def _get_insight_type(insight: Insight) -> str:+def get_insight_type(insight: Insight) -> str:"""Return a normalized lowercase insight type string for analytics (used by the dashboard tile event)."""if insight.query:source = insight.query.get("source", insight.query)@@ -819,7 +819,7 @@ class InsightSerializer(InsightBasicSerializer):"dashboard tile added",{"tile_type": "insight",- "insight_type": _get_insight_type(insight),+ "insight_type": get_insight_type(insight),"dashboard_id": dashboard.id,},team=insight.team,@@ -1021,7 +1021,7 @@ class InsightSerializer(InsightBasicSerializer):"dashboard tile added",{"tile_type": "insight",- "insight_type": _get_insight_type(instance),+ "insight_type": get_insight_type(instance),"dashboard_id": dashboard.id,},team=instance.team,@@ -1052,7 +1052,7 @@ class InsightSerializer(InsightBasicSerializer):"dashboard tile removed",{"tile_type": "insight",- "insight_type": _get_insight_type(instance),+ "insight_type": get_insight_type(instance),"dashboard_id": tile.dashboard_id,},team=instance.team,diff --git a/ee/clickhouse/views/insights.py b/products/product_analytics/backend/api/insight_ee.pysimilarity index 88%rename from ee/clickhouse/views/insights.pyrename to products/product_analytics/backend/api/insight_ee.pyindex ed5a837b1189..fad0b5fdf77d 100644--- a/ee/clickhouse/views/insights.py+++ b/products/product_analytics/backend/api/insight_ee.py@@ -1,3 +1,5 @@+"""Insights viewset variant enforcing dashboard edit permissions, selected by routes.py on EE_AVAILABLE installs."""+from rest_framework.permissions import SAFE_METHODS, BasePermissionfrom rest_framework.request import Requestdiff --git a/products/product_analytics/backend/api/insight_suggestions.py b/products/product_analytics/backend/api/insight_suggestions.pyindex 4ccf30bdc40c..eec88e598b91 100644--- a/products/product_analytics/backend/api/insight_suggestions.py+++ b/products/product_analytics/backend/api/insight_suggestions.py@@ -23,6 +23,7 @@ from posthog.models import Teamfrom products.annotations.backend.api.annotation_context import build_annotations_block, resolve_query_date_rangefrom products.product_analytics.backend.api.ai_billing import billable_ai_properties+from products.product_analytics.backend.logic import get_query_specific_instructionslogger = structlog.get_logger(__name__)@@ -162,32 +163,6 @@ def summarize_insight_result(result: Any) -> Any:return result-def get_query_specific_instructions(kind: str) -> str:- if kind == "TrendsQuery":- return (- "Focus on identifying significant changes in volume, growth trends, and seasonality. "- "Compare the current period to the start. Identify which breakdown segment (if any) is driving the trend."- )- elif kind == "FunnelsQuery":- return (- "Focus on conversion rates between steps. When there are three or more steps, name the step-to-step "- "transition with the largest loss. When there are only two steps (one transition), describe the single "- "drop-off directly without superlatives like 'the biggest' or 'the main bottleneck' — there is nothing "- "to compare it against. Compare conversion across breakdown segments if available."- )- elif kind == "RetentionQuery":- return (- "Focus on the retention curve shape. Identify when the drop-off stabilizes. "- "Compare retention rates between different cohorts or breakdown segments."- )- elif kind == "StickinessQuery":- return "Focus on how frequently users engage. Identify if there is a core group of power users."- elif kind == "LifecycleQuery":- return "Focus on the balance between new, returning, resurrecting, and dormant users. Identify which group is dominating the total count."-- return "Focus on the most significant patterns and anomalies in the data."--def get_insight_analysis(query: InsightVizNode,team: Team,diff --git a/products/product_analytics/backend/api/insight_variable.py b/products/product_analytics/backend/api/insight_variable.pyindex f405156dc10b..8941a76e91a5 100644--- a/products/product_analytics/backend/api/insight_variable.py+++ b/products/product_analytics/backend/api/insight_variable.py@@ -200,28 +200,3 @@ class InsightVariableViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):SharingAccessTokenAuthentication | SharingPasswordProtectedAuthentication,):raise PermissionDenied("Insight variables cannot be accessed via sharing authentication")---def map_stale_to_latest(stale_variables: dict, latest_variables: list[InsightVariable]) -> dict:- # Keep the variables in an insight up to date based on variable code names that exist- current_variables = stale_variables- insight_variables = latest_variables- final_variables = {}-- # Create a lookup for insight variables by code_name for quick access- insight_variables_by_code_name = {var.code_name: var for var in insight_variables}-- # For each variable in current_variables, update with data from insight_variables if code_name matches- for _, v in current_variables.items():- code_name = v.get("code_name")- if code_name in insight_variables_by_code_name:- # Update the variable with corresponding data from insight_variables- matched_var = insight_variables_by_code_name[code_name]- # Add attributes from matched_var that can be serialized to JSON- final_variables[str(matched_var.id)] = {- **v,- "code_name": matched_var.code_name,- "variableId": str(matched_var.id),- }-- return final_variablesdiff --git a/products/product_analytics/backend/api/test/test_insight_variable.py b/products/product_analytics/backend/api/test/test_insight_variable.pyindex 7c69a3c111f8..61dc6a8ab6da 100644--- a/products/product_analytics/backend/api/test/test_insight_variable.py+++ b/products/product_analytics/backend/api/test/test_insight_variable.py@@ -9,11 +9,8 @@ from rest_framework.exceptions import PermissionDeniedfrom posthog.auth import SharingAccessTokenAuthentication-from products.product_analytics.backend.api.insight_variable import (- InsightVariableSerializer,- InsightVariableViewSet,- map_stale_to_latest,-)+from products.product_analytics.backend.api.insight_variable import InsightVariableSerializer, InsightVariableViewSet+from products.product_analytics.backend.logic import map_stale_to_latestfrom products.product_analytics.backend.models.insight_variable import InsightVariablediff --git a/products/product_analytics/backend/facade/__init__.py b/products/product_analytics/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.pynew file mode 100644index 000000000000..7b0dd0d06225--- /dev/null+++ b/products/product_analytics/backend/facade/api.py@@ -0,0 +1,20 @@+"""+Facade for product_analytics.++The public entry point core and other products import product-analytics+functionality from; ``facade.models`` carries the sanctioned model-class+crossings. Functions here stay thin and delegate to ``backend.logic``.+"""++from products.product_analytics.backend import logic+from products.product_analytics.backend.models.insight_variable import InsightVariable+++def map_stale_to_latest(stale_variables: dict, latest_variables: list[InsightVariable]) -> dict:+ """Refresh an insight's stored variables against the team's latest ``InsightVariable`` rows."""+ return logic.map_stale_to_latest(stale_variables, latest_variables)+++def get_query_specific_instructions(kind: str) -> str:+ """Analysis guidance for a query kind, used by LLM insight and subscription summaries."""+ return logic.get_query_specific_instructions(kind)diff --git a/products/product_analytics/backend/facade/models.py b/products/product_analytics/backend/facade/models.pynew file mode 100644index 000000000000..95c9eabba26e--- /dev/null+++ b/products/product_analytics/backend/facade/models.py@@ -0,0 +1,17 @@+"""+Model-class wiring for product_analytics.++Re-exports the ``Insight`` and ``InsightVariable`` model classes for+cross-product consumers under the watched-models allowance (MODEL_CROSSINGS):+dashboards, alerts, exports, sharing and other areas hold ForeignKeys or M2Ms+into ``Insight`` and need ORM semantics (relation traversal, cascade deletes,+queryset-typed access-control filtering) that a frozen contract cannot+express. The whole model surface (``backend/models/`` and+``backend/migrations/``) stays in the contract-check inputs, so a change to+these classes still runs the full suite.+"""++from products.product_analytics.backend.models.insight import Insight+from products.product_analytics.backend.models.insight_variable import InsightVariable++__all__ = ["Insight", "InsightVariable"]diff --git a/products/product_analytics/backend/logic.py b/products/product_analytics/backend/logic.pynew file mode 100644index 000000000000..9376f8407f8a--- /dev/null+++ b/products/product_analytics/backend/logic.py@@ -0,0 +1,52 @@+from products.product_analytics.backend.models.insight_variable import InsightVariable+++def map_stale_to_latest(stale_variables: dict, latest_variables: list[InsightVariable]) -> dict:+ # Keep the variables in an insight up to date based on variable code names that exist+ current_variables = stale_variables+ insight_variables = latest_variables+ final_variables = {}++ # Create a lookup for insight variables by code_name for quick access+ insight_variables_by_code_name = {var.code_name: var for var in insight_variables}++ # For each variable in current_variables, update with data from insight_variables if code_name matches+ for _, v in current_variables.items():+ code_name = v.get("code_name")+ if code_name in insight_variables_by_code_name:+ # Update the variable with corresponding data from insight_variables+ matched_var = insight_variables_by_code_name[code_name]+ # Add attributes from matched_var that can be serialized to JSON+ final_variables[str(matched_var.id)] = {+ **v,+ "code_name": matched_var.code_name,+ "variableId": str(matched_var.id),+ }++ return final_variables+++def get_query_specific_instructions(kind: str) -> str:+ if kind == "TrendsQuery":+ return (+ "Focus on identifying significant changes in volume, growth trends, and seasonality. "+ "Compare the current period to the start. Identify which breakdown segment (if any) is driving the trend."+ )+ elif kind == "FunnelsQuery":+ return (+ "Focus on conversion rates between steps. When there are three or more steps, name the step-to-step "+ "transition with the largest loss. When there are only two steps (one transition), describe the single "+ "drop-off directly without superlatives like 'the biggest' or 'the main bottleneck' — there is nothing "+ "to compare it against. Compare conversion across breakdown segments if available."+ )+ elif kind == "RetentionQuery":+ return (+ "Focus on the retention curve shape. Identify when the drop-off stabilizes. "+ "Compare retention rates between different cohorts or breakdown segments."+ )+ elif kind == "StickinessQuery":+ return "Focus on how frequently users engage. Identify if there is a core group of power users."+ elif kind == "LifecycleQuery":+ return "Focus on the balance between new, returning, resurrecting, and dormant users. Identify which group is dominating the total count."++ return "Focus on the most significant patterns and anomalies in the data."diff --git a/products/product_analytics/backend/routes.py b/products/product_analytics/backend/routes.pyindex b36bcbd026c0..265de184d93f 100644--- a/products/product_analytics/backend/routes.py+++ b/products/product_analytics/backend/routes.py@@ -4,6 +4,7 @@ from posthog.settings import EE_AVAILABLEimport products.alerts.backend.api.alert as alertfrom products.product_analytics.backend.api.insight import InsightViewSet+from products.product_analytics.backend.api.insight_ee import EnterpriseInsightsViewSetfrom products.product_analytics.backend.api.insight_variable import InsightVariableViewSetfrom products.product_analytics.backend.api.paths_v2 import PathsV2ViewSet@@ -12,13 +13,7 @@ def register_routes(routers: RouterRegistry) -> None:# EE installs override the insights viewset with EnterpriseInsightsViewSet.# The non-EE InsightViewSet is the fallback. Either way, the route name and# nested sub-routes (sharing, thresholds) stay identical.- insights_viewset: type[InsightViewSet]- if EE_AVAILABLE:- from ee.clickhouse.views.insights import EnterpriseInsightsViewSet-- insights_viewset = EnterpriseInsightsViewSet- else:- insights_viewset = InsightViewSet+ insights_viewset: type[InsightViewSet] = EnterpriseInsightsViewSet if EE_AVAILABLE else InsightViewSetinsights_router = routers.projects.register(r"insights", insights_viewset, "project_insights", ["team_id"])diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex 083ddeb6dfd2..5de3284dadb6 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -480,10 +480,12 @@ CARVE_OUTS: frozenset[tuple[str, str]] = frozenset(## Keyed per class, not per product, so a product on the list can't quietly grow a new crossing: an# unlisted class is a leak again, and sanctioning it costs a doctrine amendment. The list only-# shrinks. The bar for an entry, and why these five are load-bearing, live in+# shrinks. The bar for an entry, and why these are load-bearing, live in# products/architecture.md § Wiring couplings.MODEL_CROSSINGS: frozenset[tuple[str, str]] = frozenset({+ ("product_analytics", "Insight"),+ ("product_analytics", "InsightVariable"),("warehouse_sources", "DataWarehouseCredential"),("warehouse_sources", "DataWarehouseTable"),("warehouse_sources", "ExternalDataJob"),