:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(data-modeling): add consolidate_dags fleet command (#73650)
Jovan Sakoviccfb72f8cbac9
diff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.pyindex 4915c9dbe064..e392c8b73c7f 100644--- a/products/data_modeling/backend/logic/schedule_reconcile.py+++ b/products/data_modeling/backend/logic/schedule_reconcile.py@@ -290,7 +290,7 @@ def preview_dag_schedules(dag: DAG, *, seed: bool = False) -> DagSchedulePrevieweffective = compute_effective_cadences(nodes=graph.nodes, edges=graph.edges, declared_targets=declared)effective, clamped = clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)desired_tiers = bucket_into_cadence_tiers(effective)- existing_ids = _list_existing_schedule_ids(str(dag.id))+ existing_ids = list_existing_schedule_ids(str(dag.id))plan = plan_schedule_reconciliation(str(dag.id), desired_tiers, existing_ids)return DagSchedulePreview(effective=effective,@@ -307,7 +307,7 @@ def preview_dag_schedules(dag: DAG, *, seed: bool = False) -> DagSchedulePreview@async_to_sync-async def _list_existing_schedule_ids(dag_id: str) -> set[str]:+async def list_existing_schedule_ids(dag_id: str) -> set[str]:temporal = await async_connect()return await _list_execute_dag_schedule_ids(temporal, dag_id)diff --git a/products/data_modeling/backend/management/commands/consolidate_dags.py b/products/data_modeling/backend/management/commands/consolidate_dags.pynew file mode 100644index 000000000000..92a93d4a0600--- /dev/null+++ b/products/data_modeling/backend/management/commands/consolidate_dags.py@@ -0,0 +1,646 @@+import uuid+import dataclasses+from collections import defaultdict, deque+from datetime import timedelta+from typing import Any++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError, CommandParser++import structlog+from temporalio.client import Client+from temporalio.service import RPCError, RPCStatusCode++from posthog.temporal.common.client import sync_connect+from posthog.temporal.common.schedule import delete_schedule++from products.data_modeling.backend.logic.cohort_scheduling import is_tier_schedule_id+from products.data_modeling.backend.logic.freshness import (+ STREAMING,+ all_source_floors,+ format_cadence,+ normalize_seed_target,+)+from products.data_modeling.backend.logic.node_frequency import (+ build_frequency_graph,+ get_declared_target,+ schedulable_nodes,+ set_declared_target,+)+from products.data_modeling.backend.logic.saved_query_dag_sync import sync_saved_query_to_dag+from products.data_modeling.backend.logic.schedule_reconcile import (+ delete_v1_saved_query_schedules,+ list_existing_schedule_ids,+ null_saved_query_intervals,+ reconcile_dag_schedules,+)+from products.data_modeling.backend.models.dag import DAG, DEFAULT_DAG_NAME+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.edge import Edge+from products.data_modeling.backend.models.node import Node, NodeType++logger = structlog.get_logger(__name__)++# How the target DAG is currently scheduled — decides which Temporal work is safe.+MODE_TIERED = "tiered" # per-cadence tier schedules ({dag_id}:{seconds})+MODE_LEGACY_V2 = "legacy-v2" # single whole-DAG execute-dag schedule (id == dag_id)+MODE_V1 = "v1-only" # no execute-dag schedule; queries run on per-query v1 schedules+++class MoveItem:+ saved_query: DataWarehouseSavedQuery+ declared_target: timedelta | None+++class DropItem:+ saved_query_id: str+ node_id: str+ name: str+ declared_target: timedelta | None+++class SourceDagPlan:+ dag: DAG+ moves: list[MoveItem] # dependency (topological) order+ drops: list[DropItem]+ moved_node_ids: set[str] # kept for the dry run's edge-impact count+ dropped_node_ids: set[str]+++class Command(BaseCommand):+ help = (+ "Plan and (with --apply) execute collapsing a team's overlapping DAGs into one. The dry run "+ "is the planner: it partitions each source DAG's nodes into MOVE/DROP, counts the edges a "+ "merge would re-point or dedup, flags saved queries whose declared freshness targets differ "+ "between copies (a 'which cadence wins?' call for a human), and checks for anomalous "+ "cross-DAG edges. For every non-managed source DAG, saved queries already in the "+ "target are dropped (their duplicate node dies with the source DAG) and the rest are moved "+ "by re-syncing them into the target in dependency order, then the source DAG is deleted "+ "(cascading its nodes and edges). Tears down the source DAGs' execute-dag schedules, then "+ "finalizes the target from its persistent state: seed declared targets from leftover v1 "+ "intervals, sweep v1 per-query schedules, null the intervals, reconcile tiers once. "+ "Because the finalize derives from the target rather than this run's moves, re-running "+ "with --apply completes a partially-applied consolidation. Dry run by default; pass "+ "--apply to execute."+ )++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team-id", type=int, required=True)+ parser.add_argument(+ "--target-dag-id",+ type=str,+ default=None,+ help="Force the merge target DAG (default: the canonical 'Default' DAG, else the largest)",+ )+ parser.add_argument(+ "--apply",+ action="store_true",+ default=False,+ help="Execute the consolidation. Without this flag the command is a dry run and changes nothing.",+ )+ parser.add_argument(+ "--verbose",+ action="store_true",+ help="List per-query names under each source DAG's move/drop counts (default: counts only)",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ team_id: int = options["team_id"]+ apply_changes: bool = options["apply"]+ all_dags = list(DAG.objects.filter(team_id=team_id))+ if not all_dags:+ raise CommandError(f"Team {team_id} has no DAGs")++ # System-managed DAGs (Revenue Analytics) are never consolidated: the managed viewset+ # re-asserts its nodes' placement on every sync, so a move out is silently undone, and+ # syncing a query into a managed DAG is refused outright. Exclude them as source and target.+ managed_dags = [dag for dag in all_dags if dag.is_managed]+ dags = [dag for dag in all_dags if not dag.is_managed]++ forced_id: str | None = options["target_dag_id"]+ if forced_id:+ try:+ forced_uuid = uuid.UUID(forced_id)+ except ValueError:+ raise CommandError(f"--target-dag-id must be a UUID, got {forced_id!r}")+ if any(dag.id == forced_uuid for dag in managed_dags):+ raise CommandError(f"--target-dag-id {forced_id} is a system-managed DAG and cannot be a merge target")++ if not dags:+ raise CommandError(f"Team {team_id} has no non-managed DAGs to consolidate")++ target = self._pick_target(dags, forced_id)+ source_dags = sorted((dag for dag in dags if dag.id != target.id), key=lambda d: d.name)++ self.stdout.write(f"\nTeam {team_id} — {len(dags)} DAG(s)")+ if managed_dags:+ excluded = ", ".join(f"{dag.name} ({dag.id})" for dag in managed_dags)+ self.stdout.write(f"Excluding {len(managed_dags)} system-managed DAG(s): {excluded}")+ self.stdout.write(f"Merge target: {target.name} ({target.id}) — {self._target_reason(target, options)}")++ plans = self._build_plan(target, source_dags)+ self._print_plan(target, plans, team_id=team_id, dags=dags, verbose=options["verbose"])++ if not apply_changes:+ self.stdout.write(+ "\n(dry run — nothing was changed; target schedule mode is detected at apply time; "+ "pass --apply to execute)"+ )+ return++ if not settings.TEST:+ confirm = input(+ f"\n\tWill consolidate {len(source_dags)} source DAG(s) into {target.name} ({target.id}) "+ f"for team {team_id}, deleting the source DAGs. Proceed? (y/n) "+ )+ if confirm.strip().lower() != "y":+ self.stdout.write("Aborting")+ return++ # Connect before mutating anything: schedule teardown is mandatory once DAGs start moving,+ # so a Temporal outage must abort the run while it is still a pure no-op.+ try:+ temporal = sync_connect()+ except Exception as error:+ raise CommandError(f"Cannot connect to Temporal, aborting before any change: {error}")+ mode = self._detect_target_mode(self._list_dag_schedules_or_abort(str(target.id)))+ self.stdout.write(f"\nTarget schedule mode: {mode}")+ if mode == MODE_V1:+ # A v2-scheduled source would strand its queries: its execute-dag schedules die with+ # the source DAG, but a v1-only target has no schedule to hand coverage to.+ v2_sources = [+ f"{plan.dag.name} ({plan.dag.id})"+ for plan in plans+ if self._list_dag_schedules_or_abort(str(plan.dag.id))+ ]+ if v2_sources:+ raise CommandError(+ f"target {target.name} ({target.id}) is v1-only but source(s) "+ f"{', '.join(v2_sources)} are v2-scheduled — migrate the target to tiers first "+ "via reconcile_freshness_schedules, or choose a tiered target"+ )+ self.stdout.write(+ " target has no execute-dag schedule and every source is v1-only — graph-only "+ "consolidation: v1 per-query schedules and sync intervals are kept so the moved "+ "queries stay scheduled"+ )++ consolidated_sq_ids: set[str] = set()+ kept_dags: list[str] = []+ for plan in plans:+ kept_reason = self._apply_source_dag(plan, target, temporal, consolidated_sq_ids)+ if kept_reason:+ kept_dags.append(f"{plan.dag.name} ({plan.dag.id}): {kept_reason}")++ v1_failed_sq_ids = self._finalize_target(target, temporal)++ self.stdout.write(f"\nDone: consolidated {len(consolidated_sq_ids)} saved query(ies) into {target.name}")+ if v1_failed_sq_ids:+ self.stdout.write(+ self.style.WARNING(+ f" v1 schedule delete failed for {len(v1_failed_sq_ids)} saved query(ies) "+ f"(intervals kept for retry): {', '.join(sorted(v1_failed_sq_ids))}"+ )+ )+ if kept_dags:+ for line in kept_dags:+ self.stdout.write(self.style.ERROR(f" kept source DAG {line}"))+ raise CommandError(+ f"consolidation incomplete: {len(kept_dags)} source DAG(s) kept; "+ "resolve the failures above and re-run (the command converges on re-run)"+ )++ def _pick_target(self, dags: list[DAG], target_dag_id: str | None) -> DAG:+ if target_dag_id:+ try:+ wanted = uuid.UUID(target_dag_id)+ except ValueError:+ raise CommandError(f"--target-dag-id must be a UUID, got {target_dag_id!r}")+ for dag in dags:+ if dag.id == wanted:+ return dag+ raise CommandError(f"--target-dag-id {target_dag_id} is not a DAG of this team")++ for dag in dags:+ if dag.name == DEFAULT_DAG_NAME:+ return dag++ counts: dict[Any, int] = defaultdict(int)+ for dag_id in Node.objects.filter(dag__in=dags).values_list("dag_id", flat=True):+ counts[dag_id] += 1+ return sorted(dags, key=lambda d: (-counts.get(d.id, 0), d.name))[0]++ def _target_reason(self, target: DAG, options: dict[str, Any]) -> str:+ if options["target_dag_id"]:+ return "chosen via --target-dag-id"+ if target.name == DEFAULT_DAG_NAME:+ return "canonical 'Default' DAG"+ return "no Default DAG — largest DAG by node count"++ def _build_plan(self, target: DAG, source_dags: list[DAG]) -> list[SourceDagPlan]:+ """Partition every source DAG's schedulable nodes into MOVE/DROP and+ topologically order the moves, all read-only so any cycle aborts before a single mutation.+ """+ target_sq_ids = {str(sq_id) for sq_id in schedulable_nodes(target).values_list("saved_query_id", flat=True)}+ claimed: set[str] = set() # saved queries a preceding source DAG already moves+ plans: list[SourceDagPlan] = []+ for dag in source_dags:+ moves_by_node: dict[str, MoveItem] = {}+ drops: list[DropItem] = []+ floors = self._source_floors(dag) if dag.sync_frequency_interval is not None else {}+ for node in schedulable_nodes(dag).select_related("saved_query"):+ saved_query = node.saved_query+ if saved_query is None:+ continue+ sq_id = str(saved_query.id)+ # Query-interval intent survives the move on the saved query itself, and a moved+ # no-interval query adopts the target DAG's default cadence — both seeded in the+ # finalize. What has no carrier is the case where the target has no default either:+ # cadence then lives only on the *source* DAG's interval, which the finalize can't+ # see, so capture it as a declared target before the source DAG — the only place it+ # exists — is deleted; without it the moved node has no effective cadence and+ # reconcile drops it from every tier.+ declared = get_declared_target(node)+ if (+ declared is None+ and saved_query.sync_frequency_interval is None+ and target.sync_frequency_interval is None+ and dag.sync_frequency_interval is not None+ ):+ declared = normalize_seed_target(dag.sync_frequency_interval, floors.get(str(node.id), STREAMING))+ if sq_id in target_sq_ids or sq_id in claimed:+ drops.append(+ DropItem(saved_query_id=sq_id, node_id=str(node.id), name=node.name, declared_target=declared)+ )+ else:+ moves_by_node[str(node.id)] = MoveItem(saved_query=saved_query, declared_target=declared)+ claimed.add(sq_id)+ order = self._dependency_order(dag, set(moves_by_node))+ plans.append(+ SourceDagPlan(+ dag=dag,+ moves=[moves_by_node[node_id] for node_id in order],+ drops=drops,+ moved_node_ids=set(moves_by_node),+ dropped_node_ids={drop.node_id for drop in drops},+ )+ )+ return plans++ def _source_floors(self, dag: DAG) -> dict[str, timedelta]:+ graph = build_frequency_graph(dag)+ return all_source_floors(graph.edges, graph.source_intervals)++ def _cadence_intent(self, node: Node, dag: DAG, floors: dict[str, timedelta]) -> timedelta | None:+ """A node's cadence intent, resolved in the same order as `seed_targets`.++ The DAG-interval fallback matters because the finalize nulls every query interval before+ reconciling: a query that was only ever scheduled by its DAG's default cadence would then+ have no declared target and no interval, and `reconcile_dag_schedules` drops a node with no+ effective cadence from every tier — it would stop materializing with nothing left to show why.+ """+ interval = None+ if node.saved_query is not None and node.saved_query.sync_frequency_interval is not None:+ interval = node.saved_query.sync_frequency_interval+ elif dag.sync_frequency_interval is not None:+ interval = dag.sync_frequency_interval+ if interval is None:+ return None+ return normalize_seed_target(interval, floors.get(str(node.id), STREAMING))++ def _dependency_order(self, dag: DAG, node_ids: set[str]) -> list[str]:+ """Kahn's algorithm over the source DAG's edges restricted to the moved nodes: a moved+ query's node must exist in the target before a moved dependent's sync resolves it. The+ model forbids cycles, but a corrupt graph must abort here, before anything is mutated.+ """+ children: dict[str, list[str]] = defaultdict(list)+ in_degree = dict.fromkeys(node_ids, 0)+ for source_id, target_id in Edge.objects.filter(dag=dag).values_list("source_id", "target_id"):+ src, tgt = str(source_id), str(target_id)+ if src in node_ids and tgt in node_ids:+ children[src].append(tgt)+ in_degree[tgt] += 1+ queue = deque(sorted(node_id for node_id, degree in in_degree.items() if degree == 0))+ order: list[str] = []+ while queue:+ node_id = queue.popleft()+ order.append(node_id)+ for child in children[node_id]:+ in_degree[child] -= 1+ if in_degree[child] == 0:+ queue.append(child)+ if len(order) != len(node_ids):+ raise CommandError(f"cycle detected among nodes to move in DAG {dag.id}; aborting before any change")+ return order++ def _print_plan(+ self, target: DAG, plans: list[SourceDagPlan], *, team_id: int, dags: list[DAG], verbose: bool+ ) -> None:+ if not plans:+ self.stdout.write(" Only one DAG — nothing to consolidate.")+ return+ total_moved = 0+ total_dropped = 0+ total_repoint_edges = 0+ total_dedup_edges = 0+ for plan in plans:+ total_moved += len(plan.moves)+ total_dropped += len(plan.drops)+ repoint, dedup = self._count_edge_impact(plan.dag, plan.moved_node_ids, plan.dropped_node_ids)+ total_repoint_edges += repoint+ total_dedup_edges += dedup+ self.stdout.write(f"\n Source DAG {plan.dag.name} ({plan.dag.id}):")+ self.stdout.write(f" move {len(plan.moves)}, drop {len(plan.drops)}")+ self.stdout.write(f" edges to re-point (touch a moved node): {repoint}")+ self.stdout.write(f" edges to drop as redundant (only dropped nodes): {dedup}")+ self.stdout.write(+ f" v1 schedules swept in the target-wide finalize (if target is v2-scheduled): "+ f"{len(plan.moves) + len(plan.drops)}"+ )+ self.stdout.write(f" execute-dag schedules to tear down: all listed for DAG {plan.dag.id}")+ if verbose:+ if plan.moves:+ move_names = ", ".join(item.saved_query.name for item in plan.moves)+ self.stdout.write(f" move (in dependency order): {move_names}")+ if plan.drops:+ self.stdout.write(f" drop: {', '.join(sorted(drop.name for drop in plan.drops))}")++ conflicts = self._find_target_conflicts(dags)+ self._print_conflicts(conflicts)+ cross_dag_edges = self._count_cross_dag_edges(team_id)++ target_after = schedulable_nodes(target).count() + total_moved+ self.stdout.write(f"\nSummary for target {target.name} ({target.id}):")+ self.stdout.write(f" nodes in target after merge: {target_after}")+ self.stdout.write(f" moved: {total_moved}, dropped: {total_dropped}")+ self.stdout.write(f" edges to re-point: {total_repoint_edges}, edges to drop: {total_dedup_edges}")+ self.stdout.write(f" source DAGs to delete: {len(plans)}")+ self.stdout.write(f" freshness-target conflicts: {len(conflicts)}")+ if cross_dag_edges:+ self.stdout.write(self.style.WARNING(f" ⚠ anomalous cross-DAG edges found: {cross_dag_edges}"))+ else:+ self.stdout.write(" cross-DAG edges: 0 (edges are within-DAG by construction)")+ self.stdout.write(" target reconciled once at the end (if on cadence tiers)")++ def _count_edge_impact(self, dag: DAG, moved_ids: set[str], dropped_ids: set[str]) -> tuple[int, int]:+ """Count edges a real merge would touch. Edges are within-DAG (source/target/edge all share+ the DAG), so an edge touching a moved node must be re-pointed to the target DAG; an edge+ whose only involved nodes are dropped is redundant against the target's existing edge.+ """+ repoint = 0+ dedup = 0+ for source_id, target_id in Edge.objects.filter(dag=dag).values_list("source_id", "target_id"):+ src, tgt = str(source_id), str(target_id)+ if src in moved_ids or tgt in moved_ids:+ repoint += 1+ elif src in dropped_ids or tgt in dropped_ids:+ dedup += 1+ return repoint, dedup++ def _find_target_conflicts(self, dags: list[DAG]) -> list[tuple[str, list[tuple[str, timedelta | None]]]]:+ """Saved queries with schedulable nodes in 2+ DAGs whose declared freshness targets differ.+ A conflict is 2+ distinct non-None declared targets across the copies — after a merge only+ one node survives, so a human must pick the winning cadence. All-unset or agreeing targets+ are not conflicts (unset means 'no opinion', so a lone declared target wins cleanly).+ """+ by_saved_query: dict[object, list[tuple[str, str, timedelta | None]]] = defaultdict(list)+ dag_names = {dag.id: dag.name for dag in dags}+ for node in Node.objects.filter(dag__in=dags).exclude(type=NodeType.TABLE).exclude(saved_query__deleted=True):+ if node.saved_query_id is None:+ continue+ by_saved_query[node.saved_query_id].append((dag_names[node.dag_id], node.name, get_declared_target(node)))++ conflicts: list[tuple[str, list[tuple[str, timedelta | None]]]] = []+ for copies in by_saved_query.values():+ if len(copies) < 2:+ continue+ declared = {target for _dag_name, _query_name, target in copies if target is not None}+ if len(declared) < 2:+ continue+ query_name = copies[0][1]+ copies_report = sorted((dag_name, target) for dag_name, _query_name, target in copies)+ conflicts.append((query_name, copies_report))+ return sorted(conflicts, key=lambda c: c[0])++ def _print_conflicts(self, conflicts: list[tuple[str, list[tuple[str, timedelta | None]]]]) -> None:+ self.stdout.write("\nFreshness-target conflicts (which cadence wins after merge?):")+ if not conflicts:+ self.stdout.write(" none")+ return+ for query_name, copies in conflicts:+ self.stdout.write(self.style.WARNING(f" ⚠ {query_name}:"))+ for dag_name, target in copies:+ label = format_cadence(target) if target is not None else "unset"+ self.stdout.write(f" {dag_name}: {label}")++ def _count_cross_dag_edges(self, team_id: int) -> int:+ """Defensive check: edges whose endpoints' DAGs disagree with the edge's own DAG. The model+ forbids these, so a non-zero count means data corruption worth surfacing before any merge.+ """+ node_dags = dict(Node.objects.filter(team_id=team_id).values_list("id", "dag_id"))+ anomalies = 0+ for source_id, target_id, dag_id in Edge.objects.filter(team_id=team_id).values_list(+ "source_id", "target_id", "dag_id"+ ):+ if node_dags.get(source_id) != dag_id or node_dags.get(target_id) != dag_id:+ anomalies += 1+ return anomalies++ def _list_dag_schedules_or_abort(self, dag_id: str) -> set[str]:+ """Authoritative listing of a DAG's execute-dag schedule ids via the PostHogDagId search+ attribute — never guessed from an id formula, so off-scheme schedules can't escape. Only+ used before the first mutation, where aborting is still a pure no-op.+ """+ try:+ return list_existing_schedule_ids(dag_id)+ except Exception as error:+ raise CommandError(f"Cannot list Temporal schedules for DAG {dag_id}, aborting before any change: {error}")++ def _detect_target_mode(self, target_schedule_ids: set[str]) -> str:+ if any(is_tier_schedule_id(schedule_id) for schedule_id in target_schedule_ids):+ return MODE_TIERED+ if target_schedule_ids:+ return MODE_LEGACY_V2+ return MODE_V1++ def _apply_source_dag(+ self,+ plan: SourceDagPlan,+ target: DAG,+ temporal: Client,+ consolidated_sq_ids: set[str],+ ) -> str | None:+ """Consolidate one source DAG. Returns None on success, or the reason the DAG was kept.++ Ordering, chosen so a crash at any point leaves a state a re-run converges from:+ 1. (DB) sync each MOVE query into the target in dependency order — a crash here leaves+ duplicates the re-run classifies as DROP.+ 2. (Temporal) delete the source DAG's execute-dag schedules, from an authoritative+ listing — idempotent, so a crash after this is retried harmlessly.+ 3. (DB) delete the source DAG row, cascading its nodes and edges. This must come LAST:+ the row is the only durable pointer to the DAG's Temporal schedules, so deleting it+ before the teardown succeeded would orphan schedules forever.+ The consolidated queries' v1 schedules are swept afterwards by the target-wide finalize,+ which re-runs derive from the target's persistent state.+ """+ self.stdout.write(f"\n Source DAG {plan.dag.name} ({plan.dag.id}):")+ failed_moves: list[str] = []+ moved_sq_ids: list[str] = []+ for item in plan.moves:+ try:+ node = sync_saved_query_to_dag(item.saved_query, dag=target, reconcile=False)+ except Exception as error:+ failed_moves.append(item.saved_query.name)+ logger.exception(+ "Failed to move saved query into target DAG",+ saved_query_id=str(item.saved_query.id),+ source_dag_id=str(plan.dag.id),+ target_dag_id=str(target.id),+ )+ self.stderr.write(f" FAILED to move {item.saved_query.name}: {error}")+ continue+ if node is not None:+ self._carry_declared_target(node, item.declared_target, item.saved_query.name)+ moved_sq_ids.append(str(item.saved_query.id))+ self.stdout.write(f" moved {item.saved_query.name}")+ orphaned_drops: list[str] = []+ for drop in plan.drops:+ node = Node.objects.filter(dag=target, saved_query_id=drop.saved_query_id).first()+ if node is None:+ # The plan expected an earlier source DAG to have moved this query in. It did not,+ # so the copy about to be cascaded away is the only place its declared target+ # exists. Keep this DAG instead of destroying intent a re-run could still carry.+ orphaned_drops.append(drop.name)+ self.stderr.write(f" NOT dropping {drop.name}: its query never reached the target")+ continue+ self._carry_declared_target(node, drop.declared_target, drop.name)+ self.stdout.write(f" dropped duplicate {drop.name}")++ if failed_moves:+ # The successful moves are now duplicates a re-run classifies as DROP; deleting the DAG+ # here would destroy the only node of every query that failed to move.+ return f"{len(failed_moves)} move(s) failed ({', '.join(failed_moves)})"+ if orphaned_drops:+ return f"{len(orphaned_drops)} duplicate(s) never reached the target ({', '.join(orphaned_drops)})"++ if not self._teardown_execute_dag_schedules(temporal, str(plan.dag.id)):+ return "execute-dag schedule teardown failed; DAG kept so a re-run can retry it"++ plan.dag.delete()+ self.stdout.write(f" deleted source DAG {plan.dag.id}")+ consolidated_sq_ids.update(moved_sq_ids)+ consolidated_sq_ids.update(drop.saved_query_id for drop in plan.drops)+ return None++ def _carry_declared_target(self, node: Node, declared: timedelta | None, name: str) -> None:+ """Carry a source node's declared freshness target onto its target-DAG node. The target+ DAG's copy wins a disagreement (the dry run surfaces these conflicts for a human first).+ """+ if declared is None:+ return+ existing = get_declared_target(node)+ if existing is None:+ set_declared_target(node, declared)+ elif existing != declared:+ self.stdout.write(+ f" cadence conflict on {name}: keeping target's {format_cadence(existing)} "+ f"(source declared {format_cadence(declared)})"+ )++ def _teardown_execute_dag_schedules(self, temporal: Client, dag_id: str) -> bool:+ """Delete the execute-dag schedules Temporal actually has for this DAG, from an+ authoritative listing (PostHogDagId search attribute) rather than an id formula, so an+ off-scheme schedule cannot be orphaned by the DAG's deletion. NOT_FOUND means a concurrent+ delete won the race; a listing or delete failure keeps the DAG for a re-run.+ """+ try:+ schedule_ids = list_existing_schedule_ids(dag_id)+ except Exception:+ logger.exception("Failed to list execute-dag schedules", dag_id=dag_id)+ self.stderr.write(f" FAILED to list execute-dag schedules for DAG {dag_id}")+ return False+ ok = True+ for schedule_id in sorted(schedule_ids):+ try:+ delete_schedule(temporal, schedule_id=schedule_id)+ self.stdout.write(f" deleted execute-dag schedule {schedule_id}")+ except RPCError as error:+ if error.status != RPCStatusCode.NOT_FOUND:+ ok = False+ logger.exception("Failed to delete execute-dag schedule", schedule_id=schedule_id)+ self.stderr.write(f" FAILED to delete execute-dag schedule {schedule_id}")+ except Exception:+ ok = False+ logger.exception("Failed to delete execute-dag schedule", schedule_id=schedule_id)+ self.stderr.write(f" FAILED to delete execute-dag schedule {schedule_id}")+ return ok++ def _finalize_target(self, target: DAG, temporal: Client) -> set[str]:+ """Converge the target after the moves: seed declared targets from leftover v1 intervals,+ sweep the v1 per-query schedules, null the consumed intervals, and reconcile the tier+ schedules once. Everything here derives from the target's persistent state — never this+ run's move list — so re-running the command completes a consolidation a crash left+ half-finished; that re-run IS the recovery mechanism, at the cost of a no-op run+ re-sweeping and re-reconciling the target.++ The schedule mode is re-detected here rather than taken from the pre-flight check: a+ concurrent reconcile can convert the target to tiers while the moves run, and acting on+ the stale v1-only snapshot would skip the sweep and leave overlapping v1 + tier schedules.++ On a legacy-v2 target the whole-DAG schedule (node_ids=None) picks the moved nodes up+ automatically, so only tiered targets are reconciled; the seeded declared targets preserve+ cadence intent for the eventual tier conversion either way. On a v1-only target nothing+ runs — every source was verified v1-only before any mutation, so the kept v1 schedules and+ intervals keep the moved queries scheduled. Returns the saved-query ids whose v1 delete+ failed (their intervals are kept as the retry signal).+ """+ try:+ mode = self._detect_target_mode(list_existing_schedule_ids(str(target.id)))+ except Exception as error:+ raise CommandError(+ f"consolidation applied but re-detecting target {target.id} schedule mode failed ({error}); "+ "re-run with --apply to finish the finalize"+ )+ self.stdout.write(f"\n finalize: target schedule mode {mode}")+ if mode not in (MODE_TIERED, MODE_LEGACY_V2):+ return set()+ self._seed_targets_from_intervals(target)+ nodes = list(schedulable_nodes(target).select_related("saved_query"))+ v1_failed = delete_v1_saved_query_schedules(+ nodes, team_id=target.team_id, dag_id=str(target.id), temporal=temporal+ )+ swept_ids = {str(node.saved_query_id) for node in nodes if node.saved_query_id is not None} - v1_failed+ cleared = null_saved_query_intervals(target, only_saved_query_ids=swept_ids)+ self.stdout.write(+ f"\n swept v1 schedules for {len(nodes)} saved query(ies) ({len(v1_failed)} failed), "+ f"cleared sync_frequency_interval on {cleared}"+ )+ if mode == MODE_TIERED:+ try:+ reconcile_dag_schedules(target, require_tiered=True)+ self.stdout.write(f" reconciled target DAG {target.id} tier schedules")+ except Exception as error:+ logger.exception("Failed to reconcile target DAG after consolidation", dag_id=str(target.id))+ raise CommandError(+ f"consolidation applied but the final reconcile of target {target.id} failed ({error}); "+ "run reconcile_freshness_schedules for this team to converge the tier schedules"+ )+ return v1_failed++ def _seed_targets_from_intervals(self, target: DAG) -> None:+ """A query about to lose its v1 sync_frequency_interval must not lose its cadence intent:+ seed each target-DAG node's declared target from its query's interval (normalized, never+ overwriting) before the interval is nulled — persist_seed_targets/convert_dag_to_tiers in+ spirit, scoped to the target DAG and idempotent so crash-recovery re-runs converge.+ """+ floors = self._source_floors(target)+ for node in schedulable_nodes(target).select_related("saved_query"):+ if get_declared_target(node) is not None:+ continue+ seed = self._cadence_intent(node, target, floors)+ if seed is None:+ continue+ set_declared_target(node, seed)diff --git a/products/data_modeling/backend/test/test_consolidate_dags.py b/products/data_modeling/backend/test/test_consolidate_dags.pynew file mode 100644index 000000000000..7f33f0af300f--- /dev/null+++ b/products/data_modeling/backend/test/test_consolidate_dags.py@@ -0,0 +1,542 @@+import uuid+from contextlib import contextmanager+from datetime import timedelta+from io import StringIO+from types import SimpleNamespace++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 parameterized import parameterized+from temporalio.client import ScheduleListActionStartWorkflow++from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id+from products.data_modeling.backend.logic.node_frequency import get_declared_target, set_declared_target+from products.data_modeling.backend.models.dag import DAG, REVENUE_ANALYTICS_DAG_NAME+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.edge import Edge+from products.data_modeling.backend.models.node import Node, NodeType++M15 = timedelta(minutes=15)+H6 = timedelta(hours=6)++COMMAND = "products.data_modeling.backend.management.commands.consolidate_dags"+RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"+++def _listing_client(schedules_by_dag):+ # query-aware fake: schedule listings are per-DAG (PostHogDagId search attribute), and the+ # command lists the target, each source, and the reconcile path — they must not see each+ # other's schedules+ 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, query="", **_kwargs):+ dag_id = query.split("'")[1] if "'" in query else ""++ async def gen():+ for schedule_id in schedules_by_dag.get(dag_id, []):+ yield _listing(schedule_id)++ return gen()++ client = mock.Mock()+ client.list_schedules = fake_list_schedules+ return client+++@contextmanager+def _temporal_boundary(schedules_by_dag=None, v2_delete_error=None):+ v2_delete = mock.Mock()+ if v2_delete_error is not None:+ v2_delete.side_effect = v2_delete_error+ with (+ mock.patch(f"{COMMAND}.sync_connect"),+ mock.patch(f"{COMMAND}.delete_schedule", v2_delete),+ mock.patch(f"{RECONCILE}.delete_schedule") as v1_delete,+ mock.patch(+ f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_listing_client(schedules_by_dag or {}))+ ),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as tier_create,+ mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()) as tier_update,+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),+ ):+ yield SimpleNamespace(+ v1_delete=v1_delete, v2_delete=v2_delete, tier_create=tier_create, tier_update=tier_update+ )+++class TestConsolidateDags(BaseTest):+ def _query(self, name: str, sql: str, interval: timedelta | None = None) -> DataWarehouseSavedQuery:+ return DataWarehouseSavedQuery.objects.create(+ name=name, team=self.team, query={"query": sql, "kind": "HogQLQuery"}, sync_frequency_interval=interval+ )++ def _node(self, dag: DAG, saved_query: DataWarehouseSavedQuery) -> Node:+ return Node.objects.create(team=self.team, dag=dag, saved_query=saved_query, type=NodeType.MAT_VIEW)++ def _run(self, *args: str, apply: bool = False) -> str:+ out = StringIO()+ err = StringIO()+ flags = ["--apply"] if apply else []+ call_command("consolidate_dags", "--team-id", str(self.team.pk), *flags, *args, stdout=out, stderr=err)+ return out.getvalue() + err.getvalue()++ def test_end_to_end_shared_dropped_unique_moved_with_rebuilt_edges(self):+ # The moved query depends on the dropped one, so its edges must rebuild against the+ # target's existing copy; the source DAG and both its nodes must be gone afterwards.+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ shared = self._query("shared_mv", "SELECT 1")+ target_shared_node = self._node(target, shared)+ self._node(source, shared)+ moved = self._query("only_in_source", "SELECT * FROM shared_mv")+ self._node(source, moved)++ with _temporal_boundary():+ output = self._run(apply=True)++ self.assertFalse(DAG.objects.filter(id=source.id).exists())+ moved_node = Node.objects.get(dag=target, saved_query=moved)+ self.assertTrue(Edge.objects.filter(dag=target, source=target_shared_node, target=moved_node).exists())+ self.assertEqual(Node.objects.filter(saved_query=shared).count(), 1)+ self.assertEqual(Node.objects.filter(saved_query=moved).count(), 1)+ self.assertIn("moved only_in_source", output)+ self.assertIn("dropped duplicate shared_mv", output)+ self.assertIn("deleted source DAG", output)++ def test_moves_sync_in_dependency_order(self):+ # dep_child depends on dep_parent, both only in the source: syncing the child first would+ # fail dependency resolution in the target (Node.DoesNotExist) and keep the source DAG.+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ parent = self._query("dep_parent", "SELECT * FROM events")+ child = self._query("dep_child", "SELECT * FROM dep_parent")+ parent_node = self._node(source, parent)+ child_node = self._node(source, child)+ Edge.objects.create(team=self.team, dag=source, source=parent_node, target=child_node)++ with _temporal_boundary():+ self._run(apply=True)++ self.assertFalse(DAG.objects.filter(id=source.id).exists())+ new_parent = Node.objects.get(dag=target, saved_query=parent)+ new_child = Node.objects.get(dag=target, saved_query=child)+ self.assertTrue(Edge.objects.filter(dag=target, source=new_parent, target=new_child).exists())+ events = Node.objects.get(dag=target, name="events", type=NodeType.TABLE)+ self.assertTrue(Edge.objects.filter(dag=target, source=events, target=new_parent).exists())++ @parameterized.expand(+ [+ ("tiered", "tier", True, True),+ ("legacy_v2", "legacy", True, False),+ ("v1_only", "none", False, False),+ ]+ )+ def test_target_schedule_mode_controls_teardown(self, _name, existing_kind, expect_sweep, expect_reconcile):+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ shared = self._query("shared_mv", "SELECT 1", interval=H6)+ self._node(target, shared)+ self._node(source, shared)+ moved = self._query("only_in_source", "SELECT * FROM events", interval=H6)+ self._node(source, moved)++ tier_id = tier_schedule_id(str(target.id), H6)+ schedules_by_dag = {+ "tier": {str(target.id): [tier_id]},+ "legacy": {str(target.id): [str(target.id)]},+ "none": {},+ }[existing_kind]++ with _temporal_boundary(schedules_by_dag=schedules_by_dag) as mocks:+ self._run(apply=True)++ self.assertFalse(DAG.objects.filter(id=source.id).exists())+ moved.refresh_from_db()+ shared.refresh_from_db()+ moved_node = Node.objects.get(dag=target, saved_query=moved)+ if expect_sweep:+ swept = {call.kwargs["schedule_id"] for call in mocks.v1_delete.call_args_list}+ self.assertEqual(swept, {str(moved.id), str(shared.id)})+ self.assertIsNone(moved.sync_frequency_interval)+ self.assertIsNone(shared.sync_frequency_interval)+ # cadence intent survives the nulled interval as a declared node target+ self.assertEqual(get_declared_target(moved_node), H6)+ else:+ mocks.v1_delete.assert_not_called()+ self.assertEqual(moved.sync_frequency_interval, H6)+ self.assertEqual(shared.sync_frequency_interval, H6)+ self.assertIsNone(get_declared_target(moved_node))+ if expect_reconcile:+ mocks.tier_update.assert_called_once()+ self.assertEqual(mocks.tier_update.call_args.kwargs["id"], tier_id)+ mocks.tier_create.assert_not_called()+ else:+ mocks.tier_update.assert_not_called()+ mocks.tier_create.assert_not_called()++ def test_refuses_v2_scheduled_source_when_target_is_v1_only(self):+ # moving these queries would strand them: their execute-dag schedules die with the source+ # DAG but a v1-only target has no schedule to hand coverage to+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ moved = self._query("only_in_source", "SELECT 1", interval=H6)+ self._node(source, moved)++ with _temporal_boundary(schedules_by_dag={str(source.id): [str(source.id)]}) as mocks:+ with self.assertRaisesRegex(CommandError, "v2-scheduled"):+ self._run(apply=True)++ self.assertTrue(DAG.objects.filter(id=source.id).exists())+ self.assertFalse(Node.objects.filter(dag=target, saved_query=moved).exists())+ moved.refresh_from_db()+ self.assertEqual(moved.sync_frequency_interval, H6)+ mocks.v1_delete.assert_not_called()+ mocks.v2_delete.assert_not_called()++ def test_rerun_finalizes_target_after_crashed_run(self):+ # a prior run that crashed after deleting its source DAGs leaves a moved query on the+ # target with its interval intact, no declared target, and a live v1 schedule; a plain+ # re-run must finish seed/sweep/null/reconcile from the target's own state+ target = DAG.get_or_create_default(self.team)+ stranded = self._query("stranded_mv", "SELECT 1", interval=H6)+ node = self._node(target, stranded)+ tier_id = tier_schedule_id(str(target.id), H6)++ with _temporal_boundary(schedules_by_dag={str(target.id): [tier_id]}) as mocks:+ self._run(apply=True)++ node.refresh_from_db()+ stranded.refresh_from_db()+ self.assertEqual(get_declared_target(node), H6)+ self.assertIsNone(stranded.sync_frequency_interval)+ swept = {call.kwargs["schedule_id"] for call in mocks.v1_delete.call_args_list}+ self.assertEqual(swept, {str(stranded.id)})+ mocks.tier_update.assert_called_once()+ self.assertEqual(mocks.tier_update.call_args.kwargs["id"], tier_id)++ def test_source_dag_interval_carries_as_declared_target(self):+ # Legacy-migrated source shape: query intervals nulled, cadence lives only on+ # dag.sync_frequency_interval. The finalize seeds from the *target* DAG, whose interval is+ # NULL here, so unless the source cadence is captured at plan time the moved query arrives+ # with no effective cadence and reconcile drops it from every tier.+ target = DAG.get_or_create_default(self.team)+ target.sync_frequency_interval = None+ target.save()+ source = DAG.objects.create(team=self.team, name="posthog_team", sync_frequency_interval=H6)+ moved = self._query("only_in_source", "SELECT 1")+ self._node(source, moved)+ tier_id = tier_schedule_id(str(target.id), H6)++ with _temporal_boundary(schedules_by_dag={str(target.id): [tier_id], str(source.id): [str(source.id)]}):+ self._run(apply=True)++ self.assertFalse(DAG.objects.filter(id=source.id).exists())+ moved_node = Node.objects.get(dag=target, saved_query=moved)+ self.assertEqual(get_declared_target(moved_node), H6)++ def test_finalize_redetects_target_mode_after_mid_run_conversion(self):+ # The pre-flight check sees a v1-only target; a concurrent reconcile converts it to tiers+ # before the finalize. Acting on the stale snapshot would skip the seed/sweep/reconcile and+ # leave the moved query double-scheduled (v1 + tier).+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ moved = self._query("only_in_source", "SELECT 1", interval=H6)+ self._node(source, moved)+ tier_id = tier_schedule_id(str(target.id), H6)++ target_listings = iter([set(), {tier_id}])++ def fake_listing(dag_id):+ if dag_id == str(target.id):+ return next(target_listings)+ return set()++ with (+ _temporal_boundary(schedules_by_dag={str(target.id): [tier_id]}) as mocks,+ mock.patch(f"{COMMAND}.list_existing_schedule_ids", side_effect=fake_listing),+ ):+ self._run(apply=True)++ moved.refresh_from_db()+ self.assertIsNone(moved.sync_frequency_interval)+ swept = {call.kwargs["schedule_id"] for call in mocks.v1_delete.call_args_list}+ self.assertEqual(swept, {str(moved.id)})+ mocks.tier_update.assert_called_once()+ self.assertEqual(get_declared_target(Node.objects.get(dag=target, saved_query=moved)), H6)++ def test_failed_move_keeps_source_dag_and_raises(self):+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ good = self._query("good_view", "SELECT 1")+ bad = self._query("bad_view", "SELECT * FROM nonexistent_table_xyz")+ self._node(source, good)+ self._node(source, bad)++ with _temporal_boundary() as mocks:+ with self.assertRaisesRegex(CommandError, "incomplete"):+ self._run(apply=True)++ # the DAG survives so the failed query's only node is not destroyed; the successful move+ # remains in the target as a duplicate a re-run classifies as DROP+ self.assertTrue(DAG.objects.filter(id=source.id).exists())+ self.assertTrue(Node.objects.filter(dag=source, saved_query=bad).exists())+ self.assertTrue(Node.objects.filter(dag=target, saved_query=good).exists())+ mocks.v2_delete.assert_not_called()++ def test_schedule_teardown_failure_keeps_source_dag(self):+ # deleting the DAG row before its execute-dag schedules are gone would orphan the+ # schedules forever (the row is the only pointer to them)+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ moved = self._query("only_in_source", "SELECT 1")+ self._node(source, moved)+ schedules_by_dag = {str(target.id): [str(target.id)], str(source.id): [str(source.id)]}++ with _temporal_boundary(schedules_by_dag=schedules_by_dag, v2_delete_error=RuntimeError("temporal down")):+ with self.assertRaisesRegex(CommandError, "incomplete"):+ self._run(apply=True)++ self.assertTrue(DAG.objects.filter(id=source.id).exists())+ self.assertTrue(Node.objects.filter(dag=target, saved_query=moved).exists())++ def test_dry_run_by_default_mutates_nothing(self):+ source = DAG.objects.create(team=self.team, name="posthog_team")+ target = DAG.get_or_create_default(self.team)+ shared = self._query("shared_mv", "SELECT 1", interval=H6)+ self._node(target, shared)+ self._node(source, shared)+ moved = self._query("only_in_source", "SELECT 1", interval=H6)+ self._node(source, moved)++ with _temporal_boundary() as mocks:+ output = self._run()++ self.assertIn("move 1, drop 1", output)+ self.assertIn("dry run", output)+ self.assertTrue(DAG.objects.filter(id=source.id).exists())+ self.assertFalse(Node.objects.filter(dag=target, saved_query=moved).exists())+ moved.refresh_from_db()+ self.assertEqual(moved.sync_frequency_interval, H6)+ mocks.v1_delete.assert_not_called()+ mocks.v2_delete.assert_not_called()++ def test_dry_run_reports_edge_impact(self):+ # An edge touching a moved node must be re-pointed to the target; an edge whose only+ # involved node is dropped is redundant against the target's existing edge.+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ shared = self._query("shared_mv", "SELECT 1")+ self._node(target, shared)+ dropped_node = self._node(source, shared)+ moved_node = self._node(source, self._query("only_in_source", "SELECT 1"))+ events = Node.objects.create(team=self.team, dag=source, name="events", type=NodeType.TABLE)+ Edge.objects.create(team=self.team, dag=source, source=events, target=moved_node)+ Edge.objects.create(team=self.team, dag=source, source=events, target=dropped_node)++ output = self._run()++ self.assertIn("edges to re-point (touch a moved node): 1", output)+ self.assertIn("edges to drop as redundant (only dropped nodes): 1", output)+ self.assertIn("edges to re-point: 1, edges to drop: 1", output)++ def test_duplicate_is_kept_when_the_claiming_dag_failed_to_move_it(self):+ # dag_a claims the shared query for MOVE and dag_b's copy is planned as a DROP. If dag_a's+ # move fails, dag_b's node is the last place that query's declared target exists — dropping+ # it and deleting dag_b would destroy the intent with only a "dropped duplicate" line.+ DAG.get_or_create_default(self.team)+ dag_a = DAG.objects.create(team=self.team, name="dag_a")+ dag_b = DAG.objects.create(team=self.team, name="dag_b")+ shared = self._query("shared_mv", "SELECT * FROM nonexistent_table_xyz")+ self._node(dag_a, shared)+ self._node(dag_b, shared)++ with _temporal_boundary():+ with self.assertRaisesRegex(CommandError, "incomplete"):+ self._run(apply=True)++ # dag_a could not move it, so dag_b's copy is the last node the query has anywhere+ self.assertTrue(DAG.objects.filter(id=dag_b.id).exists())+ self.assertTrue(Node.objects.filter(dag=dag_b, saved_query=shared).exists())++ def test_dag_default_cadence_seeds_a_moved_node_with_no_interval(self):+ # A query only ever scheduled by its DAG's default cadence has no interval of its own. The+ # finalize nulls every interval and then reconciles, so with no DAG-level fallback the moved+ # node arrives with nothing declared, gets no effective cadence, and is dropped from every+ # tier — it stops materializing with nothing left in Postgres or Temporal to show why.+ target = DAG.get_or_create_default(self.team)+ target.sync_frequency_interval = H6+ target.save()+ source = DAG.objects.create(team=self.team, name="posthog_team")+ moved = self._query("only_in_source", "SELECT 1") # no interval of its own+ self._node(source, moved)++ tier_id = tier_schedule_id(str(target.id), H6)+ with _temporal_boundary(schedules_by_dag={str(target.id): [tier_id]}):+ self._run(apply=True)++ moved_node = Node.objects.get(dag=target, saved_query=moved)+ self.assertEqual(get_declared_target(moved_node), H6)++ def test_verbose_lists_query_names(self):+ # --verbose is how an operator confirms *which* queries move before committing to --apply+ # on live data, so the per-name listing has to actually appear behind the flag.+ DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ self._node(source, self._query("only_in_source", "SELECT 1"))++ self.assertNotIn("only_in_source", self._run())+ self.assertIn("move (in dependency order): only_in_source", self._run("--verbose"))++ def test_conflicting_freshness_targets_flagged(self):+ # Same query in two DAGs with different declared cadences: only one node survives the merge,+ # so the dry run must surface both copies for a human to pick the winner.+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ shared = self._query("conflicted", "SELECT 1")+ set_declared_target(self._node(target, shared), H6)+ set_declared_target(self._node(source, shared), M15)++ output = self._run()++ self.assertIn("freshness-target conflicts: 1", output)+ self.assertIn("⚠ conflicted:", output)+ self.assertIn("6hour", output)+ self.assertIn("15min", output)++ @parameterized.expand([("both_agree", H6, H6), ("one_unset", H6, None), ("both_unset", None, None)])+ def test_non_conflicting_freshness_targets_not_flagged(self, _name, target_a, target_b):+ # Unset means "no opinion", so a lone declared target wins cleanly — not a conflict.+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ shared = self._query("agreeing", "SELECT 1")+ a = self._node(target, shared)+ b = self._node(source, shared)+ if target_a is not None:+ set_declared_target(a, target_a)+ if target_b is not None:+ set_declared_target(b, target_b)++ self.assertIn("freshness-target conflicts: 0", self._run())++ @parameterized.expand(+ [+ ("default_preferred", "default"),+ ("largest_without_default", "largest"),+ ("explicit_wins", "explicit"),+ ]+ )+ def test_target_selection(self, _name, kind):+ if kind == "largest":+ small = DAG.objects.create(team=self.team, name="small")+ large = DAG.objects.create(team=self.team, name="large")+ self._node(small, self._query("a", "SELECT 1"))+ self._node(large, self._query("b", "SELECT 1"))+ self._node(large, self._query("c", "SELECT 1"))++ output = self._run()++ self.assertIn(f"Merge target: large ({large.id})", output)+ self.assertIn("largest DAG by node count", output)+ return++ default = DAG.get_or_create_default(self.team)+ other = DAG.objects.create(team=self.team, name="posthog_team")+ self._node(other, self._query("a", "SELECT 1"))++ if kind == "explicit":+ output = self._run("--target-dag-id", str(other.id))+ self.assertIn(f"Merge target: posthog_team ({other.id})", output)+ self.assertIn("chosen via --target-dag-id", output)+ else:+ output = self._run()+ self.assertIn(f"Merge target: Default ({default.id})", output)+ self.assertIn("canonical 'Default' DAG", output)++ def test_managed_dag_never_touched(self):+ target = DAG.get_or_create_default(self.team)+ managed = DAG.get_or_create_revenue_analytics(self.team)+ managed_query = self._query("stripe.prod.mrr_revenue_view", "SELECT 1")+ self._node(managed, managed_query)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ moved = self._query("only_in_source", "SELECT 1")+ self._node(source, moved)++ with _temporal_boundary():+ output = self._run(apply=True)++ self.assertIn(f"Excluding 1 system-managed DAG(s): {REVENUE_ANALYTICS_DAG_NAME}", output)+ self.assertTrue(DAG.objects.filter(id=managed.id).exists())+ self.assertTrue(Node.objects.filter(dag=managed, saved_query=managed_query).exists())+ self.assertFalse(DAG.objects.filter(id=source.id).exists())+ self.assertTrue(Node.objects.filter(dag=target, saved_query=moved).exists())++ @parameterized.expand(+ [+ ("managed_target", "managed"),+ ("unknown_target", "unknown"),+ ("not_a_uuid", "garbage"),+ ]+ )+ def test_bad_target_dag_id_errors_before_any_change(self, _name, kind):+ DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ self._node(source, self._query("only_in_source", "SELECT 1"))+ managed = DAG.get_or_create_revenue_analytics(self.team)+ target_id = {"managed": str(managed.id), "unknown": str(uuid.uuid4()), "garbage": "not-a-uuid"}[kind]++ with _temporal_boundary():+ with self.assertRaises(CommandError):+ self._run("--target-dag-id", target_id, apply=True)++ self.assertTrue(DAG.objects.filter(id=source.id).exists())++ @parameterized.expand([("two_sources", 2), ("three_sources", 3)])+ def test_query_in_several_source_dags_lands_exactly_once(self, _name: str, source_count: int):+ # `saved_query_unique_within_team_dag` means the query can only land once: the first source+ # moves it, every later one must drop. Three sources exercises a drop against a target that+ # already holds the node, which two sources never reaches.+ target = DAG.get_or_create_default(self.team)+ shared = self._query("shared_everywhere", "SELECT 1")+ sources = [DAG.objects.create(team=self.team, name=f"dag_{i}") for i in range(source_count)]+ for source in sources:+ self._node(source, shared)++ with _temporal_boundary():+ output = self._run(apply=True)++ self.assertFalse(DAG.objects.filter(id__in=[dag.id for dag in sources]).exists())+ self.assertEqual(Node.objects.filter(saved_query=shared).count(), 1)+ self.assertTrue(Node.objects.filter(dag=target, saved_query=shared).exists())+ self.assertIn(f"moved: 1, dropped: {source_count - 1}", output)++ @parameterized.expand(+ [+ ("moved_node_inherits", "move", None, M15),+ ("dropped_copies_onto_unset_target", "drop", None, M15),+ ("target_declared_wins", "drop", H6, H6),+ ]+ )+ def test_declared_target_carried_from_source(self, _name, kind, target_declared, expected):+ target = DAG.get_or_create_default(self.team)+ source = DAG.objects.create(team=self.team, name="posthog_team")+ saved_query = self._query("carried", "SELECT 1")+ if kind == "drop":+ target_node = self._node(target, saved_query)+ if target_declared is not None:+ set_declared_target(target_node, target_declared)+ source_node = self._node(source, saved_query)+ set_declared_target(source_node, M15)++ with _temporal_boundary():+ self._run(apply=True)++ node = Node.objects.get(dag=target, saved_query=saved_query)+ self.assertEqual(get_declared_target(node), expected)