Skip to content

: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.

feat(data-modeling): add --adopt-unresolvable to consolidate_dags (#75397)

Jovan Sakovic818f7d02d4a2
diff --git a/products/data_modeling/backend/logic/saved_query_dag_sync.py b/products/data_modeling/backend/logic/saved_query_dag_sync.py
index ef4ed545a0a9..25e6e4499df4 100644
--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py
+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, TypedDict
import structlog
@@ -22,6 +22,26 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
+# properties["system"] marker set by consolidate_dags --adopt-unresolvable when a query's SQL
+# would not resolve and its node was created without edges. A successful sync clears it.
+DEGRADED_SYNC_KEY = "degraded_sync"
+
+
+class DegradedSyncMarker(TypedDict):
+ error: str
+ at: str
+
+
+def node_type_for(saved_query: "DataWarehouseSavedQuery") -> NodeType:
+ """The node type a saved query's DAG node should carry."""
+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+
+ if saved_query.origin == DataWarehouseSavedQuery.Origin.ENDPOINT:
+ return NodeType.ENDPOINT
+ if saved_query.table_id is not None:
+ return NodeType.MAT_VIEW
+ return NodeType.VIEW
+
def get_dag_id(team_id: int) -> str:
"""Return the standard dag_id for a team."""
@@ -133,7 +153,6 @@ def sync_saved_query_to_dag(
Raises QueryError or CycleDetectionError if the query would create an invalid DAG.
Raises ManagedDAGError if dag is system-managed and allow_managed is False.
"""
- from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
extra_properties = extra_properties or {}
team = saved_query.team
@@ -145,13 +164,7 @@ def sync_saved_query_to_dag(
if not model_query:
raise ValueError(f"DataWarehouseSavedQuery has no query: saved_query_id={saved_query.id}")
- # determine node type
- if saved_query.origin == DataWarehouseSavedQuery.Origin.ENDPOINT:
- node_type = NodeType.ENDPOINT
- elif saved_query.table:
- node_type = NodeType.MAT_VIEW
- else:
- node_type = NodeType.VIEW
+ node_type = node_type_for(saved_query)
target, _ = Node.objects.get_or_create(
team=team,
@@ -185,6 +198,13 @@ def sync_saved_query_to_dag(
target.delete()
raise
+ # resolution succeeded, so an edge-less adoption marker no longer describes this node
+ system = (target.properties or {}).get("system")
+ if isinstance(system, dict):
+ system.pop(DEGRADED_SYNC_KEY, None)
+ if not system:
+ target.properties.pop("system", None)
+
# name is included in update_fields because Node.save() auto-syncs it from saved_query
target.save(update_fields=["name", "type", "properties"])
# After the save, so it reads fresh state under a row lock rather than riding along on the
diff --git a/products/data_modeling/backend/management/commands/consolidate_dags.py b/products/data_modeling/backend/management/commands/consolidate_dags.py
index 92a93d4a0600..7f18af326802 100644
--- a/products/data_modeling/backend/management/commands/consolidate_dags.py
+++ b/products/data_modeling/backend/management/commands/consolidate_dags.py
@@ -5,12 +5,17 @@ from datetime import timedelta
from typing import Any
from django.conf import settings
+from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.db import transaction
+from django.utils import timezone
import structlog
from temporalio.client import Client
from temporalio.service import RPCError, RPCStatusCode
+from posthog.hogql.errors import BaseHogQLError
+
from posthog.temporal.common.client import sync_connect
from posthog.temporal.common.schedule import delete_schedule
@@ -27,7 +32,12 @@ from products.data_modeling.backend.logic.node_frequency import (
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.saved_query_dag_sync import (
+ DEGRADED_SYNC_KEY,
+ DegradedSyncMarker,
+ node_type_for,
+ sync_saved_query_to_dag,
+)
from products.data_modeling.backend.logic.schedule_reconcile import (
delete_v1_saved_query_schedules,
list_existing_schedule_ids,
@@ -37,6 +47,7 @@ from products.data_modeling.backend.logic.schedule_reconcile import (
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.modeling import UnknownParentError
from products.data_modeling.backend.models.node import Node, NodeType
logger = structlog.get_logger(__name__)
@@ -46,6 +57,13 @@ 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
+# The sync failures --adopt-unresolvable may adopt: the query's SQL failing to parse or resolve
+# (BaseHogQLError covers parse errors and the BoundedResolver family), a parent that is not a
+# known table or view, or a parent whose node lives in a DAG the resolver cannot see (surfaces
+# as Node/SavedQuery DoesNotExist). Operational failures (DB errors, ManagedDAGError, a query
+# with no SQL at all) stay failed moves — a retry could still move those intact.
+ADOPTABLE_SYNC_ERRORS = (BaseHogQLError, UnknownParentError, ObjectDoesNotExist)
+
@dataclasses.dataclass
class MoveItem:
@@ -83,8 +101,10 @@ class Command(BaseCommand):
"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."
+ "with --apply completes a partially-applied consolidation. A query whose SQL fails "
+ "dependency resolution normally keeps its source DAG and fails the run; "
+ "--adopt-unresolvable instead lands it in the target with no edges and a "
+ "properties.system.degraded_sync marker. Dry run by default; pass --apply to execute."
)
def add_arguments(self, parser: CommandParser) -> None:
@@ -106,6 +126,18 @@ class Command(BaseCommand):
action="store_true",
help="List per-query names under each source DAG's move/drop counts (default: counts only)",
)
+ parser.add_argument(
+ "--adopt-unresolvable",
+ action="store_true",
+ default=False,
+ help=(
+ "When a query's SQL fails dependency resolution during a move, create its node in "
+ "the target with no incoming edges (marked properties.system.degraded_sync) instead "
+ "of keeping the source DAG and failing the run. The query keeps failing at "
+ "materialization time as it already does; edges rebuild on its next successful "
+ "sync. Caveat: until then the node runs at level 0, before any real parents."
+ ),
+ )
def handle(self, *args: Any, **options: Any) -> None:
team_id: int = options["team_id"]
@@ -190,14 +222,30 @@ class Command(BaseCommand):
consolidated_sq_ids: set[str] = set()
kept_dags: list[str] = []
+ adopted_names: list[str] = []
for plan in plans:
- kept_reason = self._apply_source_dag(plan, target, temporal, consolidated_sq_ids)
+ kept_reason = self._apply_source_dag(
+ plan,
+ target,
+ temporal,
+ consolidated_sq_ids,
+ adopted_names,
+ adopt_unresolvable=options["adopt_unresolvable"],
+ )
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 adopted_names:
+ self.stdout.write(
+ self.style.WARNING(
+ f" adopted {len(adopted_names)} query(ies) without edges (SQL failed to resolve): "
+ f"{', '.join(sorted(adopted_names))} — they run at level 0 until their next "
+ "successful sync rebuilds edges"
+ )
+ )
if v1_failed_sq_ids:
self.stdout.write(
self.style.WARNING(
@@ -472,6 +520,9 @@ class Command(BaseCommand):
target: DAG,
temporal: Client,
consolidated_sq_ids: set[str],
+ adopted_names: list[str],
+ *,
+ adopt_unresolvable: bool = False,
) -> str | None:
"""Consolidate one source DAG. Returns None on success, or the reason the DAG was kept.
@@ -493,14 +544,22 @@ class Command(BaseCommand):
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}")
+ adoptable = adopt_unresolvable and isinstance(error, ADOPTABLE_SYNC_ERRORS)
+ node = self._adopt_without_edges(item.saved_query, target, error) if adoptable else None
+ if node is None:
+ 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
+ self._carry_declared_target(node, item.declared_target, item.saved_query.name)
+ moved_sq_ids.append(str(item.saved_query.id))
+ adopted_names.append(item.saved_query.name)
+ self.stdout.write(self.style.WARNING(f" adopted {item.saved_query.name} without edges: {error}"))
continue
if node is not None:
self._carry_declared_target(node, item.declared_target, item.saved_query.name)
@@ -535,6 +594,39 @@ class Command(BaseCommand):
consolidated_sq_ids.update(drop.saved_query_id for drop in plan.drops)
return None
+ def _adopt_without_edges(self, saved_query: DataWarehouseSavedQuery, target: DAG, error: Exception) -> Node | None:
+ """Last-resort landing for a query whose SQL will not resolve: create its node in the
+ target with no incoming edges so the consolidation can proceed and the source DAG can be
+ deleted. The query keeps failing at materialization time exactly as it did in the source
+ DAG (feeding the suspension circuit breaker), the marker makes these nodes findable
+ fleet-wide, and the next successful sync clears the marker and rebuilds real edges.
+ Returns None if even the bare node cannot be created, falling back to keeping the DAG.
+ """
+ marker: DegradedSyncMarker = {"error": str(error)[:500], "at": timezone.now().isoformat()}
+ try:
+ # Atomic so a failed marker save rolls the creation back too: a committed but
+ # unmarked node would make the re-run classify this query as DROP instead of
+ # retrying the move, stranding it edge-less and invisible to the marker sweep.
+ with transaction.atomic():
+ node, _ = Node.objects.get_or_create(
+ team_id=saved_query.team_id,
+ saved_query=saved_query,
+ dag=target,
+ defaults={"name": saved_query.name, "type": node_type_for(saved_query)},
+ )
+ properties = node.properties or {}
+ properties.setdefault("system", {})[DEGRADED_SYNC_KEY] = marker
+ node.properties = properties
+ node.save(update_fields=["properties"])
+ return node
+ except Exception:
+ logger.exception(
+ "Failed to adopt unresolvable saved query into target DAG",
+ saved_query_id=str(saved_query.id),
+ target_dag_id=str(target.id),
+ )
+ 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).
diff --git a/products/data_modeling/backend/test/test_consolidate_dags.py b/products/data_modeling/backend/test/test_consolidate_dags.py
index 7f33f0af300f..21f09cf1789f 100644
--- a/products/data_modeling/backend/test/test_consolidate_dags.py
+++ b/products/data_modeling/backend/test/test_consolidate_dags.py
@@ -16,6 +16,7 @@ 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.logic.saved_query_dag_sync import sync_saved_query_to_dag
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
@@ -291,6 +292,120 @@ class TestConsolidateDags(BaseTest):
self.assertTrue(Node.objects.filter(dag=target, saved_query=good).exists())
mocks.v2_delete.assert_not_called()
+ def test_adopt_unresolvable_lands_broken_query_edge_less_and_deletes_source_dag(self):
+ # One broken query must not hold the team's consolidation hostage: with the flag, the
+ # unresolvable query is adopted into the target with no edges and a marker, cadence intent
+ # intact, while healthy queries move normally and the source DAG is deleted.
+ target = DAG.get_or_create_default(self.team)
+ source = DAG.objects.create(team=self.team, name="posthog_team")
+ good = self._query("good_view", "SELECT * FROM events")
+ bad = self._query("bad_view", "SELECT * FROM nonexistent_table_xyz")
+ self._node(source, good)
+ set_declared_target(self._node(source, bad), M15)
+
+ with _temporal_boundary():
+ output = self._run("--adopt-unresolvable", apply=True)
+
+ self.assertFalse(DAG.objects.filter(id=source.id).exists())
+ adopted = Node.objects.get(dag=target, saved_query=bad)
+ self.assertFalse(Edge.objects.filter(dag=target, target=adopted).exists())
+ self.assertIn("nonexistent_table_xyz", adopted.properties["system"]["degraded_sync"]["error"])
+ self.assertEqual(get_declared_target(adopted), M15)
+ good_node = Node.objects.get(dag=target, saved_query=good)
+ events = Node.objects.get(dag=target, name="events", type=NodeType.TABLE)
+ self.assertTrue(Edge.objects.filter(dag=target, source=events, target=good_node).exists())
+ self.assertIn("adopted bad_view without edges", output)
+
+ def test_adopted_node_unblocks_its_dependents_moves(self):
+ # The reason the flag exists: one unresolvable query must not cascade into N failed
+ # moves. Parent in a managed DAG (excluded from consolidation) → dependent fails
+ # Node.DoesNotExist and is adopted edge-less → the dependent's own dependent resolves
+ # the adopted node in the target and moves with a real edge.
+ target = DAG.get_or_create_default(self.team)
+ managed = DAG.get_or_create_revenue_analytics(self.team)
+ managed_parent = self._query("stripe_view", "SELECT 1")
+ self._node(managed, managed_parent)
+ source = DAG.objects.create(team=self.team, name="posthog_team")
+ blocked = self._query("blocked_view", "SELECT * FROM stripe_view")
+ dependent = self._query("dependent_view", "SELECT * FROM blocked_view")
+ blocked_node = self._node(source, blocked)
+ dependent_node = self._node(source, dependent)
+ Edge.objects.create(team=self.team, dag=source, source=blocked_node, target=dependent_node)
+
+ with _temporal_boundary():
+ output = self._run("--adopt-unresolvable", apply=True)
+
+ self.assertFalse(DAG.objects.filter(id=source.id).exists())
+ adopted = Node.objects.get(dag=target, saved_query=blocked)
+ self.assertFalse(Edge.objects.filter(dag=target, target=adopted).exists())
+ self.assertIn("degraded_sync", adopted.properties["system"])
+ moved = Node.objects.get(dag=target, saved_query=dependent)
+ self.assertTrue(Edge.objects.filter(dag=target, source=adopted, target=moved).exists())
+ self.assertIn("adopted blocked_view without edges", output)
+ self.assertIn("moved dependent_view", output)
+
+ def test_adopt_unresolvable_does_not_adopt_non_resolution_failures(self):
+ # The flag exists for SQL that cannot resolve. A sync that fails for operational reasons
+ # (DB blip, programming error) must stay a failed move — adopting it would delete the
+ # source DAG and report success on a query a plain retry would have moved intact.
+ 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)
+
+ with _temporal_boundary():
+ with mock.patch(f"{COMMAND}.sync_saved_query_to_dag", side_effect=RuntimeError("db down")):
+ with self.assertRaisesRegex(CommandError, "incomplete"):
+ self._run("--adopt-unresolvable", apply=True)
+
+ self.assertTrue(DAG.objects.filter(id=source.id).exists())
+ self.assertFalse(Node.objects.filter(dag=target, saved_query=moved).exists())
+
+ def test_adoption_failure_rolls_back_the_node(self):
+ # If the marker save fails after get_or_create committed the node, an unmarked edge-less
+ # node would survive; the re-run would then classify the query as DROP instead of
+ # retrying the move, stranding it without the marker forever. Create + mark must commit
+ # or roll back together so the re-run sees a clean MOVE to retry.
+ target = DAG.get_or_create_default(self.team)
+ source = DAG.objects.create(team=self.team, name="posthog_team")
+ bad = self._query("bad_view", "SELECT * FROM nonexistent_table_xyz")
+ self._node(source, bad)
+
+ real_save = Node.save
+
+ def failing_marker_save(node, *args, **kwargs):
+ if kwargs.get("update_fields") == ["properties"]:
+ raise RuntimeError("connection lost")
+ return real_save(node, *args, **kwargs)
+
+ with _temporal_boundary():
+ with mock.patch.object(Node, "save", autospec=True, side_effect=failing_marker_save):
+ with self.assertRaisesRegex(CommandError, "incomplete"):
+ self._run("--adopt-unresolvable", apply=True)
+
+ self.assertTrue(DAG.objects.filter(id=source.id).exists())
+ self.assertFalse(Node.objects.filter(dag=target, saved_query=bad).exists())
+
+ def test_degraded_sync_marker_cleared_when_query_resolves_again(self):
+ # A stale marker after the customer fixes their SQL would make the post-fix re-sync sweep
+ # (and any dashboard keyed on the marker) report a healthy node as degraded forever.
+ target = DAG.get_or_create_default(self.team)
+ fixed = self._query("fixed_view", "SELECT * FROM events")
+ node = Node.objects.create(
+ team=self.team,
+ dag=target,
+ saved_query=fixed,
+ type=NodeType.VIEW,
+ properties={"system": {"degraded_sync": {"error": "Unknown table", "at": "2026-07-30T00:00:00+00:00"}}},
+ )
+
+ sync_saved_query_to_dag(fixed, dag=target, reconcile=False)
+
+ node.refresh_from_db()
+ self.assertNotIn("system", node.properties)
+ events = Node.objects.get(dag=target, name="events", type=NodeType.TABLE)
+ self.assertTrue(Edge.objects.filter(dag=target, source=events, target=node).exists())
+
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)