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): keep materializing a model whose table went missing (#100153)

Jovan Sakovic0b80d9d0638d
diff --git a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py b/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
index d35e06c2f801..27d019df2e57 100644
--- a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
+++ b/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
@@ -55,8 +55,8 @@ def _update_saved_query_with_table(
saved_query_table.row_count = inputs.row_count
saved_query_table.save()
- # The table is what makes the query a matview, so this is the one place that always knows the
- # node type is stale — every other materialization entry point can leave it behind.
+ # Every other materialization entry point can leave a stale node type behind, so repair it here.
+ # A query reverted mid-run is left alone: it no longer asks to materialize.
promote_view_nodes_to_matview(saved_query)
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index 10d86be82e1d..48f6270503a5 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -1173,13 +1173,21 @@ class TestPrepareQueryableTableActivity:
assert warehouse_table.row_count == 250
await database_sync_to_async(warehouse_table.delete)()
- async def test_retypes_view_node_to_matview_once_a_table_is_linked(
- self, activity_environment, ateam, asaved_query, anode, ajob
+ @pytest.mark.parametrize(
+ "is_materialized,expected_type",
+ [(True, NodeType.MAT_VIEW), (False, NodeType.VIEW)],
+ )
+ async def test_linking_a_table_retypes_the_node_only_while_the_query_asks_to_materialize(
+ self, activity_environment, ateam, asaved_query, anode, ajob, is_materialized, expected_type
):
- # revert_materialization leaves the node typed VIEW; every scheduled DAG run then treats
- # it as ephemeral and skips materialization without recording a job.
+ # A node left typed VIEW is treated as ephemeral by every scheduled DAG run, which skips
+ # materialization without recording a job. Linking a table is where that gets repaired —
+ # unless the query was reverted mid-run, where retyping would resurrect a materialization
+ # the customer just turned off.
anode.type = NodeType.VIEW
await database_sync_to_async(anode.save)()
+ asaved_query.is_materialized = is_materialized
+ await database_sync_to_async(asaved_query.save)()
inputs = PrepareQueryableTableInputs(
team_id=ateam.pk,
@@ -1209,7 +1217,7 @@ class TestPrepareQueryableTableActivity:
await activity_environment.run(prepare_queryable_table_activity, inputs)
await database_sync_to_async(anode.refresh_from_db)()
- assert anode.type == NodeType.MAT_VIEW
+ assert anode.type == expected_type
await database_sync_to_async(warehouse_table.delete)()
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 92c241ee9aec..de24d4f8bbef 100644
--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py
+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py
@@ -1,7 +1,7 @@
from typing import TYPE_CHECKING, TypedDict
from django.db import IntegrityError, transaction
-from django.db.models import QuerySet
+from django.db.models import Q, QuerySet
import structlog
@@ -36,13 +36,35 @@ class DegradedSyncMarker(TypedDict):
at: str
+def materializes(saved_query: "DataWarehouseSavedQuery") -> bool:
+ """Whether a saved query is asking to be materialized.
+
+ `is_materialized` is the customer's intent, and `table` is one artifact of acting on it. The two
+ come apart, because `table` is `on_delete=SET_NULL`: a backing table that goes away nulls
+ `table_id` and leaves the intent untouched. Reading the artifact instead of the intent then
+ types the node VIEW, which `get_dag_structure` calls ephemeral and a run skips, so the table can
+ never come back and the query stops updating for good, without an error.
+
+ Managed views are excluded because their flag is not a statement of intent: the Revenue
+ Analytics viewsets set `is_materialized` at provisioning, before anything runs, so reading it
+ would enroll a large population of views that have never materialized a row.
+ """
+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+
+ if saved_query.origin == DataWarehouseSavedQuery.Origin.MANAGED_VIEWSET:
+ return saved_query.table_id is not None
+ # The column is nullable, and NULL predates its default: it means the same as False here, which
+ # is also how `_materializes_q` reads it.
+ return bool(saved_query.is_materialized)
+
+
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:
+ if materializes(saved_query):
return NodeType.MAT_VIEW
return NodeType.VIEW
@@ -344,8 +366,16 @@ def update_node_type(saved_query: "DataWarehouseSavedQuery", type: NodeType) ->
maybe_reconcile_dag(dag)
+def _materializes_q() -> Q:
+ """`materializes` as a filter, for the callers that cannot ask row by row."""
+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+
+ managed = Q(saved_query__origin=DataWarehouseSavedQuery.Origin.MANAGED_VIEWSET)
+ return (~managed & Q(saved_query__is_materialized=True)) | (managed & Q(saved_query__table_id__isnull=False))
+
+
def _promote_view_nodes(nodes: QuerySet[Node]) -> int:
- """Retype the nodes in `nodes` that a table backs but the graph still calls ephemeral views.
+ """Retype the nodes in `nodes` that materialize but the graph still calls ephemeral views.
`get_dag_structure` calls every VIEW node ephemeral, so a scheduled run reports success for one
without materializing it and without writing a job row — it just stops updating, silently. A
@@ -353,11 +383,11 @@ def _promote_view_nodes(nodes: QuerySet[Node]) -> int:
below existed, only the `materialize` action ever typed it back.
Only VIEW nodes are touched: ENDPOINT nodes are a materializing type already and must keep
- theirs. Views with no backing table are left alone, being genuinely ephemeral. No reconcile
- follows, because tier membership keys off the node's frequency target, not its type.
+ theirs. Views nobody asked to materialize are left alone, being genuinely ephemeral. No
+ reconcile follows, because tier membership keys off the node's frequency target, not its type.
"""
return (
- nodes.filter(type=NodeType.VIEW, saved_query__table_id__isnull=False)
+ nodes.filter(_materializes_q(), type=NodeType.VIEW)
.exclude(saved_query__deleted=True)
.update(type=NodeType.MAT_VIEW)
)
diff --git a/products/data_modeling/backend/test/test_saved_query_dag_sync.py b/products/data_modeling/backend/test/test_saved_query_dag_sync.py
index a0e94c897d89..ff65d1d4fb85 100644
--- a/products/data_modeling/backend/test/test_saved_query_dag_sync.py
+++ b/products/data_modeling/backend/test/test_saved_query_dag_sync.py
@@ -22,6 +22,7 @@ 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.modeling import ResolutionCycleError
from products.data_modeling.backend.models.node import NodeType
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@pytest.mark.django_db
@@ -131,6 +132,43 @@ class TestSyncSavedQueryToDag(BaseTest):
dag = DAG.objects.get(team=self.team, name=DEFAULT_DAG_NAME)
self.assertEqual(node.dag_id, dag.id)
+ @parameterized.expand(
+ [
+ ("asked_for_it_and_has_a_table", True, True, None, NodeType.MAT_VIEW),
+ # The backing table went away. Typing this a view is what stopped the node being
+ # scheduled, so it could never run again and never get its table back.
+ ("asked_for_it_and_lost_its_table", True, False, None, NodeType.MAT_VIEW),
+ ("never_asked_for_it", False, False, None, NodeType.VIEW),
+ # Revenue Analytics sets the flag when it provisions a view, before anything runs, so
+ # for managed views the table is the only honest evidence.
+ (
+ "managed_view_that_has_never_run",
+ True,
+ False,
+ DataWarehouseSavedQuery.Origin.MANAGED_VIEWSET,
+ NodeType.VIEW,
+ ),
+ ]
+ )
+ def test_node_type_follows_the_request_to_materialize(
+ self, name: str, is_materialized: bool, with_table: bool, origin: str | None, expected: str
+ ) -> None:
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ name=name,
+ team=self.team,
+ query={"query": "SELECT 1", "kind": "HogQLQuery"},
+ is_materialized=is_materialized,
+ **({"origin": origin} if origin is not None else {}),
+ )
+ if with_table:
+ saved_query.table = DataWarehouseTable.objects.create(team=self.team, name=f"{name}_tbl", format="Delta")
+ saved_query.save()
+
+ node = sync_saved_query_to_dag(saved_query)
+
+ assert node is not None
+ self.assertEqual(node.type, expected)
+
def test_sync_creates_table_node_for_posthog_source(self):
saved_query = DataWarehouseSavedQuery.objects.create(
name="test_view",
diff --git a/products/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.py
index aa499da52366..e3e4a0bbc000 100644
--- a/products/data_modeling/backend/test/test_schedule_reconcile.py
+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py
@@ -32,7 +32,7 @@ from products.data_modeling.backend.logic.schedule_reconcile import (
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 NodeType
+from products.data_modeling.backend.models.node import Node, NodeType
from products.data_modeling.backend.schedule import DATA_MODELING_EXECUTE_DAG_WORKFLOW
from products.data_modeling.backend.test.helpers import (
no_existing_schedules,
@@ -486,30 +486,61 @@ class TestMaybeReconcileDag(BaseTest):
@pytest.mark.django_db
class TestPromoteDagViewNodesToMatview(BaseTest):
- def _backed(self, dag, name, node_type):
+ def _backed(
+ self, dag: DAG, name: str, node_type: str, *, with_table: bool = True, origin: str | None = None
+ ) -> Node:
node = _saved_query_node(self.team, dag, name, node_type)
saved_query = node.saved_query
assert saved_query is not None
- saved_query.table = DataWarehouseTable.objects.create(team=self.team, name=f"{name}_tbl", format="Delta")
+ saved_query.is_materialized = True
+ if with_table:
+ saved_query.table = DataWarehouseTable.objects.create(team=self.team, name=f"{name}_tbl", format="Delta")
+ if origin is not None:
+ saved_query.origin = origin
saved_query.save()
return node
- def test_retypes_only_table_backed_view_nodes(self):
+ def test_retypes_only_the_view_nodes_that_materialize(self) -> None:
dag = DAG.get_or_create_default(self.team)
stranded = self._backed(dag, "stranded", NodeType.VIEW)
endpoint = self._backed(dag, "endpoint_backed", NodeType.ENDPOINT)
ephemeral = _saved_query_node(self.team, dag, "ephemeral", NodeType.VIEW)
+ # A backing table that went away nulls table_id and leaves the intent behind. This is the
+ # node that used to stay a view forever, so it could never get its table back.
+ lost_its_table = self._backed(dag, "lost_its_table", NodeType.VIEW, with_table=False)
- assert promote_dag_view_nodes_to_matview(dag) == 1
+ assert promote_dag_view_nodes_to_matview(dag) == 2
- for node in (stranded, endpoint, ephemeral):
+ for node in (stranded, endpoint, ephemeral, lost_its_table):
node.refresh_from_db()
assert stranded.type == NodeType.MAT_VIEW
- # A view with no backing table is a real ephemeral view; retyping it would schedule
- # materializations for something that has nothing to materialize.
+ assert lost_its_table.type == NodeType.MAT_VIEW
+ # Nobody asked for this one to materialize, so it is a real ephemeral view.
assert ephemeral.type == NodeType.VIEW
assert endpoint.type == NodeType.ENDPOINT
+ def test_a_managed_view_is_promoted_on_its_table_not_its_flag(self) -> None:
+ # Revenue Analytics sets is_materialized when it provisions a view, before anything runs,
+ # so the flag there is not a request to materialize and many carry it untruthfully.
+ dag = DAG.get_or_create_default(self.team)
+ never_ran = self._backed(
+ dag,
+ "managed_never_ran",
+ NodeType.VIEW,
+ with_table=False,
+ origin=DataWarehouseSavedQuery.Origin.MANAGED_VIEWSET,
+ )
+ has_run = self._backed(
+ dag, "managed_has_run", NodeType.VIEW, origin=DataWarehouseSavedQuery.Origin.MANAGED_VIEWSET
+ )
+
+ assert promote_dag_view_nodes_to_matview(dag) == 1
+
+ never_ran.refresh_from_db()
+ has_run.refresh_from_db()
+ assert never_ran.type == NodeType.VIEW
+ assert has_run.type == NodeType.MAT_VIEW
+
def test_conversion_to_tiers_repairs_stranded_nodes(self):
# The v1 sweep that follows conversion is what makes a view-typed node go dark, so the
# repair has to happen as part of converting, not on some later pass.
diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.py
index fbe42036fd2b..b8e26aaabb37 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query.py
@@ -446,6 +446,12 @@ class ViewDescriptionField(serializers.CharField):
return view_annotation_map(instance).get("")
+# Only these two are still written to the column: MODIFIED on edit, CANCELLED by the cancel action.
+# Every other value was last written by the v1 materialization workflow, which no longer exists, so it
+# describes a run no current code path could have produced.
+STATUSES_STILL_WRITTEN = frozenset({DataWarehouseSavedQuery.Status.MODIFIED, DataWarehouseSavedQuery.Status.CANCELLED})
+
+
class DataWarehouseSavedQuerySerializerMixin:
"""Shared methods for DataWarehouseSavedQuery serializers.
@@ -471,13 +477,13 @@ class DataWarehouseSavedQuerySerializerMixin:
@extend_schema_field(serializers.DateTimeField(allow_null=True))
def get_last_run_at(self, view: DataWarehouseSavedQuery) -> datetime | None:
run = self._serving_run(view)
- return run.last_run_at if run is not None else view.last_run_at
+ return run.last_run_at if run is not None else None
@extend_schema_field(serializers.ChoiceField(choices=DataWarehouseSavedQuery.Status.choices, allow_null=True))
def get_status(self, view: DataWarehouseSavedQuery) -> str | None:
run = self._serving_run(view)
if run is None:
- return view.status
+ return view.status if view.status in STATUSES_STILL_WRITTEN else None
# Modified means "edited and not materialized since", which no run can express. A run that
# happened after the edit answers it, so the column only wins while the edit is the newer fact.
edited_since_the_run = (
@@ -490,7 +496,7 @@ class DataWarehouseSavedQuerySerializerMixin:
@extend_schema_field(serializers.CharField(allow_null=True))
def get_latest_error(self, view: DataWarehouseSavedQuery) -> str | None:
run = self._serving_run(view)
- return run.error if run is not None else view.latest_error
+ return run.error if run is not None else None
@extend_schema_field(serializers.CharField(allow_null=True))
def get_sync_frequency(self, schema: DataWarehouseSavedQuery):
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.py
index 7fc728d902c3..c56b0e5ed87e 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -2767,11 +2767,37 @@ class TestSavedQueryStateComesFromTheServingRun(APIBaseTest):
self.assertEqual(self._detail(view)["status"], "Completed")
- def test_modified_survives_when_the_view_has_never_run(self):
+ def test_modified_survives_when_the_view_has_never_run(self) -> None:
view = self._view("never_ran", status=DataWarehouseSavedQuery.Status.MODIFIED)
self.assertEqual(self._detail(view)["status"], "Modified")
+ def test_cancelled_survives_when_the_view_has_never_run(self) -> None:
+ view = self._view("cancelled_never_ran", status=DataWarehouseSavedQuery.Status.CANCELLED)
+
+ self.assertEqual(self._detail(view)["status"], "Cancelled")
+
+ @parameterized.expand(
+ [
+ (DataWarehouseSavedQuery.Status.FAILED,),
+ (DataWarehouseSavedQuery.Status.RUNNING,),
+ (DataWarehouseSavedQuery.Status.COMPLETED,),
+ ]
+ )
+ def test_a_run_state_no_code_path_writes_any_more_is_not_reported(self, frozen_status: str) -> None:
+ view = self._view(
+ f"frozen_{frozen_status}",
+ status=frozen_status,
+ latest_error="Table reference no longer exists for model.",
+ last_run_at=timezone.now() - timedelta(days=90),
+ )
+
+ body = self._detail(view)
+
+ self.assertIsNone(body["status"])
+ self.assertIsNone(body["latest_error"])
+ self.assertIsNone(body["last_run_at"])
+
def test_the_list_route_agrees_with_the_detail_route(self):
# the two read through different halves of _serving_run: prefetch on list, lookup on detail
view = self._view("both_routes", status=DataWarehouseSavedQuery.Status.FAILED, latest_error="stale")