:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-modeling): wire per-node freshness targets into live scheduling (#67554)
Jovan Sakovic029094a4d694
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex f89a55240d11..8809d2222808 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -10,6 +10,8 @@ name on first access keeps this module off the ``django.setup()`` path._B = "products.data_modeling.backend."_LAZY = {+ "UnsatisfiableFrequencyError": "logic.freshness",+ "UnsupportedFrequencyTargetError": "logic.freshness","HasDependentsError": "logic.saved_query_dag_sync","delete_node_from_dag": "logic.saved_query_dag_sync","sync_saved_query_to_dag": "logic.saved_query_dag_sync",@@ -18,6 +20,9 @@ _LAZY = {"materialize_saved_query": "logic.node_materialization","saved_query_materialized_at": "logic.saved_query_freshness","start_node_materialization": "logic.node_materialization",+ "apply_saved_query_frequency_target": "logic.schedule_reconcile",+ "tiered_schedules_enabled": "logic.schedule_reconcile",+ "get_declared_target": "logic.node_frequency","compute_enrichment_hash": "logic.enrich_view_semantics","enrichment_gates_pass": "logic.enrich_view_semantics","enrich_view_semantics_sync": "logic.enrich_view_semantics",diff --git a/products/data_modeling/backend/logic/cohort_scheduling.py b/products/data_modeling/backend/logic/cohort_scheduling.pyindex 27ff7ce7a379..baafbe0b898d 100644--- a/products/data_modeling/backend/logic/cohort_scheduling.py+++ b/products/data_modeling/backend/logic/cohort_scheduling.py@@ -44,6 +44,11 @@ def dag_id_from_schedule_id(schedule_id: str) -> str:return schedule_id.rsplit(":", 1)[0]+def is_tier_schedule_id(schedule_id: str) -> bool:+ """Whether a schedule id is a cadence tier's (vs the pre-tier bare DAG id)."""+ return ":" in schedule_id++@dataclasses.dataclassclass ScheduleReconcilePlan:"""What to do to Temporal to make a DAG's schedules match its desired cadence tiers.diff --git a/products/data_modeling/backend/logic/freshness.py b/products/data_modeling/backend/logic/freshness.pyindex d88fe96c96d9..112271475510 100644--- a/products/data_modeling/backend/logic/freshness.py+++ b/products/data_modeling/backend/logic/freshness.py@@ -37,8 +37,6 @@ import dataclassesfrom collections import defaultdict, dequefrom datetime import timedelta-from products.data_modeling.backend.logic.graph_traversal import reachable-# A streamed source (e.g. the events table) is continuously fresh, so it imposes no# floor: a descendant may be as tight as the buckets allow. Imported sources instead# carry their real sync interval.@@ -146,46 +144,72 @@ def compute_effective_cadences(return resolved-def declared_target_bounds(- *,- node_id: str,- edges: list[tuple[str, str]],- declared_targets: dict[str, timedelta],- source_intervals: dict[str, timedelta],-) -> tuple[timedelta, timedelta | None]:- """Return (source_floor, consumer_ceiling) for a node's declarable target.+def all_source_floors(edges: list[tuple[str, str]], source_intervals: dict[str, timedelta]) -> dict[str, timedelta]:+ """Every node's source floor (slowest ancestor source interval) in one forward pass.- source_floor = the slowest interval among ancestor source nodes (STREAMING sources- add no floor). consumer_ceiling = the finest declared target among descendants, or- None if no descendant declares one. A floor coarser than the ceiling means the node- is unsatisfiable.+ One forward pass instead of a per-node ancestor walk, so a whole-graph check is O(N+E) rather+ than O(N^2). STREAMING for a node with no ancestor source. Nodes in a cycle are omitted+ (callers default them to STREAMING; the scheduling path rejects cycles upstream)."""children, parents = _adjacency(edges)+ all_ids = set(source_intervals) | {node for edge in edges for node in edge}+ in_degree = {node: len(parents.get(node, [])) for node in all_ids}+ queue = deque(node for node in all_ids if in_degree[node] == 0)+ floor: dict[str, timedelta] = {}+ while queue:+ node = queue.popleft()+ floor[node] = max([source_intervals.get(node, STREAMING), *(floor[parent] for parent in parents.get(node, []))])+ for child in children.get(node, []):+ in_degree[child] -= 1+ if in_degree[child] == 0:+ queue.append(child)+ return floor- ancestor_source_intervals = [- source_intervals[ancestor] for ancestor in reachable(node_id, parents) if ancestor in source_intervals- ]- source_floor = max(ancestor_source_intervals) if ancestor_source_intervals else STREAMING-- descendant_targets = [- declared_targets[descendant] for descendant in reachable(node_id, children) if descendant in declared_targets- ]- consumer_ceiling = min(descendant_targets) if descendant_targets else None- return source_floor, consumer_ceiling+def all_consumer_ceilings(+ edges: list[tuple[str, str]], declared_targets: dict[str, timedelta]+) -> dict[str, timedelta | None]:+ """Every node's consumer ceiling (finest declared target among strict descendants) in one+ reverse pass. None when no descendant declares a target. Cyclic nodes are omitted."""+ children, parents = _adjacency(edges)+ all_ids = set(declared_targets) | {node for edge in edges for node in edge}+ out_degree = {node: len(children.get(node, [])) for node in all_ids}+ queue = deque(node for node in all_ids if out_degree[node] == 0)+ ceiling: dict[str, timedelta | None] = {}+ while queue:+ node = queue.popleft()+ candidates = [declared_targets[child] for child in children.get(node, []) if child in declared_targets]+ candidates += [c for child in children.get(node, []) if (c := ceiling.get(child)) is not None]+ ceiling[node] = min(candidates) if candidates else None+ for parent in parents.get(node, []):+ out_degree[parent] -= 1+ if out_degree[parent] == 0:+ queue.append(parent)+ return ceilingdef nearest_schedulable_bucket_at_least(floor: timedelta) -> timedelta:"""The finest schedulable bucket no finer than `floor` — coarsen up to a runnable cadence.A source delivering every 45min means running finer than 1hour recomputes identical data, so- the meaningful cadence is the smallest bucket >= the floor. Falls back to the coarsest bucket- when the floor is coarser than every bucket (nothing coarser is schedulable).+ the meaningful cadence is the smallest bucket >= the floor. A floor coarser than every bucket+ (a rogue >30day source interval — the column is an unconstrained DurationField) clamps to the+ coarsest bucket: running more often than a source delivers only wastes a run, never breaks+ freshness. Mirrors nearest_schedulable_bucket_at_most's "fresher is always safe" fallback."""coarser_or_equal = [bucket for bucket in SCHEDULABLE_BUCKETS if bucket >= floor]return min(coarser_or_equal) if coarser_or_equal else max(SCHEDULABLE_BUCKETS)+def nearest_schedulable_bucket_at_most(cadence: timedelta) -> timedelta:+ """The coarsest schedulable bucket no coarser than `cadence` — round a non-bucket seed down to a+ finer bucket so "no older than `cadence`" stays honored (fresher is always safe). Falls back to+ the finest bucket for a sub-minute cadence, the finest anything can actually be scheduled at.+ """+ finer_or_equal = [bucket for bucket in SCHEDULABLE_BUCKETS if bucket <= cadence]+ return max(finer_or_equal) if finer_or_equal else min(SCHEDULABLE_BUCKETS)++@dataclasses.dataclassclass ClampedCadence:"""A node whose effective cadence was coarsened to what its ancestor sources can deliver."""@@ -206,19 +230,18 @@ def clamp_to_source_floor(source floor, returning the adjusted cadences and the list of changes.Clamping each node independently stays consistent because the floor spans the whole ancestor- cone (`declared_target_bounds`): a consumer that pulled an ancestor too fine shares that same+ cone (`all_source_floors`): a consumer that pulled an ancestor too fine shares that samesource and clamps to the same bucket. Streaming/best-effort sources have a zero floor and arenever clamped."""+ floors = all_source_floors(edges, source_intervals)clamped: dict[str, timedelta | None] = {}changes: list[ClampedCadence] = []for node_id, cadence in effective.items():if cadence is None:clamped[node_id] = Nonecontinue- source_floor, _consumer_ceiling = declared_target_bounds(- node_id=node_id, edges=edges, declared_targets={}, source_intervals=source_intervals- )+ source_floor = floors.get(node_id, STREAMING)if is_finer_than(cadence, source_floor):target = nearest_schedulable_bucket_at_least(source_floor)clamped[node_id] = target@@ -230,6 +253,20 @@ def clamp_to_source_floor(return clamped, changes+def normalize_seed_target(seed: timedelta, source_floor: timedelta) -> timedelta:+ """Round a raw v1 seed cadence to a schedulable, satisfiable declared target.++ Snap a non-bucket seed down to a finer bucket (fresher honors "no older than X"), then coarsen+ to the source floor if the source cannot deliver that fast. So a go-live backfill persists a+ target that equals what the scheduler will run, rather than an unschedulable (45min) or+ unsatisfiable (finer than the source) one that reconcile would have to clamp anyway.+ """+ bucket = nearest_schedulable_bucket_at_most(seed)+ if is_finer_than(bucket, source_floor):+ return nearest_schedulable_bucket_at_least(source_floor)+ return bucket++def validate_declared_target(*,node_id: str,@@ -244,9 +281,8 @@ def validate_declared_target(raise UnsupportedFrequencyTargetError(f"Requested freshness ({format_cadence(target)}) is not a schedulable cadence; pick one of: {supported}")- source_floor, consumer_ceiling = declared_target_bounds(- node_id=node_id, edges=edges, declared_targets=declared_targets, source_intervals=source_intervals- )+ source_floor = all_source_floors(edges, source_intervals).get(node_id, STREAMING)+ consumer_ceiling = all_consumer_ceilings(edges, declared_targets).get(node_id)if is_finer_than(target, source_floor):raise UnsatisfiableFrequencyError(f"Requested freshness ({format_cadence(target)}) is more frequent than this node's sources can deliver;"@@ -281,11 +317,12 @@ def find_invalid_targets(graph edits move floors. Runtime freshness stays correct (finest demand wins) — whatbreaks is declared == effective, so run this on any graph mutation and surface the result."""+ floors = all_source_floors(edges, source_intervals)+ ceilings = all_consumer_ceilings(edges, declared_targets)invalid: list[InvalidTarget] = []for node_id, declared in declared_targets.items():- source_floor, consumer_ceiling = declared_target_bounds(- node_id=node_id, edges=edges, declared_targets=declared_targets, source_intervals=source_intervals- )+ source_floor = floors.get(node_id, STREAMING)+ consumer_ceiling = ceilings.get(node_id)if is_finer_than(declared, source_floor) or (consumer_ceiling is not None and is_coarser_than(declared, consumer_ceiling)):diff --git a/products/data_modeling/backend/logic/node_frequency.py b/products/data_modeling/backend/logic/node_frequency.pyindex 6dc422896c45..15e8f6b725be 100644--- a/products/data_modeling/backend/logic/node_frequency.py+++ b/products/data_modeling/backend/logic/node_frequency.py@@ -11,9 +11,9 @@ import uuidimport dataclassesfrom datetime import timedelta-from django.db.models import Q+from django.db.models import Q, QuerySet-from products.data_modeling.backend.logic.freshness import STREAMING+from products.data_modeling.backend.logic.freshness import STREAMING, all_source_floors, normalize_seed_targetfrom products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.edge import Edgefrom products.data_modeling.backend.models.node import Node, NodeType@@ -165,6 +165,34 @@ def build_frequency_graph(dag: DAG) -> FrequencyGraph:)+def schedulable_nodes(dag: DAG) -> QuerySet[Node]:+ """The DAG's schedulable nodes: everything that carries a live saved query (not a source+ table, not a soft-deleted query). The one definition of "what gets a freshness target"."""+ return Node.objects.filter(dag=dag).exclude(type=NodeType.TABLE).exclude(saved_query__deleted=True)+++def persist_seed_targets(dag: DAG, default: timedelta | None = None) -> int:+ """Persist a seed target on every schedulable node lacking one; never overwrites. Each seed is+ normalized (see `normalize_seed_target`) so the persisted target equals what the scheduler will+ run. `default` is the operator escape hatch for scheduled DAGs with no interval metadata+ anywhere. Returns how many targets were written.+ """+ graph = build_frequency_graph(dag)+ floors = all_source_floors(graph.edges, graph.source_intervals)+ seeds = seed_targets(dag)+ written = 0+ for node in schedulable_nodes(dag):+ node_id = str(node.id)+ if get_declared_target(node) is not None:+ continue+ raw = seeds.get(node_id, default)+ if raw is None:+ continue+ set_declared_target(node, normalize_seed_target(raw, floors.get(node_id, STREAMING)))+ written += 1+ return written++def seed_targets(dag: DAG) -> dict[str, timedelta]:"""Derive a starting target per schedulable node from what the DAG already carries.@@ -175,12 +203,7 @@ def seed_targets(dag: DAG) -> dict[str, timedelta]:the preview overlays these in memory, and a backfill can persist them."""seeds: dict[str, timedelta] = {}- for node in (- Node.objects.filter(dag=dag)- .exclude(type=NodeType.TABLE)- .exclude(saved_query__deleted=True)- .select_related("saved_query")- ):+ for node in schedulable_nodes(dag).select_related("saved_query"):interval = Noneif node.saved_query is not None and node.saved_query.sync_frequency_interval is not None:interval = node.saved_query.sync_frequency_intervaldiff --git a/products/data_modeling/backend/logic/saved_query_dag_sync.py b/products/data_modeling/backend/logic/saved_query_dag_sync.pyindex 3111db9062ba..fcb1f5717773 100644--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py@@ -7,6 +7,7 @@ from posthog.hogql.database.models import SavedQuery as HogQLSavedQueryfrom posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTablefrom posthog.hogql.errors import QueryError+from products.data_modeling.backend.logic.schedule_reconcile import maybe_reconcile_dagfrom products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.edge import Edgefrom products.data_modeling.backend.models.modeling import UnknownParentError, get_parents_from_model_query@@ -108,6 +109,7 @@ def sync_saved_query_to_dag(extra_properties: dict | None = None, # TODO(andrew): remove this after backfilldag: DAG | None = None,allow_managed: bool = False,+ reconcile: bool = True,) -> Node | None:"""Create or update Node and Edges for a SavedQuery.@@ -184,6 +186,8 @@ def sync_saved_query_to_dag(# name is included in update_fields because Node.save() auto-syncs it from saved_querytarget.save(update_fields=["name", "type", "properties"])+ if reconcile:+ maybe_reconcile_dag(dag)return target@@ -220,9 +224,17 @@ def delete_node_from_dag(saved_query: "DataWarehouseSavedQuery") -> None:deps = get_dependent_saved_queries(saved_query)if deps:raise HasDependentsError("Node cannot be deleted because it has dependents")- Node.objects.filter(team=saved_query.team, saved_query=saved_query).delete()+ nodes = Node.objects.filter(team=saved_query.team, saved_query=saved_query).select_related("dag", "dag__team")+ dags = {node.dag for node in nodes if node.dag is not None}+ nodes.delete()+ for dag in dags:+ maybe_reconcile_dag(dag)def update_node_type(saved_query: "DataWarehouseSavedQuery", type: NodeType) -> None:"""Update a Node's type to MAT_VIEW when materialized."""- Node.objects.filter(team=saved_query.team, saved_query=saved_query).update(type=type)+ nodes = Node.objects.filter(team=saved_query.team, saved_query=saved_query).select_related("dag", "dag__team")+ dags = {node.dag for node in nodes if node.dag is not None}+ nodes.update(type=type)+ for dag in dags:+ maybe_reconcile_dag(dag)diff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.pyindex 60378005aeb5..4915c9dbe064 100644--- a/products/data_modeling/backend/logic/schedule_reconcile.py+++ b/products/data_modeling/backend/logic/schedule_reconcile.py@@ -14,8 +14,10 @@ import uuidimport dataclassesfrom collections.abc import Iterablefrom datetime import timedelta+from typing import TYPE_CHECKINGfrom django.conf import settings+from django.db import transactionimport structlogfrom asgiref.sync import async_to_sync@@ -23,21 +25,25 @@ from temporalio.client import (Client,Schedule,ScheduleActionStartWorkflow,+ ScheduleAlreadyRunningError,ScheduleListActionStartWorkflow,ScheduleOverlapPolicy,SchedulePolicy,ScheduleState,)from temporalio.common import RetryPolicy+from temporalio.service import RPCError, RPCStatusCode-from posthog.temporal.common.client import async_connect-from posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_update_schedule+from posthog.exceptions_capture import capture_exception+from posthog.ph_client import feature_enabled_or_false+from posthog.temporal.common.client import async_connect, sync_connect+from posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_update_schedule, delete_schedulefrom posthog.temporal.common.search_attributes import POSTHOG_DAG_ID_KEY-from posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputsfrom products.data_modeling.backend.logic.cohort_scheduling import (ScheduleReconcilePlan,bucket_into_cadence_tiers,+ is_tier_schedule_id,plan_schedule_reconciliation,tier_schedule_id,)@@ -50,22 +56,135 @@ from products.data_modeling.backend.logic.freshness import (compute_effective_cadences,find_invalid_targets,format_cadence,+ validate_declared_target,+)+from products.data_modeling.backend.logic.node_frequency import (+ FrequencyGraph,+ build_frequency_graph,+ persist_seed_targets,+ schedulable_nodes,+ seed_targets,+ set_declared_target,)-from products.data_modeling.backend.logic.node_frequency import build_frequency_graph, seed_targetsfrom products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.node import Nodefrom products.data_modeling.backend.schedule import (DATA_MODELING_EXECUTE_DAG_WORKFLOW,build_schedule_spec,dag_schedule_search_attributes,)+if TYPE_CHECKING:+ from posthog.models.team import Team++ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+logger = structlog.get_logger(__name__)+TIERED_SCHEDULES_FLAG = "data-modeling-tiered-schedules"+++def tiered_schedules_enabled(team: "Team") -> bool:+ """Whether per-node cadence tiers may drive this team's DAG schedules."""+ return feature_enabled_or_false(+ TIERED_SCHEDULES_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ send_feature_flag_events=False,+ )+++def maybe_reconcile_dag(dag: DAG) -> None:+ """Trigger hook for graph/target mutations: reconcile an already-tiered DAG, best-effort.++ Runs after commit so the reconcile reads the mutated graph, and never raises past the+ commit — the user's write already succeeded. Only DAGs already converted to cadence+ tiers are touched: legacy single-schedule DAGs are converted solely by the+ reconcile_freshness_schedules command, so a stray mutation can neither unschedule an+ unseeded DAG nor create tiers alongside live v1 schedules on an unmigrated team.+ """+ if not tiered_schedules_enabled(dag.team):+ return+ transaction.on_commit(lambda: _reconcile_dag_best_effort(dag))+++def _reconcile_dag_best_effort(dag: DAG) -> None:+ try:+ graph = build_frequency_graph(dag)+ _warn_on_invalid_targets(dag, graph)+ reconcile_dag_schedules(dag, require_tiered=True, graph=graph)+ except Exception as error:+ logger.exception("Freshness schedule reconcile failed", dag_id=str(dag.id), team_id=dag.team_id)+ capture_exception(error)+++def _warn_on_invalid_targets(dag: DAG, graph: FrequencyGraph | None = None) -> None:+ """Surface declared targets that drifted outside their bounds; never blocks the mutation."""+ if graph is None:+ graph = build_frequency_graph(dag)+ for invalid in find_invalid_targets(+ edges=graph.edges, declared_targets=graph.declared_targets, source_intervals=graph.source_intervals+ ):+ logger.warning(+ "Declared freshness target outside its legal range",+ dag_id=str(dag.id),+ node_id=invalid.node_id,+ declared=str(invalid.declared),+ source_floor=str(invalid.source_floor),+ consumer_ceiling=str(invalid.consumer_ceiling),+ )+++def apply_saved_query_frequency_target(+ saved_query: "DataWarehouseSavedQuery", target: timedelta | None, *, reconcile: bool = True+) -> int:+ """Write a frequency target through to the DAG node(s) carrying this saved query.++ On tiered v2 the node target is the only durable store of frequency intent. `target=None`+ clears it ("never" / revert) and must be a deliberate caller choice, never a default —+ otherwise a caller with no frequency opinion would silently wipe targets. Non-None targets+ are validated against the node's [floor, ceiling] bounds (raising for the caller to+ surface) before writing, then each affected DAG is queued for reconcile (skippable for+ callers batching many writes into one reconcile).++ Returns the number of nodes written (0 = no DAG node, so a non-None target was stored nowhere).+ """+ written = 0+ for node in Node.objects.filter(team=saved_query.team, saved_query=saved_query).select_related("dag", "dag__team"):+ if target is None:+ set_declared_target(node, None)+ else:+ graph = build_frequency_graph(node.dag)+ validate_declared_target(+ node_id=str(node.id),+ target=target,+ edges=graph.edges,+ declared_targets=graph.declared_targets,+ source_intervals=graph.source_intervals,+ )+ set_declared_target(node, target)+ written += 1+ if reconcile:+ maybe_reconcile_dag(node.dag)+ return written-def reconcile_dag_schedules(dag: DAG) -> None:- """Make Temporal's schedules for this DAG match its nodes' effective cadences."""++def reconcile_dag_schedules(dag: DAG, *, require_tiered: bool = False, graph: FrequencyGraph | None = None) -> None:+ """Make Temporal's schedules for this DAG match its nodes' effective cadences.++ Converging a covered DAG to zero schedules is refused only while it still has just legacy+ (non-tier) schedules — an empty tier set there almost always means unseeded targets. Once tier+ schedules exist, an empty tier set is a deliberate wind-down (last target reverted/cleared) and+ those tiers are torn down. With `require_tiered`, a DAG that has no tiered schedule yet (legacy+ single schedule or nothing) is left untouched.+ """team = dag.team- graph = build_frequency_graph(dag)+ if graph is None:+ graph = build_frequency_graph(dag)effective = compute_effective_cadences(nodes=graph.nodes, edges=graph.edges, declared_targets=graph.declared_targets)@@ -77,9 +196,73 @@ def reconcile_dag_schedules(dag: DAG) -> None:organization_id=str(team.organization_id),team_timezone=team.timezone,desired_tiers=desired_tiers,+ require_tiered=require_tiered,)+def convert_dag_to_tiers(dag: DAG, default: timedelta | None = None) -> int:+ """Seed per-node targets from the DAG's current cadence, then reconcile it to per-cadence tier+ schedules. The shared conversion step both entry points (the v1 migrate command and+ reconcile_freshness_schedules) run before clearing the now-redundant saved-query intervals.+ Returns how many targets were seeded.+ """+ seeded = persist_seed_targets(dag, default=default)+ reconcile_dag_schedules(dag)+ return seeded+++def null_saved_query_intervals(dag: DAG, *, only_saved_query_ids: Iterable[str] | None = None) -> int:+ """Clear `sync_frequency_interval` on the DAG's schedulable saved queries — on tiered teams the+ node target is authoritative, and a lingering interval could revive a v1 schedule. Pass+ `only_saved_query_ids` to skip queries whose v1 delete failed, so a re-run retries them.+ """+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery++ saved_query_ids = list(schedulable_nodes(dag).values_list("saved_query_id", flat=True))+ if only_saved_query_ids is not None:+ allowed = {str(sq_id) for sq_id in only_saved_query_ids}+ saved_query_ids = [sq_id for sq_id in saved_query_ids if str(sq_id) in allowed]+ return DataWarehouseSavedQuery.objects.filter(+ id__in=saved_query_ids, team_id=dag.team_id, sync_frequency_interval__isnull=False+ ).update(sync_frequency_interval=None)+++def delete_v1_saved_query_schedules(+ nodes: Iterable[Node], *, team_id: int, dag_id: str, temporal: Client | None = None+) -> set[str]:+ """Delete live v1 per-query Temporal schedules for the given nodes' saved queries.++ NOT_FOUND is treated as already-gone, so this is a safe no-op on a team that never had v1+ schedules — which lets the tiered conversion run on a v1 team directly instead of stacking+ tiers on top of live v1 schedules. Returns the saved-query ids whose delete genuinely failed,+ so the caller keeps their interval for a retry instead of orphaning a live schedule.+ """+ node_list = list(nodes)+ if temporal is None:+ temporal = sync_connect()+ deleted = 0+ failed: list[str] = []+ for node in node_list:+ saved_query = node.saved_query+ if saved_query is None:+ continue+ try:+ delete_schedule(temporal, schedule_id=str(saved_query.id))+ deleted += 1+ except RPCError as e:+ if e.status == RPCStatusCode.NOT_FOUND:+ logger.warning("v1 schedule already gone", saved_query_id=str(saved_query.id), team_id=team_id)+ else:+ failed.append(str(saved_query.id))+ logger.exception("Failed to delete v1 schedule", saved_query_id=str(saved_query.id), team_id=team_id)+ if failed:+ logger.warning(+ "Some v1 schedules could not be deleted", dag_id=dag_id, team_id=team_id, failed_schedule_ids=failed+ )+ logger.info("Swept v1 per-query schedules", dag_id=dag_id, team_id=team_id, deleted=deleted, total=len(node_list))+ return set(failed)++@dataclasses.dataclassclass DagSchedulePreview:"""What reconcile would do for a DAG, computed read-only (no schedule writes)."""@@ -137,6 +320,7 @@ async def _apply_reconciliation(organization_id: str,team_timezone: str,desired_tiers: dict[timedelta, set[str]],+ require_tiered: bool = False,) -> None:unsupported = sorted(interval for interval in desired_tiers if interval not in SCHEDULABLE_BUCKETS)if unsupported:@@ -147,6 +331,20 @@ async def _apply_reconciliation(temporal = await async_connect()existing_ids = await _list_execute_dag_schedule_ids(temporal, dag_id)+ if require_tiered and not any(is_tier_schedule_id(schedule_id) for schedule_id in existing_ids):+ logger.debug("DAG not converted to cadence tiers yet, skipping reconcile", dag_id=dag_id)+ return+ # An empty tier set on a DAG that still has only legacy (non-tier) schedules means an unseeded+ # conversion — protect it. Once tier schedules exist, empty desired is a deliberate wind-down+ # (last target reverted/cleared/"never"), so let the teardown sweep the stale tiers instead of+ # leaving them firing execute-dag on node_ids that no longer materialize.+ if not desired_tiers and existing_ids and not any(is_tier_schedule_id(schedule_id) for schedule_id in existing_ids):+ logger.warning(+ "Refusing to unschedule an unseeded DAG with only legacy schedules",+ dag_id=dag_id,+ existing_schedule_ids=sorted(existing_ids),+ )+ returnplan = plan_schedule_reconciliation(dag_id, desired_tiers, existing_ids)# Includes the schedule-type tag: get_v2_scheduled_dag_ids' unscoped sweep filters on@@ -160,8 +358,17 @@ async def _apply_reconciliation(try:for schedule_id, (interval, node_ids) in plan.to_create.items():schedule = _build_tier_schedule(dag_id, team_id, team_timezone, interval, node_ids)- await a_create_schedule(temporal, id=schedule_id, schedule=schedule, search_attributes=search_attributes)- created.append(schedule_id)+ try:+ await a_create_schedule(+ temporal, id=schedule_id, schedule=schedule, search_attributes=search_attributes+ )+ created.append(schedule_id)+ except ScheduleAlreadyRunningError:+ # A concurrent reconcile of the same DAG created this tier from the same graph;+ # converge onto it. It is deliberately NOT in `created`: it isn't ours to roll back.+ await a_update_schedule(+ temporal, id=schedule_id, schedule=schedule, search_attributes=search_attributes+ )for schedule_id, (interval, node_ids) in plan.to_update.items():schedule = _build_tier_schedule(dag_id, team_id, team_timezone, interval, node_ids)await a_update_schedule(temporal, id=schedule_id, schedule=schedule, search_attributes=search_attributes)@@ -173,8 +380,14 @@ async def _apply_reconciliation(logger.exception("Failed to roll back created schedule", schedule_id=schedule_id, dag_id=dag_id)raise+ # A failed delete leaves transient dual coverage (e.g. the legacy whole-DAG schedule alongside+ # tiers); the next reconcile sweeps it, so log and keep going rather than fail the converge.for schedule_id in plan.to_delete:- await a_delete_schedule(temporal, schedule_id=schedule_id)+ try:+ await a_delete_schedule(temporal, schedule_id=schedule_id)+ except Exception as error:+ logger.exception("Failed to delete stale schedule", schedule_id=schedule_id, dag_id=dag_id)+ capture_exception(error)async def _list_execute_dag_schedule_ids(temporal: Client, dag_id: str) -> set[str]:@@ -193,6 +406,10 @@ async def _list_execute_dag_schedule_ids(temporal: Client, dag_id: str) -> set[sdef _build_tier_schedule(dag_id: str, team_id: int, team_timezone: str, interval: timedelta, node_ids: Iterable[str]) -> Schedule:+ from posthog.temporal.data_modeling.workflows.execute_dag import ( # noqa: PLC0415 — the workflows package imports this product's models back; importing it lazily keeps this module importable from models code and temporal off django.setup()+ ExecuteDAGInputs,+ )+inputs = ExecuteDAGInputs(team_id=team_id, dag_id=dag_id, node_ids=sorted(node_ids), duckgres_only=False)spec = build_schedule_spec(entity_id=uuid.UUID(dag_id), interval=interval, team_timezone=team_timezone)return Schedule(diff --git a/products/data_modeling/backend/management/commands/migrate_teams_to_dag_schedules.py b/products/data_modeling/backend/management/commands/migrate_teams_to_dag_schedules.pyindex 39dbf1da5ed7..6a30948544e3 100644--- a/products/data_modeling/backend/management/commands/migrate_teams_to_dag_schedules.py+++ b/products/data_modeling/backend/management/commands/migrate_teams_to_dag_schedules.py@@ -1,13 +1,14 @@import timefrom dataclasses import asdictfrom datetime import timedelta+from itertools import groupbyfrom typing import castfrom django.conf import settingsfrom django.core.management.base import BaseCommand, CommandError+from django.db.models import QuerySetimport structlog-import temporaliofrom temporalio.client import (Schedule,ScheduleActionStartWorkflow,@@ -18,9 +19,15 @@ from temporalio.client import (from temporalio.common import RetryPolicyfrom posthog.temporal.common.client import sync_connect-from posthog.temporal.common.schedule import create_schedule, delete_schedule, schedule_exists+from posthog.temporal.common.schedule import create_schedule, schedule_existsfrom posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputs+from products.data_modeling.backend.logic.schedule_reconcile import (+ convert_dag_to_tiers,+ delete_v1_saved_query_schedules,+ null_saved_query_intervals,+ tiered_schedules_enabled,+)from products.data_modeling.backend.models import DAG, Nodefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.schedule import build_schedule_spec, dag_schedule_search_attributes@@ -76,40 +83,151 @@ class Command(BaseCommand):migrated = 0skipped = 0failed = 0- for i, dag in enumerate(dags.iterator()):- try:- result = self._migrate_dag(dag, dry_run=options["dry_run"])- if result:+ processed = 0+ dry_run = options["dry_run"]+ # Group DAGs by team so a saved query shared across two of a team's DAGs is seeded from+ # every DAG before any interval is nulled (see _migrate_team_tiered). DAGs are ordered by+ # team_id, which groupby requires to keep each team's rows contiguous.+ for _team_id, group in groupby(dags.iterator(), key=lambda dag: dag.team_id):+ team_dags = list(group)+ if tiered_schedules_enabled(team_dags[0].team):+ outcomes = self._migrate_team_tiered(team_dags, dry_run=dry_run)+ else:+ outcomes = [self._migrate_dag_legacy(dag, dry_run=dry_run) for dag in team_dags]+ for outcome in outcomes:+ if outcome == "migrated":migrated += 1- else:+ elif outcome == "skipped":skipped += 1- except Exception:- failed += 1- logger.exception("Failed to migrate DAG", dag_id=str(dag.id), team_id=dag.team_id)- logger.info(f"Progress: {i + 1}/{total} (migrated={migrated}, skipped={skipped}, failed={failed})")- if not options["dry_run"]:- time.sleep(BATCH_DELAY_SECONDS)- if options["dry_run"]:+ else:+ failed += 1+ processed += 1+ logger.info(f"Progress: {processed}/{total} (migrated={migrated}, skipped={skipped}, failed={failed})")+ if not dry_run:+ time.sleep(BATCH_DELAY_SECONDS)+ if dry_run:logger.info(f"Dry run complete. Would migrate: {migrated}, Would skip: {skipped}")else:logger.info(f"Done! Migrated: {migrated}, Skipped: {skipped}, Failed: {failed}")- def _migrate_dag(self, dag: DAG, *, dry_run: bool) -> bool:- """Migrate a single DAG to a v2 schedule.-- Returns True if migrated, False if skipped.- """- team = dag.team- # find all materialized nodes in this DAG that have saved queries with sync schedules- scheduled_nodes = Node.objects.filter(+ def _scheduled_nodes(self, dag: DAG) -> QuerySet[Node]:+ """Materialized nodes in this DAG whose saved query still carries a v1 sync interval."""+ return Node.objects.filter(dag=dag,saved_query__isnull=False,saved_query__sync_frequency_interval__isnull=False,saved_query__deleted=False,).select_related("saved_query")++ def _migrate_team_tiered(self, team_dags: list[DAG], *, dry_run: bool) -> list[str]:+ """Migrate all of a team's v1 DAGs straight to per-cadence-tier v2 schedules.++ Two-phase so it stays correct when a saved query has schedulable nodes in two of the team's+ DAGs: phase 1 seeds every DAG's node targets (never overwriting) while the shared+ sync_frequency_interval is still intact; phase 2 sweeps the v1 schedules and nulls the+ consumed intervals. Nulling per DAG mid-seed would leave the second DAG to re-seed from the+ 1-day DAG default — a silent freshness regression. Mirrors reconcile_freshness_schedules.++ Idempotent by construction: seeding never overwrites an existing target, the reconcile+ converges whatever schedules exist, and the v1 deletes tolerate NOT_FOUND.++ Returns one outcome ("migrated"/"skipped"/"failed") per DAG, in team_dags order.+ """+ outcomes: list[str] = []+ seeded: list[tuple[DAG, list[Node]]] = []+ # Phase 1 — seed every DAG before any interval is nulled.+ for dag in team_dags:+ try:+ nodes = list(self._scheduled_nodes(dag))+ if not nodes:+ logger.info("No scheduled nodes found, skipping", dag_id=str(dag.id), team_id=dag.team_id)+ outcomes.append("skipped")+ continue+ intervals = sorted(+ {str(node.saved_query.sync_frequency_interval) for node in nodes if node.saved_query is not None}+ )+ if dry_run:+ logger.info(+ "Would migrate DAG to cadence tiers",+ dag_id=str(dag.id),+ dag_name=dag.name,+ team_id=dag.team_id,+ intervals=intervals,+ scheduled_nodes=len(nodes),+ )+ outcomes.append("migrated")+ continue+ seeded_targets = convert_dag_to_tiers(dag)+ logger.info(+ "Migrated DAG to cadence tiers",+ dag_id=str(dag.id),+ team_id=dag.team_id,+ seeded_targets=seeded_targets,+ intervals=intervals,+ )+ seeded.append((dag, nodes))+ outcomes.append("migrated")+ except Exception:+ logger.exception("Failed to migrate DAG", dag_id=str(dag.id), team_id=dag.team_id)+ outcomes.append("failed")+ if dry_run or not seeded:+ return outcomes+ # Phase 2 — every DAG is now seeded, so sweeping v1 schedules and nulling the consumed+ # intervals can no longer strand another DAG's seed. Isolate the connect so a Temporal+ # outage skips this team's sweep (idempotent, retried on re-run) instead of aborting the+ # whole fleet run and leaving every later team unprocessed.+ try:+ temporal = sync_connect()+ except Exception:+ logger.exception(+ "Failed to connect to Temporal for v1 sweep; leaving it for a re-run",+ team_id=team_dags[0].team_id,+ )+ return outcomes+ for dag, nodes in seeded:+ try:+ failed_schedule_ids = delete_v1_saved_query_schedules(+ nodes, team_id=dag.team_id, dag_id=str(dag.id), temporal=temporal+ )+ # Null intervals only for queries whose v1 schedule actually went away: a failed+ # delete keeps its interval so a re-run retries it.+ deleted_sq_ids = [+ str(node.saved_query_id)+ for node in nodes+ if node.saved_query_id is not None and str(node.saved_query_id) not in failed_schedule_ids+ ]+ cleared = null_saved_query_intervals(dag, only_saved_query_ids=deleted_sq_ids)+ logger.info(+ "Cleared sync_frequency_interval on saved queries",+ dag_id=str(dag.id),+ team_id=dag.team_id,+ count=cleared,+ )+ except Exception:+ logger.exception(+ "Failed to sweep v1 schedules after tier conversion",+ dag_id=str(dag.id),+ team_id=dag.team_id,+ )+ return outcomes++ def _migrate_dag_legacy(self, dag: DAG, *, dry_run: bool) -> str:+ """Migrate one DAG to a single per-DAG v2 schedule (pre-tiers path, flag off).++ Returns "migrated", "skipped", or "failed".+ """+ try:+ return self._do_migrate_dag_legacy(dag, dry_run=dry_run)+ except Exception:+ logger.exception("Failed to migrate DAG", dag_id=str(dag.id), team_id=dag.team_id)+ return "failed"++ def _do_migrate_dag_legacy(self, dag: DAG, *, dry_run: bool) -> str:+ team = dag.team+ scheduled_nodes = self._scheduled_nodes(dag)if not scheduled_nodes.exists():logger.info("No scheduled nodes found, skipping", dag_id=str(dag.id), team_id=team.pk)- return False+ return "skipped"# check that all scheduled saved queries share the same sync frequencydistinct_intervals = scheduled_nodes.values_list("saved_query__sync_frequency_interval", flat=True).distinct()intervals = list(distinct_intervals)@@ -120,7 +238,7 @@ class Command(BaseCommand):team_id=team.pk,intervals=[str(i) for i in intervals],)- return False+ return "skipped"interval = cast(timedelta, intervals[0])if dry_run:logger.info(@@ -131,7 +249,7 @@ class Command(BaseCommand):interval=str(interval),scheduled_nodes=scheduled_nodes.count(),)- return True+ return "migrated"# create the v2 DAG scheduletemporal = sync_connect()schedule_id = str(dag.id)@@ -184,44 +302,7 @@ class Command(BaseCommand):dag.sync_frequency_interval = intervaldag.save(update_fields=["name", "sync_frequency_interval"])logger.info("Renamed DAG", dag_id=str(dag.id), team_id=team.pk)- # delete old per-node schedules- deleted_count = 0- failed_schedule_ids: list[str] = []- for node in scheduled_nodes:- saved_query = node.saved_query- if saved_query is None:- continue- try:- delete_schedule(temporal, schedule_id=str(saved_query.id))- deleted_count += 1- except temporalio.service.RPCError as e:- if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:- logger.warning(- "Old schedule not found (already deleted?)",- saved_query_id=str(saved_query.id),- team_id=team.pk,- )- else:- failed_schedule_ids.append(str(saved_query.id))- logger.exception(- "Failed to delete old schedule",- saved_query_id=str(saved_query.id),- team_id=team.pk,- )- if failed_schedule_ids:- logger.warning(- "Some old schedules could not be deleted",- dag_id=str(dag.id),- team_id=team.pk,- failed_schedule_ids=failed_schedule_ids,- )- logger.info(- "Deleted old per-node schedules",- dag_id=str(dag.id),- team_id=team.pk,- deleted=deleted_count,- total=scheduled_nodes.count(),- )+ delete_v1_saved_query_schedules(scheduled_nodes, team_id=team.pk, dag_id=str(dag.id), temporal=temporal)# null out sync_frequency_interval on migrated saved queries so v1 schedules are not re-createdmigrated_sq_ids = [node.saved_query_id for node in scheduled_nodes if node.saved_query_id is not None]DataWarehouseSavedQuery.objects.filter(id__in=migrated_sq_ids).update(sync_frequency_interval=None)@@ -231,4 +312,4 @@ class Command(BaseCommand):team_id=team.pk,count=len(migrated_sq_ids),)- return True+ return "migrated"diff --git a/products/data_modeling/backend/management/commands/reconcile_freshness_schedules.py b/products/data_modeling/backend/management/commands/reconcile_freshness_schedules.pynew file mode 100644index 000000000000..eaa553749672--- /dev/null+++ b/products/data_modeling/backend/management/commands/reconcile_freshness_schedules.py@@ -0,0 +1,103 @@+import uuid+from datetime import timedelta++from django.core.management import call_command+from django.core.management.base import BaseCommand, CommandError++import structlog++from posthog.models.team import Team++from products.data_modeling.backend.logic.node_frequency import schedulable_nodes+from products.data_modeling.backend.logic.schedule_reconcile import (+ convert_dag_to_tiers,+ delete_v1_saved_query_schedules,+ null_saved_query_intervals,+ tiered_schedules_enabled,+)+from products.data_modeling.backend.models.dag import DAG++logger = structlog.get_logger(__name__)+++class Command(BaseCommand):+ help = (+ "Convert a team's DAGs to per-cadence-tier schedules: persist a freshness target on every "+ "schedulable node lacking one (seeded from its current cadence, never overwriting), then "+ "reconcile Temporal so one execute-dag schedule exists per tier — sweeping the legacy "+ "single per-DAG schedule and any v1 per-query schedules, so it is safe on a v1 team "+ "directly. Saved-query sync_frequency_intervals are nulled once targets "+ "are persisted (the node target becomes the only store of frequency intent). Caveat: "+ "re-running the conversion re-seeds a node whose target was explicitly cleared ('never') "+ "from the DAG's interval."+ )++ def add_arguments(self, parser):+ parser.add_argument("--team-id", type=int, required=True)+ parser.add_argument("--dag-id", type=str, default=None, help="Limit to one DAG (default: all of the team's)")+ parser.add_argument(+ "--default-interval-seconds",+ type=int,+ default=None,+ help="Target for nodes with no seedable cadence anywhere (must be a supported bucket)",+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ default=False,+ help="Delegate to preview_freshness_schedules --seed; writes nothing",+ )++ def handle(self, *args, **options):+ team = Team.objects.filter(id=options["team_id"]).first()+ if team is None:+ raise CommandError(f"No team with id {options['team_id']}")++ if options["dry_run"]:+ if options["default_interval_seconds"] is not None:+ raise CommandError(+ "--default-interval-seconds has no effect under --dry-run: the preview does not seed "+ "defaults, so it would report the very nodes the real run schedules as unscheduled"+ )+ preview_args = ["--team-id", str(team.pk), "--seed"]+ if options["dag_id"]:+ preview_args += ["--dag-id", options["dag_id"]]+ call_command("preview_freshness_schedules", *preview_args, stdout=self.stdout)+ return++ if not tiered_schedules_enabled(team):+ raise CommandError(+ f"Team {team.pk} is not on the tiered-schedules flag; converting it would create "+ "tiers that no mutation trigger maintains"+ )++ dags = DAG.objects.filter(team_id=team.pk)+ if options["dag_id"]:+ try:+ dags = dags.filter(id=uuid.UUID(options["dag_id"]))+ except ValueError:+ raise CommandError(f"--dag-id must be a UUID, got {options['dag_id']!r}")+ dag_list = list(dags)+ if not dag_list:+ raise CommandError("No matching DAGs")++ default = (+ timedelta(seconds=options["default_interval_seconds"])+ if options["default_interval_seconds"] is not None+ else None+ )+ # Seed every DAG before touching intervals: a query in two DAGs seeds from the shared+ # interval, so sweeping/nulling mid-loop would corrupt the other DAG's seed.+ seeded_by_dag = [(dag, convert_dag_to_tiers(dag, default=default)) for dag in dag_list]+ for dag, seeded in seeded_by_dag:+ nodes = list(schedulable_nodes(dag).select_related("saved_query"))+ sq_ids = [str(node.saved_query_id) for node in nodes if node.saved_query_id is not None]+ # Sweep any legacy v1 per-query schedules (no-op on a v2 team); null only the intervals+ # whose v1 schedule is gone, so a failed delete keeps its interval for a re-run.+ failed = delete_v1_saved_query_schedules(nodes, team_id=dag.team_id, dag_id=str(dag.id))+ swept = [sq_id for sq_id in sq_ids if sq_id not in failed]+ cleared = null_saved_query_intervals(dag, only_saved_query_ids=swept)+ self.stdout.write(+ f"DAG {dag.name} ({dag.id}): seeded {seeded} target(s), reconciled, "+ f"swept {len(swept)} v1 schedule(s), cleared {cleared} interval(s)"+ )diff --git a/products/data_modeling/backend/models/datawarehouse_managed_viewset.py b/products/data_modeling/backend/models/datawarehouse_managed_viewset.pyindex 93254f76ede0..a69ffabfe007 100644--- a/products/data_modeling/backend/models/datawarehouse_managed_viewset.py+++ b/products/data_modeling/backend/models/datawarehouse_managed_viewset.py@@ -21,7 +21,6 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel, sane_reprfrom products.data_modeling.backend.facade.managed_viewset_hooks import get_expected_views_provider-from products.data_modeling.backend.logic.saved_query_dag_sync import sync_saved_query_to_dagfrom products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.node import Node@@ -74,6 +73,9 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModDeletes views that are no longer referenced.Materializes views by default."""+ # Deferred: schedule_reconcile pulls in temporalio; a module-level import would drag it onto django.setup()+ from products.data_modeling.backend.logic.saved_query_dag_sync import sync_saved_query_to_dag # noqa: PLC0415+ from products.data_modeling.backend.logic.schedule_reconcile import maybe_reconcile_dag # noqa: PLC0415provider = get_expected_views_provider(self.kind)if provider is None:@@ -197,7 +199,8 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModmanaged_dag = DAG.get_or_create_revenue_analytics(self.team)for saved_query in saved_queries_to_schedule:try:- sync_saved_query_to_dag(saved_query, dag=managed_dag, allow_managed=True)+ # reconcile once after both loops, not once per view+ sync_saved_query_to_dag(saved_query, dag=managed_dag, allow_managed=True, reconcile=False)# Drop any stale node left in another DAG (e.g. a legacy Default-DAG placement),# unless something there still depends on it (don't orphan a dependent).for stale in Node.objects.filter(team=self.team, saved_query=saved_query).exclude(dag=managed_dag):@@ -214,7 +217,7 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModfor saved_query in saved_queries_to_schedule:try:- saved_query.schedule_materialization()+ saved_query.schedule_materialization(reconcile=False)except Exception as e:capture_exception(e, {"managed_viewset_id": self.id, "view_name": saved_query.name})logger.warning(@@ -224,6 +227,9 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModerror=str(e),)+ if saved_queries_to_schedule:+ maybe_reconcile_dag(managed_dag)+views_deleted = 0for orphaned_view in orphaned_views_to_revert:try:diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 7782ab3f66d5..3a6488e56be8 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -181,7 +181,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,else:DataWarehouseModelPath.objects.update_from_saved_query(self)- def schedule_materialization(self, unpause: bool = False):+ def schedule_materialization(self, unpause: bool = False, reconcile: bool = True):"""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.@@ -189,6 +189,14 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,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,+ UnsupportedFrequencyTargetError,+ )+ from products.data_modeling.backend.logic.schedule_reconcile import (+ apply_saved_query_frequency_target,+ tiered_schedules_enabled,+ )from products.data_modeling.backend.schedule import get_v2_saved_query_idsfrom products.data_warehouse.backend.facade.api import (saved_query_workflow_exists,@@ -198,11 +206,19 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,try:# If this query's DAG already runs on a v2 schedule, that schedule materializes it. Never- # create or revive a per-query v1 schedule, and clear any lingering frequency that would- # cause one to be recreated. 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.+ # 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.if self.id in get_v2_saved_query_ids([self.id]):+ # 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 with+ # no interval carries no frequency opinion and must not touch existing targets.+ if tiered_schedules_enabled(self.team) and self.sync_frequency_interval is not None:+ apply_saved_query_frequency_target(self, self.sync_frequency_interval, reconcile=reconcile)+ # 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.if self.sync_frequency_interval is not None:self.sync_frequency_interval = Noneself.save(update_fields=["sync_frequency_interval"])@@ -214,6 +230,10 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,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.+ raiseexcept Exception as e:capture_exception(e, {"saved_query_id": self.id, "saved_query_name": self.name})logger.exception(@@ -229,6 +249,10 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,self.save(update_fields=["is_materialized"])def revert_materialization(self):+ from products.data_modeling.backend.logic.schedule_reconcile import (+ apply_saved_query_frequency_target,+ tiered_schedules_enabled,+ )from products.data_modeling.backend.models.modeling import DataWarehouseModelPathfrom products.data_warehouse.backend.facade.api import delete_saved_query_schedule@@ -253,6 +277,20 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,if should_delete_saved_query_schedule:delete_saved_query_schedule(self)+ # A reverted matview must also leave its cadence tier, or it would keep being+ # materialized on tiered v2. Best-effort like the schedule delete above — the+ # revert itself already succeeded.+ try:+ if tiered_schedules_enabled(self.team):+ apply_saved_query_frequency_target(self, None)+ except Exception as e:+ capture_exception(e, {"saved_query_id": self.id, "saved_query_name": self.name})+ logger.exception(+ "failed_to_clear_frequency_target_on_revert",+ team_id=self.team_id,+ saved_query_id=str(self.id),+ )+def soft_delete(self):self.deleted = Trueself.deleted_at = datetime.now()diff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex 1956288f8a67..e95a5a0318a4 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -24,6 +24,7 @@ from posthog.temporal.common.client import sync_connectfrom posthog.temporal.data_modeling.run_workflow import RunWorkflowInputs, Selectorfrom posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputs+from products.data_modeling.backend.facade.api import get_declared_targetfrom products.data_modeling.backend.facade.models import DAG, Edge, Node, NodeTypefrom products.warehouse_sources.backend.facade.models import sync_frequency_interval_to_sync_frequency@@ -90,6 +91,11 @@ class NodeSerializer(serializers.ModelSerializer):return node.properties.get("user", {}).get("tag")def get_sync_interval(self, node: Node) -> str | None:+ # The node's freshness target is authoritative on tiered v2 teams (where the saved+ # query's interval is NULL); the saved-query interval covers v1 teams.+ target = get_declared_target(node)+ if target is not None:+ return sync_frequency_interval_to_sync_frequency(target)if node.saved_query:return sync_frequency_interval_to_sync_frequency(node.saved_query.sync_frequency_interval)return Nonediff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.pyindex 1aec6cb8a92f..51dac2bd8320 100644--- a/products/data_modeling/backend/schedule.py+++ b/products/data_modeling/backend/schedule.py@@ -29,7 +29,7 @@ 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 import Node+from products.data_modeling.backend.models.node import Nodeif TYPE_CHECKING:from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuerydiff --git a/products/data_modeling/backend/test/helpers.py b/products/data_modeling/backend/test/helpers.pynew file mode 100644index 000000000000..3f285e8a5396--- /dev/null+++ b/products/data_modeling/backend/test/helpers.py@@ -0,0 +1,75 @@+from datetime import timedelta++from unittest import mock++from temporalio.client import ScheduleListActionStartWorkflow++from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.node import Node, NodeType+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+++def table_node(team, dag: DAG, name: str, properties: dict) -> Node:+ return Node.objects.create(team=team, dag=dag, name=name, type=NodeType.TABLE, properties=properties)+++def saved_query_node(team, dag: DAG, name: str, node_type: str) -> Node:+ saved_query = DataWarehouseSavedQuery.objects.create(+ name=name, team=team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ )+ return Node.objects.create(team=team, dag=dag, saved_query=saved_query, type=node_type)+++def warehouse_source_node(+ team,+ dag: DAG,+ *,+ sync_frequency_interval: timedelta | None,+ should_sync: bool = True,+ with_schema: bool = True,+) -> Node:+ table = DataWarehouseTable.objects.create(name="stripe_charges", team=team)+ if with_schema:+ source = ExternalDataSource.objects.create(+ team=team,+ source_id="source_id",+ connection_id="connection_id",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.STRIPE,+ prefix="posthog_test_",+ )+ ExternalDataSchema.objects.create(+ name="stripe_charges",+ team=team,+ source=source,+ table=table,+ sync_frequency_interval=sync_frequency_interval,+ should_sync=should_sync,+ )+ return table_node(team, dag, "stripe_charges", {"origin": "warehouse", "warehouse_table_id": str(table.id)})+++def temporal_listing(schedule_ids):+ """A mocked Temporal client whose list_schedules yields one execute-dag listing per id."""++ def _listing(schedule_id):+ action = mock.Mock(spec=ScheduleListActionStartWorkflow, workflow="data-modeling-execute-dag")+ return mock.Mock(id=schedule_id, schedule=mock.Mock(action=action))++ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ for schedule_id in schedule_ids:+ yield _listing(schedule_id)++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules+ return temporal+++def no_existing_schedules():+ """A mocked Temporal client that reports no existing schedules."""+ return temporal_listing([])diff --git a/products/data_modeling/backend/test/test_freshness.py b/products/data_modeling/backend/test/test_freshness.pyindex 74dbc61482f3..2d11dbbeb788 100644--- a/products/data_modeling/backend/test/test_freshness.py+++ b/products/data_modeling/backend/test/test_freshness.py@@ -10,19 +10,24 @@ from products.data_modeling.backend.logic.freshness import (InvalidTarget,UnsatisfiableFrequencyError,UnsupportedFrequencyTargetError,+ all_consumer_ceilings,+ all_source_floors,clamp_to_source_floor,compute_effective_cadences,- declared_target_bounds,find_invalid_targets,+ normalize_seed_target,validate_declared_target,)M5 = timedelta(minutes=5)M15 = timedelta(minutes=15)+M30 = timedelta(minutes=30)M45 = timedelta(minutes=45)H1 = timedelta(hours=1)H6 = timedelta(hours=6)DAY = timedelta(days=1)+DAY30 = timedelta(days=30)+DAY45 = timedelta(days=45)class TestComputeEffectiveCadences(TestCase):@@ -81,56 +86,6 @@ class TestComputeEffectiveCadences(TestCase):compute_effective_cadences(nodes={"a", "b"}, edges=[("a", "b"), ("b", "a")], declared_targets={"a": H1})-class TestFrequencyTargetBounds(TestCase):- @parameterized.expand(- [- # streamed source (events) imposes no floor -> a 15min endpoint is allowed- (- "streamed_source_no_floor",- "ep",- [("src", "ep")],- {"ep": M15},- {"src": STREAMING},- (STREAMING, None),- ),- # imported source refreshing every 6h floors an intermediate node at 6h- (- "imported_source_floors",- "a",- [("src", "a"), ("a", "ep")],- {"ep": H1},- {"src": H6},- (H6, H1),- ),- # ceiling comes from the tightest descendant demand- (- "ceiling_from_tightest_descendant",- "a",- [("src", "a"), ("a", "epA"), ("a", "epB")],- {"epA": H1, "epB": M15},- {"src": STREAMING},- (STREAMING, M15),- ),- # floor above ceiling: no legal target exists (unsatisfiable)- (- "unsatisfiable_floor_above_ceiling",- "a",- [("src", "a"), ("a", "ep")],- {"ep": M15},- {"src": H6},- (H6, M15),- ),- ]- )- def test_bounds(self, _name, node_id, edges, targets, source_intervals, expected):- self.assertEqual(- declared_target_bounds(- node_id=node_id, edges=edges, declared_targets=targets, source_intervals=source_intervals- ),- expected,- )--class TestValidateFrequencyTarget(TestCase):@parameterized.expand([@@ -239,6 +194,9 @@ class TestClampToSourceFloor(TestCase):("finer_than_floor", {"a": M15}, {"src": H6}, {"a": H6}, H6),# floor is not a bucket (45min) -> clamp up to the nearest bucket (1h), never finer("non_bucket_floor_rounds_up", {"a": M15}, {"src": M45}, {"a": H1}, H1),+ # a rogue source floor coarser than every bucket clamps to the coarsest (30day),+ # never crashes: the interval column is an unconstrained DurationField+ ("floor_beyond_coarsest_clamps_to_coarsest", {"a": M15}, {"src": DAY45}, {"a": DAY30}, DAY30),# already at the floor -> untouched("at_floor", {"a": H6}, {"src": H6}, {"a": H6}, None),# coarser than the floor -> untouched@@ -260,3 +218,50 @@ class TestClampToSourceFloor(TestCase):self.assertEqual(changes[0].demanded, effective["a"])self.assertEqual(changes[0].source_floor, source_intervals["src"])self.assertEqual(changes[0].clamped_to, expected_clamped_to)+++class TestNormalizeSeedTarget(TestCase):+ @parameterized.expand(+ [+ # already a schedulable bucket within bounds -> unchanged+ ("bucket_within_bounds", M15, STREAMING, M15),+ # non-bucket seed snaps down to the nearest finer bucket (fresher is safe)+ ("non_bucket_snaps_down", M45, STREAMING, M30),+ # a bucket finer than the source floor coarsens up to the floor+ ("finer_than_floor_coarsens", M15, H1, H1),+ # non-bucket over a slow source: snap down then coarsen to the floor+ ("snaps_then_coarsens_to_floor", M45, H6, H6),+ # already coarser than the floor -> left alone+ ("coarser_than_floor_stays", DAY, H6, DAY),+ ]+ )+ def test_normalize(self, _name, seed, source_floor, expected):+ self.assertEqual(normalize_seed_target(seed, source_floor), expected)+++class TestBatchBounds(TestCase):+ @parameterized.expand(+ [+ # chain src->a->b: the 6h source floors every descendant+ ("chain_floors_descendants", [("src", "a"), ("a", "b")], {"src": H6}, "b", H6),+ # fan-in of two sources: the node inherits the slowest (daily)+ ("fan_in_takes_slowest_source", [("srcA", "m"), ("srcB", "m")], {"srcA": H6, "srcB": DAY}, "m", DAY),+ # no ancestor source -> no floor+ ("no_source_is_streaming", [("a", "b")], {}, "b", STREAMING),+ ]+ )+ def test_source_floors(self, _name, edges, source_intervals, node_id, expected):+ self.assertEqual(all_source_floors(edges, source_intervals).get(node_id, STREAMING), expected)++ @parameterized.expand(+ [+ # a takes the tightest of its two consumers+ ("tightest_consumer", [("a", "epA"), ("a", "epB")], {"epA": H1, "epB": M15}, "a", M15),+ # transitive: demand propagates up past an untargeted intermediate+ ("transitive_demand", [("a", "b"), ("b", "c")], {"c": H1}, "a", H1),+ # no descendant declares a target -> no ceiling+ ("no_descendant_target", [("a", "b")], {}, "a", None),+ ]+ )+ def test_consumer_ceilings(self, _name, edges, declared_targets, node_id, expected):+ self.assertEqual(all_consumer_ceilings(edges, declared_targets).get(node_id), expected)diff --git a/products/data_modeling/backend/test/test_migrate_teams_to_dag_schedules.py b/products/data_modeling/backend/test/test_migrate_teams_to_dag_schedules.pynew file mode 100644index 000000000000..9a5fc10beb1d--- /dev/null+++ b/products/data_modeling/backend/test/test_migrate_teams_to_dag_schedules.py@@ -0,0 +1,180 @@+from datetime import timedelta+from io import StringIO++import pytest+from posthog.test.base import BaseTest+from unittest import mock++from django.core.management import call_command++import temporalio.service++from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id+from products.data_modeling.backend.logic.node_frequency import get_declared_target+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.node import Node, NodeType+from products.data_modeling.backend.test.helpers import temporal_listing as _temporal_listing++M15 = timedelta(minutes=15)+DAY = timedelta(hours=24)++RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"+COMMAND = "products.data_modeling.backend.management.commands.migrate_teams_to_dag_schedules"+++class TestMigrateTeamsToDagSchedulesTiered(BaseTest):+ def _v1_dag_with_mixed_frequencies(self):+ dag = DAG.objects.create(team=self.team, name="Default")+ nodes = {}+ for name, interval in (("fast", M15), ("slow", DAY)):+ saved_query = DataWarehouseSavedQuery.objects.create(+ name=name,+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ sync_frequency_interval=interval,+ )+ nodes[name] = Node.objects.create(team=self.team, dag=dag, saved_query=saved_query, type=NodeType.VIEW)+ return dag, nodes++ def _run(self, existing_schedule_ids, delete_side_effect=None):+ create = mock.AsyncMock()+ update = mock.AsyncMock()+ v1_delete = mock.Mock(side_effect=delete_side_effect)+ with (+ mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=True),+ mock.patch(f"{COMMAND}.sync_connect", return_value=mock.Mock()),+ mock.patch(f"{RECONCILE}.delete_schedule", v1_delete),+ mock.patch(+ f"{RECONCILE}.async_connect",+ new=mock.AsyncMock(return_value=_temporal_listing(existing_schedule_ids)),+ ),+ mock.patch(f"{RECONCILE}.a_create_schedule", create),+ mock.patch(f"{RECONCILE}.a_update_schedule", update),+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),+ ):+ call_command("migrate_teams_to_dag_schedules", "--team-ids", str(self.team.pk), stdout=StringIO())+ return create, update, v1_delete++ def test_mixed_frequencies_migrate_to_separate_tiers(self):+ # the single-schedule migration refused mixed-frequency DAGs entirely; tiers are the point+ dag, nodes = self._v1_dag_with_mixed_frequencies()++ create, _update, v1_delete = self._run(existing_schedule_ids=[])++ created_ids = {call.kwargs["id"] for call in create.call_args_list}+ self.assertEqual(created_ids, {tier_schedule_id(str(dag.id), M15), tier_schedule_id(str(dag.id), DAY)})+ self.assertEqual(v1_delete.call_count, 2)++ # targets persisted from the v1 intervals; intervals nulled once consumed+ for name, interval in (("fast", M15), ("slow", DAY)):+ node = nodes[name]+ node.refresh_from_db()+ self.assertEqual(get_declared_target(node), interval)+ assert node.saved_query is not None+ node.saved_query.refresh_from_db()+ self.assertIsNone(node.saved_query.sync_frequency_interval)++ def test_rerun_converges_instead_of_no_opping(self):+ # the old command's cleanup was nested in the schedule-creation branch, so re-runs on+ # half-migrated DAGs did nothing forever+ dag, nodes = self._v1_dag_with_mixed_frequencies()+ tier_ids = [tier_schedule_id(str(dag.id), M15), tier_schedule_id(str(dag.id), DAY)]+ not_found = temporalio.service.RPCError("not found", temporalio.service.RPCStatusCode.NOT_FOUND, b"")++ create, update, v1_delete = self._run(existing_schedule_ids=tier_ids, delete_side_effect=not_found)++ create.assert_not_called()+ self.assertEqual({call.kwargs["id"] for call in update.call_args_list}, set(tier_ids))+ self.assertEqual(v1_delete.call_count, 2)+ for node in nodes.values():+ assert node.saved_query is not None+ node.saved_query.refresh_from_db()+ self.assertIsNone(node.saved_query.sync_frequency_interval)++ def test_transient_v1_delete_failure_keeps_interval_for_retry(self):+ # a transient (non-NOT_FOUND) delete failure must keep that query's interval so a re-run+ # retries, instead of orphaning a v1 schedule beside the tiers+ dag, nodes = self._v1_dag_with_mixed_frequencies()+ assert nodes["fast"].saved_query is not None+ failed_id = str(nodes["fast"].saved_query.id)+ transient = temporalio.service.RPCError("boom", temporalio.service.RPCStatusCode.UNAVAILABLE, b"")++ def delete(_temporal, *, schedule_id):+ if schedule_id == failed_id:+ raise transient++ self._run(existing_schedule_ids=[], delete_side_effect=delete)++ for name in ("fast", "slow"):+ assert nodes[name].saved_query is not None+ nodes[name].saved_query.refresh_from_db()+ # failed delete keeps its interval (retryable); the successful one is cleared+ self.assertEqual(nodes["fast"].saved_query.sync_frequency_interval, M15)+ self.assertIsNone(nodes["slow"].saved_query.sync_frequency_interval)++ def test_query_in_two_dags_keeps_its_own_interval(self):+ # a saved query with nodes in two of the team's DAGs must seed both from its own interval;+ # nulling the shared interval per DAG mid-migration would leave the second node to re-seed+ # from the DAG's 1-day default — a silent freshness regression+ shared = DataWarehouseSavedQuery.objects.create(+ name="shared",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ sync_frequency_interval=M15,+ )+ dag_a = DAG.objects.create(team=self.team, name="A", sync_frequency_interval=DAY)+ dag_b = DAG.objects.create(team=self.team, name="B", sync_frequency_interval=DAY)+ node_a = Node.objects.create(team=self.team, dag=dag_a, saved_query=shared, type=NodeType.VIEW)+ node_b = Node.objects.create(team=self.team, dag=dag_b, saved_query=shared, type=NodeType.VIEW)++ self._run(existing_schedule_ids=[])++ node_a.refresh_from_db()+ node_b.refresh_from_db()+ self.assertEqual(get_declared_target(node_a), M15)+ self.assertEqual(get_declared_target(node_b), M15)+ shared.refresh_from_db()+ self.assertIsNone(shared.sync_frequency_interval)++ def test_temporal_outage_in_sweep_does_not_abort_the_run(self):+ # a connect failure during phase 2 must skip this team's v1 sweep (idempotent on re-run),+ # not propagate out and abort the whole fleet run before later teams are processed+ dag, nodes = self._v1_dag_with_mixed_frequencies()++ with (+ mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=True),+ mock.patch(f"{COMMAND}.sync_connect", side_effect=RuntimeError("temporal down")),+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_temporal_listing([]))),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()),+ mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()),+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),+ ):+ # completes without raising — the outage is swallowed per team+ call_command("migrate_teams_to_dag_schedules", "--team-ids", str(self.team.pk), stdout=StringIO())++ # phase 1 still seeded the targets; phase 2 was skipped, so intervals stay for the re-run+ for name, interval in (("fast", M15), ("slow", DAY)):+ node = nodes[name]+ node.refresh_from_db()+ self.assertEqual(get_declared_target(node), interval)+ assert node.saved_query is not None+ node.saved_query.refresh_from_db()+ self.assertEqual(node.saved_query.sync_frequency_interval, interval)++ def test_flag_off_keeps_single_schedule_migration(self):+ dag, _nodes = self._v1_dag_with_mixed_frequencies()++ with (+ mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=False),+ mock.patch(f"{COMMAND}.sync_connect", return_value=mock.Mock()),+ mock.patch(f"{COMMAND}.schedule_exists", return_value=False),+ mock.patch(f"{COMMAND}.create_schedule") as create,+ mock.patch(f"{RECONCILE}.delete_schedule"),+ ):+ call_command("migrate_teams_to_dag_schedules", "--team-ids", str(self.team.pk), stdout=StringIO())++ # mixed frequencies are still refused on the legacy path — no schedule created+ create.assert_not_called()+ self.assertTrue(DAG.objects.filter(id=dag.id).exists())diff --git a/products/data_modeling/backend/test/test_node_frequency.py b/products/data_modeling/backend/test/test_node_frequency.pyindex 5977d1852b56..ad2926595c11 100644--- a/products/data_modeling/backend/test/test_node_frequency.py+++ b/products/data_modeling/backend/test/test_node_frequency.py@@ -5,18 +5,17 @@ from posthog.test.base import BaseTestfrom parameterized import parameterized-from posthog.models.team import Team-from products.data_modeling.backend.logic.freshness import (STREAMING,UnsatisfiableFrequencyError,+ all_source_floors,compute_effective_cadences,- declared_target_bounds,validate_declared_target,)from products.data_modeling.backend.logic.node_frequency import (build_frequency_graph,get_declared_target,+ persist_seed_targets,resolve_source_intervals,seed_targets,set_declared_target,@@ -25,55 +24,20 @@ from products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.edge import Edgefrom products.data_modeling.backend.models.node import Node, NodeType-from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource-from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.data_modeling.backend.test.helpers import (+ saved_query_node as _saved_query_node,+ table_node as _table_node,+ warehouse_source_node as _warehouse_source_node,+)M15 = timedelta(minutes=15)+M30 = timedelta(minutes=30)+M45 = timedelta(minutes=45)H1 = timedelta(hours=1)H6 = timedelta(hours=6)DAY = timedelta(days=1)-def _table_node(team: Team, dag: DAG, name: str, properties: dict) -> Node:- return Node.objects.create(team=team, dag=dag, name=name, type=NodeType.TABLE, properties=properties)---def _saved_query_node(team: Team, dag: DAG, name: str, node_type: str) -> Node:- saved_query = DataWarehouseSavedQuery.objects.create(- name=name, team=team, query={"query": "SELECT 1", "kind": "HogQLQuery"}- )- return Node.objects.create(team=team, dag=dag, saved_query=saved_query, type=node_type)---def _warehouse_source_node(- team: Team,- dag: DAG,- *,- sync_frequency_interval: timedelta | None,- should_sync: bool = True,- with_schema: bool = True,-) -> Node:- table = DataWarehouseTable.objects.create(name="stripe_charges", team=team)- if with_schema:- source = ExternalDataSource.objects.create(- team=team,- source_id="source_id",- connection_id="connection_id",- status=ExternalDataSource.Status.COMPLETED,- source_type=ExternalDataSourceType.STRIPE,- prefix="posthog_test_",- )- ExternalDataSchema.objects.create(- name="stripe_charges",- team=team,- source=source,- table=table,- sync_frequency_interval=sync_frequency_interval,- should_sync=should_sync,- )- return _table_node(team, dag, "stripe_charges", {"origin": "warehouse", "warehouse_table_id": str(table.id)})--@pytest.mark.django_dbclass TestFrequencyTargetAccessors(BaseTest):def _node(self) -> Node:@@ -156,12 +120,7 @@ class TestBuildFrequencyGraph(BaseTest):)self.assertEqual(effective[str(matview.id)], M15)- floor, _ceiling = declared_target_bounds(- node_id=str(matview.id),- edges=graph.edges,- declared_targets=graph.declared_targets,- source_intervals=graph.source_intervals,- )+ floor = all_source_floors(graph.edges, graph.source_intervals).get(str(matview.id), STREAMING)self.assertEqual(floor, STREAMING)def test_imported_source_floor_makes_a_tighter_descendant_unsatisfiable(self):@@ -171,12 +130,7 @@ class TestBuildFrequencyGraph(BaseTest):Edge.objects.create(team=self.team, dag=dag, source=source, target=matview)graph = build_frequency_graph(dag)- floor, _ceiling = declared_target_bounds(- node_id=str(matview.id),- edges=graph.edges,- declared_targets=graph.declared_targets,- source_intervals=graph.source_intervals,- )+ floor = all_source_floors(graph.edges, graph.source_intervals).get(str(matview.id), STREAMING)self.assertEqual(floor, H6)with self.assertRaises(UnsatisfiableFrequencyError):validate_declared_target(@@ -217,3 +171,30 @@ class TestSeedTargets(BaseTest):dag = DAG.objects.create(team=self.team, name="seed-demo-src", sync_frequency_interval=H1)_table_node(self.team, dag, "events", {"origin": "posthog"})self.assertEqual(seed_targets(dag), {})+++class TestPersistSeedTargets(BaseTest):+ def test_clamps_seed_finer_than_source_before_persisting(self):+ # a node's v1 cadence (15min via the DAG) is finer than its 6h source: the backfill must+ # persist the clamped 6h target the scheduler will actually run, not the raw 15min seed+ dag = DAG.objects.create(team=self.team, name="backfill-clamp", sync_frequency_interval=M15)+ source = _warehouse_source_node(self.team, dag, sync_frequency_interval=H6)+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=matview)++ self.assertEqual(persist_seed_targets(dag), 1)+ matview.refresh_from_db()+ self.assertEqual(get_declared_target(matview), H6)++ def test_snaps_non_bucket_seed_down_to_a_finer_bucket(self):+ # a 45min v1 cadence over a streamed source isn't schedulable; persist the nearest finer+ # bucket (30min) so declared == effective and reconcile never sees a non-bucket target+ dag = DAG.objects.create(team=self.team, name="backfill-snap", sync_frequency_interval=M45)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=matview)++ self.assertEqual(persist_seed_targets(dag), 1)+ matview.refresh_from_db()+ self.assertEqual(get_declared_target(matview), M30)diff --git a/products/data_modeling/backend/test/test_preview_freshness_schedules.py b/products/data_modeling/backend/test/test_preview_freshness_schedules.pyindex 1c561b65eb95..e4c979a9022d 100644--- a/products/data_modeling/backend/test/test_preview_freshness_schedules.py+++ b/products/data_modeling/backend/test/test_preview_freshness_schedules.py@@ -12,35 +12,16 @@ from products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.edge import Edgefrom products.data_modeling.backend.models.node import Node, NodeType+from products.data_modeling.backend.test.helpers import (+ no_existing_schedules as _no_existing_schedules,+ saved_query_node as _saved_query_node,+ table_node as _table_node,+)M15 = timedelta(minutes=15)H6 = timedelta(hours=6)-def _no_existing_schedules():- async def fake_list_schedules(*_args, **_kwargs):- async def gen():- return- yield # pragma: no cover — empty async generator-- return gen()-- temporal = mock.Mock()- temporal.list_schedules = fake_list_schedules- return temporal---def _table_node(team, dag, name, properties):- return Node.objects.create(team=team, dag=dag, name=name, type=NodeType.TABLE, properties=properties)---def _saved_query_node(team, dag, name, node_type):- saved_query = DataWarehouseSavedQuery.objects.create(- name=name, team=team, query={"query": "SELECT 1", "kind": "HogQLQuery"}- )- return Node.objects.create(team=team, dag=dag, saved_query=saved_query, type=node_type)--@pytest.mark.django_dbclass TestPreviewFreshnessSchedules(BaseTest):def test_previews_tiers_without_touching_any_schedule(self):diff --git a/products/data_modeling/backend/test/test_reconcile_freshness_schedules.py b/products/data_modeling/backend/test/test_reconcile_freshness_schedules.pynew file mode 100644index 000000000000..fadb0fe2fb9d--- /dev/null+++ b/products/data_modeling/backend/test/test_reconcile_freshness_schedules.py@@ -0,0 +1,144 @@+from datetime import timedelta+from io import StringIO++import pytest+from posthog.test.base import BaseTest+from unittest import mock++from django.core.management import call_command+from django.core.management.base import CommandError++from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id+from products.data_modeling.backend.logic.node_frequency import get_declared_target+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.node import Node, NodeType+from products.data_modeling.backend.test.helpers import temporal_listing as _temporal_listing++H6 = timedelta(hours=6)++RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"+COMMAND = "products.data_modeling.backend.management.commands.reconcile_freshness_schedules"+++class TestReconcileFreshnessSchedules(BaseTest):+ def _legacy_dag(self) -> tuple[DAG, Node]:+ dag = DAG.objects.create(team=self.team, name="Default", sync_frequency_interval=H6)+ saved_query = DataWarehouseSavedQuery.objects.create(+ name="v",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ sync_frequency_interval=H6,+ )+ node = Node.objects.create(team=self.team, dag=dag, saved_query=saved_query, type=NodeType.VIEW)+ return dag, node++ def test_converts_legacy_dag_seeding_targets_first(self):+ dag, node = self._legacy_dag()+ legacy_id = str(dag.id)++ with (+ mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=True),+ mock.patch(f"{RECONCILE}.sync_connect"),+ mock.patch(f"{RECONCILE}.delete_schedule"),+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_temporal_listing([legacy_id]))),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ call_command("reconcile_freshness_schedules", "--team-id", str(self.team.pk), stdout=StringIO())++ node.refresh_from_db()+ self.assertEqual(get_declared_target(node), H6)+ assert node.saved_query is not None+ node.saved_query.refresh_from_db()+ self.assertIsNone(node.saved_query.sync_frequency_interval)+ create.assert_called_once()+ self.assertEqual(create.call_args.kwargs["id"], tier_schedule_id(legacy_id, H6))+ delete.assert_called_once_with(mock.ANY, schedule_id=legacy_id)++ def test_refuses_unflagged_team(self):+ self._legacy_dag()+ with mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=False):+ with self.assertRaisesRegex(CommandError, "tiered-schedules flag"):+ call_command("reconcile_freshness_schedules", "--team-id", str(self.team.pk), stdout=StringIO())++ def test_sweeps_live_v1_schedules(self):+ dag, node = self._legacy_dag()+ assert node.saved_query is not None+ v1_id = str(node.saved_query.id)++ with (+ mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=True),+ mock.patch(f"{RECONCILE}.sync_connect"),+ mock.patch(f"{RECONCILE}.delete_schedule") as delete_v1,+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_temporal_listing([]))),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()),+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),+ ):+ call_command("reconcile_freshness_schedules", "--team-id", str(self.team.pk), stdout=StringIO())++ delete_v1.assert_called_once_with(mock.ANY, schedule_id=v1_id)+ node.saved_query.refresh_from_db()+ self.assertIsNone(node.saved_query.sync_frequency_interval)++ def test_dry_run_rejects_default_interval(self):+ self._legacy_dag()+ with self.assertRaisesRegex(CommandError, "default-interval-seconds"):+ call_command(+ "reconcile_freshness_schedules",+ "--team-id",+ str(self.team.pk),+ "--dry-run",+ "--default-interval-seconds",+ "3600",+ stdout=StringIO(),+ )++ def test_query_in_two_dags_seeds_from_its_own_interval(self):+ D1 = timedelta(days=1)+ saved_query = DataWarehouseSavedQuery.objects.create(+ name="shared",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ sync_frequency_interval=H6,+ )+ dag_a = DAG.objects.create(team=self.team, name="A", sync_frequency_interval=D1)+ dag_b = DAG.objects.create(team=self.team, name="B", sync_frequency_interval=D1)+ node_a = Node.objects.create(team=self.team, dag=dag_a, saved_query=saved_query, type=NodeType.VIEW)+ node_b = Node.objects.create(team=self.team, dag=dag_b, saved_query=saved_query, type=NodeType.VIEW)++ with (+ mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=True),+ mock.patch(f"{RECONCILE}.sync_connect"),+ mock.patch(f"{RECONCILE}.delete_schedule"),+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_temporal_listing([]))),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()),+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),+ ):+ call_command("reconcile_freshness_schedules", "--team-id", str(self.team.pk), stdout=StringIO())++ node_a.refresh_from_db()+ node_b.refresh_from_db()+ self.assertEqual(get_declared_target(node_a), H6)+ self.assertEqual(get_declared_target(node_b), H6)++ def test_dry_run_delegates_to_preview_and_writes_nothing(self):+ dag, node = self._legacy_dag()++ out = StringIO()+ with (+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_temporal_listing([]))),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ call_command("reconcile_freshness_schedules", "--team-id", str(self.team.pk), "--dry-run", stdout=out)++ node.refresh_from_db()+ self.assertIsNone(get_declared_target(node))+ assert node.saved_query is not None+ node.saved_query.refresh_from_db()+ self.assertEqual(node.saved_query.sync_frequency_interval, H6)+ create.assert_not_called()+ delete.assert_not_called()+ self.assertIn("dry run", out.getvalue())diff --git a/products/data_modeling/backend/test/test_saved_query_dag_sync.py b/products/data_modeling/backend/test/test_saved_query_dag_sync.pyindex 0c7b6d065646..e999b29c940f 100644--- a/products/data_modeling/backend/test/test_saved_query_dag_sync.py+++ b/products/data_modeling/backend/test/test_saved_query_dag_sync.py@@ -1,5 +1,6 @@import pytestfrom posthog.test.base import BaseTest+from unittest import mockfrom parameterized import parameterized@@ -434,3 +435,37 @@ class TestUpdateNodeType(BaseTest):# shouldn't raise, exception is captured thoughupdate_node_type(saved_query, NodeType.MAT_VIEW)update_node_type(saved_query, NodeType.VIEW)+++class TestGraphMutationTriggers(BaseTest):+ def _saved_query(self, name: str = "trigger_view") -> DataWarehouseSavedQuery:+ return DataWarehouseSavedQuery.objects.create(+ name=name, team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ )++ def test_each_graph_mutation_queues_a_reconcile(self):+ # the tiered scheduler converges from the graph, so every mutation path must invoke+ # the trigger hook — dropping one silently freezes that DAG's schedules+ saved_query = self._saved_query()+ module = "products.data_modeling.backend.logic.saved_query_dag_sync"++ with mock.patch(f"{module}.maybe_reconcile_dag") as reconcile:+ sync_saved_query_to_dag(saved_query)+ reconcile.assert_called_once()++ with mock.patch(f"{module}.maybe_reconcile_dag") as reconcile:+ update_node_type(saved_query, NodeType.MAT_VIEW)+ reconcile.assert_called_once()++ with mock.patch(f"{module}.maybe_reconcile_dag") as reconcile:+ delete_node_from_dag(saved_query)+ reconcile.assert_called_once()++ def test_sync_can_defer_reconcile_for_batch_callers(self):+ saved_query = self._saved_query("batched_view")+ module = "products.data_modeling.backend.logic.saved_query_dag_sync"++ with mock.patch(f"{module}.maybe_reconcile_dag") as reconcile:+ sync_saved_query_to_dag(saved_query, reconcile=False)+ reconcile.assert_not_called()diff --git a/products/data_modeling/backend/test/test_schedule_materialization.py b/products/data_modeling/backend/test/test_schedule_materialization.pyindex 89c7171ad0b9..1d9487d18dc3 100644--- a/products/data_modeling/backend/test/test_schedule_materialization.py+++ b/products/data_modeling/backend/test/test_schedule_materialization.py@@ -3,12 +3,15 @@ from datetime import timedeltafrom posthog.test.base import BaseTestfrom unittest import mock+from products.data_modeling.backend.logic.freshness import UnsupportedFrequencyTargetError+from products.data_modeling.backend.logic.node_frequency import get_declared_target, set_declared_targetfrom products.data_modeling.backend.models import DAG, Nodefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.node import NodeTypeSERVICE = "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"class TestScheduleMaterializationV2Guard(BaseTest):@@ -48,6 +51,70 @@ class TestScheduleMaterializationV2Guard(BaseTest):self.sq.refresh_from_db()assert self.sq.sync_frequency_interval == timedelta(hours=12)+ def test_tiered_flag_writes_target_through_and_nulls_interval(self):+ node = Node.objects.get(saved_query=self.sq)+ with (+ mock.patch(GET_V2_DAG_IDS, return_value={str(self.dag.id)}),+ mock.patch(f"{RECONCILE}.tiered_schedules_enabled", return_value=True),+ mock.patch(f"{RECONCILE}.maybe_reconcile_dag") as reconcile,+ ):+ self.sq.schedule_materialization()+ node.refresh_from_db()+ self.sq.refresh_from_db()+ assert get_declared_target(node) == timedelta(hours=12)+ assert self.sq.sync_frequency_interval is None+ reconcile.assert_called_once()++ def test_tiered_call_without_interval_keeps_existing_target(self):+ # a caller with no frequency opinion (e.g. re-enabling materialization) must not+ # wipe the node target — the interval is transport, not state+ node = Node.objects.get(saved_query=self.sq)+ set_declared_target(node, timedelta(hours=6))+ self.sq.sync_frequency_interval = None+ self.sq.save(update_fields=["sync_frequency_interval"])+ with (+ mock.patch(GET_V2_DAG_IDS, return_value={str(self.dag.id)}),+ mock.patch(f"{RECONCILE}.tiered_schedules_enabled", return_value=True),+ mock.patch(f"{RECONCILE}.maybe_reconcile_dag"),+ ):+ self.sq.schedule_materialization()+ node.refresh_from_db()+ assert get_declared_target(node) == timedelta(hours=6)++ def test_revert_materialization_on_tiered_clears_target(self):+ # without this a reverted matview stays in its cadence tier and keeps materializing+ node = Node.objects.get(saved_query=self.sq)+ set_declared_target(node, timedelta(hours=12))+ with (+ mock.patch(f"{RECONCILE}.tiered_schedules_enabled", return_value=True),+ mock.patch(f"{RECONCILE}.maybe_reconcile_dag"),+ mock.patch("products.data_warehouse.backend.facade.api.delete_saved_query_schedule"),+ ):+ self.sq.revert_materialization()+ node.refresh_from_db()+ assert get_declared_target(node) is None++ def test_tiered_flag_surfaces_invalid_frequency_without_disabling(self):+ # an invalid frequency is a request problem: it must reach the caller as a validation+ # error, not silently flip is_materialized like infrastructure failures do+ self.sq.is_materialized = True+ self.sq.sync_frequency_interval = timedelta(minutes=45)+ self.sq.save(update_fields=["is_materialized", "sync_frequency_interval"])+ with (+ mock.patch(GET_V2_DAG_IDS, return_value={str(self.dag.id)}),+ mock.patch(f"{RECONCILE}.tiered_schedules_enabled", return_value=True),+ ):+ try:+ self.sq.schedule_materialization()+ raise AssertionError("expected UnsupportedFrequencyTargetError")+ except UnsupportedFrequencyTargetError:+ pass+ self.sq.refresh_from_db()+ assert self.sq.is_materialized is True+ # validation raises before the interval is nulled — the rejected write stays+ # visible for retry+ assert self.sq.sync_frequency_interval == timedelta(minutes=45)+def test_disables_materialization_when_v2_lookup_fails(self):self.sq.is_materialized = Trueself.sq.save(update_fields=["is_materialized"])diff --git a/products/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.pyindex 22f198a507fa..e31aca1feedb 100644--- a/products/data_modeling/backend/test/test_schedule_reconcile.py+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py@@ -4,59 +4,31 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest import mock-from temporalio.client import ScheduleListActionStartWorkflow+from temporalio.client import ScheduleAlreadyRunningError, ScheduleListActionStartWorkflowfrom posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEYfrom products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_idfrom products.data_modeling.backend.logic.freshness import UnsupportedFrequencyTargetErrorfrom products.data_modeling.backend.logic.node_frequency import set_declared_target-from products.data_modeling.backend.logic.schedule_reconcile import reconcile_dag_schedules+from products.data_modeling.backend.logic.schedule_reconcile import maybe_reconcile_dag, reconcile_dag_schedulesfrom products.data_modeling.backend.models.dag import DAG-from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.edge import Edge-from products.data_modeling.backend.models.node import Node, NodeType+from products.data_modeling.backend.models.node import NodeTypefrom products.data_modeling.backend.schedule import DATA_MODELING_EXECUTE_DAG_WORKFLOW-from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource-from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.data_modeling.backend.test.helpers import (+ saved_query_node as _saved_query_node,+ table_node as _table_node,+ warehouse_source_node as _warehouse_source_node,+)++RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"M15 = timedelta(minutes=15)H1 = timedelta(hours=1)H6 = timedelta(hours=6)-def _table_node(team, dag, name, properties):- return Node.objects.create(team=team, dag=dag, name=name, type=NodeType.TABLE, properties=properties)---def _saved_query_node(team, dag, name, node_type):- saved_query = DataWarehouseSavedQuery.objects.create(- name=name, team=team, query={"query": "SELECT 1", "kind": "HogQLQuery"}- )- return Node.objects.create(team=team, dag=dag, saved_query=saved_query, type=node_type)---def _warehouse_source_node(team, dag, *, sync_frequency_interval):- table = DataWarehouseTable.objects.create(name="stripe_charges", team=team)- source = ExternalDataSource.objects.create(- team=team,- source_id="source_id",- connection_id="connection_id",- status=ExternalDataSource.Status.COMPLETED,- source_type=ExternalDataSourceType.STRIPE,- prefix="posthog_test_",- )- ExternalDataSchema.objects.create(- name="stripe_charges",- team=team,- source=source,- table=table,- sync_frequency_interval=sync_frequency_interval,- should_sync=True,- )- return _table_node(team, dag, "stripe_charges", {"origin": "warehouse", "warehouse_table_id": str(table.id)})--def _listing(schedule_id, workflow="data-modeling-execute-dag"):action = mock.Mock(spec=ScheduleListActionStartWorkflow, workflow=workflow)return mock.Mock(id=schedule_id, schedule=mock.Mock(action=action))@@ -85,12 +57,11 @@ class TestReconcileDagSchedules(BaseTest):temporal = mock.Mock()temporal.list_schedules = fake_list_schedules- module = "products.data_modeling.backend.logic.schedule_reconcile"with (- mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=temporal)),- mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock()) as create,- mock.patch(f"{module}.a_update_schedule", new=mock.AsyncMock()) as update,- mock.patch(f"{module}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()) as update,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,):reconcile_dag_schedules(dag)@@ -130,12 +101,11 @@ class TestReconcileDagSchedules(BaseTest):temporal = mock.Mock()temporal.list_schedules = fake_list_schedules- module = "products.data_modeling.backend.logic.schedule_reconcile"with (- mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=temporal)),- mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock()) as create,- mock.patch(f"{module}.a_update_schedule", new=mock.AsyncMock()) as update,- mock.patch(f"{module}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()) as update,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,):reconcile_dag_schedules(dag)@@ -173,12 +143,11 @@ class TestReconcileDagSchedules(BaseTest):if len(created_ids) >= 2: # second tier creation fails partway through the migrationraise RuntimeError("temporal unavailable")- module = "products.data_modeling.backend.logic.schedule_reconcile"with (- mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=temporal)),- mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock(side_effect=failing_create)),- mock.patch(f"{module}.a_update_schedule", new=mock.AsyncMock()),- mock.patch(f"{module}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock(side_effect=failing_create)),+ mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()),+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,):with self.assertRaises(RuntimeError):reconcile_dag_schedules(dag)@@ -188,6 +157,100 @@ class TestReconcileDagSchedules(BaseTest):delete.assert_called_once_with(temporal, schedule_id=created_ids[0])self.assertNotEqual(created_ids[0], legacy_id)+ def test_refuses_to_unschedule_covered_dag_without_targets(self):+ # a covered DAG with no targets means unseeded conversion, not a wind-down —+ # converging to zero schedules would silently stop all materialization+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=endpoint)++ legacy_id = str(dag.id)++ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ yield _listing(legacy_id)++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules++ with (+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ reconcile_dag_schedules(dag)++ create.assert_not_called()+ delete.assert_not_called()++ def test_winds_down_tier_schedules_when_all_targets_cleared(self):+ # reverting/clearing the last target leaves empty desired tiers; once tier schedules exist+ # that is a deliberate wind-down, so the stale tier must be torn down rather than left+ # firing execute-dag on node_ids that no longer materialize+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=endpoint)+ # no target on any node -> desired tiers empty, but a tier schedule is still live++ stale_tier = tier_schedule_id(str(dag.id), M15)++ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ yield _listing(stale_tier)++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules++ with (+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ reconcile_dag_schedules(dag)++ create.assert_not_called()+ delete.assert_called_once_with(temporal, schedule_id=stale_tier)++ def test_concurrent_create_converges_to_update_without_rollback(self):+ # a concurrent reconcile already created the tier; the loser must converge onto it,+ # not roll it back — rolling back would delete the winner's live schedule+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=endpoint)+ set_declared_target(endpoint, M15)++ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ return+ yield # pragma: no cover — empty async generator++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules++ with (+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(+ f"{RECONCILE}.a_create_schedule",+ new=mock.AsyncMock(side_effect=ScheduleAlreadyRunningError()),+ ),+ mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()) as update,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ reconcile_dag_schedules(dag)++ update.assert_called_once()+ self.assertEqual(update.call_args.kwargs["id"], tier_schedule_id(str(dag.id), M15))+ delete.assert_not_called()+def test_refuses_non_bucket_tier_before_touching_temporal(self):# the guard must fire before any Temporal call — a non-bucket tier would crash# build_schedule_spec mid-apply and leave the DAG partially reconciled@@ -197,8 +260,7 @@ class TestReconcileDagSchedules(BaseTest):Edge.objects.create(team=self.team, dag=dag, source=source, target=endpoint)set_declared_target(endpoint, timedelta(minutes=45))- module = "products.data_modeling.backend.logic.schedule_reconcile"- with mock.patch(f"{module}.async_connect", new=mock.AsyncMock()) as connect:+ with mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock()) as connect:with self.assertRaises(UnsupportedFrequencyTargetError):reconcile_dag_schedules(dag)connect.assert_not_called()@@ -224,13 +286,91 @@ class TestReconcileDagSchedules(BaseTest):temporal = mock.Mock()temporal.list_schedules = fake_list_schedules- module = "products.data_modeling.backend.logic.schedule_reconcile"with (- mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=temporal)),- mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,):reconcile_dag_schedules(dag)# clamped to the 6h source floor, not the declared 15mincreate.assert_called_once()self.assertEqual(create.call_args.kwargs["id"], tier_schedule_id(dag_id, H6))+++class TestMaybeReconcileDag(BaseTest):+ def _dag_with_target(self):+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=endpoint)+ set_declared_target(endpoint, M15)+ return dag++ def _temporal_listing(self, schedule_ids):+ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ for schedule_id in schedule_ids:+ yield _listing(schedule_id)++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules+ return temporal++ def test_flag_off_never_touches_temporal(self):+ dag = self._dag_with_target()+ with (+ mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=False),+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock()) as connect,+ ):+ with self.captureOnCommitCallbacks(execute=True):+ maybe_reconcile_dag(dag)+ connect.assert_not_called()++ def test_untiered_dag_is_left_alone(self):+ # a legacy single-schedule DAG converts only via the conversion command; a mutation+ # trigger must neither unschedule it nor create tiers next to live v1 schedules+ dag = self._dag_with_target()+ with (+ mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),+ mock.patch(+ f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=self._temporal_listing([str(dag.id)]))+ ),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()) as update,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ with self.captureOnCommitCallbacks(execute=True):+ maybe_reconcile_dag(dag)+ create.assert_not_called()+ update.assert_not_called()+ delete.assert_not_called()++ def test_tiered_dag_reconciles_after_commit(self):+ dag = self._dag_with_target()+ tier_id = tier_schedule_id(str(dag.id), M15)+ with (+ mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),+ mock.patch(+ f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=self._temporal_listing([tier_id]))+ ),+ mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()) as update,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),+ ):+ with self.captureOnCommitCallbacks(execute=True):+ maybe_reconcile_dag(dag)+ update.assert_called_once()+ self.assertEqual(update.call_args.kwargs["id"], tier_id)++ def test_reconcile_failure_never_raises_past_commit(self):+ dag = self._dag_with_target()+ with (+ mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(side_effect=RuntimeError("temporal down"))),+ mock.patch(f"{RECONCILE}.capture_exception") as capture,+ ):+ with self.captureOnCommitCallbacks(execute=True):+ maybe_reconcile_dag(dag)+ capture.assert_called_once()diff --git a/products/data_modeling/backend/tests/api/test_node_api.py b/products/data_modeling/backend/tests/api/test_node_api.pyindex cc37b56ad20c..96fd9f47978d 100644--- a/products/data_modeling/backend/tests/api/test_node_api.py+++ b/products/data_modeling/backend/tests/api/test_node_api.py@@ -1,3 +1,5 @@+from datetime import timedelta+from posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, patch@@ -6,6 +8,7 @@ from rest_framework import statusfrom posthog.models import Team+from products.data_modeling.backend.logic.node_frequency import set_declared_targetfrom products.data_modeling.backend.models import DAG, Edge, Node, NodeTypefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery@@ -111,6 +114,32 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["count"], 3)+ @parameterized.expand(+ [+ # node target wins even when the saved-query interval disagrees (tiered v2 teams+ # carry NULL intervals, so a saved-query-only read shows a blank frequency)+ ("target_first", timedelta(hours=6), timedelta(hours=12), "6hour"),+ ("saved_query_fallback", None, timedelta(hours=12), "12hour"),+ ("neither", None, None, None),+ ]+ )+ def test_node_sync_interval_reads_target_first(+ self,+ _name: str,+ target: timedelta | None,+ saved_query_interval: timedelta | None,+ expected: str | None,+ ):+ self.saved_query.sync_frequency_interval = saved_query_interval+ self.saved_query.save(update_fields=["sync_frequency_interval"])+ if target is not None:+ set_declared_target(self.view_node, target)++ response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["sync_interval"], expected)+def test_node_response_includes_dag_name(self):response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/{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 04472f571029..8a6fd5e6c044 100644--- a/products/data_warehouse/backend/models/test/test_managed_viewset.py+++ b/products/data_warehouse/backend/models/test/test_managed_viewset.py@@ -65,6 +65,22 @@ class TestDataWarehouseManagedViewSetModel(BaseTest):]self.team.revenue_analytics_config.save()+ def test_sync_views_reconciles_dag_schedules_once(self):+ # sync_views touches N views; reconciling per view would issue N redundant+ # Temporal converges for the one managed DAG+ managed_viewset = DataWarehouseManagedViewSet.objects.create(+ team=self.team,+ kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,+ )++ with (+ patch(SCHEDULE_MATERIALIZATION),+ patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag") as reconcile,+ ):+ managed_viewset.sync_views()++ reconcile.assert_called_once()+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/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.pyindex b862bf1a50ff..b95494c01ba7 100644--- a/products/data_warehouse/backend/presentation/views/saved_query.py+++ b/products/data_warehouse/backend/presentation/views/saved_query.py@@ -301,7 +301,8 @@ class DataWarehouseSavedQuerySerializer(help_text=("How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', ""'24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest "- "cadence available."+ "cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored "+ "on the view's DAG node, so this field may read back as null after a successful write."),)latest_history_id = serializers.SerializerMethodField(read_only=True)@@ -529,6 +530,7 @@ class DataWarehouseSavedQuerySerializer(sync_frequency = validated_data.pop("sync_frequency", None)+ dag_managed_frequency = Falseif sync_frequency and posthoganalytics.feature_enabled("data-modeling-backend-v2",str(instance.team.uuid),@@ -537,7 +539,14 @@ class DataWarehouseSavedQuerySerializer("project": str(instance.team.id),},):- raise serializers.ValidationError("Schedule is managed by the DAG. Edit the DAG schedule instead.")+ 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.+ if not tiered_schedules_enabled(instance.team):+ raise serializers.ValidationError("Schedule is managed by the DAG. Edit the DAG schedule instead.")+ dag_managed_frequency = Truesoft_update = validated_data.pop("soft_update", False)@@ -562,7 +571,13 @@ class DataWarehouseSavedQuerySerializer(if str(edited_history_id) != str(latest_activity_id):raise serializers.ValidationError("The query was modified by someone else.")- if sync_frequency == "never":+ 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.+ locked_instance.sync_frequency_interval = None+ validated_data["sync_frequency_interval"] = None+ elif sync_frequency == "never":locked_instance.sync_frequency_interval = Nonevalidated_data["sync_frequency_interval"] = Noneelif sync_frequency:@@ -572,6 +587,28 @@ class DataWarehouseSavedQuerySerializer(view: DataWarehouseSavedQuery = super().update(locked_instance, validated_data)+ if dag_managed_frequency:+ from products.data_modeling.backend.facade.api import (+ UnsatisfiableFrequencyError,+ UnsupportedFrequencyTargetError,+ apply_saved_query_frequency_target,+ )++ target = (+ None if sync_frequency == "never" else sync_frequency_to_sync_frequency_interval(sync_frequency)+ )+ try:+ # Validates inside the transaction (a rejected frequency rolls the whole+ # update back) and queues the schedule reconcile for after commit.+ nodes_written = apply_saved_query_frequency_target(view, target)+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:+ raise serializers.ValidationError(str(e))+ if target is not None and nodes_written == 0:+ raise serializers.ValidationError(+ "Cannot set a materialization frequency: this view is not wired into the data "+ "modeling DAG yet. Re-save the view to create its node, then set the frequency."+ )+if has_description:self._write_view_description(view, description)@@ -649,21 +686,24 @@ class DataWarehouseSavedQuerySerializer(.first())self.context["activity_log"] = latest_activity_log- # update the temporal schedule if it exists- 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,- )+ # 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:@@ -1072,9 +1112,19 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSesaved_query.is_materialized = Truesaved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])+ from products.data_modeling.backend.facade.api import (+ UnsatisfiableFrequencyError,+ UnsupportedFrequencyTargetError,+ )+# Enable materialization - this handles model path setup and schedule creation# If this fails, it will set is_materialized = False- saved_query.schedule_materialization(unpause=should_unpause)+ try:+ saved_query.schedule_materialization(unpause=should_unpause)+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:+ # The requested cadence can't be honored (e.g. finer than an upstream source+ # delivers) — a request problem, not a server one.+ raise serializers.ValidationError(str(e))# Refresh from DB to check if schedule_materialization set is_materialized = False on failuresaved_query.refresh_from_db()diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.pyindex 2b03da361001..e9509c841c0c 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py@@ -678,6 +678,140 @@ class TestSavedQuery(APIBaseTest):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) -> dict:+ 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)+ 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),+ ]+ )+ def test_update_sync_frequency_on_tiered_v2_writes_target_through(+ self, sync_frequency: str, expected_target: timedelta | None+ ):+ from products.data_modeling.backend.logic.node_frequency import get_declared_target, set_declared_target+ from products.data_modeling.backend.models import Node++ saved_query = self._create_saved_query_for_frequency_tests()+ node = Node.objects.get(saved_query_id=saved_query["id"])+ set_declared_target(node, timedelta(hours=12))+ 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(+ "products.data_warehouse.backend.presentation.views.saved_query.saved_query_workflow_exists"+ ) as v1_exists,+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",+ {"sync_frequency": sync_frequency},+ )++ self.assertEqual(response.status_code, 200, response.json())+ # the node target is the only store of frequency intent; the interval stays NULL+ updated = DataWarehouseSavedQuery.objects.get(id=saved_query["id"])+ self.assertIsNone(updated.sync_frequency_interval)+ node.refresh_from_db()+ self.assertEqual(get_declared_target(node), expected_target)+ reconcile.assert_called_once()+ # a stale v1 schedule from a half-finished migration must not be revived by the PATCH+ v1_exists.assert_not_called()++ def test_update_sync_frequency_on_tiered_v2_without_node_is_rejected(self):+ from products.data_modeling.backend.models import Node++ saved_query = self._create_saved_query_for_frequency_tests()+ Node.objects.filter(saved_query_id=saved_query["id"]).delete()+ 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"),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",+ {"sync_frequency": "24hour"},+ )++ self.assertEqual(response.status_code, 400, response.json())+ self.assertIn("not wired into the data modeling DAG", str(response.json()))+ updated = DataWarehouseSavedQuery.objects.get(id=saved_query["id"])+ self.assertIsNone(updated.sync_frequency_interval)++ def test_update_sync_frequency_on_tiered_v2_rolls_back_invalid_target(self):+ from products.data_modeling.backend.logic.freshness import UnsatisfiableFrequencyError++ saved_query = self._create_saved_query_for_frequency_tests()+ 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",+ side_effect=UnsatisfiableFrequencyError("target is fresher than its sources deliver"),+ ),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",+ {"sync_frequency": "15min"},+ )++ self.assertEqual(response.status_code, 400)+ # validation happens inside the transaction: the interval write rolls back with it+ updated = DataWarehouseSavedQuery.objects.get(id=saved_query["id"])+ self.assertIsNone(updated.sync_frequency_interval)++ def test_update_sync_frequency_on_untiered_v2_stays_blocked(self):+ 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,+ ),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",+ {"sync_frequency": "24hour"},+ )++ self.assertEqual(response.status_code, 400)+ self.assertIn("managed by the DAG", response.json()["detail"])+def test_sync_frequency_is_a_writable_field(self):# Regression: sync_frequency used to be a read-only SerializerMethodField, so it was# marked readOnly in the generated OpenAPI/MCP schemas and silently dropped from writes.diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex 1c07333335d7..165101e8a6cc 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -939,7 +939,7 @@ export interface DataWarehouseSavedQueryApi {* @nullable*/description?: string | null- /** How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.+ /** How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.** * `never` - never* * `15min` - 15min@@ -1055,7 +1055,7 @@ export interface PatchedDataWarehouseSavedQueryApi {* @nullable*/description?: string | null- /** How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.+ /** How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.** * `never` - never* * `15min` - 15mindiff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.tsindex 5b7cb79f1f78..cf0c4794fc7c 100644--- a/products/data_warehouse/frontend/generated/api.zod.ts+++ b/products/data_warehouse/frontend/generated/api.zod.ts@@ -314,7 +314,7 @@ export const WarehouseSavedQueriesCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()@@ -376,7 +376,7 @@ export const WarehouseSavedQueriesUpdateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()@@ -440,7 +440,7 @@ export const WarehouseSavedQueriesPartialUpdateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()@@ -506,7 +506,7 @@ export const WarehouseSavedQueriesAncestorsCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()@@ -568,7 +568,7 @@ export const WarehouseSavedQueriesCancelCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()@@ -634,7 +634,7 @@ export const WarehouseSavedQueriesDescendantsCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()@@ -696,7 +696,7 @@ export const WarehouseSavedQueriesMaterializeCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()@@ -761,7 +761,7 @@ export const WarehouseSavedQueriesRevertMaterializationCreateBody = /* @__PURE__]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()@@ -823,7 +823,7 @@ export const WarehouseSavedQueriesRunCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()@@ -888,7 +888,7 @@ export const WarehouseSavedQueriesResumeSchedulesCreateBody = /* @__PURE__ */ zo]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n\* `never` - never\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day"),folder_id: zod.uuid()diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.pyindex ff891cf001e3..62146660670c 100644--- a/products/endpoints/backend/logic/materialization.py+++ b/products/endpoints/backend/logic/materialization.py@@ -9,6 +9,8 @@ query transforms live in ``products.endpoints.backend.materialization_transformsimport dataclassesfrom typing import cast+from django.db import transaction+import structlogfrom rest_framework.exceptions import APIException, ValidationErrorfrom rest_framework.request import Request@@ -27,6 +29,8 @@ from posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Detail, log_activityfrom products.data_modeling.backend.facade.api import (+ UnsatisfiableFrequencyError,+ UnsupportedFrequencyTargetError,delete_node_from_dag,saved_query_materialized_at,sync_saved_query_to_dag,@@ -197,31 +201,42 @@ class EndpointMaterializationService:if not can_mat:raise ValidationError(f"Cannot materialize endpoint. Reason: {reason}")- saved_query = self._get_or_build_saved_query(version)- self._configure_saved_query(saved_query, version, data_freshness_seconds, bucket_overrides)- version.enable_materialization(saved_query, bucket_overrides)+ # Atomic so a rejected freshness target unwinds the whole enable (saved query, version link,+ # node) instead of leaving a dangling materialization. schedule_materialization's side effect+ # is deferred to on_commit (tiered) or terminal (v1), so nothing rolls back after it fires.+ with transaction.atomic():+ saved_query = self._get_or_build_saved_query(version)+ self._configure_saved_query(saved_query, version, data_freshness_seconds, bucket_overrides)+ version.enable_materialization(saved_query, bucket_overrides)- # NOTE: schedule_materialization only triggers an immediate run when it CREATES the- # Temporal schedule; re-enabling an existing materialization just (re)syncs the schedule.- saved_query.schedule_materialization()+ # 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.+ try:+ sync_saved_query_to_dag(saved_query)+ except Exception as e:+ logger.exception(+ "Failed to sync endpoint node to DAG",+ endpoint_name=endpoint.name,+ saved_query_id=saved_query.id,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ "saved_query_id": saved_query.id,+ },+ )- try:- sync_saved_query_to_dag(saved_query)- except Exception as e:- logger.exception(- "Failed to sync endpoint node to DAG",- endpoint_name=endpoint.name,- saved_query_id=saved_query.id,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team.pk,- "endpoint_name": endpoint.name,- "saved_query_id": saved_query.id,- },- )+ # NOTE: schedule_materialization only triggers an immediate run when it CREATES the+ # Temporal schedule; re-enabling an existing materialization just (re)syncs the schedule.+ try:+ saved_query.schedule_materialization()+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:+ # The chosen data freshness can't be honored (e.g. finer than an upstream import+ # delivers) — a request problem, not a server one.+ raise ValidationError(str(e))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 f95b0c19ac33..e1d4e893974b 100644--- a/products/endpoints/backend/tests/test_endpoint_materialization.py+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py@@ -23,8 +23,9 @@ 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 UnsatisfiableFrequencyErrorfrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPath-from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery+from products.data_modeling.backend.facade.models import 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 (@@ -62,14 +63,20 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):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()+ )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()def tearDown(self):self.sync_workflow_patcher.stop()self.workflow_exists_patcher.stop()self.delete_schedule_patcher.stop()+ self.v2_dag_ids_patcher.stop()super().tearDown()def test_enable_materialization_creates_saved_query(self):@@ -123,6 +130,38 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):"DataWarehouseModelPath should be created for the saved_query",)+ def test_unsatisfiable_freshness_rolls_back_the_whole_enable(self):+ # if scheduling rejects the chosen freshness (finer than an upstream source can deliver),+ # the enable must unwind completely — no dangling saved query, version link, or DAG node+ # left behind with no schedule; the request just 400s+ endpoint = create_endpoint_with_version(+ name="rollback_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.object(+ DataWarehouseSavedQuery,+ "schedule_materialization",+ side_effect=UnsatisfiableFrequencyError("15min is finer than the 24h upstream source"),+ ):+ 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)+ self.assertFalse(+ DataWarehouseSavedQuery.objects.filter(team=self.team, name=f"{endpoint.name}_v{version.version}").exists()+ )+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@@ -1766,6 +1805,65 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):"EndpointVersion must be linked to the saved query before materialization is scheduled",)+ def test_enable_materialization_syncs_dag_node_before_scheduling(self):+ # the v2 detection and freshness write-through in schedule_materialization resolve the+ # saved query through its Node row — scheduling before the node exists silently routes+ # new endpoints on v2 teams back onto v1 schedules+ endpoint = create_endpoint_with_version(+ name="node-first",+ team=self.team,+ query=self.sample_hogql_query,+ created_by=self.user,+ is_active=True,+ )++ observed: dict = {}++ def capture_node_state(self_saved_query):+ observed["node_exists"] = Node.objects.filter(saved_query_id=self_saved_query.id).exists()++ with mock.patch.object(+ DataWarehouseSavedQuery,+ "schedule_materialization",+ autospec=True,+ side_effect=capture_node_state,+ ):+ 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_200_OK, response.json())+ self.assertTrue(+ observed.get("node_exists"),+ "The DAG node must exist before materialization is scheduled",+ )++ def test_unsatisfiable_freshness_returns_400(self):+ endpoint = create_endpoint_with_version(+ name="too-fresh",+ team=self.team,+ query=self.sample_hogql_query,+ created_by=self.user,+ is_active=True,+ )++ with mock.patch.object(+ DataWarehouseSavedQuery,+ "schedule_materialization",+ autospec=True,+ side_effect=UnsatisfiableFrequencyError("target 0:15:00 is fresher than its sources deliver (6:00:00)"),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"is_materialized": True, "data_freshness_seconds": 900},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertIn("fresher than", response.json()["detail"])+def _create_materialized_trends_endpoint(self, name: str, breakdowns: list[dict], optional: list[str]):"""Shared helper for the optional-breakdown tests. Stands up a materialized TrendsQueryendpoint whose saved_query is in COMPLETED status with a backing DataWarehouseTable —diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b3c30a99273a..bcd54c2c9049 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17362,7 +17362,7 @@ export namespace Schemas {* @nullable*/description?: string | null;- /** How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.+ /** How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.** * `never` - never* * `15min` - 15min@@ -44346,7 +44346,7 @@ export namespace Schemas {* @nullable*/description?: string | null;- /** How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.+ /** How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.** * `never` - never* * `15min` - 15mindiff --git a/services/mcp/src/generated/data_warehouse/api.ts b/services/mcp/src/generated/data_warehouse/api.tsindex f59a4941c740..5786757a2925 100644--- a/services/mcp/src/generated/data_warehouse/api.ts+++ b/services/mcp/src/generated/data_warehouse/api.ts@@ -274,7 +274,7 @@ export const WarehouseSavedQueriesCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"),folder_id: zod.string()@@ -350,7 +350,7 @@ export const WarehouseSavedQueriesPartialUpdateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"),folder_id: zod.string()@@ -429,7 +429,7 @@ export const WarehouseSavedQueriesMaterializeCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"),folder_id: zod.string()@@ -503,7 +503,7 @@ export const WarehouseSavedQueriesRevertMaterializationCreateBody = /* @__PURE__]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"),folder_id: zod.string()@@ -574,7 +574,7 @@ export const WarehouseSavedQueriesRunCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"),folder_id: zod.string()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.jsonindex 0efd32a097ac..8d6412399b0d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json@@ -69,7 +69,7 @@"type": "null"}],- "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"}},"required": ["name", "query"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-materialize.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-materialize.jsonindex c7338c5aa96d..28d462218c24 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-materialize.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-materialize.json@@ -105,7 +105,7 @@"type": "null"}],- "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"}},"required": ["id", "name", "query"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-run.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-run.jsonindex c7338c5aa96d..28d462218c24 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-run.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-run.json@@ -105,7 +105,7 @@"type": "null"}],- "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"}},"required": ["id", "name", "query"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.jsonindex c7338c5aa96d..28d462218c24 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json@@ -105,7 +105,7 @@"type": "null"}],- "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"}},"required": ["id", "name", "query"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.jsonindex 721453e91d6d..484bb5739920 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json@@ -84,7 +84,7 @@"type": "null"}],- "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"+ "description": "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest cadence available. On teams whose DAG schedules are managed per-node, the cadence is stored on the view's DAG node, so this field may read back as null after a successful write.\n\n* `never` - never\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"}},"required": ["id"],