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.

fix(data-modeling): give every saved view a dag node (#116637)

Thiago Salvatore17b9acfae0c7
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index b5392b8a6dab..9cb02dc46daa 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -29,6 +29,7 @@ _LAZY = {
"describe_dependents": "logic.saved_query_dag_sync",
"promote_view_nodes_to_matview": "logic.saved_query_dag_sync",
"sync_saved_query_to_dag": "logic.saved_query_dag_sync",
+ "adopt_saved_query_without_edges": "logic.saved_query_dag_sync",
"update_node_type": "logic.saved_query_dag_sync",
"link_endpoint_nodes": "logic.node_endpoint",
"endpoint_link": "logic.node_endpoint",
diff --git a/products/data_modeling/backend/logic/node_frequency.py b/products/data_modeling/backend/logic/node_frequency.py
index 31c461f459f2..6b888915150a 100644
--- a/products/data_modeling/backend/logic/node_frequency.py
+++ b/products/data_modeling/backend/logic/node_frequency.py
@@ -9,7 +9,7 @@ typed column.
import uuid
import dataclasses
-from collections.abc import Iterable
+from collections.abc import Collection, Iterable
from datetime import timedelta
from django.db.models import Q, QuerySet
@@ -354,11 +354,13 @@ def schedulable_nodes(dag: DAG) -> QuerySet[Node]:
return Node.objects.filter(dag=dag, type__in=SAVED_QUERY_NODE_TYPES).exclude(saved_query__deleted=True)
-def persist_seed_targets(dag: DAG, default: timedelta | None = None) -> int:
+def persist_seed_targets(
+ dag: DAG, default: timedelta | None = None, only_node_ids: Collection[str] | 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.
+ anywhere. `only_node_ids` limits the seeding to those nodes. Returns how many targets were written.
"""
graph = build_frequency_graph(dag)
floors = all_source_floors(graph.edges, graph.source_intervals)
@@ -366,6 +368,8 @@ def persist_seed_targets(dag: DAG, default: timedelta | None = None) -> int:
written = 0
for node in schedulable_nodes(dag):
node_id = str(node.id)
+ if only_node_ids is not None and node_id not in only_node_ids:
+ continue
if get_declared_target(node) is not None:
continue
raw = seeds.get(node_id, default)
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 ac8402f255cf..664f108e1fd8 100644
--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py
+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py
@@ -336,6 +336,17 @@ def replace_incoming_edges(
return unresolved
+def lineage_database(team: "Team") -> Database:
+ """The HogQL database a DAG sync resolves dependencies against."""
+ # Internal DAG sync (no user); bypass warehouse HogQL access control so dependency resolution
+ # sees every referenced table/view.
+ return Database.create_for(
+ team=team,
+ bypass_warehouse_access_control=True,
+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,
+ )
+
+
def sync_saved_query_to_dag(
saved_query: "DataWarehouseSavedQuery",
extra_properties: dict | None = None, # TODO(andrew): remove this after backfill
@@ -379,14 +390,8 @@ def sync_saved_query_to_dag(
node_type = node_type_for(saved_query)
- # Internal DAG sync (no user); bypass warehouse HogQL access control so dependency resolution
- # sees every referenced table/view.
if database is None:
- database = Database.create_for(
- team=team,
- bypass_warehouse_access_control=True,
- allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,
- )
+ database = lineage_database(team)
# parsed before the node exists, so a query that cannot be parsed leaves nothing to undo
model_name = saved_query.name
dependencies = get_parents_from_model_query(team, model_name, model_query, database=database)
@@ -427,6 +432,24 @@ def sync_saved_query_to_dag(
return target
+def adopt_saved_query_without_edges(team_id: int, saved_query_id: UUID, error: str, dag_id: UUID | None = None) -> None:
+ """Give a saved query whose lineage did not sync a node marked sync-failed, without rebuilding its edges."""
+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+
+ saved_query = DataWarehouseSavedQuery.objects.select_related("team").get(team_id=team_id, id=saved_query_id)
+ dag = DAG.objects.get(team_id=team_id, id=dag_id) if dag_id else DAG.get_or_create_default(saved_query.team)
+ with transaction.atomic():
+ node, _ = Node.objects.get_or_create(
+ team_id=team_id,
+ saved_query=saved_query,
+ dag=dag,
+ defaults={"name": saved_query.name, "type": node_type_for(saved_query)},
+ )
+ node = Node.objects.select_for_update().get(pk=node.pk)
+ node.mark_lineage_sync_failed(error)
+ node.save(update_fields=["properties"])
+
+
def _nameless_refusal(view_name: str) -> str:
return f"Can't delete {view_name} yet. Something else reads from it. Update or delete it first."
diff --git a/products/data_modeling/backend/management/commands/backfill_saved_query_nodes.py b/products/data_modeling/backend/management/commands/backfill_saved_query_nodes.py
new file mode 100644
index 000000000000..9ac53885312b
--- /dev/null
+++ b/products/data_modeling/backend/management/commands/backfill_saved_query_nodes.py
@@ -0,0 +1,156 @@
+from collections.abc import Iterable
+from datetime import timedelta
+from itertools import groupby
+
+from django.core.exceptions import ObjectDoesNotExist
+from django.core.management.base import BaseCommand, CommandParser
+from django.db import transaction
+from django.db.models import Exists, OuterRef
+
+from posthog.hogql.database.database import Database
+from posthog.hogql.errors import BaseHogQLError
+
+from posthog.dataclasses import frozen
+from posthog.models import Team
+
+from products.data_modeling.backend.logic.node_frequency import persist_seed_targets
+from products.data_modeling.backend.logic.saved_query_dag_sync import (
+ adopt_saved_query_without_edges,
+ lineage_database,
+ sync_saved_query_to_dag,
+)
+from products.data_modeling.backend.logic.schedule_reconcile import reconcile_dag_schedules
+from products.data_modeling.backend.logic.tier_run_report import MATERIALIZING_TYPES
+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.modeling import UnknownParentError
+from products.data_modeling.backend.models.node import Node
+
+DEFAULT_MATERIALIZED_TARGET = timedelta(days=1)
+ADOPTABLE_SYNC_ERRORS = (BaseHogQLError, UnknownParentError, ObjectDoesNotExist)
+
+
+@frozen
+class TeamBackfill:
+ synced: int
+ adopted: int
+ seeded: int
+ failed: dict[str, str]
+
+
+class Command(BaseCommand):
+ help = (
+ "Give every live saved query that has no DAG node a node in its team's default DAG. "
+ "A query whose lineage does not resolve gets a node with no edges and a sync-failed marker. "
+ "A materialized query gets a freshness target, its own interval or else its DAG's or else 1 day, "
+ "so a tier schedule picks it up. Any other sync error is reported and left for a re-run. "
+ "Each team's DAG schedules are reconciled afterwards, and always for a team passed with --team-id. "
+ "Managed-viewset queries are skipped. Dry run unless --apply is passed."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, action="append", dest="team_ids", help="Limit to this team.")
+ parser.add_argument("--apply", action="store_true", help="Write the nodes. Without it, only list them.")
+
+ def handle(self, *args: object, team_ids: list[int] | None, apply: bool, **options: object) -> None:
+ nodeless = nodeless_saved_queries(team_ids)
+ teams = sorted({saved_query.team_id for saved_query in nodeless})
+ self.stdout.write(f"{len(nodeless)} nodeless saved queries across {len(teams)} teams")
+ if not apply:
+ for saved_query in nodeless:
+ self.stdout.write(f" team {saved_query.team_id}: {saved_query.name} ({saved_query.id})")
+ return
+
+ dags_to_reconcile = {
+ team.pk: DAG.get_or_create_default(team) for team in Team.objects.filter(id__in=team_ids or [])
+ }
+ for team_id, grouped in groupby(nodeless, key=lambda saved_query: saved_query.team_id):
+ team_queries = list(grouped)
+ dag = DAG.get_or_create_default(team_queries[0].team)
+ self._report(team_id, backfill_team(team_queries, dag))
+ dags_to_reconcile[team_id] = dag
+ for team_id, dag in dags_to_reconcile.items():
+ self._reconcile(team_id, dag)
+
+ def _report(self, team_id: int, result: TeamBackfill) -> None:
+ for name, error in result.failed.items():
+ self.stderr.write(f" team {team_id}: FAILED {name}, re-run to retry: {error}")
+ self.stdout.write(
+ f" team {team_id}: synced {result.synced}, adopted without edges {result.adopted}, "
+ f"failed {len(result.failed)}, seeded targets {result.seeded}"
+ )
+
+ def _reconcile(self, team_id: int, dag: DAG) -> None:
+ try:
+ applied = reconcile_dag_schedules(dag, require_tiered=True)
+ except Exception as error:
+ self.stderr.write(
+ f" team {team_id}: schedule reconcile FAILED, re-run with --team-id {team_id} --apply: {error!r}"
+ )
+ return
+ if not applied:
+ self.stderr.write(f" team {team_id}: schedules not reconciled, the DAG still runs on a pre-tier schedule")
+
+
+def nodeless_saved_queries(team_ids: list[int] | None) -> list[DataWarehouseSavedQuery]:
+ queryset = (
+ DataWarehouseSavedQuery.objects.exclude(deleted=True)
+ .filter(managed_viewset__isnull=True)
+ .exclude(Exists(Node.objects.filter(saved_query_id=OuterRef("pk"))))
+ .select_related("team")
+ .order_by("team_id", "created_at")
+ )
+ if team_ids:
+ queryset = queryset.filter(team_id__in=team_ids)
+ return list(queryset)
+
+
+def backfill_team(saved_queries: list[DataWarehouseSavedQuery], dag: DAG) -> TeamBackfill:
+ database = lineage_database(dag.team)
+ with transaction.atomic():
+ synced, unresolved = sync_until_stuck(saved_queries, dag, database)
+ adoptable = {
+ saved_query: error for saved_query, error in unresolved.items() if isinstance(error, ADOPTABLE_SYNC_ERRORS)
+ }
+ for saved_query, error in adoptable.items():
+ adopt_saved_query_without_edges(saved_query.team_id, saved_query.id, str(error), dag_id=dag.id)
+ # A child that only failed because its parent had no node can sync now that the parent has one.
+ resynced, _ = sync_until_stuck(list(adoptable), dag, database)
+ synced.extend(resynced)
+ adoptable = {saved_query: error for saved_query, error in adoptable.items() if saved_query not in resynced}
+ materializing_node_ids = Node.objects.filter(
+ dag=dag, saved_query__in=[*synced, *adoptable], type__in=MATERIALIZING_TYPES
+ ).values_list("id", flat=True)
+ seeded = persist_seed_targets(
+ dag,
+ default=DEFAULT_MATERIALIZED_TARGET,
+ only_node_ids={str(node_id) for node_id in materializing_node_ids},
+ )
+ return TeamBackfill(
+ synced=len(synced),
+ adopted=len(adoptable),
+ seeded=seeded,
+ failed={
+ saved_query.name: repr(error) for saved_query, error in unresolved.items() if saved_query not in adoptable
+ },
+ )
+
+
+def sync_until_stuck(
+ saved_queries: Iterable[DataWarehouseSavedQuery], dag: DAG, database: Database
+) -> tuple[list[DataWarehouseSavedQuery], dict[DataWarehouseSavedQuery, Exception]]:
+ pending = list(saved_queries)
+ synced: list[DataWarehouseSavedQuery] = []
+ while True:
+ failures: dict[DataWarehouseSavedQuery, Exception] = {}
+ for saved_query in pending:
+ try:
+ with transaction.atomic():
+ sync_saved_query_to_dag(saved_query, dag=dag, reconcile=False, database=database)
+ except Exception as error:
+ failures[saved_query] = error
+ continue
+ synced.append(saved_query)
+ if not failures or len(failures) == len(pending):
+ return synced, failures
+ pending = list(failures)
diff --git a/products/data_modeling/backend/test/test_backfill_saved_query_nodes.py b/products/data_modeling/backend/test/test_backfill_saved_query_nodes.py
new file mode 100644
index 000000000000..8cae8d080419
--- /dev/null
+++ b/products/data_modeling/backend/test/test_backfill_saved_query_nodes.py
@@ -0,0 +1,54 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+
+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.edge import Edge
+from products.data_modeling.backend.models.node import LineageIssueKind, Node
+
+COMMAND = "products.data_modeling.backend.management.commands.backfill_saved_query_nodes"
+
+
+class TestBackfillSavedQueryNodes(BaseTest):
+ def _view(
+ self, name: str, sql: str, is_materialized: bool = False, interval: timedelta | None = None
+ ) -> DataWarehouseSavedQuery:
+ return DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name=name,
+ query={"kind": "HogQLQuery", "query": sql},
+ is_materialized=is_materialized,
+ sync_frequency_interval=interval,
+ )
+
+ def test_gives_every_nodeless_view_a_node_only_when_applied(self) -> None:
+ downstream = self._view("downstream_view", "SELECT event FROM upstream_view")
+ upstream = self._view("upstream_view", "SELECT event FROM events")
+ broken = self._view("broken_view", "SELECT 1 FROM no_such_table")
+ materialized = self._view("materialized_view", "SELECT event FROM events", is_materialized=True)
+ legacy_cadence = self._view(
+ "legacy_cadence_view", "SELECT event FROM events", is_materialized=True, interval=timedelta(minutes=5)
+ )
+
+ with patch(f"{COMMAND}.reconcile_dag_schedules") as reconcile:
+ call_command("backfill_saved_query_nodes")
+ self.assertFalse(Node.objects.filter(team=self.team).exists())
+
+ call_command("backfill_saved_query_nodes", "--apply")
+
+ reconcile.assert_called_once_with(DAG.get_or_create_default(self.team), require_tiered=True)
+ upstream_node = Node.objects.get(saved_query=upstream)
+ downstream_node = Node.objects.get(saved_query=downstream)
+ self.assertTrue(Edge.objects.filter(source=upstream_node, target=downstream_node).exists())
+ broken_node = Node.objects.get(saved_query=broken)
+ self.assertFalse(Edge.objects.filter(target=broken_node).exists())
+ assert broken_node.lineage_issue is not None
+ self.assertEqual(broken_node.lineage_issue["kind"], LineageIssueKind.SYNC_FAILED)
+ self.assertEqual(get_declared_target(Node.objects.get(saved_query=materialized)), timedelta(days=1))
+ self.assertEqual(get_declared_target(Node.objects.get(saved_query=legacy_cadence)), timedelta(minutes=15))
+ self.assertIsNone(get_declared_target(upstream_node))
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/editing.py b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
index ab97d1a6c877..63df70a7481c 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/editing.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
@@ -59,6 +59,15 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
+GENERIC_LINEAGE_SYNC_ERROR = (
+ "Could not build this view's lineage. Check the query's tables and columns, then save again."
+)
+
+
+def _lineage_sync_error_detail(error: Exception) -> str:
+ # The marker is served verbatim by the node API, so only a message written for the user may reach it.
+ return str(error) if isinstance(error, ExposedHogQLError) else GENERIC_LINEAGE_SYNC_ERROR
+
def _as_uuid(value: object) -> uuid.UUID | None:
# Clients echo the revision back in whatever UUID form their stack produces, so parse both
@@ -402,6 +411,7 @@ class DataWarehouseSavedQuerySerializer(
except Exception as e:
capture_exception(e)
logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
+ modeling_api.adopt_saved_query_without_edges(view.team_id, view.id, _lineage_sync_error_detail(e))
if sync_frequency is not None:
if sync_frequency != "never":
assert_user_can_read_query(
@@ -588,13 +598,17 @@ class DataWarehouseSavedQuerySerializer(
# DAG the move just left. The savepoint keeps a failed sync best effort without
# poisoning the update's own transaction.
if "query" in validated_data:
+ node = Node.objects.filter(team_id=view.team_id, saved_query=view).select_related("dag").first()
+ dag = node.dag if node else None
try:
with transaction.atomic():
- node = Node.objects.filter(team_id=view.team_id, saved_query=view).select_related("dag").first()
- modeling_api.sync_saved_query_to_dag(view, dag=node.dag if node else None)
+ modeling_api.sync_saved_query_to_dag(view, dag=dag)
except Exception as e:
capture_exception(e)
logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
+ modeling_api.adopt_saved_query_without_edges(
+ view.team_id, view.id, _lineage_sync_error_detail(e), dag_id=dag.id if dag else None
+ )
self._report_view_action(
"view updated",
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py b/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py
index 35e2e38480ab..561c248eddb0 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py
@@ -5,6 +5,8 @@ from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from parameterized import parameterized
+
from products.data_modeling.backend.facade.api import get_declared_target
from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Node
@@ -24,17 +26,30 @@ class TestSavedQueryWriteFields(APIBaseTest):
response = self._create_view(edited_history_id=str(uuid.uuid4()))
self.assertEqual(response.status_code, 201, response.content)
- def test_create_frequency_failure_rolls_back_the_view(self) -> None:
- with patch("products.data_modeling.backend.facade.api.sync_saved_query_to_dag", side_effect=RuntimeError):
- response = self._create_view(sync_frequency="6hour")
- self.assertEqual(response.status_code, 400, response.content)
- self.assertFalse(DataWarehouseSavedQuery.objects.filter(team=self.team, name="event_view").exists())
+ def _assert_marked_sync_failed(self, saved_query_id: str) -> None:
+ lineage_issue = Node.objects.get(saved_query_id=saved_query_id).lineage_issue
+ assert lineage_issue is not None
+ self.assertEqual(lineage_issue["kind"], "sync_failed")
- def test_create_keeps_the_view_when_the_dag_sync_fails(self) -> None:
+ @parameterized.expand([("plain", {}), ("with_frequency", {"sync_frequency": "6hour"})])
+ def test_create_gives_a_view_whose_dag_sync_fails_a_marked_node(self, _name: str, fields: dict[str, Any]) -> None:
with patch("products.data_modeling.backend.facade.api.sync_saved_query_to_dag", side_effect=RuntimeError):
- response = self._create_view()
+ response = self._create_view(**fields)
self.assertEqual(response.status_code, 201, response.content)
- self.assertTrue(DataWarehouseSavedQuery.objects.filter(team=self.team, name="event_view").exists())
+ self._assert_marked_sync_failed(response.json()["id"])
+
+ def test_update_keeps_a_query_whose_dag_sync_fails_and_marks_its_node(self) -> None:
+ created = self._create_view().json()
+ with patch("products.data_modeling.backend.facade.api.sync_saved_query_to_dag", side_effect=RuntimeError):
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",
+ {
+ "query": {"kind": "HogQLQuery", "query": "select event from events LIMIT 7"},
+ "edited_history_id": created["latest_history_id"],
+ },
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ self._assert_marked_sync_failed(created["id"])
def test_create_places_the_view_in_the_default_dag_with_its_cadence(self) -> None:
other = DAG.objects.create(team=self.team, name="Other")
diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.py
index 51d0c20880cc..493f8d284955 100644
--- a/products/endpoints/backend/logic/materialization.py
+++ b/products/endpoints/backend/logic/materialization.py
@@ -9,7 +9,7 @@ query transforms live in ``products.endpoints.backend.materialization_transforms
import dataclasses
from typing import cast
-from django.db import transaction
+from django.db import DatabaseError, transaction
import structlog
from rest_framework.exceptions import APIException, ValidationError
@@ -242,7 +242,6 @@ class EndpointMaterializationService:
# The DAG node must exist before scheduling: the v2 detection and the freshness-target
# write-through both resolve this saved query through its Node row.
- sync_error: Exception | None = None
try:
sync_saved_query_to_dag(saved_query)
link_endpoint_nodes(
@@ -251,8 +250,11 @@ class EndpointMaterializationService:
endpoint_name=endpoint.name,
version=version.version,
)
+ except DatabaseError:
+ # An infrastructure fault, not a lineage problem the author can fix: let it surface
+ # as a server error so the status="error" metric sees it.
+ raise
except Exception as e:
- sync_error = e
logger.exception(
"Failed to sync endpoint node to DAG",
endpoint_name=endpoint.name,
@@ -267,6 +269,10 @@ class EndpointMaterializationService:
"saved_query_id": saved_query.id,
},
)
+ # The node is missing because the query's dependencies did not resolve, which
+ # the author fixes by editing the query. Reporting that as a server error would
+ # tell them to retry, and would page on-call through the status="error" metric.
+ raise ValidationError(f"Cannot materialize endpoint. Reason: {e}")
# NOTE: on v1, schedule_materialization only triggers an immediate run when it CREATES
# the Temporal schedule; re-enabling an existing materialization just (re)syncs it.
@@ -286,11 +292,6 @@ class EndpointMaterializationService:
# is what stops the enable reporting success on an endpoint nothing will ever refresh.
saved_query.refresh_from_db(fields=["is_materialized"])
if not saved_query.is_materialized:
- if sync_error is not None:
- # The node is missing because the query's dependencies did not resolve, which
- # the author fixes by editing the query. Reporting that as a server error would
- # tell them to retry, and would page on-call through the status="error" metric.
- raise ValidationError(f"Cannot materialize endpoint. Reason: {sync_error}")
raise APIException(f"Failed to schedule materialization for endpoint {endpoint.name}.")
def _get_or_build_saved_query(self, version: EndpointVersion) -> DataWarehouseSavedQuery: