: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(data-modeling): extract enable-materialization into the facade (#109206)
Thiago Salvatore056762243c88
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 29c7e5666f65..5ba2e2b3eeeb 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -47,6 +47,13 @@ _LAZY = {"all_saved_query_names": "logic.saved_query_reads","allowed_saved_query_ids": "logic.saved_query_reads","backing_table_ids_by_saved_query": "logic.saved_query_reads",+ "reachable_node_ids": "logic.saved_query_reads",+ "saved_query_node_ids": "logic.saved_query_reads",+ "upstream_table_refs": "logic.saved_query_reads",+ "MaterializationFailedError": "facade.contracts",+ "MaterializationForbiddenError": "facade.contracts",+ "MaterializationRefusedError": "facade.contracts",+ "enable_saved_query_materialization": "logic.saved_query_materialization","saved_query_materialized_at": "logic.saved_query_freshness","latest_saved_query_materialization_job": "logic.saved_query_freshness","is_materialization_fresh": "logic.saved_query_freshness",diff --git a/products/data_modeling/backend/facade/contracts.py b/products/data_modeling/backend/facade/contracts.pyindex d5708b6f5f5c..93162b8122ec 100644--- a/products/data_modeling/backend/facade/contracts.py+++ b/products/data_modeling/backend/facade/contracts.py@@ -14,6 +14,8 @@ from datetime import datetimefrom pydantic.dataclasses import dataclass+from posthog.dataclasses import frozen+@dataclass(frozen=True)class DataModelingJob:@@ -54,3 +56,21 @@ class Dependent:saved_query_id: str | None = Nonecreated_by_id: int | None = Nonelineage_node_id: str | None = None+++@frozen+class UpstreamTableRef:+ name: str+ warehouse_table_id: str | None = None+++class MaterializationRefusedError(Exception):+ pass+++class MaterializationForbiddenError(Exception):+ pass+++class MaterializationFailedError(Exception):+ passdiff --git a/products/data_modeling/backend/logic/saved_query_materialization.py b/products/data_modeling/backend/logic/saved_query_materialization.pynew file mode 100644index 000000000000..1303e93d4f7e--- /dev/null+++ b/products/data_modeling/backend/logic/saved_query_materialization.py@@ -0,0 +1,184 @@+from collections.abc import Callable, Mapping+from datetime import timedelta+from uuid import UUID++import structlog++from posthog.exceptions_capture import capture_exception+from posthog.models import User+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.rbac.query_access import assert_user_can_read_query++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.data_modeling.backend.facade.contracts import (+ MaterializationFailedError,+ MaterializationForbiddenError,+ MaterializationRefusedError,+)+from products.data_modeling.backend.logic.freshness import UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError+from products.data_modeling.backend.logic.node_frequency import SavedQueryFrequencyBounds, saved_query_target_bounds+from products.data_modeling.backend.logic.node_materialization import SavedQueryNotFoundError+from products.data_modeling.backend.logic.saved_query_dag_sync import update_node_type+from products.data_modeling.backend.logic.schedule_reconcile import check_saved_query_frequency_target+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.node import NodeType++logger = structlog.get_logger(__name__)++VisibleBlockerNames = Callable[[SavedQueryFrequencyBounds], Mapping[str, str]]++MANAGED_VIEWSET_REFUSAL = "Cannot materialize a query from a managed viewset."+EDIT_ACCESS_REFUSAL = "You need edit access to this view to materialize it."+LINEAGE_CHANGED_REFUSAL = "This view's lineage changed while we were setting it up. Reopen it and pick a cadence again."+MATERIALIZATION_FAILED_MESSAGE = "Materialization failed. Please try again or contact support."+MATERIALIZATION_ENABLED_ACTIVITY = "materialization_enabled"+SAVED_QUERY_ACTIVITY_SCOPE = "DataWarehouseSavedQuery"+++def enable_saved_query_materialization(+ team_id: int,+ saved_query_id: UUID | str,+ *,+ user: User,+ sync_frequency_interval: timedelta | None,+ visible_blocker_names: VisibleBlockerNames,+ was_impersonated: bool,+) -> None:+ """Materialize a saved query at the given cadence and start its first run."""+ saved_query = (+ DataWarehouseSavedQuery.objects.filter(team_id=team_id, id=saved_query_id).exclude(deleted=True).first()+ )+ if saved_query is None:+ raise SavedQueryNotFoundError(f"Saved query {saved_query_id} not found for team {team_id}")+ _enable_materialization(+ saved_query,+ user=user,+ sync_frequency_interval=sync_frequency_interval,+ visible_blocker_names=visible_blocker_names,+ was_impersonated=was_impersonated,+ )+++def _enable_materialization(+ saved_query: DataWarehouseSavedQuery,+ *,+ user: User,+ sync_frequency_interval: timedelta | None,+ visible_blocker_names: VisibleBlockerNames,+ was_impersonated: bool,+) -> None:+ if saved_query.managed_viewset_id is not None:+ raise MaterializationRefusedError(MANAGED_VIEWSET_REFUSAL)++ _require_edit_access(saved_query, user)+ assert_user_can_read_query(saved_query.query, saved_query.team_id, user)++ if sync_frequency_interval is not None:+ # Ask before writing, so the ordinary refusal never has to be undone below. Names only+ # what this caller may read, matching the bounds payload — otherwise one rejected+ # materialize reads back a node they were never shown.+ _refuse_a_cadence_the_lineage_forbids(saved_query, sync_frequency_interval, visible_blocker_names)++ previous_interval = saved_query.sync_frequency_interval+ previously_materialized = saved_query.is_materialized+ _save_materialization(saved_query, is_materialized=True, sync_frequency_interval=sync_frequency_interval)++ # Enable materialization - this handles model path setup and schedule creation+ # If this fails, it will set is_materialized = False+ try:+ saved_query.schedule_materialization(trigger_immediate_run=True, triggered_by_id=user.pk)+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as error:+ # The check above already refused every cadence the lineage forbids, so reaching here+ # means the lineage moved mid-request. Say so plainly rather than forwarding a message+ # built from unredacted names. `schedule_materialization` re-raises these without+ # applying its disable-on-failure contract, and this action is not inside an atomic+ # block, so undo the enable by hand: otherwise the 400 leaves is_materialized=True+ # behind and the UI reads the rejection as a success.+ _save_materialization(+ saved_query, is_materialized=previously_materialized, sync_frequency_interval=previous_interval+ )+ raise MaterializationRefusedError(LINEAGE_CHANGED_REFUSAL) from error++ # Refresh from DB to check if schedule_materialization set is_materialized = False on failure+ saved_query.refresh_from_db()+ if saved_query.is_materialized is False:+ raise MaterializationFailedError(MATERIALIZATION_FAILED_MESSAGE)++ _mark_nodes_materialized(saved_query)+ _log_materialization_enabled(+ saved_query,+ user=user,+ was_impersonated=was_impersonated,+ previous_interval=previous_interval,+ sync_frequency_interval=sync_frequency_interval,+ )+++def _require_edit_access(saved_query: DataWarehouseSavedQuery, user: User) -> None:+ access = UserAccessControl(user=user, team=saved_query.team)+ if not access.check_access_level_for_object(saved_query, "editor"):+ raise MaterializationForbiddenError(EDIT_ACCESS_REFUSAL)+++def _refuse_a_cadence_the_lineage_forbids(+ saved_query: DataWarehouseSavedQuery,+ sync_frequency_interval: timedelta,+ visible_blocker_names: VisibleBlockerNames,+) -> None:+ bounds = saved_query_target_bounds(saved_query.team_id, saved_query.pk)+ try:+ check_saved_query_frequency_target(+ saved_query,+ sync_frequency_interval,+ visible_names=visible_blocker_names(bounds) if bounds else {},+ )+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as error:+ raise MaterializationRefusedError(str(error)) from error+++def _save_materialization(+ saved_query: DataWarehouseSavedQuery, *, is_materialized: bool | None, sync_frequency_interval: timedelta | None+) -> None:+ saved_query.sync_frequency_interval = sync_frequency_interval+ saved_query.is_materialized = is_materialized+ saved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])+++def _mark_nodes_materialized(saved_query: DataWarehouseSavedQuery) -> None:+ # set data modeling node type to matview+ try:+ update_node_type(saved_query, NodeType.MAT_VIEW)+ except Exception as e:+ capture_exception(e)+ logger.exception("Failed to update node type to matview", saved_query_name=saved_query.name)+++def _log_materialization_enabled(+ saved_query: DataWarehouseSavedQuery,+ *,+ user: User,+ was_impersonated: bool,+ previous_interval: timedelta | None,+ sync_frequency_interval: timedelta | None,+) -> None:+ log_activity(+ organization_id=saved_query.team.organization_id,+ team_id=saved_query.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=saved_query.id,+ scope=SAVED_QUERY_ACTIVITY_SCOPE,+ activity=MATERIALIZATION_ENABLED_ACTIVITY,+ detail=Detail(+ name=saved_query.name,+ changes=[+ Change(+ field="sync_frequency_interval",+ action="changed",+ type=SAVED_QUERY_ACTIVITY_SCOPE,+ before=str(previous_interval) if previous_interval else None,+ after=str(sync_frequency_interval),+ ),+ ],+ ),+ )diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.pyindex 917a71d4172a..995a78b31570 100644--- a/products/data_modeling/backend/logic/saved_query_reads.py+++ b/products/data_modeling/backend/logic/saved_query_reads.py@@ -5,14 +5,17 @@ from typing import TYPE_CHECKINGfrom uuid import UUIDfrom django.conf import settings+from django.db.models import Q-from ..facade.contracts import SavedQuerySummary+from ..facade.contracts import SavedQuerySummary, UpstreamTableReffrom ..models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom ..models.edge import Edgefrom ..models.node import Node, NodeTypefrom .saved_query_freshness import saved_query_materialized_atPOSTHOG_TABLE_ORIGIN = "posthog"+PROXY_SAVED_QUERY_ID_PROPERTY = "saved_query_id"+WAREHOUSE_TABLE_ID_PROPERTY = "warehouse_table_id"if TYPE_CHECKING:from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl@@ -245,3 +248,82 @@ def dependent_saved_query_ids(team_id: int, saved_query_ids: Collection[UUID]) -for source_id, target_id in edges:dependents[source_id].add(target_id)return {saved_query_id: frozenset(ids) for saved_query_id, ids in dependents.items()}+++def saved_query_node_ids(team_id: int, saved_query_id: UUID | str) -> set[str]:+ """The DAG nodes that stand for this saved query, cross-DAG proxy table nodes included."""+ return _node_ids_standing_for(team_id, {str(saved_query_id)})+++def _node_ids_standing_for(team_id: int, saved_query_ids: set[str]) -> set[str]:+ return {+ str(node_id)+ for node_id in Node.objects.filter(team_id=team_id)+ .filter(Q(saved_query_id__in=saved_query_ids) | Q(properties__saved_query_id__in=saved_query_ids))+ .values_list("id", flat=True)+ }+++def reachable_node_ids(team_id: int, start_node_ids: set[str], *, upstream: bool, max_depth: int | None) -> set[str]:+ """Node ids reachable from `start_node_ids` within `max_depth` hops, the start nodes excluded.++ One query per hop, each reading the frontier's edges off the `Edge` foreign-key indexes, so+ the work is bounded by the cone that is reached rather than by every edge the team owns.+ Upstream follows edges into the frontier back to their sources; downstream follows edges+ out of it to their targets.+ """+ edges = Edge.objects.filter(team_id=team_id)++ reached: set[str] = set()+ frontier = set(start_node_ids)+ depth = 0+ while frontier and (max_depth is None or depth < max_depth):+ if upstream:+ neighbor_ids = edges.filter(target_id__in=frontier).values_list("source_id", flat=True)+ else:+ neighbor_ids = edges.filter(source_id__in=frontier).values_list("target_id", flat=True)+ frontier = {str(neighbor_id) for neighbor_id in neighbor_ids} - reached - start_node_ids+ reached |= frontier+ depth += 1+ return reached+++def upstream_table_refs(team_id: int, saved_query_id: UUID | str) -> frozenset[UpstreamTableRef]:+ """The tables this saved query reads from, directly or through other views in any DAG."""+ return frozenset(+ UpstreamTableRef(name=name, warehouse_table_id=_warehouse_table_id(properties))+ for name, properties in _upstream_table_nodes(team_id, str(saved_query_id))+ if _proxied_saved_query_id(properties) is None+ )+++def _upstream_table_nodes(team_id: int, saved_query_id: str) -> list[tuple[str, dict[str, object]]]:+ tables_by_node_id: dict[str, tuple[str, dict[str, object]]] = {}+ walked_saved_query_ids: set[str] = set()+ pending_saved_query_ids = {saved_query_id}+ while pending_saved_query_ids:+ walked_saved_query_ids |= pending_saved_query_ids+ start_node_ids = _node_ids_standing_for(team_id, pending_saved_query_ids)+ reached = reachable_node_ids(team_id, start_node_ids, upstream=True, max_depth=None)+ for node_id, name, properties in Node.objects.filter(+ team_id=team_id, id__in=reached, type=NodeType.TABLE+ ).values_list("id", "name", "properties"):+ tables_by_node_id[str(node_id)] = (name, properties or {})+ pending_saved_query_ids = _proxied_saved_query_ids(tables_by_node_id.values()) - walked_saved_query_ids+ return list(tables_by_node_id.values())+++def _proxied_saved_query_ids(table_nodes: Iterable[tuple[str, dict[str, object]]]) -> set[str]:+ return {+ proxied_id for _, properties in table_nodes if (proxied_id := _proxied_saved_query_id(properties)) is not None+ }+++def _proxied_saved_query_id(properties: dict[str, object]) -> str | None:+ proxied_id = properties.get(PROXY_SAVED_QUERY_ID_PROPERTY)+ return str(proxied_id) if proxied_id else None+++def _warehouse_table_id(properties: dict[str, object]) -> str | None:+ warehouse_table_id = properties.get(WAREHOUSE_TABLE_ID_PROPERTY)+ return str(warehouse_table_id) if warehouse_table_id else Nonediff --git a/products/data_modeling/backend/test/test_saved_query_materialization.py b/products/data_modeling/backend/test/test_saved_query_materialization.pynew file mode 100644index 000000000000..dd1ccce70623--- /dev/null+++ b/products/data_modeling/backend/test/test_saved_query_materialization.py@@ -0,0 +1,144 @@+from datetime import timedelta++from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, patch++from posthog.constants import AvailableFeature+from posthog.models import ActivityLog, User+from posthog.models.organization import OrganizationMembership++from products.access_control.backend.models.access_control import AccessControl+from products.data_modeling.backend.facade import api+from products.data_modeling.backend.logic.freshness import UnsatisfiableFrequencyError+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.edge import Edge+from products.data_modeling.backend.models.node import Node, NodeType+from products.data_modeling.backend.test.helpers import warehouse_source_node++GET_V2_DAG_IDS = "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids"+NODE_MATERIALIZATION_SYNC_CONNECT = "products.data_modeling.backend.logic.node_materialization.sync_connect"+++def _name_no_blockers(_bounds: object) -> dict[str, str]:+ return {}+++class TestEnableSavedQueryMaterialization(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.dag = DAG.objects.create(team=self.team, name=f"posthog_{self.team.id}")+ self.saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="event_view",+ query={"kind": "HogQLQuery", "query": "select event as event from events LIMIT 100"},+ created_by=self.user,+ )+ self.node = Node.objects.create(+ team=self.team, dag=self.dag, name="event_view", saved_query=self.saved_query, type=NodeType.VIEW+ )++ def _enable(self, sync_frequency_interval: timedelta, user: User | None = None) -> None:+ api.enable_saved_query_materialization(+ self.team.id,+ self.saved_query.id,+ user=user or self.user,+ sync_frequency_interval=sync_frequency_interval,+ visible_blocker_names=_name_no_blockers,+ was_impersonated=False,+ )++ def test_enabling_retypes_the_node_logs_the_change_and_starts_a_run_for_the_user(self) -> None:+ temporal = AsyncMock()+ with (+ patch(GET_V2_DAG_IDS, return_value={str(self.dag.id)}),+ patch(NODE_MATERIALIZATION_SYNC_CONNECT, return_value=temporal),+ self.captureOnCommitCallbacks(execute=True),+ ):+ self._enable(timedelta(hours=1))++ self.saved_query.refresh_from_db()+ self.node.refresh_from_db()+ activity = ActivityLog.objects.get(item_id=str(self.saved_query.id), activity="materialization_enabled")+ workflow_inputs = temporal.start_workflow.call_args.args[1]+ assert self.saved_query.is_materialized is True+ assert self.node.type == NodeType.MAT_VIEW+ assert activity.user == self.user+ assert activity.detail is not None+ assert activity.detail["changes"][0]["after"] == str(timedelta(hours=1))+ assert workflow_inputs["manually_triggered_by_id"] == self.user.pk++ def test_a_cadence_faster_than_the_source_is_refused_before_anything_is_written(self) -> None:+ source = warehouse_source_node(self.team, self.dag, sync_frequency_interval=timedelta(hours=24))+ Edge.objects.create(team=self.team, dag=self.dag, source=source, target=self.node)++ with (+ patch.object(DataWarehouseSavedQuery, "schedule_materialization") as schedule_materialization,+ self.assertRaises(api.MaterializationRefusedError),+ ):+ self._enable(timedelta(minutes=15))++ self.saved_query.refresh_from_db()+ schedule_materialization.assert_not_called()+ assert self.saved_query.is_materialized is False+ assert self.saved_query.sync_frequency_interval is None++ def test_a_cadence_refused_while_scheduling_restores_the_previous_materialization(self) -> None:+ self.saved_query.is_materialized = True+ self.saved_query.sync_frequency_interval = timedelta(hours=12)+ self.saved_query.save(update_fields=["is_materialized", "sync_frequency_interval"])++ with (+ patch.object(+ DataWarehouseSavedQuery,+ "schedule_materialization",+ side_effect=UnsatisfiableFrequencyError("lineage moved"),+ ),+ self.assertRaises(api.MaterializationRefusedError),+ ):+ self._enable(timedelta(hours=1))++ self.saved_query.refresh_from_db()+ assert self.saved_query.is_materialized is True+ assert self.saved_query.sync_frequency_interval == timedelta(hours=12)++ def test_a_schedule_that_disables_materialization_fails_without_logging_an_enable(self) -> None:+ def disable_materialization(saved_query: DataWarehouseSavedQuery, **_kwargs: object) -> None:+ saved_query.is_materialized = False+ saved_query.save(update_fields=["is_materialized"])++ with (+ patch.object(+ DataWarehouseSavedQuery, "schedule_materialization", autospec=True, side_effect=disable_materialization+ ),+ self.assertRaises(api.MaterializationFailedError),+ ):+ self._enable(timedelta(hours=1))++ self.node.refresh_from_db()+ assert self.node.type == NodeType.VIEW+ assert not ActivityLog.objects.filter(item_id=str(self.saved_query.id)).exists()++ def test_a_user_who_can_only_view_the_saved_query_cannot_materialize_it(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_view",+ resource_id=str(self.saved_query.id),+ access_level="viewer",+ organization_member=OrganizationMembership.objects.get(user=viewer, organization=self.organization),+ )++ with (+ patch.object(DataWarehouseSavedQuery, "schedule_materialization") as schedule_materialization,+ self.assertRaises(api.MaterializationForbiddenError),+ ):+ self._enable(timedelta(hours=1), user=viewer)++ self.saved_query.refresh_from_db()+ schedule_materialization.assert_not_called()+ assert self.saved_query.is_materialized is Falsediff --git a/products/data_modeling/backend/test/test_saved_query_reads.py b/products/data_modeling/backend/test/test_saved_query_reads.pyindex ef341c508e88..2a1541405993 100644--- a/products/data_modeling/backend/test/test_saved_query_reads.py+++ b/products/data_modeling/backend/test/test_saved_query_reads.py@@ -1,3 +1,5 @@+from uuid import uuid4+from posthog.test.base import BaseTestfrom parameterized import parameterized@@ -9,10 +11,13 @@ from posthog.models.organization import OrganizationMembershipfrom products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControlfrom products.access_control.backend.models.access_control import AccessControlfrom products.data_modeling.backend.facade import api+from products.data_modeling.backend.facade.contracts import UpstreamTableRef+from products.data_modeling.backend.logic.saved_query_reads import POSTHOG_TABLE_ORIGINfrom products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.edge import Edgefrom products.data_modeling.backend.models.node import Node, NodeType+from products.data_modeling.backend.test.helpers import saved_query_node, table_nodeclass TestSavedQueryReads(BaseTest):@@ -100,3 +105,39 @@ class TestSavedQueryReads(BaseTest):source.id: frozenset({near.id, far.id}),near.id: frozenset(),}++ def test_upstream_table_refs_walks_through_views_and_other_dags_to_tables_only(self) -> None:+ dag = DAG.objects.create(team=self.team, name="Default")+ other_dag = DAG.objects.create(team=self.team, name="Finance")+ invoices = table_node(self.team, other_dag, "invoices", {"origin": POSTHOG_TABLE_ORIGIN})+ revenue = saved_query_node(self.team, other_dag, "revenue", NodeType.VIEW)+ Edge.objects.create(team=self.team, dag=other_dag, source=invoices, target=revenue)+ warehouse_table_id = str(uuid4())+ charges = table_node(+ self.team, dag, "stripe_charges", {"origin": "warehouse", "warehouse_table_id": warehouse_table_id}+ )+ events = table_node(self.team, dag, "events", {"origin": POSTHOG_TABLE_ORIGIN})+ proxy = table_node(+ self.team, dag, "revenue", {"origin": "cross_dag_view", "saved_query_id": str(revenue.saved_query_id)}+ )+ persons = table_node(self.team, dag, "persons", {"origin": POSTHOG_TABLE_ORIGIN})+ middle = saved_query_node(self.team, dag, "middle", NodeType.VIEW)+ target = saved_query_node(self.team, dag, "target", NodeType.VIEW)+ downstream = saved_query_node(self.team, dag, "downstream", NodeType.VIEW)+ for source, dependent in [+ (charges, middle),+ (events, middle),+ (proxy, middle),+ (middle, target),+ (target, downstream),+ (persons, downstream),+ ]:+ Edge.objects.create(team=self.team, dag=dag, source=source, target=dependent)++ assert api.upstream_table_refs(self.team.id, target.saved_query_id) == frozenset(+ {+ UpstreamTableRef(name="stripe_charges", warehouse_table_id=warehouse_table_id),+ UpstreamTableRef(name="events"),+ UpstreamTableRef(name="invoices"),+ }+ )diff --git a/products/data_warehouse/backend/presentation/views/saved_query/lineage.py b/products/data_warehouse/backend/presentation/views/saved_query/lineage.pyindex ba784b7e0a76..51d4cb70890e 100644--- a/products/data_warehouse/backend/presentation/views/saved_query/lineage.py+++ b/products/data_warehouse/backend/presentation/views/saved_query/lineage.py@@ -1,10 +1,9 @@"""Walking a saved query's ancestors and descendants through the data modeling DAG."""-from django.db.models import Q-from rest_framework import request, serializers-from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery, Edge, Node, NodeType+from products.data_modeling.backend.facade.api import reachable_node_ids, saved_query_node_ids+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery, Node, NodeTypeclass SavedQueryLineageRequestSerializer(serializers.Serializer):@@ -64,16 +63,11 @@ def _related_saved_queries(saved_query: DataWarehouseSavedQuery, *, upstream: boits name. A table node carries the id in its properties(`saved_query_dag_sync.resolve_dependency_to_node`) rather than the `saved_query` FK."""- start_node_ids = {- str(node_id)- for node_id in Node.objects.filter(team=saved_query.team)- .filter(Q(saved_query=saved_query) | Q(properties__saved_query_id=str(saved_query.id)))- .values_list("id", flat=True)- }+ start_node_ids = saved_query_node_ids(saved_query.team_id, saved_query.id)if not start_node_ids:return set()- reached = _reachable_node_ids(saved_query.team_id, start_node_ids, upstream=upstream, max_depth=max_depth)+ reached = reachable_node_ids(saved_query.team_id, start_node_ids, upstream=upstream, max_depth=max_depth)identifiers: set[str] = set()for node_type, saved_query_id, name, properties in Node.objects.filter(@@ -91,27 +85,3 @@ def _related_saved_queries(saved_query: DataWarehouseSavedQuery, *, upstream: boelse:identifiers.add(name)return identifiers---def _reachable_node_ids(team_id: int, start_node_ids: set[str], *, upstream: bool, max_depth: int | None) -> set[str]:- """Node ids reachable from `start_node_ids` within `max_depth` hops, the start nodes excluded.-- One query per hop, each reading the frontier's edges off the `Edge` foreign-key indexes, so- the work is bounded by the cone that is reached rather than by every edge the team owns.- Upstream follows edges into the frontier back to their sources; downstream follows edges- out of it to their targets.- """- edges = Edge.objects.filter(team_id=team_id)-- reached: set[str] = set()- frontier = set(start_node_ids)- depth = 0- while frontier and (max_depth is None or depth < max_depth):- if upstream:- neighbor_ids = edges.filter(target_id__in=frontier).values_list("source_id", flat=True)- else:- neighbor_ids = edges.filter(source_id__in=frontier).values_list("target_id", flat=True)- frontier = {str(neighbor_id) for neighbor_id in neighbor_ids} - reached - start_node_ids- reached |= frontier- depth += 1- return reacheddiff --git a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py b/products/data_warehouse/backend/presentation/views/saved_query/viewset.pyindex f1e847ef447e..82677e3c649a 100644--- a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py+++ b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py@@ -21,13 +21,19 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models import User-from posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activity+from posthog.models.activity_logging.activity_log import Detail, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_paramsfrom posthog.rate_limit import MaterializationRateThrottle, RunSavedQueryRateThrottle-from posthog.rbac.query_access import assert_user_can_read_queryfrom posthog.temporal.common.client import sync_connectfrom products.access_control.backend.presentation.access_control import AccessControlViewSetMixin+from products.data_modeling.backend.facade.api import (+ MaterializationFailedError,+ MaterializationForbiddenError,+ MaterializationRefusedError,+ SavedQueryNotFoundError,+ enable_saved_query_materialization,+)from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataWarehouseSavedQueryfrom products.warehouse_sources.backend.facade.models import sync_frequency_to_sync_frequency_interval@@ -425,104 +431,30 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe"""saved_query: DataWarehouseSavedQuery = self.get_object()- if saved_query.managed_viewset is not None:- raise serializers.ValidationError("Cannot materialize a query from a managed viewset.")-- assert_user_can_read_query(saved_query.query, self.team_id, cast(User, request.user))-params = SavedQueryMaterializeSerializer(data=request.data)params.is_valid(raise_exception=True)- sync_frequency_interval = sync_frequency_to_sync_frequency_interval(params.validated_data["sync_frequency"])-- from products.data_modeling.backend.facade.api import (- UnsatisfiableFrequencyError,- UnsupportedFrequencyTargetError,- check_saved_query_frequency_target,- saved_query_target_bounds,- )-- if sync_frequency_interval is not None:- # Ask before writing, so the ordinary refusal never has to be undone below. Names only- # what this caller may read, matching the bounds payload — otherwise one rejected- # materialize reads back a node they were never shown.- bounds = saved_query_target_bounds(self.team_id, saved_query.pk)- try:- check_saved_query_frequency_target(- saved_query,- sync_frequency_interval,- visible_names=(- sync_cadence.visible_blocker_names(bounds, self.user_access_control, team_id=self.team_id)- if bounds- else {}- ),- )- except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:- raise serializers.ValidationError(str(e))-- previous_interval = saved_query.sync_frequency_interval- previously_materialized = saved_query.is_materialized- saved_query.sync_frequency_interval = sync_frequency_interval- saved_query.is_materialized = True- saved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])-- # Enable materialization - this handles model path setup and schedule creation- # If this fails, it will set is_materialized = Falsetry:- saved_query.schedule_materialization(trigger_immediate_run=True, triggered_by_id=request.user.pk)- except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError):- # The check above already refused every cadence the lineage forbids, so reaching here- # means the lineage moved mid-request. Say so plainly rather than forwarding a message- # built from unredacted names. `schedule_materialization` re-raises these without- # applying its disable-on-failure contract, and this action is not inside an atomic- # block, so undo the enable by hand: otherwise the 400 leaves is_materialized=True- # behind and the UI reads the rejection as a success.- saved_query.sync_frequency_interval = previous_interval- saved_query.is_materialized = previously_materialized- saved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])- raise serializers.ValidationError(- "This view's lineage changed while we were setting it up. Reopen it and pick a cadence again."- )-- # Refresh from DB to check if schedule_materialization set is_materialized = False on failure- saved_query.refresh_from_db()- if saved_query.is_materialized is False:- return response.Response(- {"error": "Materialization failed. Please try again or contact support."},- status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ enable_saved_query_materialization(+ self.team_id,+ saved_query.id,+ user=cast(User, request.user),+ sync_frequency_interval=sync_frequency_to_sync_frequency_interval(+ params.validated_data["sync_frequency"]+ ),+ visible_blocker_names=lambda bounds: sync_cadence.visible_blocker_names(+ bounds, self.user_access_control, team_id=self.team_id+ ),+ was_impersonated=is_impersonated(request),)-- # set data modeling node type to matview- try:- from products.data_modeling.backend.facade.api import update_node_type- from products.data_modeling.backend.facade.models import NodeType-- update_node_type(saved_query, NodeType.MAT_VIEW)- except Exception as e:- capture_exception(e)- logger.exception("Failed to update node type to matview", saved_query_name=saved_query.name)-- log_activity(- organization_id=self.team.organization_id,- team_id=self.team_id,- user=cast(User, request.user),- was_impersonated=is_impersonated(request),- item_id=saved_query.id,- scope="DataWarehouseSavedQuery",- activity="materialization_enabled",- detail=Detail(- name=saved_query.name,- changes=[- Change(- field="sync_frequency_interval",- action="changed",- type="DataWarehouseSavedQuery",- before=str(previous_interval) if previous_interval else None,- after=str(sync_frequency_interval),- ),- ],- ),- )+ except SavedQueryNotFoundError:+ raise exceptions.NotFound()+ except MaterializationForbiddenError as e:+ raise exceptions.PermissionDenied(str(e))+ except MaterializationRefusedError as e:+ raise serializers.ValidationError(str(e))+ except MaterializationFailedError as e:+ return response.Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)return response.Response(status=status.HTTP_200_OK)