: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
fix(data-modeling): stop scheduling v2 saved queries without a node (#78259)
Jovan Sakovica59815e4ebfb
diff --git a/products/data_modeling/backend/logic/saved_query_dag_sync.py b/products/data_modeling/backend/logic/saved_query_dag_sync.pyindex 864acdac87c0..fb91fd956407 100644--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py@@ -254,6 +254,17 @@ class HasDependentsError(Exception):pass+class MissingDagNodeError(Exception):+ """Raised when a saved query on a v2 team has no node to schedule through.++ On v2 the node is the unit of execution: the DAG run materializes nodes, so a saved query+ with no node is not reachable by any schedule. Without this the query would be left claiming+ to be materialized while nothing refreshes it.+ """++ pass++def get_dependent_saved_queries(saved_query: "DataWarehouseSavedQuery") -> list["DataWarehouseSavedQuery"]:"""Get SavedQueries that depend on this one (immediate dependents only).diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 9f6175f01e8d..d57f13e61736 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -203,6 +203,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,UnsatisfiableFrequencyError,UnsupportedFrequencyTargetError,)+ from products.data_modeling.backend.logic.saved_query_dag_sync import MissingDagNodeErrorfrom products.data_modeling.backend.logic.schedule_reconcile import (apply_saved_query_frequency_target,bootstrap_dag_to_tiers,@@ -222,22 +223,29 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,# create or revive a per-query v1 schedule. This Temporal lookup stays inside the try so# that, if it fails, we honor the failure contract below rather than leaving# is_materialized=True with no schedule backing it.- on_v2 = self.id in get_v2_saved_query_ids([self.id])+ on_v2 = self.id in get_v2_saved_query_ids([self.id], team_id=self.team_id)+ node = (+ Node.objects.filter(team_id=self.team_id, saved_query_id=self.id)+ .select_related("dag", "dag__team")+ .first()+ )dag_to_bootstrap = Noneif not on_v2:# Nothing creates a DAG's first v2 schedule outside the migration commands, so a# brand-new team would fall through to v1 forever. Bootstrap it instead — declined# unless the DAG has never been scheduled at all.- node = (- Node.objects.filter(team_id=self.team_id, saved_query_id=self.id)- .select_related("dag", "dag__team")- .first()- )if node is not None and node.dag is not None and dag_can_bootstrap_to_tiers(node.dag):dag_to_bootstrap = node.dagon_v2 = Trueif on_v2:+ if node is None:+ # v2 executes nodes, so scheduling without one would report success while+ # nothing ever materializes the query. Fail into the contract below instead,+ # which clears is_materialized and captures the error.+ raise MissingDagNodeError(+ f"Saved query {self.id} is on a v2 team but has no DAG node to schedule through"+ )# Tiered v2: the interval is one-shot transport for frequency intent — consume# it into the node target(s) and reconcile. Validation raises before the# nulling below, so a rejected frequency stays visible for retry. A call withdiff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.pyindex 653c2ed5afa3..4b01e9628747 100644--- a/products/data_modeling/backend/schedule.py+++ b/products/data_modeling/backend/schedule.py@@ -12,9 +12,9 @@ Frequency tiers:import uuidimport hashlib+from collections import defaultdictfrom collections.abc import Collectionfrom datetime import timedelta-from typing import TYPE_CHECKINGfrom asgiref.sync import async_to_syncfrom temporalio.client import ScheduleCalendarSpec, ScheduleListActionStartWorkflow, ScheduleRange, ScheduleSpec@@ -29,11 +29,10 @@ from posthog.temporal.common.search_attributes import ()from products.data_modeling.backend.logic.cohort_scheduling import dag_id_from_schedule_id+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.node import Node-if TYPE_CHECKING:- from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-# v2 (DAG-based) schedules run this workflow; their schedule id is the bare DAG id, or# "{dag_id}:{interval_seconds}" for a per-cadence-tier schedule. The v1 backend# (`data-modeling-run`, one schedule per saved query) is frozen and being migrated away from.@@ -90,9 +89,22 @@ async def get_v2_scheduled_dag_ids(candidate_dag_ids: Collection[str] | None = Nreturn dag_ids-def get_v2_saved_query_ids(candidate_ids: Collection[uuid.UUID] | None = None) -> set[uuid.UUID]:+def get_v2_saved_query_ids(+ candidate_ids: Collection[uuid.UUID] | None = None, *, team_id: int | None = None+) -> set[uuid.UUID]:"""Return saved query IDs whose DAG already runs on a v2 schedule.+ A saved query counts as on v2 when any DAG it belongs to has a v2 schedule, because it can sit+ in several DAGs and one v1-scheduled placement does not make a v1 schedule safe to mint.++ `team_id` extends that to saved queries with no node, answering from the team's DAGs instead.+ A node can be absent because `sync_saved_query_to_dag` deletes it when dependency resolution+ raises, and reading "no node" as "not on v2" mints a v1 per-query schedule beside the team's+ live tier, which then materializes the query twice on every cycle. Only a caller that is about+ to create a v1 schedule needs this, so it stays opt-in: it answers about the team rather than+ about a placement, and such a caller must still check for a node before scheduling. Pass the+ team the candidates belong to, never one derived from the ids themselves.+Optionally restrict the lookup to `candidate_ids` to keep the query bounded. These savedqueries must be skipped by v1 schedule commands so we never undo migration progress."""@@ -101,18 +113,27 @@ def get_v2_saved_query_ids(candidate_ids: Collection[uuid.UUID] | None = None) -return set()# Resolve the candidate saved queries to their DAGs first so the Temporal lookup is scoped# to just those DAGs rather than listing every schedule in the namespace.- dag_id_by_saved_query = {- saved_query_id: str(dag_id)- for saved_query_id, dag_id in Node.objects.filter(- saved_query_id__in=candidate_ids, saved_query_id__isnull=False- ).values_list("saved_query_id", "dag_id")- if dag_id is not None- }- if not dag_id_by_saved_query:+ dag_ids_by_saved_query: dict[uuid.UUID, set[str]] = defaultdict(set)+ for saved_query_id, dag_id in Node.objects.filter(+ saved_query_id__in=candidate_ids, saved_query_id__isnull=False+ ).values_list("saved_query_id", "dag_id"):+ if dag_id is not None:+ dag_ids_by_saved_query[saved_query_id].add(str(dag_id))++ if team_id is not None:+ nodeless = set(candidate_ids) - dag_ids_by_saved_query.keys()+ team_dag_ids = (+ {str(dag_id) for dag_id in DAG.objects.filter(team_id=team_id).values_list("id", flat=True)}+ if nodeless+ else set()+ )+ if team_dag_ids:+ dag_ids_by_saved_query.update(dict.fromkeys(nodeless, team_dag_ids))+ if not dag_ids_by_saved_query:return set()- v2_dag_ids = get_v2_scheduled_dag_ids(set(dag_id_by_saved_query.values()))- return {saved_query_id for saved_query_id, dag_id in dag_id_by_saved_query.items() if dag_id in v2_dag_ids}+ v2_dag_ids = get_v2_scheduled_dag_ids({dag_id for ids in dag_ids_by_saved_query.values() for dag_id in ids})+ return {saved_query_id for saved_query_id, ids in dag_ids_by_saved_query.items() if ids & v2_dag_ids}v2_dag_ids = get_v2_scheduled_dag_ids()if not v2_dag_ids:@@ -123,8 +144,8 @@ def get_v2_saved_query_ids(candidate_ids: Collection[uuid.UUID] | None = None) -def partition_saved_queries_by_v2_schedule(- saved_queries: list["DataWarehouseSavedQuery"],-) -> tuple[list["DataWarehouseSavedQuery"], list["DataWarehouseSavedQuery"]]:+ saved_queries: list[DataWarehouseSavedQuery],+) -> tuple[list[DataWarehouseSavedQuery], list[DataWarehouseSavedQuery]]:"""Split saved queries into (v1_eligible, on_v2).A saved query is "on v2" when any DAG it belongs to already has a `data-modeling-execute-dag`diff --git a/products/data_modeling/backend/test/test_schedule.py b/products/data_modeling/backend/test/test_schedule.pyindex 1a37baf59516..ddc181b504ab 100644--- a/products/data_modeling/backend/test/test_schedule.py+++ b/products/data_modeling/backend/test/test_schedule.py@@ -353,6 +353,43 @@ class TestV2ScheduleGuard(BaseTest):assert eligible == []assert on_v2 == []+ def _saved_query(self, name: str) -> DataWarehouseSavedQuery:+ return DataWarehouseSavedQuery.objects.create(+ name=name,+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ )++ def test_saved_query_without_a_node_is_not_reported_as_v1_eligible(self):+ nodeless = self._saved_query("sync_failed")+ with mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ return_value={str(self.v2_dag.id)},+ ):+ result = get_v2_saved_query_ids([nodeless.id], team_id=self.team.pk)+ assert result == {nodeless.id}++ def test_saved_query_without_a_node_stays_v1_eligible_when_no_dag_is_v2_scheduled(self):+ nodeless = self._saved_query("sync_failed_on_v1_team")+ with mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ return_value=set(),+ ):+ result = get_v2_saved_query_ids([nodeless.id], team_id=self.team.pk)+ assert result == set()++ @parameterized.expand([("v2_node_created_first", True), ("v1_node_created_first", False)])+ def test_saved_query_in_two_dags_is_on_v2_when_either_dag_is(self, _name: str, v2_first: bool):+ shared = self._saved_query("in_two_dags")+ for dag in [self.v2_dag, self.v1_dag] if v2_first else [self.v1_dag, self.v2_dag]:+ Node.objects.create(team=self.team, dag=dag, saved_query=shared, type=NodeType.VIEW)+ with mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ return_value={str(self.v2_dag.id)},+ ):+ result = get_v2_saved_query_ids([shared.id], team_id=self.team.pk)+ assert result == {shared.id}+class TestGetV2ScheduledDagIds:def _listing(self, schedule_id: str, workflow: str):diff --git a/products/data_modeling/backend/test/test_schedule_materialization.py b/products/data_modeling/backend/test/test_schedule_materialization.pyindex 7b7d12ed367a..327f49498ebc 100644--- a/products/data_modeling/backend/test/test_schedule_materialization.py+++ b/products/data_modeling/backend/test/test_schedule_materialization.py@@ -60,6 +60,25 @@ class TestScheduleMaterializationV2Guard(BaseTest):self.sq.refresh_from_db()assert self.sq.sync_frequency_interval is None+ def test_saved_query_whose_node_vanished_is_refused_instead_of_scheduled(self):+ nodeless = DataWarehouseSavedQuery.objects.create(+ name="sync_failed",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ sync_frequency_interval=timedelta(hours=12),+ is_materialized=True,+ )+ with (+ mock.patch(GET_V2_DAG_IDS, return_value={str(self.dag.id)}),+ mock.patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,+ mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),+ self.captureOnCommitCallbacks(execute=True),+ ):+ nodeless.schedule_materialization()+ sync_wf.assert_not_called()+ nodeless.refresh_from_db()+ assert nodeless.is_materialized is False+def test_creates_v1_schedule_when_dag_not_on_v2(self):# an unmigrated v1 DAG: a live per-query schedule already covers this query, so the# bootstrap below must not fire and stack tiers on top of itdiff --git a/products/data_warehouse/backend/models/test/test_managed_viewset.py b/products/data_warehouse/backend/models/test/test_managed_viewset.pyindex 8a6fd5e6c044..125b357074b8 100644--- a/products/data_warehouse/backend/models/test/test_managed_viewset.py+++ b/products/data_warehouse/backend/models/test/test_managed_viewset.py@@ -81,6 +81,36 @@ class TestDataWarehouseManagedViewSetModel(BaseTest):reconcile.assert_called_once()+ def test_failed_dag_sync_does_not_mint_a_v1_schedule(self):+ managed_viewset = DataWarehouseManagedViewSet.objects.create(+ team=self.team,+ kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,+ )++ with (+ patch(+ "products.data_modeling.backend.logic.saved_query_dag_sync.sync_saved_query_to_dag",+ side_effect=Exception("dependency resolution failed"),+ ),+ patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),+ ),+ patch(+ "products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"+ ) as sync_wf,+ patch(+ "products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",+ return_value=False,+ ),+ ):+ managed_viewset.sync_views()++ sync_wf.assert_not_called()+ assert not DataWarehouseSavedQuery.objects.filter(+ managed_viewset=managed_viewset, is_materialized=True+ ).exists()+def test_sync_views_creates_views(self):"""Test that enabling managed viewset creates the expected views"""managed_viewset = DataWarehouseManagedViewSet.objects.create(diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.pyindex b19f985fcb58..4b877a5821f9 100644--- a/products/endpoints/backend/logic/materialization.py+++ b/products/endpoints/backend/logic/materialization.py@@ -225,9 +225,11 @@ class EndpointMaterializationService:# The DAG node must exist before scheduling: the v2 detection and the freshness-target# write-through both resolve this saved query through its Node row.+ sync_error: Exception | None = Nonetry:sync_saved_query_to_dag(saved_query)except Exception as e:+ sync_error = elogger.exception("Failed to sync endpoint node to DAG",endpoint_name=endpoint.name,@@ -254,6 +256,18 @@ class EndpointMaterializationService:# delivers) — a request problem, not a server one.raise ValidationError(str(e))+ # schedule_materialization applies a disable-on-failure contract rather than raising,+ # so a failure to schedule shows up only as is_materialized flipping back. Checking it+ # is what stops the enable reporting success on an endpoint nothing will ever refresh.+ saved_query.refresh_from_db(fields=["is_materialized"])+ if not saved_query.is_materialized:+ if sync_error is not None:+ # The node is missing because the query's dependencies did not resolve, which+ # the author fixes by editing the query. Reporting that as a server error would+ # tell them to retry, and would page on-call through the status="error" metric.+ raise ValidationError(f"Cannot materialize endpoint. Reason: {sync_error}")+ raise APIException(f"Failed to schedule materialization for endpoint {endpoint.name}.")+def _get_or_build_saved_query(self, version: EndpointVersion) -> DataWarehouseSavedQuery:"""Find this version's saved query, or build a new (unsaved) one.diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.pyindex cab2d401e923..f429ea3fdc21 100644--- a/products/endpoints/backend/tests/test_endpoint_materialization.py+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py@@ -25,7 +25,7 @@ from posthog.sync import database_sync_to_asyncfrom products.data_modeling.backend.facade.api import UnsatisfiableFrequencyErrorfrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPath-from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery, Node+from products.data_modeling.backend.facade.models import DAG, DataModelingJob, DataWarehouseSavedQuery, Nodefrom products.data_warehouse.backend.facade.api import get_saved_query_schedulefrom products.endpoints.backend.logic.execution import EndpointExecutionServicefrom products.endpoints.backend.logic.materialization import (@@ -162,6 +162,37 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):DataWarehouseSavedQuery.objects.filter(team=self.team, name=f"{endpoint.name}_v{version.version}").exists())+ def test_enable_fails_as_a_request_error_when_the_dag_sync_leaves_no_node(self):+ # the endpoint path swallows a dag sync failure, and scheduling then disables itself rather+ # than raising, so without a check the enable reports success on an endpoint that nothing+ # will ever refresh. an unresolvable dependency is the author's to fix, so it must not+ # report as a server error and page on-call+ DAG.objects.create(team=self.team, name="Default")+ self.mock_v2_dag_ids.side_effect = lambda candidate_dag_ids=None: set(candidate_dag_ids or [])+ endpoint = create_endpoint_with_version(+ name="nodeless_endpoint",+ team=self.team,+ query=self.sample_hogql_query,+ created_by=self.user,+ is_active=True,+ )+ version = endpoint.versions.first()+ assert version is not None++ with mock.patch(+ "products.endpoints.backend.logic.materialization.sync_saved_query_to_dag",+ side_effect=Exception("dependency resolution failed"),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"is_materialized": True, "data_freshness_seconds": 86400},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ version.refresh_from_db()+ self.assertIsNone(version.saved_query)+def test_data_freshness_updates_saved_query_sync_interval(self):"""Test that updating data_freshness_seconds updates the SavedQuery's sync_interval."""# Create and materialize an endpoint@@ -1853,7 +1884,7 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):with (mock.patch("products.data_modeling.backend.schedule.get_v2_saved_query_ids",- side_effect=lambda ids: set(ids),+ side_effect=lambda ids, **_kwargs: set(ids),),mock.patch("products.data_modeling.backend.logic.node_materialization.sync_connect",