:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(data-modeling): make the v2 backend unconditional (#83336)
Jovan Sakovicc216513e874d
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex c8f2be66447d..a630ed7b3133 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -302,7 +302,6 @@ export const FEATURE_FLAGS = {DASHBOARD_SAVED_VIEWS: 'dashboard-saved-views', // owner: #team-analytics-platform, target organizations for saved dashboard-list viewsDASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,newDASHBOARD_WIDGETS: 'dashboard-widgets', // owner: @mattp #team-analytics-platform- DATA_MODELING_BACKEND_V2: 'data-modeling-backend-v2', // owner: #team-data-modelingDATA_MODELING_INCREMENTAL_VIEWS: 'data-modeling-incremental-views', // owner: #team-data-modelingDATA_MODELING_SUSPEND_FAILING_NODES: 'data-modeling-suspend-failing-nodes', // owner: #team-data-modelingDATA_MODELING_TAB: 'data-modeling-tab', // owner: #team-data-modelingdiff --git a/posthog/temporal/data_modeling/AGENTS.md b/posthog/temporal/data_modeling/AGENTS.mdindex 70e7a8508224..12557a748b9b 100644--- a/posthog/temporal/data_modeling/AGENTS.md+++ b/posthog/temporal/data_modeling/AGENTS.md@@ -1,24 +1,27 @@# Data-modeling Temporal workflowsTemporal workflows and activities that materialize data-modeling saved queries.-Two implementations live here side by side during the v1 → v2 migration.+v2 is the only backend. The v1 code stays registered until its schedules are removed.-## v1 — FROZEN+## v1 — dead, pending removal- `run_workflow.py` (1814-line monolith).-- Dispatched from `products/data_modeling/backend/presentation/views/node.py` when- `_is_v2_backend_enabled(...)` is false.-- Almost all US teams are still on v1; almost all EU teams are on v2.+- Node and saved-query interactive paths always start v2. No production or management-command+ call site creates a `data-modeling-run` schedule. Endpoint compatibility paths can still trigger+ a pre-existing schedule until the v1 control cleanup lands.+- `RunWorkflow` stays in `WORKFLOWS` (`__init__.py`) on purpose. A schedule that points at a+ deregistered workflow type keeps firing, fails its workflow task, and writes no job row, so+ the workflow can only be removed after its schedules are gone.**Do not extend v1.** No new features, no refactors, no new error types.-Bug fixes that affect both versions can land here, but treat that as the-exception — the goal is to keep the migration window small.+The v1 code exists only until its schedules are removed.## v2 — active- `workflows/materialize_view.py` and `workflows/execute_dag.py`.- Activities in `activities/*.py`.-- Dispatched when `_is_v2_backend_enabled(...)` is true.+- Node `run` starts `data-modeling-execute-dag`. Node `materialize` and saved-query `run` start+ `data-modeling-materialize-view` through `start_node_materialization`.All new work targets v2: new activities, new error types, configuration knobs,reliability fixes, and tests.diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 9174bfa91efb..a0ec3cac600e 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -14,6 +14,7 @@ _LAZY = {"UnsupportedFrequencyTargetError": "logic.freshness","humanize_cadence": "logic.freshness","HasDependentsError": "logic.saved_query_dag_sync",+ "MissingDagNodeError": "logic.saved_query_dag_sync","delete_node_from_dag": "logic.saved_query_dag_sync","promote_view_nodes_to_matview": "logic.saved_query_dag_sync","sync_saved_query_to_dag": "logic.saved_query_dag_sync",diff --git a/products/data_modeling/backend/logic/node_materialization.py b/products/data_modeling/backend/logic/node_materialization.pyindex b6bf80be5916..d6660030a8cf 100644--- a/products/data_modeling/backend/logic/node_materialization.py+++ b/products/data_modeling/backend/logic/node_materialization.py@@ -1,6 +1,6 @@import asynciofrom dataclasses import asdict-from datetime import UTC, datetime, timedelta+from datetime import timedeltafrom uuid import UUIDfrom django.conf import settings@@ -9,10 +9,10 @@ import structlogfrom temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom posthog.temporal.common.client import sync_connect-from posthog.temporal.data_modeling.run_workflow import RunWorkflowInputs, Selectorfrom posthog.temporal.data_modeling.workflows.materialize_view import MaterializeViewWorkflowInputsfrom products.data_modeling.backend.logic.node_suspension import resume_nodes+from products.data_modeling.backend.logic.saved_query_dag_sync import MissingDagNodeErrorfrom products.data_modeling.backend.models import Nodefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.schedule import get_v2_saved_query_ids@@ -20,38 +20,25 @@ from products.data_modeling.backend.schedule import get_v2_saved_query_idslogger = structlog.get_logger(__name__)-def start_node_materialization(node: Node, *, is_v2: bool) -> None:+def start_node_materialization(node: Node) -> None:"""Start a one-off materialization workflow for a single node.- Shared by node `materialize` and saved-query `run` so the v1/v2 dispatch lives in one place.+ Shared by node `materialize` and saved-query `run`."""# An explicit run is a request to try again, so it gets a fresh failure window.resume_nodes([node], by="manual_run")- if is_v2:- inputs: MaterializeViewWorkflowInputs | RunWorkflowInputs = MaterializeViewWorkflowInputs(- team_id=node.team_id,- dag_id=str(node.dag_id),- node_id=str(node.id),- )- workflow_name = "data-modeling-materialize-view"- workflow_id = f"materialize-view-{node.id}"- else:- inputs = RunWorkflowInputs(- team_id=node.team_id,- select=[Selector(label=str(node.saved_query_id), ancestors=0, descendants=0)],- )- workflow_name = "data-modeling-run"- # Mirror the scheduled-run id shape ({saved_query_id}-{iso timestamp}) so- # resolve_log_source can recover the saved query id and the run's logs show up- # in the materialization history UI.- workflow_id = f"{node.saved_query_id}-{datetime.now(UTC).isoformat()}"+ inputs = MaterializeViewWorkflowInputs(+ team_id=node.team_id,+ dag_id=str(node.dag_id),+ node_id=str(node.id),+ )temporal = sync_connect()asyncio.run(temporal.start_workflow(- workflow_name,+ "data-modeling-materialize-view",asdict(inputs),- id=workflow_id,+ id=f"materialize-view-{node.id}",task_queue=str(settings.DATA_MODELING_TASK_QUEUE),id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,@@ -109,7 +96,7 @@ def materialize_saved_query(saved_query: DataWarehouseSavedQuery) -> None:node = Node.objects.filter(saved_query_id=saved_query.id).first()if node is None:# v2 was already confirmed, so a node should exist; a missing one is a data inconsistency.- # Skip rather than fall back to the v1 schedule, which no longer exists on a v2 team.- logger.warning("materialize_saved_query_missing_node", saved_query_id=str(saved_query.id))- return- start_node_materialization(node, is_v2=True)+ # Raise rather than return: returning reports a materialization the caller can then find no+ # trace of, and there is no v1 schedule left to fall back to.+ raise MissingDagNodeError(f"Saved query {saved_query.id} has no DAG node to materialize")+ start_node_materialization(node)diff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.pyindex 8391202624ca..67967809d085 100644--- a/products/data_modeling/backend/logic/schedule_reconcile.py+++ b/products/data_modeling/backend/logic/schedule_reconcile.py@@ -158,13 +158,15 @@ def dag_can_bootstrap_to_tiers(dag: DAG) -> bool:A DAG carrying live v1 schedules is deliberately left alone — tiers next to them wouldmaterialize everything twice. It stays for a migration command to convert and sweep.++ Deliberately not gated on `data-modeling-tiered-schedules`. Nothing mints v1 schedules any+ more, so a DAG this declines gets no scheduler at all rather than the older one, and the flag+ evaluates false for every self-hosted deployment."""- if not tiered_schedules_enabled(dag.team):- return Falsereturn not dag_has_live_v1_schedules(dag)-def bootstrap_dag_to_tiers(dag: DAG) -> None:+def bootstrap_dag_to_tiers(dag: DAG, *, requested_by: "DataWarehouseSavedQuery | None" = None) -> None:"""Seed the DAG's targets and queue the reconcile that creates its first tier schedules.Everything here is a side effect, and `transaction.on_commit` runs the callback immediately@@ -175,17 +177,26 @@ def bootstrap_dag_to_tiers(dag: DAG) -> None:Reconciles without `require_tiered`, because this is the pass that creates the DAG's firsttier schedules: `maybe_reconcile_dag` cannot stand in for it, since it declines a DAG thathas no tier schedule yet.++ `requested_by` is the saved query whose enable triggered this, and is marked not materialized+ if the reconcile fails."""persist_seed_targets(dag)- transaction.on_commit(lambda: _bootstrap_dag_best_effort(dag))+ transaction.on_commit(lambda: _bootstrap_dag_best_effort(dag, requested_by))-def _bootstrap_dag_best_effort(dag: DAG) -> None:+def _bootstrap_dag_best_effort(dag: DAG, requested_by: "DataWarehouseSavedQuery | None" = None) -> None:try:reconcile_dag_schedules(dag)except Exception as error:logger.exception("Freshness schedule bootstrap failed", dag_id=str(dag.id), team_id=dag.team_id)capture_exception(error)+ if requested_by is not None:+ # A bootstrap that fails creates no schedule, so nothing will ever run the query that+ # asked for one. Retract the claim here rather than re-raise: this runs after the+ # caller's transaction committed, so there is no longer a caller to catch it.+ requested_by.is_materialized = False+ requested_by.save(update_fields=["is_materialized"])def _warn_on_invalid_targets(dag: DAG, graph: FrequencyGraph | None = None) -> None:diff --git a/products/data_modeling/backend/management/commands/create_missing_saved_query_schedules.py b/products/data_modeling/backend/management/commands/create_missing_saved_query_schedules.pydeleted file mode 100644index ab7d2a787b32..000000000000--- a/products/data_modeling/backend/management/commands/create_missing_saved_query_schedules.py+++ /dev/null@@ -1,134 +0,0 @@-import logging--from django.conf import settings-from django.core.management.base import BaseCommand, CommandError--import structlog--from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-from products.data_modeling.backend.schedule import partition_saved_queries_by_v2_schedule-from products.data_warehouse.backend.facade.api import saved_query_workflow_exists, sync_saved_query_workflow--logger = structlog.get_logger(__name__)---class Command(BaseCommand):- help = "Creates missing Temporal schedules for materialized saved queries that should be refreshing"-- def add_arguments(self, parser):- parser.add_argument(- "--saved-query-ids",- default=None,- type=str,- help="Comma separated list of saved query UUIDs to check",- )- parser.add_argument(- "--team-ids",- default=None,- type=str,- help="Comma separated list of team IDs to filter by",- )- parser.add_argument(- "--start-after-saved-query-id",- default=None,- type=str,- help="Resume after this saved query UUID (exclusive), following the id ordering used by this command",- )- parser.add_argument(- "--dry-run",- action="store_true",- default=False,- help="Only show what would be created without making changes",- )-- def handle(self, **options):- logger.setLevel(logging.INFO)-- queryset = DataWarehouseSavedQuery.objects.filter(- deleted=False,- sync_frequency_interval__isnull=False,- )-- if options.get("saved_query_ids") is not None:- try:- sq_ids = [uid.strip() for uid in options["saved_query_ids"].split(",")]- except ValueError:- raise CommandError("saved-query-ids must be a comma separated list of UUIDs")- queryset = queryset.filter(id__in=sq_ids)-- if options.get("team_ids") is not None:- try:- team_ids = [int(tid) for tid in options["team_ids"].split(",")]- except ValueError:- raise CommandError("team-ids must be a comma separated list of team IDs")- queryset = queryset.filter(team_id__in=team_ids)-- if options.get("start_after_saved_query_id") is not None:- queryset = queryset.filter(id__gt=options["start_after_saved_query_id"])-- saved_queries = list(queryset.order_by("id"))-- if len(saved_queries) == 0:- raise CommandError("No materialized saved queries found matching filters")-- # Never create a v1 schedule for a saved query whose DAG already runs on v2.- saved_queries, on_v2 = partition_saved_queries_by_v2_schedule(saved_queries)- if on_v2:- logger.info(f"Skipping {len(on_v2)} saved queries on DAGs already migrated to v2")- if not saved_queries:- logger.info("All matching saved queries are on v2 DAGs, nothing to do")- return-- logger.info(f"Found {len(saved_queries)} materialized saved queries to check")-- missing = []- already_exists = 0-- for num, sq in enumerate(saved_queries):- if saved_query_workflow_exists(sq):- already_exists += 1- else:- missing.append(sq)- logger.info(- "Missing schedule",- saved_query_id=str(sq.id),- team_id=sq.team_id,- name=sq.name,- )-- if (num + 1) % 100 == 0:- logger.info(f"Check progress: {num + 1}/{len(saved_queries)}")-- logger.info(f"Check complete: {len(missing)} missing, {already_exists} already exist")-- if not missing:- logger.info("All schedules exist, nothing to do")- return-- if options["dry_run"]:- logger.info("Dry run, not creating schedules")- return-- if not settings.TEST:- confirm = input(f"\n\tWill create schedules for {len(missing)} saved queries. Proceed? (y/n) ")- if confirm.strip().lower() != "y":- logger.info("Aborting")- return-- created = 0- failed = 0-- for num, sq in enumerate(missing):- try:- sq.setup_model_paths()- sync_saved_query_workflow(sq, create=True)- created += 1- logger.info("Created schedule", saved_query_id=str(sq.id), team_id=sq.team_id)- except Exception:- failed += 1- logger.exception("Error creating schedule", saved_query_id=str(sq.id))-- if (num + 1) % 100 == 0:- logger.info(f"Create progress: {num + 1}/{len(missing)}")-- logger.info(f"Done! Created: {created}, Failed: {failed}, Already existed: {already_exists}")diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 8bd8a250a026..8eb359e40094 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -67,12 +67,7 @@ def validate_saved_query_name(value):class V1SchedulingPathReached(Exception):- """Reported, never raised. Marks a caller that still mints a v1 per-query schedule.-- v1 scheduling is being retired and the fleet no longer runs it, so this exists to find any- remaining path into it before the workflow type is deregistered — a schedule pointing at a- deregistered type does not fail loudly, it fires forever with failing workflow tasks.- """+ """Raised when a saved query cannot be scheduled through v2."""class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields, DeletedMetaFields):@@ -212,12 +207,9 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,else:DataWarehouseModelPath.objects.update_from_saved_query(self)- def schedule_materialization(- self, unpause: bool = False, reconcile: bool = True, trigger_immediate_run: bool = False- ):+ def schedule_materialization(self, reconcile: bool = True, trigger_immediate_run: bool = False):"""It will schedule the saved query workflow to run at the configured frequency.- If unpause is True, it will unpause the saved query workflow if it already exists.trigger_immediate_run is for callers enabling materialization: on v2 it starts the firstmaterialization right away instead of waiting for the next scheduled DAG tick, matching@@ -226,7 +218,6 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,the DAG schedule still covers the query.If the workflow fails to schedule, it will disable materialization for this view.- This also guarantees model paths are properly created or updated."""from products.data_modeling.backend.logic.freshness import (UnsatisfiableFrequencyError,@@ -241,12 +232,8 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,)from products.data_modeling.backend.models.node import Nodefrom products.data_modeling.backend.schedule import get_v2_saved_query_ids- from products.data_warehouse.backend.facade.api import (- saved_query_workflow_exists,- sync_saved_query_workflow,- unpause_saved_query_schedule,- )+ node: Node | None = Nonetry:# If this query's DAG already runs on a v2 schedule, that schedule materializes it. Never# create or revive a per-query v1 schedule. This Temporal lookup stays inside the try so@@ -289,7 +276,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,# Last, so a frequency the validation above rejects leaves no seeded targets and# no schedules behind: on_commit fires immediately for the callers that are not# inside an atomic block, and two of the three are not.- bootstrap_dag_to_tiers(dag_to_bootstrap)+ bootstrap_dag_to_tiers(dag_to_bootstrap, requested_by=self)# On any v2 flavor the interval must end up NULL: a lingering value would let# a v1 per-query schedule be recreated, and on tiered teams the node target is# the only durable store of frequency intent.@@ -302,30 +289,21 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,transaction.on_commit(self._start_immediate_materialization)return- # Both regions hold zero `data-modeling-run` schedules, so nothing should reach here.- # Report each arrival with the caller's context, but still schedule: a customer's- # materialization must not be what proves this path is dead.+ raise V1SchedulingPathReached(f"Saved query {self.id} has no v2 schedule")+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError):+ # The query is fine — the requested frequency is not. Surface it to the caller+ # instead of silently disabling materialization.+ raise+ except Exception as e:capture_exception(- V1SchedulingPathReached(f"Saved query {self.id} scheduled through the v1 per-query path"),+ e,{- "saved_query_id": str(self.id),+ "saved_query_id": self.id,+ "saved_query_name": self.name,"team_id": self.team_id,"dag_id": str(node.dag_id) if node is not None else None,},)-- self.setup_model_paths()-- schedule_exists = saved_query_workflow_exists(self)- if schedule_exists and unpause:- unpause_saved_query_schedule(self)- sync_saved_query_workflow(self, create=not schedule_exists)- except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError):- # The query is fine — the requested frequency is not. Surface it to the caller- # instead of silently disabling materialization.- raise- except Exception as e:- capture_exception(e, {"saved_query_id": self.id, "saved_query_name": self.name})logger.exception("failed_to_schedule_saved_query",team_id=self.team_id,diff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex d18afb21373b..f1493523ccec 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -20,11 +20,9 @@ from posthog.hogql.database.database import Databasefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField-from posthog.models import Team, User-from posthog.ph_client import feature_enabled_or_false+from posthog.models import Userfrom posthog.rbac.query_access import assert_user_can_read_queryfrom posthog.temporal.common.client import sync_connect-from posthog.temporal.data_modeling.run_workflow import RunWorkflowInputs, Selectorfrom posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputsfrom products.access_control.backend.facade.user_access_control import AccessControlLevel@@ -157,21 +155,6 @@ _READ_DENIED = "Reading data models requires data warehouse read access."# the temporal workflow and lineage API should migrate to Graph-def _is_v2_backend_enabled(user: User, team: Team) -> bool:- return feature_enabled_or_false(- "data-modeling-backend-v2",- str(user.distinct_id),- groups={- "organization": str(team.organization_id),- "project": str(team.id),- },- group_properties={- "organization": {"id": str(team.organization_id)},- "project": {"id": str(team.id)},- },- )--def _get_upstream_nodes(node: Node, include_tables: bool = False) -> set[str]:"""Get all upstream (ancestor) node IDs recursively, optionally excluding TABLE nodes."""nodes: set[str] = set()@@ -337,43 +320,18 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# for exactly the nodes that need it most.resume_nodes(Node.objects.filter(team_id=self.team_id, id__in=node_ids), by="manual_run")- if _is_v2_backend_enabled(cast(User, req.user), self.team):- inputs: ExecuteDAGInputs | RunWorkflowInputs = ExecuteDAGInputs(- team_id=self.team_id,- dag_id=str(node.dag_id),- node_ids=list(node_ids),- )- workflow_name = "data-modeling-execute-dag"- workflow_id = f"execute-dag-{uuid4()}"- else:- # v1 workflow is frozen — do not extend this branch.- # v2 lives at posthog/temporal/data_modeling/workflows/. Teams are- # being migrated off v1 via the `_is_v2_backend_enabled` flag.- saved_query_ids = list(- # nosemgrep: idor-lookup-without-team (node_ids from prior team-scoped graph traversal)- Node.objects.filter(- id__in=node_ids,- saved_query_id__isnull=False,- ).values_list("saved_query_id", flat=True)- )- selectors = [- Selector(- label=str(sq_id),- ancestors="ALL" if direction == "upstream" else 0,- descendants="ALL" if direction == "downstream" else 0,- )- for sq_id in saved_query_ids- ]- inputs = RunWorkflowInputs(team_id=self.team_id, select=selectors)- workflow_name = "data-modeling-run"- workflow_id = f"data-modeling-run-{node.dag_id}-{uuid4()}"+ inputs = ExecuteDAGInputs(+ team_id=self.team_id,+ dag_id=str(node.dag_id),+ node_ids=list(node_ids),+ )temporal = sync_connect()asyncio.run(temporal.start_workflow(- workflow_name,+ "data-modeling-execute-dag",asdict(inputs),- id=workflow_id,+ id=f"execute-dag-{uuid4()}",task_queue=str(settings.DATA_MODELING_TASK_QUEUE),retry_policy=RetryPolicy(initial_interval=timedelta(seconds=10),@@ -470,7 +428,7 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if node.saved_query is not None:assert_user_can_read_query(node.saved_query.query, self.team_id, cast(User, req.user))- start_node_materialization(node, is_v2=_is_v2_backend_enabled(cast(User, req.user), self.team))+ start_node_materialization(node)return response.Response(status=status.HTTP_200_OK)diff --git a/products/data_modeling/backend/test/test_schedule_materialization.py b/products/data_modeling/backend/test/test_schedule_materialization.pyindex e35dc6f503ca..fcb504a12dea 100644--- a/products/data_modeling/backend/test/test_schedule_materialization.py+++ b/products/data_modeling/backend/test/test_schedule_materialization.py@@ -14,7 +14,6 @@ from products.data_modeling.backend.models.datawarehouse_saved_query import (from products.data_modeling.backend.models.node import NodeTypeMODEL = "products.data_modeling.backend.models.datawarehouse_saved_query"-SERVICE = "products.data_warehouse.backend.logic.data_load.saved_query_service"GET_V2_DAG_IDS = "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids"RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"NODE_MAT = "products.data_modeling.backend.logic.node_materialization"@@ -50,15 +49,12 @@ class TestScheduleMaterializationV2Guard(BaseTest):def test_skips_v1_and_nulls_frequency_when_dag_on_v2(self):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),mock.patch.object(DataWarehouseSavedQuery, "setup_model_paths") as setup_paths,mock.patch(f"{NODE_MAT}.sync_connect") as sync_connect,mock.patch(f"{MODEL}.capture_exception") as capture,self.captureOnCommitCallbacks(execute=True),):self.sq.schedule_materialization()- sync_wf.assert_not_called()setup_paths.assert_not_called()# reporting on the healthy path would bury the one signal that matterscapture.assert_not_called()@@ -77,33 +73,24 @@ class TestScheduleMaterializationV2Guard(BaseTest):)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 it+ def test_disables_materialization_when_dag_is_not_on_v2(self):+ self.sq.is_materialized = True+ self.sq.save(update_fields=["is_materialized"])with (mock.patch(GET_V2_DAG_IDS, return_value=set()),- mock.patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,- mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=True),mock.patch(f"{RECONCILE}.schedule_exists", return_value=True),- mock.patch.object(DataWarehouseSavedQuery, "setup_model_paths"),mock.patch(f"{MODEL}.capture_exception") as capture,):self.sq.schedule_materialization()- sync_wf.assert_called_once()+self.sq.refresh_from_db()- assert self.sq.sync_frequency_interval == timedelta(hours=12)- # the fleet runs no v1 schedules, so an arrival here is the only evidence a minting path- # survives; losing this report reads as "minting is closed" and clears the workflow type- # for deregistration, which fails silently in production+ assert self.sq.is_materialized is Falseassert isinstance(capture.call_args.args[0], V1SchedulingPathReached)assert capture.call_args.args[1]["team_id"] == self.team.pk@@ -114,10 +101,9 @@ class TestScheduleMaterializationV2Guard(BaseTest):node = Node.objects.get(saved_query=self.sq)with (mock.patch(GET_V2_DAG_IDS, return_value=set()),- mock.patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,- mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),+ mock.patch(f"{RECONCILE}.sync_connect"),mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_no_schedules())),mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,mock.patch(f"{NODE_MAT}.sync_connect"),@@ -125,7 +111,6 @@ class TestScheduleMaterializationV2Guard(BaseTest):):self.sq.schedule_materialization()- sync_wf.assert_not_called()create.assert_called_once()assert is_tier_schedule_id(create.call_args.kwargs["id"])node.refresh_from_db()@@ -133,30 +118,52 @@ class TestScheduleMaterializationV2Guard(BaseTest):self.sq.refresh_from_db()assert self.sq.sync_frequency_interval is None- def test_dag_with_a_v1_scheduled_sibling_is_not_treated_as_virgin(self):- # adding a query to an unmigrated team's DAG must keep using v1 — bootstrapping tiers- # here would double-schedule every query the sibling's v1 schedule already materializes- sibling = DataWarehouseSavedQuery.objects.create(- name="sibling",- team=self.team,- query={"query": "SELECT 2", "kind": "HogQLQuery"},- sync_frequency_interval=timedelta(hours=12),- )- Node.objects.create(team=self.team, dag=self.dag, saved_query=sibling, type=NodeType.VIEW)+ def test_virgin_dag_is_born_on_tiers_with_the_tiered_flag_off(self):+ # nothing mints v1 schedules any more, so a bootstrap the flag declines leaves the query+ # with no scheduler at all — and the flag reads false on every self-hosted deployment+ node = Node.objects.get(saved_query=self.sq)with (mock.patch(GET_V2_DAG_IDS, return_value=set()),- mock.patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,- mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),- # only the sibling still has a live v1 schedule- mock.patch(- f"{RECONCILE}.schedule_exists", side_effect=lambda _t, schedule_id: schedule_id == str(sibling.id)- ),+ mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),+ mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=False),+ mock.patch(f"{RECONCILE}.sync_connect"),+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_no_schedules())),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{NODE_MAT}.sync_connect"),+ self.captureOnCommitCallbacks(execute=True),+ ):+ self.sq.schedule_materialization()++ create.assert_called_once()+ assert is_tier_schedule_id(create.call_args.kwargs["id"])+ # the flag gates the write-through path, so the requested cadence has to survive as a+ # seeded target instead+ node.refresh_from_db()+ assert get_declared_target(node) == timedelta(hours=12)++ def test_failed_bootstrap_retracts_the_materialized_claim(self):+ # the reconcile runs after the caller's transaction commits, so a failure has no caller+ # left to raise into: leaving is_materialized set would report a schedule that was+ # never created+ self.sq.is_materialized = True+ self.sq.save(update_fields=["is_materialized"])+ with (+ mock.patch(GET_V2_DAG_IDS, return_value=set()),+ mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),mock.patch(f"{RECONCILE}.sync_connect"),- mock.patch.object(DataWarehouseSavedQuery, "setup_model_paths"),+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_no_schedules())),+ mock.patch(+ f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock(side_effect=Exception("temporal unavailable"))+ ),+ mock.patch(f"{RECONCILE}.capture_exception"),+ mock.patch(f"{NODE_MAT}.sync_connect"),+ self.captureOnCommitCallbacks(execute=True),):self.sq.schedule_materialization()- sync_wf.assert_called_once()++ self.sq.refresh_from_db()+ assert self.sq.is_materialized is Falsedef test_rejected_frequency_leaves_a_virgin_dag_unbootstrapped(self):# the bootstrap is all side effects, and on_commit fires immediately for the callers that@@ -167,8 +174,6 @@ class TestScheduleMaterializationV2Guard(BaseTest):self.sq.save(update_fields=["sync_frequency_interval"])with (mock.patch(GET_V2_DAG_IDS, return_value=set()),- mock.patch(f"{SERVICE}.sync_saved_query_workflow"),- mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),mock.patch(f"{RECONCILE}.sync_connect"),@@ -250,13 +255,7 @@ class TestScheduleMaterializationV2Guard(BaseTest):def test_disables_materialization_when_v2_lookup_fails(self):self.sq.is_materialized = Trueself.sq.save(update_fields=["is_materialized"])- with (- mock.patch(GET_V2_DAG_IDS, side_effect=Exception("temporal unavailable")),- mock.patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,- mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),- mock.patch.object(DataWarehouseSavedQuery, "setup_model_paths"),- ):+ with mock.patch(GET_V2_DAG_IDS, side_effect=Exception("temporal unavailable")):self.sq.schedule_materialization()- sync_wf.assert_not_called()self.sq.refresh_from_db()assert self.sq.is_materialized is Falsediff --git a/products/data_modeling/backend/tests/api/test_node_api.py b/products/data_modeling/backend/tests/api/test_node_api.pyindex 27099f4f100c..e6f6ad5c2ac7 100644--- a/products/data_modeling/backend/tests/api/test_node_api.py+++ b/products/data_modeling/backend/tests/api/test_node_api.py@@ -10,7 +10,6 @@ from rest_framework import statusfrom temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom posthog.models import Team-from posthog.temporal.common.logger import resolve_log_sourcefrom products.data_modeling.backend.logic.node_frequency import set_declared_targetfrom products.data_modeling.backend.logic.node_suspension import mark_node_suspended, suspension_state@@ -228,26 +227,6 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("table", response.json()["error"].lower())- @patch("products.data_modeling.backend.logic.node_materialization.sync_connect")- def test_materialize_starts_workflow(self, mock_sync_connect):- mock_client = AsyncMock()- mock_sync_connect.return_value = mock_client-- response = self.client.post(- f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/materialize/",- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- mock_client.start_workflow.assert_called_once()-- # The workflow id must resolve back to the saved query id, or the run's log lines- # detach from the materialization history UI (which queries by saved query id).- workflow_id = mock_client.start_workflow.call_args.kwargs["id"]- self.assertEqual(- resolve_log_source("data-modeling-run", workflow_id),- ("data_modeling_run", str(self.saved_query.id)),- )-def _suspend(self, node: Node) -> None:mark_node_suspended(node, engine="clickhouse", reason="boom", job_id=str(uuid4()), fingerprint=None)node.save()@@ -303,9 +282,8 @@ class TestNodeViewSet(APIBaseTest):self.view_node.refresh_from_db()self.assertEqual(suspension_state(self.view_node), {})- @patch("products.data_modeling.backend.presentation.views.node.feature_enabled_or_false", return_value=True)@patch("products.data_modeling.backend.presentation.views.node.sync_connect")- def test_run_uses_execute_dag_when_v2_enabled(self, mock_sync_connect, mock_feature_flag):+ def test_run_starts_the_execute_dag_workflow(self, mock_sync_connect):mock_client = AsyncMock()mock_sync_connect.return_value = mock_client@@ -318,24 +296,8 @@ class TestNodeViewSet(APIBaseTest):call_args = mock_client.start_workflow.call_argsself.assertEqual(call_args[0][0], "data-modeling-execute-dag")- @patch("products.data_modeling.backend.presentation.views.node.feature_enabled_or_false", return_value=False)- @patch("products.data_modeling.backend.presentation.views.node.sync_connect")- def test_run_uses_run_workflow_when_v2_disabled(self, mock_sync_connect, mock_feature_flag):- mock_client = AsyncMock()- mock_sync_connect.return_value = mock_client-- response = self.client.post(- f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/run/",- {"direction": "upstream"},- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- call_args = mock_client.start_workflow.call_args- self.assertEqual(call_args[0][0], "data-modeling-run")-- @patch("products.data_modeling.backend.presentation.views.node.feature_enabled_or_false", return_value=True)@patch("products.data_modeling.backend.logic.node_materialization.sync_connect")- def test_materialize_uses_materialize_view_when_v2_enabled(self, mock_sync_connect, mock_feature_flag):+ def test_materialize_starts_the_materialize_view_workflow(self, mock_sync_connect):mock_client = AsyncMock()mock_sync_connect.return_value = mock_client@@ -350,20 +312,6 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(call_args.kwargs["id_conflict_policy"], WorkflowIDConflictPolicy.USE_EXISTING)self.assertEqual(call_args.kwargs["id_reuse_policy"], WorkflowIDReusePolicy.ALLOW_DUPLICATE)- @patch("products.data_modeling.backend.presentation.views.node.feature_enabled_or_false", return_value=False)- @patch("products.data_modeling.backend.logic.node_materialization.sync_connect")- def test_materialize_uses_run_workflow_when_v2_disabled(self, mock_sync_connect, mock_feature_flag):- mock_client = AsyncMock()- mock_sync_connect.return_value = mock_client-- response = self.client.post(- f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/materialize/",- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- call_args = mock_client.start_workflow.call_args- self.assertEqual(call_args[0][0], "data-modeling-run")-def test_lineage_returns_subgraph(self):response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?node_id={self.view_node.id}"diff --git a/products/data_warehouse/backend/models/test/test_managed_viewset.py b/products/data_warehouse/backend/models/test/test_managed_viewset.pyindex 125b357074b8..98af99b5f0ec 100644--- a/products/data_warehouse/backend/models/test/test_managed_viewset.py+++ b/products/data_warehouse/backend/models/test/test_managed_viewset.py@@ -119,7 +119,8 @@ class TestDataWarehouseManagedViewSetModel(BaseTest):)# Call sync_views to create the views- managed_viewset.sync_views()+ with patch(SCHEDULE_MATERIALIZATION):+ managed_viewset.sync_views()# Check that views were createdviews = DataWarehouseSavedQuery.objects.filter(diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.pyindex 860a45b15dbe..262038148dd3 100644--- a/products/data_warehouse/backend/presentation/views/saved_query.py+++ b/products/data_warehouse/backend/presentation/views/saved_query.py@@ -58,13 +58,7 @@ from products.data_modeling.backend.facade.models import (DataWarehouseSavedQueryColumnAnnotation,)from products.data_tools.backend.facade.models import DataWarehouseJoin, DataWarehouseSavedQueryFolder-from products.data_warehouse.backend.facade.api import (- pause_saved_query_schedule,- saved_query_workflow_exists,- sync_saved_query_workflow,- trigger_saved_query_schedule,- unpause_saved_query_schedule,-)+from products.data_warehouse.backend.facade.api import saved_query_workflow_exists, unpause_saved_query_schedulefrom products.data_warehouse.backend.presentation.views.column_annotation_base import (DESCRIPTION_HELP_TEXT,upsert_annotation,@@ -964,19 +958,12 @@ class DataWarehouseSavedQuerySerializer()dag_managed_frequency = False- if sync_frequency and posthoganalytics.feature_enabled(- "data-modeling-backend-v2",- str(instance.team.uuid),- groups={- "organization": str(instance.team.organization_id),- "project": str(instance.team.id),- },- ):+ if sync_frequency:from products.data_modeling.backend.facade.api import tiered_schedules_enabled- # On tiered v2 the frequency writes through to the DAG node's freshness target;- # on single-schedule v2 the DAG's one schedule owns cadence and per-query- # frequency edits are rejected.+ # On tiered schedules the frequency writes through to the DAG node's freshness target;+ # on a single DAG schedule that one schedule owns cadence and per-query frequency edits+ # are rejected.if not tiered_schedules_enabled(instance.team):raise serializers.ValidationError("Schedule is managed by the DAG. Edit the DAG schedule instead.")dag_managed_frequency = True@@ -1006,18 +993,10 @@ class DataWarehouseSavedQuerySerializer(raise serializers.ValidationError("The query was modified by someone else.")if dag_managed_frequency:- # Tiered v2: the node target is the only store of frequency intent. The- # interval column stays NULL so a stale v1 schedule can never be revived- # from it.+ # The node target is the only store of frequency intent. The interval column+ # stays NULL so a stale v1 schedule can never be revived from it.locked_instance.sync_frequency_interval = Nonevalidated_data["sync_frequency_interval"] = None- elif sync_frequency == "never":- locked_instance.sync_frequency_interval = None- validated_data["sync_frequency_interval"] = None- elif sync_frequency:- sync_frequency_interval = sync_frequency_to_sync_frequency_interval(sync_frequency)- validated_data["sync_frequency_interval"] = sync_frequency_interval- locked_instance.sync_frequency_interval = sync_frequency_intervalview: DataWarehouseSavedQuery = super().update(locked_instance, validated_data)@@ -1145,24 +1124,6 @@ class DataWarehouseSavedQuerySerializer(.first())self.context["activity_log"] = latest_activity_log- # Update the v1 temporal schedule if it exists. Skipped on the DAG-managed path even- # when a stale v1 schedule lingers from a half-finished migration — syncing it here- # would revive it alongside the DAG's schedules.- if not dag_managed_frequency:- temporal_schedule_exists = saved_query_workflow_exists(view)- if temporal_schedule_exists:- try:- if sync_frequency == "never":- pause_saved_query_schedule(view)- elif sync_frequency:- sync_saved_query_workflow(view, create=not temporal_schedule_exists)- except Exception as e:- capture_exception(e)- logger.exception(- "Failed to update temporal schedule when updating view: view=%s sync_frequency=%s",- view.name,- sync_frequency,- )# best effort sync to new data modeling DAG representationif "query" in validated_data:try:@@ -1513,23 +1474,15 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSereturn contextdef _team_frequency_mode(self) -> str:- """Which backend owns materialization cadence for this team.+ """Which scheduler owns materialization cadence for this team.- Mirrors the branch `update()` takes on a `sync_frequency` write: `legacy` writes the interval- column, `tiered` writes the DAG node's freshness target and is the only mode with bounds, and- `dag_schedule` rejects the write because the team's one DAG schedule owns cadence. Team-scoped,- so the per-view rejections (managed viewsets, views with no node) are not reflected here.+ Mirrors the branch `update()` takes on a `sync_frequency` write: `tiered` writes the DAG node's+ freshness target and is the only mode with bounds, and `dag_schedule` rejects the write because+ the team's one DAG schedule owns cadence. Team-scoped, so the per-view rejections (managed+ viewsets, views with no node) are not reflected here."""from products.data_modeling.backend.facade.api import tiered_schedules_enabled- v2_enabled = posthoganalytics.feature_enabled(- "data-modeling-backend-v2",- str(self.team.uuid),- groups={"organization": str(self.team.organization_id), "project": str(self.team.id)},- send_feature_flag_events=False,- )- if not v2_enabled:- return "legacy"return "tiered" if tiered_schedules_enabled(self.team) else "dag_schedule"def get_serializer_class(self):@@ -1654,8 +1607,8 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSedef run(self, request: request.Request, *args, **kwargs) -> response.Response:"""Run this saved query."""from products.data_modeling.backend.facade.api import (+ MissingDagNodeError,clear_incremental_state,- is_saved_query_on_v2_schedule,materialize_saved_query,)@@ -1666,13 +1619,17 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSeif body.validated_data["full_refresh"]:# Dropping the watermark is the whole mechanism: the next run finds no progress to- # build on and rebuilds. Done before dispatch so the run it triggers is the rebuild.+ # build on and rebuilds. Commit it before dispatch, and outside any transaction the+ # dispatch could roll back, or the worker reads the old watermark and runs+ # incrementally instead.clear_incremental_state(saved_query)- if is_saved_query_on_v2_schedule(saved_query):+ try:materialize_saved_query(saved_query)- else:- trigger_saved_query_schedule(saved_query)+ except MissingDagNodeError:+ raise exceptions.ValidationError(+ detail="This view isn't fully set up to materialize. Save the query again, then try syncing."+ )log_activity(organization_id=self.team.organization_id,@@ -1833,7 +1790,6 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSeexcept (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:raise serializers.ValidationError(str(e))- should_unpause = saved_query.sync_frequency_interval is Noneprevious_interval = saved_query.sync_frequency_intervalpreviously_materialized = saved_query.is_materialized@@ -1844,7 +1800,7 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe# Enable materialization - this handles model path setup and schedule creation# If this fails, it will set is_materialized = Falsetry:- saved_query.schedule_materialization(unpause=should_unpause, trigger_immediate_run=True)+ saved_query.schedule_materialization(trigger_immediate_run=True)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 messagediff --git a/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py b/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.pyindex 68d36041fb7c..650c393854c0 100644--- a/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py+++ b/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py@@ -94,11 +94,7 @@ class TestSavedQueryDagSyncIntegration(APIBaseTest):self.assertEqual(delete_response.status_code, status.HTTP_204_NO_CONTENT)self.assertFalse(Node.objects.filter(saved_query_id=saved_query_id).exists())- @patch("products.data_warehouse.backend.presentation.views.saved_query.sync_saved_query_workflow")- @patch(- "products.data_warehouse.backend.presentation.views.saved_query.saved_query_workflow_exists", return_value=False- )- def test_materialize_updates_node_type(self, _mock_workflow_exists, _mock_sync_workflow):+ def test_materialize_updates_node_type(self):# createcreate_response = self.client.post(f"/api/environments/{self.team.id}/warehouse_saved_queries/",@@ -117,9 +113,13 @@ class TestSavedQueryDagSyncIntegration(APIBaseTest):self.assertEqual(node.type, NodeType.VIEW)# materialize- materialize_response = self.client.post(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}/materialize/"- )+ with patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ return_value={str(node.dag_id)},+ ):+ materialize_response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}/materialize/"+ )self.assertEqual(materialize_response.status_code, status.HTTP_200_OK)node.refresh_from_db()self.assertEqual(node.type, NodeType.MAT_VIEW)diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.pyindex 097bfbfab5d2..2c6f6816544f 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py@@ -166,13 +166,7 @@ class TestSavedQuery(APIBaseTest):saved_query_id = response.data["id"]assert saved_query_id is not None- with (- patch("products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"),- patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",- return_value=False,- ),- ):+ with patch.object(DataWarehouseSavedQuery, "schedule_materialization"):response = self.client.post(f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}/materialize",)@@ -201,50 +195,17 @@ class TestSavedQuery(APIBaseTest):saved_query_id = response.data["id"]assert saved_query_id is not None- with (- patch("products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"),- patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",- return_value=False,- ),- ):- # First call to materialize- response = self.client.post(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}/materialize",- )-- assert response.status_code == 200-- saved_query = DataWarehouseSavedQuery.objects.get(id=saved_query_id)- assert saved_query.is_materialized is True- assert saved_query.sync_frequency_interval == timedelta(hours=24)-- with (- patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"- ) as mock_sync,- patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",- return_value=True,- ),- patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.unpause_saved_query_schedule"- ) as mock_unpause,- ):- # Second call to materialize - should be idempotent- response = self.client.post(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}/materialize",- )+ with patch.object(DataWarehouseSavedQuery, "schedule_materialization"):+ for _ in range(2):+ response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}/materialize",+ )- assert response.status_code == 200+ assert response.status_code == 200- saved_query.refresh_from_db()- assert saved_query.is_materialized is True- assert saved_query.sync_frequency_interval == timedelta(hours=24)- # Schedule already exists, so should not unpause (unpause=False on second call)- mock_unpause.assert_not_called()- # But should still update the schedule- mock_sync.assert_called_once()+ saved_query = DataWarehouseSavedQuery.objects.get(id=saved_query_id)+ assert saved_query.is_materialized is True+ assert saved_query.sync_frequency_interval == timedelta(hours=24)def test_materialize_leaves_nothing_persisted_when_the_frequency_is_rejected(self):response = self.client.post(@@ -292,13 +253,7 @@ class TestSavedQuery(APIBaseTest):assert response.status_code == 201saved_query_id = response.data["id"]- with (- patch("products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"),- patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",- return_value=False,- ),- ):+ with patch.object(DataWarehouseSavedQuery, "schedule_materialization"):response = self.client.post(f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}/materialize",{"sync_frequency": "1hour"},@@ -705,65 +660,6 @@ class TestSavedQuery(APIBaseTest):assert response.status_code == 404- def test_update_sync_frequency_with_existing_schedule(self):- """Test that updating sync_frequency via PATCH only sets the interval"""- response = self.client.post(- f"/api/environments/{self.team.id}/warehouse_saved_queries/",- {- "name": "event_view",- "query": {- "kind": "HogQLQuery",- "query": "select event as event from events LIMIT 100",- },- },- )- self.assertEqual(response.status_code, 201)- saved_query = response.json()-- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",- {"sync_frequency": "24hour"},- )-- self.assertEqual(response.status_code, 200)-- # Verify the interval was set- updated_query = DataWarehouseSavedQuery.objects.get(id=saved_query["id"])- self.assertEqual(updated_query.sync_frequency_interval, timedelta(hours=24))-- def test_update_sync_frequency_to_never(self):- response = self.client.post(- f"/api/environments/{self.team.id}/warehouse_saved_queries/",- {- "name": "event_view",- "query": {- "kind": "HogQLQuery",- "query": "select event as event from events LIMIT 100",- },- },- )- self.assertEqual(response.status_code, 201)- saved_query = response.json()-- with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.saved_query_workflow_exists",- return_value=True,- ) as mock_workflow_exists,- patch(- "products.data_warehouse.backend.presentation.views.saved_query.pause_saved_query_schedule"- ) as mock_pause_saved_query_schedule,- ):- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",- {"sync_frequency": "never"},- )- self.assertEqual(response.status_code, 200)- saved_query_id = response.json()["id"]- saved_query = DataWarehouseSavedQuery.objects.get(id=saved_query_id)- mock_workflow_exists.assert_called_once_with(saved_query)- mock_pause_saved_query_schedule.assert_called_once_with(saved_query)-def _create_saved_query_for_frequency_tests(self, name: str = "event_view") -> dict:response = self.client.post(f"/api/environments/{self.team.id}/warehouse_saved_queries/",@@ -778,17 +674,16 @@ class TestSavedQuery(APIBaseTest):self.assertEqual(response.status_code, 201)return response.json()- def _v2_flag_only(self, key, *args, **kwargs):- return key == "data-modeling-backend-v2"-@parameterized.expand([- ("24hour", timedelta(hours=24)),- ("never", None),+ ("24hour", "24hour", timedelta(hours=24)),+ ("never", None, None),+ # Sub-15min cadences are deprecated for saved queries and clamped up to the "15min" floor.+ ("5min", "15min", timedelta(minutes=15)),])def test_update_sync_frequency_on_tiered_v2_writes_target_through(- self, sync_frequency: str, expected_target: timedelta | None+ self, sync_frequency: str, expected_frequency: str | None, expected_target: timedelta | None):from products.data_modeling.backend.facade.api import get_declared_target, set_declared_targetfrom products.data_modeling.backend.facade.models import Node@@ -799,10 +694,6 @@ class TestSavedQuery(APIBaseTest):reconcile_module = "products.data_modeling.backend.logic.schedule_reconcile"with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=self._v2_flag_only,- ),patch(f"{reconcile_module}.tiered_schedules_enabled", return_value=True),patch(f"{reconcile_module}.maybe_reconcile_dag") as reconcile,patch(@@ -817,7 +708,7 @@ class TestSavedQuery(APIBaseTest):self.assertEqual(response.status_code, 200, response.json())# the write response must echo the cadence it just stored: an agent that reads back null# concludes the update failed and retries it- self.assertEqual(response.json()["sync_frequency"], None if expected_target is None else sync_frequency)+ self.assertEqual(response.json()["sync_frequency"], expected_frequency)# the node target is the only store of frequency intent; the interval stays NULLupdated = DataWarehouseSavedQuery.objects.get(id=saved_query["id"])self.assertIsNone(updated.sync_frequency_interval)@@ -848,10 +739,6 @@ class TestSavedQuery(APIBaseTest):reconcile_module = "products.data_modeling.backend.logic.schedule_reconcile"with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=self._v2_flag_only,- ),patch(f"{reconcile_module}.tiered_schedules_enabled", return_value=True),patch(f"{reconcile_module}.maybe_reconcile_dag"),):@@ -876,10 +763,6 @@ class TestSavedQuery(APIBaseTest):reconcile_module = "products.data_modeling.backend.logic.schedule_reconcile"with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=self._v2_flag_only,- ),patch(f"{reconcile_module}.tiered_schedules_enabled", return_value=True),patch(f"{reconcile_module}.maybe_reconcile_dag"),patch("products.data_warehouse.backend.presentation.views.saved_query.saved_query_workflow_exists"),@@ -901,10 +784,6 @@ class TestSavedQuery(APIBaseTest):reconcile_module = "products.data_modeling.backend.logic.schedule_reconcile"with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=self._v2_flag_only,- ),patch(f"{reconcile_module}.tiered_schedules_enabled", return_value=True),patch(f"{reconcile_module}.apply_saved_query_frequency_target",@@ -925,10 +804,6 @@ class TestSavedQuery(APIBaseTest):saved_query = self._create_saved_query_for_frequency_tests()with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=self._v2_flag_only,- ),patch("products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",return_value=False,@@ -1004,23 +879,16 @@ class TestSavedQuery(APIBaseTest):@parameterized.expand([- ("v1", False, False, False),- ("v2_single_schedule", True, False, True),- ("v2_tiered", True, True, False),+ ("single_schedule", False, True),+ ("tiered", True, False),])- def test_sync_frequency_managed_by_dag_tracks_the_write_path(- self, _name: str, v2_enabled: bool, tiered: bool, expected: bool- ):+ def test_sync_frequency_managed_by_dag_tracks_the_write_path(self, _name: str, tiered: bool, expected: bool):# The frontend hides the cadence control on this flag. It must mean exactly what the# write path rejects, or the control disappears from teams that can in fact edit.saved_query = self._create_saved_query_for_frequency_tests()with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=lambda key, *args, **kwargs: v2_enabled and key == "data-modeling-backend-v2",- ),patch("products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",return_value=tiered,@@ -1059,16 +927,10 @@ class TestSavedQuery(APIBaseTest):set_declared_target(Node.objects.get(saved_query_id=consumer.json()["id"]), consumer_target)return upstream- def _read_frequency_bounds(self, saved_query_id: str, *, tiered: bool = True, v2: bool = True) -> dict:- with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=lambda key, *args, **kwargs: v2 and key == "data-modeling-backend-v2",- ),- patch(- "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",- return_value=tiered,- ),+ def _read_frequency_bounds(self, saved_query_id: str, *, tiered: bool = True) -> dict:+ with patch(+ "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",+ return_value=tiered,):response = self.client.get(f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}",@@ -1078,20 +940,19 @@ class TestSavedQuery(APIBaseTest):@parameterized.expand([- ("v1_team", False, False, "legacy"),- ("v2_single_schedule", True, False, "dag_schedule"),- ("v2_tiered", True, True, "tiered"),+ ("single_schedule", False, "dag_schedule"),+ ("tiered", True, "tiered"),])def test_bounds_are_offered_only_where_a_per_view_cadence_is_writable(- self, _name: str, v2: bool, tiered: bool, expected_mode: str+ self, _name: str, tiered: bool, expected_mode: str):# The picker renders from this payload. Offering options to a team whose writes the DAG# owns puts a control on screen that can only 400, which is the bug this field exists# to close; serving none to a tiered team hides a control that does work.saved_query = self._create_saved_query_for_frequency_tests()- bounds = self._read_frequency_bounds(saved_query["id"], tiered=tiered, v2=v2)+ bounds = self._read_frequency_bounds(saved_query["id"], tiered=tiered)self.assertEqual(bounds["frequency_mode"], expected_mode)self.assertEqual(bool(bounds["options"]), expected_mode == "tiered")@@ -1106,10 +967,6 @@ class TestSavedQuery(APIBaseTest):for option in options:with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=self._v2_flag_only,- ),patch("products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",return_value=True,@@ -1142,10 +999,6 @@ class TestSavedQuery(APIBaseTest):upstream = self._create_view_with_a_consumer(consumer_target=timedelta(hours=6))with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=self._v2_flag_only,- ),patch("products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",return_value=True,@@ -1183,30 +1036,6 @@ class TestSavedQuery(APIBaseTest):self.assertEqual(response.status_code, 201)return response.json()- @parameterized.expand(- [- ("15min", "15min", timedelta(minutes=15)),- ("6hour", "6hour", timedelta(hours=6)),- ("1hour", "1hour", timedelta(hours=1)),- ("30day", "30day", timedelta(days=30)),- # Sub-15min cadences are deprecated for saved queries and clamped up to the "15min" floor.- ("5min", "15min", timedelta(minutes=15)),- ("1min", "15min", timedelta(minutes=15)),- ]- )- def test_update_sync_frequency_round_trip(self, sent: str, expected_value: str, expected_interval: timedelta):- saved_query = self._create_saved_query()-- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",- {"sync_frequency": sent},- )- self.assertEqual(response.status_code, 200, response.content)- self.assertEqual(response.json()["sync_frequency"], expected_value)-- updated_query = DataWarehouseSavedQuery.objects.get(id=saved_query["id"])- self.assertEqual(updated_query.sync_frequency_interval, expected_interval)-def test_update_sync_frequency_rejects_invalid_value(self):saved_query = self._create_saved_query()@@ -2266,13 +2095,7 @@ class TestSavedQuery(APIBaseTest):created_by=self.user,)- with (- patch("products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"),- patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",- return_value=False,- ),- ):+ with patch.object(DataWarehouseSavedQuery, "schedule_materialization"):for action in ("materialize", "revert_materialization"):# First 5 requests should succeed (rate is 5/hour)for i in range(5):@@ -2317,12 +2140,7 @@ class TestMaterializeRequestBody(SimpleTestCase):assert "sync_frequency" in serializer.errors-class TestSavedQueryRunV2Aware(APIBaseTest):- """The run action branches on the saved query's schedule version: materialize the backing node- via the v2 workflow when its DAG is on a v2 schedule, otherwise trigger the v1 per-query- schedule (which only exists for v1 saved queries).- """-+class TestSavedQueryRun(APIBaseTest):def _make_saved_query_with_node(self, name: str) -> tuple[DataWarehouseSavedQuery, DAG, Node]:dag = DAG.objects.create(team=self.team, name=f"posthog_{self.team.id}")saved_query = DataWarehouseSavedQuery.objects.create(@@ -2338,14 +2156,9 @@ class TestSavedQueryRunV2Aware(APIBaseTest):)return saved_query, dag, node- @patch("products.data_warehouse.backend.presentation.views.saved_query.trigger_saved_query_schedule")@patch("products.data_modeling.backend.logic.node_materialization.sync_connect")- @patch("products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids")- def test_run_on_v2_schedule_materializes_node_without_v1_trigger(- self, mock_v2_dags, mock_sync_connect, mock_trigger- ):- saved_query, dag, _node = self._make_saved_query_with_node("v2_view")- mock_v2_dags.return_value = {str(dag.id)}+ def test_run_materializes_node(self, mock_sync_connect):+ saved_query, _dag, _node = self._make_saved_query_with_node("v2_view")mock_client = AsyncMock()mock_sync_connect.return_value = mock_client@@ -2354,22 +2167,14 @@ class TestSavedQueryRunV2Aware(APIBaseTest):)self.assertEqual(response.status_code, 200, response.content)- mock_trigger.assert_not_called()mock_client.start_workflow.assert_called_once()self.assertEqual(mock_client.start_workflow.call_args[0][0], "data-modeling-materialize-view")- @patch("products.data_warehouse.backend.presentation.views.saved_query.trigger_saved_query_schedule")@patch("products.data_modeling.backend.logic.node_materialization.sync_connect")- @patch("products.data_modeling.backend.logic.node_materialization.get_v2_saved_query_ids")- def test_run_on_v2_without_backing_node_does_not_fall_back_to_v1(- self, mock_v2_ids, mock_sync_connect, mock_trigger- ):- # v2 is confirmed but no backing node exists: nothing is materialized, and it must not fall- # back to the v1 schedule trigger, which a v2 saved query has no schedule for.+ def test_run_without_backing_node_reports_the_failure(self, mock_sync_connect):saved_query = DataWarehouseSavedQuery.objects.create(name="orphan_view", team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"})- mock_v2_ids.return_value = {saved_query.id}mock_client = AsyncMock()mock_sync_connect.return_value = mock_client@@ -2377,8 +2182,7 @@ class TestSavedQueryRunV2Aware(APIBaseTest):f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query.id}/run/",)- self.assertEqual(response.status_code, 200, response.content)- mock_trigger.assert_not_called()+ self.assertEqual(response.status_code, 400, response.content)mock_client.start_workflow.assert_not_called()@patch("products.data_modeling.backend.logic.node_materialization.sync_connect")@@ -2400,19 +2204,6 @@ class TestSavedQueryRunV2Aware(APIBaseTest):saved_query.refresh_from_db()self.assertTrue(saved_query.is_materialized)- @patch("products.data_warehouse.backend.presentation.views.saved_query.trigger_saved_query_schedule")- @patch("products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids")- def test_run_on_v1_triggers_saved_query_schedule(self, mock_v2_dags, mock_trigger):- saved_query, _dag, _node = self._make_saved_query_with_node("v1_view")- mock_v2_dags.return_value = set()-- response = self.client.post(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query.id}/run/",- )-- self.assertEqual(response.status_code, 200, response.content)- mock_trigger.assert_called_once()-@parameterized.expand([("v1", "019c4fca-ee53-0000-e7e4-fd76c23d5157-2026-08-13T04:30:00Z"),diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_access_control.py b/products/data_warehouse/backend/tests/api/test_saved_query_access_control.pyindex 5cbb319675da..9d3c917ccf4b 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query_access_control.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query_access_control.py@@ -412,20 +412,13 @@ class TestSyncFrequencyBoundsAccessControl(WarehouseAccessControlTestMixin):set_declared_target(self.consumer_node, timedelta(hours=6))def _tiered(self):- return (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=lambda key, *args, **kwargs: key == "data-modeling-backend-v2",- ),- patch(- "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",- return_value=True,- ),+ return patch(+ "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",+ return_value=True,)def _read_upstream(self) -> tuple[dict, str]:- v2, tiered = self._tiered()- with v2, tiered:+ with self._tiered():response = self.client.get(f"/api/environments/{self.team.pk}/warehouse_saved_queries/{self.upstream.id}/")self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)return response.json()["sync_frequency_bounds"], response.content.decode()@@ -467,8 +460,7 @@ class TestSyncFrequencyBoundsAccessControl(WarehouseAccessControlTestMixin):self._deny_the_consumer(self.editor_user)self.client.force_login(self.editor_user)- v2, tiered = self._tiered()- with v2, tiered, patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"):+ with self._tiered(), patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"):response = self.client.patch(f"/api/environments/{self.team.pk}/warehouse_saved_queries/{self.upstream.id}/",{"sync_frequency": "24hour"},@@ -483,8 +475,7 @@ class TestSyncFrequencyBoundsAccessControl(WarehouseAccessControlTestMixin):self._create_access_control(self.editor_user, access_level="editor")self.client.force_login(self.editor_user)- v2, tiered = self._tiered()- with v2, tiered, patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"):+ with self._tiered(), patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"):response = self.client.patch(f"/api/environments/{self.team.pk}/warehouse_saved_queries/{self.upstream.id}/",{"sync_frequency": "24hour"},@@ -562,10 +553,6 @@ class TestSyncFrequencyTableBlockerAccessControl(WarehouseAccessControlTestMixindef _read_view(self) -> tuple[dict, str]:with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=lambda key, *args, **kwargs: key == "data-modeling-backend-v2",- ),patch("products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",return_value=True,@@ -658,10 +645,6 @@ class TestSyncFrequencyDuplicateResourceAcrossDags(WarehouseAccessControlTestMixdef _read_view(self) -> dict:with (- patch(- "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",- side_effect=lambda key, *args, **kwargs: key == "data-modeling-backend-v2",- ),patch("products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",return_value=True,diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py b/products/data_warehouse/backend/tests/api/test_saved_query_incremental.pyindex 645a370ce9ed..7b564d5673ea 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py@@ -1,5 +1,5 @@from posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import AsyncMock, patchfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_warehouse.backend.presentation.views.saved_query import (@@ -139,13 +139,7 @@ class TestSavedQueryIncremental(APIBaseTest):saved_query.incremental_state = {"watermark": "2026-01-01T00:00:00+00:00", "definition_fingerprint": "abc"}saved_query.save(update_fields=["incremental_state"])- with (- patch("products.data_warehouse.backend.presentation.views.saved_query.trigger_saved_query_schedule"),- patch(- "products.data_modeling.backend.logic.node_materialization.is_saved_query_on_v2_schedule",- return_value=False,- ),- ):+ with patch("products.data_modeling.backend.logic.node_materialization.sync_connect", return_value=AsyncMock()):response = self.client.post(self._url(f"{saved_query.id}/run/"), {"full_refresh": True})assert response.status_code == 200, response.json()@@ -158,13 +152,7 @@ class TestSavedQueryIncremental(APIBaseTest):saved_query.incremental_state = {"watermark": "2026-01-01T00:00:00+00:00"}saved_query.save(update_fields=["incremental_state"])- with (- patch("products.data_warehouse.backend.presentation.views.saved_query.trigger_saved_query_schedule"),- patch(- "products.data_modeling.backend.logic.node_materialization.is_saved_query_on_v2_schedule",- return_value=False,- ),- ):+ with patch("products.data_modeling.backend.logic.node_materialization.sync_connect", return_value=AsyncMock()):response = self.client.post(self._url(f"{saved_query.id}/run/"), {})assert response.status_code == 200, response.json()diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.pyindex 7ac3f680afb8..a4c7d33c2686 100644--- a/products/endpoints/backend/tests/test_endpoint.py+++ b/products/endpoints/backend/tests/test_endpoint.py@@ -1290,6 +1290,12 @@ class TestMaterializationPreview(ClickhouseTestMixin, APIBaseTest):self.var_id_2: {"variableId": self.var_id_2, "code_name": "end_ts", "value": "2024-02-01"},},}+ v2_dag_ids_patcher = mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),+ )+ v2_dag_ids_patcher.start()+ self.addCleanup(v2_dag_ids_patcher.stop)def _create_endpoint_with_variables(self, name="range-endpoint"):from products.product_analytics.backend.facade.models import InsightVariablediff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.pyindex fcc32a019228..8a6bc1bec287 100644--- a/products/endpoints/backend/tests/test_endpoint_execution.py+++ b/products/endpoints/backend/tests/test_endpoint_execution.py@@ -61,14 +61,14 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):default_value="$pageview",)- # Mock sync_saved_query_workflow to avoid Temporal connection- self.sync_workflow_patcher = mock.patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"+ self.v2_dag_ids_patcher = mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),)- self.sync_workflow_patcher.start()+ self.v2_dag_ids_patcher.start()def tearDown(self):- self.sync_workflow_patcher.stop()+ self.v2_dag_ids_patcher.stop()super().tearDown()def _materialize_endpoint(self, endpoint, table_name: str | None = None):diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.pyindex 21c760a12ada..c8ef9cdb8afd 100644--- a/products/endpoints/backend/tests/test_endpoint_materialization.py+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py@@ -23,7 +23,7 @@ from posthog.constants import RETENTION_FIRST_EVER_OCCURRENCE, TREND_FILTER_TYPEfrom posthog.settings.temporal import DATA_MODELING_TASK_QUEUEfrom posthog.sync import database_sync_to_async-from products.data_modeling.backend.facade.api import UnsatisfiableFrequencyError+from products.data_modeling.backend.facade.api import UnsatisfiableFrequencyError, get_declared_targetfrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPathfrom products.data_modeling.backend.facade.models import DAG, DataModelingJob, DataWarehouseSavedQuery, Nodefrom products.data_warehouse.backend.facade.api import get_saved_query_schedule@@ -53,30 +53,26 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):"query": "SELECT event, distinct_id FROM events WHERE event = '$pageview' LIMIT 100",}# Mock Temporal-related functions to avoid connection errors- self.sync_workflow_patcher = mock.patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"- )- self.workflow_exists_patcher = mock.patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",- return_value=False,- )self.delete_schedule_patcher = mock.patch("products.data_warehouse.backend.logic.data_load.saved_query_service.delete_saved_query_schedule")# The DAG node exists by scheduling time, so the v2 lookup would hit Temporal for real.self.v2_dag_ids_patcher = mock.patch(- "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids", return_value=set()+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),+ )+ self.tiered_schedules_patcher = mock.patch(+ "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",+ return_value=True,)- self.mock_sync_workflow = self.sync_workflow_patcher.start()- self.mock_workflow_exists = self.workflow_exists_patcher.start()self.mock_delete_schedule = self.delete_schedule_patcher.start()self.mock_v2_dag_ids = self.v2_dag_ids_patcher.start()+ self.tiered_schedules_patcher.start()def tearDown(self):- self.sync_workflow_patcher.stop()- self.workflow_exists_patcher.stop()self.delete_schedule_patcher.stop()self.v2_dag_ids_patcher.stop()+ self.tiered_schedules_patcher.stop()super().tearDown()def test_enable_materialization_creates_saved_query(self):@@ -120,15 +116,8 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):self.assertEqual(saved_query.query, version.query)self.assertTrue(saved_query.is_materialized)self.assertEqual(saved_query.origin, DataWarehouseSavedQuery.Origin.ENDPOINT)-- # Verify sync_frequency_interval is set- self.assertEqual(saved_query.sync_frequency_interval, timedelta(hours=24))-- # Verify ModelPath was created- self.assertTrue(- DataWarehouseModelPath.objects.filter(team=self.team, saved_query=saved_query).exists(),- "DataWarehouseModelPath should be created for the saved_query",- )+ self.assertIsNone(saved_query.sync_frequency_interval)+ self.assertEqual(get_declared_target(Node.objects.get(saved_query=saved_query)), timedelta(hours=24))def test_create_with_materialization_enabled_schedules_saved_query(self):response = self.client.post(@@ -232,8 +221,7 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):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."""+ def test_data_freshness_updates_node_target(self):# Create and materialize an endpointendpoint = create_endpoint_with_version(name="test_sync_frequency",@@ -256,7 +244,9 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):version.refresh_from_db()saved_query = version.saved_queryassert saved_query is not None- self.assertEqual(saved_query.sync_frequency_interval, timedelta(hours=24))+ node = Node.objects.get(saved_query=saved_query)+ self.assertIsNone(saved_query.sync_frequency_interval)+ self.assertEqual(get_declared_target(node), timedelta(hours=24))# Update to 12-hour frequencyresponse = self.client.patch(@@ -270,9 +260,10 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)- # Verify sync_interval was updatedsaved_query.refresh_from_db()- self.assertEqual(saved_query.sync_frequency_interval, timedelta(hours=12))+ node.refresh_from_db()+ self.assertIsNone(saved_query.sync_frequency_interval)+ self.assertEqual(get_declared_target(node), timedelta(hours=12))# Update to 1-hour frequencyresponse = self.client.patch(@@ -286,9 +277,10 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)- # Verify sync_interval was updatedsaved_query.refresh_from_db()- self.assertEqual(saved_query.sync_frequency_interval, timedelta(hours=1))+ node.refresh_from_db()+ self.assertIsNone(saved_query.sync_frequency_interval)+ self.assertEqual(get_declared_target(node), timedelta(hours=1))# Update to 30-minute frequencyresponse = self.client.patch(@@ -303,7 +295,9 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)saved_query.refresh_from_db()- self.assertEqual(saved_query.sync_frequency_interval, timedelta(minutes=30))+ node.refresh_from_db()+ self.assertIsNone(saved_query.sync_frequency_interval)+ self.assertEqual(get_declared_target(node), timedelta(minutes=30))# Update to 15-minute frequency (the new floor)response = self.client.patch(@@ -318,7 +312,9 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)saved_query.refresh_from_db()- self.assertEqual(saved_query.sync_frequency_interval, timedelta(minutes=15))+ node.refresh_from_db()+ self.assertIsNone(saved_query.sync_frequency_interval)+ self.assertEqual(get_declared_target(node), timedelta(minutes=15))@parameterized.expand([diff --git a/products/endpoints/backend/tests/test_endpoint_versioning.py b/products/endpoints/backend/tests/test_endpoint_versioning.pyindex ef0baf82315a..12fdea65a8d8 100644--- a/products/endpoints/backend/tests/test_endpoint_versioning.py+++ b/products/endpoints/backend/tests/test_endpoint_versioning.py@@ -387,7 +387,9 @@ class TestEndpointVersioning(ClickhouseTestMixin, APIBaseTest):# Mock Temporal-related functions to avoid connection errorswith (- patch("products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"),+ patch(+ "products.data_modeling.backend.models.datawarehouse_saved_query.DataWarehouseSavedQuery.schedule_materialization"+ ),patch("products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",return_value=False,@@ -606,8 +608,9 @@ class TestEndpointVersioning(ClickhouseTestMixin, APIBaseTest):created_by=self.user,)- # Mock sync workflow- with patch("products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"):+ with patch(+ "products.data_modeling.backend.models.datawarehouse_saved_query.DataWarehouseSavedQuery.schedule_materialization"+ ):# Enable materialization on v1response = self.client.put(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",@@ -622,7 +625,9 @@ class TestEndpointVersioning(ClickhouseTestMixin, APIBaseTest):self.assertEqual(v1.saved_query.name, "versioned_mat_v1")# Create v2 by changing query- with patch("products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"):+ with patch(+ "products.data_modeling.backend.models.datawarehouse_saved_query.DataWarehouseSavedQuery.schedule_materialization"+ ):response = self.client.put(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",{"query": {"kind": "HogQLQuery", "query": "SELECT 2"}},@@ -673,7 +678,9 @@ class TestEndpointVersioning(ClickhouseTestMixin, APIBaseTest):self.assertFalse(v2.is_materialized)# Enable materialization on v1 specifically (not the current version)- with patch("products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"):+ with patch(+ "products.data_modeling.backend.models.datawarehouse_saved_query.DataWarehouseSavedQuery.schedule_materialization"+ ):response = self.client.put(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/?version=1",{"is_materialized": True, "data_freshness_seconds": 86400},diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.pyindex da71d33645db..3cadc949b106 100644--- a/products/endpoints/backend/tests/test_insight_response_parity.py+++ b/products/endpoints/backend/tests/test_insight_response_parity.py@@ -50,19 +50,14 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):flush_persons_and_events()- self.sync_workflow_patcher = mock.patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"+ self.v2_dag_ids_patcher = mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),)- self.workflow_exists_patcher = mock.patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",- return_value=False,- )- self.sync_workflow_patcher.start()- self.workflow_exists_patcher.start()+ self.v2_dag_ids_patcher.start()def tearDown(self):- self.sync_workflow_patcher.stop()- self.workflow_exists_patcher.stop()+ self.v2_dag_ids_patcher.stop()super().tearDown()def _materialize_endpoint(self, endpoint):