:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-modeling): let suspended models be resumed (#73712)
Jovan Sakovicb3e0a9ffb36b
diff --git a/posthog/temporal/data_modeling/activities/utils.py b/posthog/temporal/data_modeling/activities/utils.pyindex 1c936ec8e638..78a83ddb8ab8 100644--- a/posthog/temporal/data_modeling/activities/utils.py+++ b/posthog/temporal/data_modeling/activities/utils.py@@ -6,13 +6,34 @@ from django.db import transactionfrom posthog.sync import database_sync_to_async_pool+from products.data_modeling.backend.facade.api import (+ clear_node_suspension,+ is_node_suspended,+ mark_node_suspended,+ query_fingerprint,+ suspension_reset_at,+)from products.data_modeling.backend.facade.models import (DataModelingJob,DataModelingJobEngine,DataModelingJobStatus,+ DataWarehouseSavedQuery,Node,)+# Suspension state lives in products/data_modeling/backend/logic/node_suspension.py, alongside the+# API and DAG-sync paths that clear it. Re-exported so the activities keep importing from here.+__all__ = [+ "CONSECUTIVE_FAILURES_TO_SUSPEND",+ "clear_node_suspension",+ "clear_node_suspension_for_engine",+ "is_node_suspended",+ "mark_node_suspended",+ "maybe_suspend_node_for_engine",+ "strip_hostname_from_error",+ "update_node_system_properties",+]+# Consecutive failed jobs (per engine) before a node is suspended from future DAG runs.CONSECUTIVE_FAILURES_TO_SUSPEND = 5@@ -66,45 +87,13 @@ def update_node_system_properties(node.properties = properties-def mark_node_suspended(node: Node, *, engine: str, reason: str, job_id: str) -> None:- engine = str(engine)- properties: dict = node.properties or {}- system = properties.get("system", {})- suspended = system.get("suspended", {})- suspended[engine] = {- "at": dt.datetime.now(dt.UTC).isoformat(),- "reason": reason,- "job_id": job_id,- }- system["suspended"] = suspended- properties["system"] = system- node.properties = properties---def clear_node_suspension(node: Node, *, engine: str) -> None:- engine = str(engine)- properties: dict = node.properties or {}- system = properties.get("system", {})- suspended = system.get("suspended", {})- if engine in suspended:- del suspended[engine]- system["suspended"] = suspended- properties["system"] = system- node.properties = properties---def is_node_suspended(node: Node, engine: str) -> bool:- engine = str(engine)- system = (node.properties or {}).get("system") or {}- return bool((system.get("suspended") or {}).get(engine))---def _count_leading_failures(saved_query_id: UUID, engine: str) -> int:- statuses = (- DataModelingJob.objects.filter(saved_query_id=saved_query_id, engine=str(engine))- .order_by("-created_at")- .values_list("status", flat=True)[:CONSECUTIVE_FAILURES_TO_SUSPEND]- )+def _count_leading_failures(saved_query_id: UUID, engine: str, *, since: str | None = None) -> int:+ jobs = DataModelingJob.objects.filter(saved_query_id=saved_query_id, engine=str(engine))+ if since is not None:+ # Otherwise the failures that caused the suspension are still the most recent jobs, and one+ # new failure re-suspends the node we just resumed.+ jobs = jobs.filter(created_at__gt=dt.datetime.fromisoformat(since))+ statuses = jobs.order_by("-created_at").values_list("status", flat=True)[:CONSECUTIVE_FAILURES_TO_SUSPEND]count = 0for status in statuses:if status != DataModelingJobStatus.FAILED:@@ -125,13 +114,17 @@ def maybe_suspend_node_for_engine(job_id: str,) -> bool:"""Suspend the node for an engine if its last N jobs for it all failed. True only on transition."""- if _count_leading_failures(saved_query_id, engine) < CONSECUTIVE_FAILURES_TO_SUSPEND:- return Falsewith transaction.atomic():node = Node.objects.select_for_update().get(id=node_id, team_id=team_id, dag_id=dag_id)if is_node_suspended(node, engine):return False- mark_node_suspended(node, engine=engine, reason=reason, job_id=job_id)+ since = suspension_reset_at(node, engine)+ if _count_leading_failures(saved_query_id, engine, since=since) < CONSECUTIVE_FAILURES_TO_SUSPEND:+ return False+ fingerprint = query_fingerprint(+ DataWarehouseSavedQuery.objects.filter(id=saved_query_id).values_list("query", flat=True).first()+ )+ mark_node_suspended(node, engine=engine, reason=reason, job_id=job_id, fingerprint=fingerprint)node.save()if str(engine) == DataModelingJobEngine.CLICKHOUSE.value:job = DataModelingJob.objects.get(id=job_id)diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 234601917c4b..57bbf2659de6 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -533,6 +533,47 @@ class TestNodeSuspension:for job in jobs:await database_sync_to_async(job.delete)()+ async def test_does_not_resuspend_on_failures_from_before_a_resume(self, ateam, anode, asaved_query, adag):+ from posthog.temporal.data_modeling.activities.utils import is_node_suspended, maybe_suspend_node_for_engine++ from products.data_modeling.backend.logic.node_suspension import resume_nodes++ jobs = [await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom") for _ in range(5)]+ first_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom")+ jobs.append(first_job)+ assert await maybe_suspend_node_for_engine(+ node_id=str(anode.id),+ team_id=ateam.pk,+ dag_id=str(adag.id),+ saved_query_id=asaved_query.id,+ engine=DataModelingJobEngine.CLICKHOUSE,+ reason="boom",+ job_id=str(first_job.id),+ )++ await database_sync_to_async(anode.refresh_from_db)()+ await database_sync_to_async(resume_nodes)([anode], by="query_edit")++ next_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom again")+ jobs.append(next_job)+ suspended_again = await maybe_suspend_node_for_engine(+ node_id=str(anode.id),+ team_id=ateam.pk,+ dag_id=str(adag.id),+ saved_query_id=asaved_query.id,+ engine=DataModelingJobEngine.CLICKHOUSE,+ reason="boom again",+ job_id=str(next_job.id),+ )++ assert suspended_again is False+ await database_sync_to_async(anode.refresh_from_db)()+ assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is False++ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.+ for job in jobs:+ await database_sync_to_async(job.delete)()+async def test_engine_suspension_is_independent(self, ateam, anode, asaved_query, adag):from posthog.temporal.data_modeling.activities.utils import is_node_suspended, maybe_suspend_node_for_enginediff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 8b340f22b336..42f02a38f8f0 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -24,6 +24,14 @@ _LAZY = {"tiered_schedules_enabled": "logic.schedule_reconcile","declared_targets_by_saved_query": "logic.node_frequency","get_declared_target": "logic.node_frequency",+ "clear_node_suspension": "logic.node_suspension",+ "is_node_suspended": "logic.node_suspension",+ "mark_node_suspended": "logic.node_suspension",+ "query_fingerprint": "logic.node_suspension",+ "resume_nodes": "logic.node_suspension",+ "resume_saved_query": "logic.node_suspension",+ "suspension_reset_at": "logic.node_suspension",+ "suspension_state": "logic.node_suspension","compute_enrichment_hash": "logic.enrich_view_semantics","enrichment_gates_pass": "logic.enrich_view_semantics","enrich_view_semantics_sync": "logic.enrich_view_semantics",diff --git a/products/data_modeling/backend/logic/node_materialization.py b/products/data_modeling/backend/logic/node_materialization.pyindex 3e5d77702ab8..fa36c412d6dc 100644--- a/products/data_modeling/backend/logic/node_materialization.py+++ b/products/data_modeling/backend/logic/node_materialization.py@@ -12,6 +12,7 @@ from posthog.temporal.common.client import sync_connectfrom posthog.temporal.data_modeling.run_workflow import RunWorkflowInputs, Selectorfrom posthog.temporal.data_modeling.workflows.materialize_view import MaterializeViewWorkflowInputs+from products.data_modeling.backend.logic.node_suspension import resume_nodesfrom products.data_modeling.backend.models import Nodefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.schedule import get_v2_saved_query_ids@@ -24,6 +25,8 @@ def start_node_materialization(node: Node, *, is_v2: bool) -> None:Shared by node `materialize` and saved-query `run` so the v1/v2 dispatch lives in one place."""+ # An explicit run is a request to try again, so it gets a fresh failure window.+ resume_nodes([node], by="manual_run")if is_v2:inputs: MaterializeViewWorkflowInputs | RunWorkflowInputs = MaterializeViewWorkflowInputs(team_id=node.team_id,diff --git a/products/data_modeling/backend/logic/node_suspension.py b/products/data_modeling/backend/logic/node_suspension.pynew file mode 100644index 000000000000..967d0a576831--- /dev/null+++ b/products/data_modeling/backend/logic/node_suspension.py@@ -0,0 +1,136 @@+"""Suspension state for DAG nodes — the materialization circuit breaker.++A suspended node is skipped by every scheduled DAG run, so it can never produce the successful+materialization that would clear it. Every path here exists to give a node a way back.+"""++import hashlib+import datetime as dt+from collections.abc import Callable, Iterable+from typing import TYPE_CHECKING++from django.db import transaction++from products.data_modeling.backend.models.node import Node++if TYPE_CHECKING:+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery++SUSPENDED_KEY = "suspended"+RESET_KEY = "suspension_reset"+++def _now() -> str:+ return dt.datetime.now(dt.UTC).isoformat()+++def _system(node: Node) -> dict:+ return (node.properties or {}).get("system") or {}+++def query_fingerprint(query: dict | None) -> str | None:+ """Recorded when a node suspends, so re-syncing an unchanged query (backfills, resync commands,+ managed-viewset sync) doesn't read as an edit and silently resume everything."""+ sql = (query or {}).get("query")+ if not isinstance(sql, str):+ return None+ return hashlib.sha256(sql.strip().encode()).hexdigest()[:16]+++def suspension_state(node: Node) -> dict[str, dict]:+ return dict(_system(node).get(SUSPENDED_KEY) or {})+++def is_node_suspended(node: Node, engine: str) -> bool:+ return bool(suspension_state(node).get(str(engine)))+++def suspension_reset_at(node: Node, engine: str) -> str | None:+ """Failures before this point no longer count toward suspension."""+ return ((_system(node).get(RESET_KEY) or {}).get(str(engine)) or {}).get("at")+++def mark_node_suspended(node: Node, *, engine: str, reason: str, job_id: str, fingerprint: str | None = None) -> None:+ properties: dict = node.properties or {}+ system = properties.setdefault("system", {})+ suspended = system.setdefault(SUSPENDED_KEY, {})+ suspended[str(engine)] = {+ "at": _now(),+ "reason": reason,+ "job_id": job_id,+ "query_fingerprint": fingerprint,+ }+ # A fresh suspension supersedes the resume that preceded it.+ (system.get(RESET_KEY) or {}).pop(str(engine), None)+ node.properties = properties+++def clear_node_suspension(node: Node, *, engine: str | None = None, by: str = "materialization") -> bool:+ """Clears one engine, or all of them when engine is None.++ Stamps a watermark because the failures that caused the suspension are still the most recent+ jobs — without it the node re-suspends on its very next failure.+ """+ suspended = suspension_state(node)+ engines = [str(engine)] if engine is not None else list(suspended)+ cleared = [e for e in engines if suspended.get(e)]+ if not cleared:+ return False++ properties: dict = node.properties or {}+ system = properties.setdefault("system", {})+ resets = system.setdefault(RESET_KEY, {})+ at = _now()+ for e in cleared:+ del system[SUSPENDED_KEY][e]+ resets[e] = {"at": at, "by": by}+ node.properties = properties+ return True+++def _persist_change(node: Node, change: Callable[[Node], bool]) -> bool:+ """Apply a change to the node's suspension state as a locked read-modify-write.++ `properties` is one JSON blob, so writing it from a caller's in-memory instance would drop+ anything a materialization committed to the same row since that instance was read. Every other+ writer of this field takes the row lock too (see the data-modeling Temporal activities).+ """+ with transaction.atomic():+ locked = Node.objects.select_for_update().filter(pk=node.pk, team_id=node.team_id).first()+ if locked is None or not change(locked):+ return False+ locked.save(update_fields=["properties"])+ node.properties = locked.properties+ return True+++def resume_nodes(nodes: Iterable[Node], *, by: str, engine: str | None = None) -> int:+ """Returns how many of the nodes were actually suspended, not how many were passed in."""+ return sum(+ _persist_change(node, lambda locked: clear_node_suspension(locked, engine=engine, by=by)) for node in nodes+ )+++def resume_saved_query(saved_query: "DataWarehouseSavedQuery", *, by: str = "api") -> int:+ """One query can back several nodes when it landed in duplicate DAGs, and "resume this model"+ means all of them."""+ return resume_nodes(+ Node.objects.filter(team_id=saved_query.team_id, saved_query_id=saved_query.id),+ by=by,+ )+++def clear_suspension_if_query_changed(node: Node, query: dict | None) -> bool:+ fingerprint = query_fingerprint(query)+ return _persist_change(node, lambda locked: _clear_stale_fingerprints(locked, fingerprint))+++def _clear_stale_fingerprints(node: Node, fingerprint: str | None) -> bool:+ """A marker with no fingerprint predates fingerprinting; free it rather than strand it."""+ stale = [+ engine for engine, entry in suspension_state(node).items() if entry.get("query_fingerprint") != fingerprint+ ]+ cleared = False+ for engine in stale:+ cleared = clear_node_suspension(node, engine=engine, by="query_edit") or cleared+ return cleareddiff --git a/products/data_modeling/backend/logic/saved_query_dag_sync.py b/products/data_modeling/backend/logic/saved_query_dag_sync.pyindex fcb1f5717773..ef4ed545a0a9 100644--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py@@ -7,6 +7,7 @@ from posthog.hogql.database.models import SavedQuery as HogQLSavedQueryfrom posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTablefrom posthog.hogql.errors import QueryError+from products.data_modeling.backend.logic.node_suspension import clear_suspension_if_query_changedfrom products.data_modeling.backend.logic.schedule_reconcile import maybe_reconcile_dagfrom products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.edge import Edge@@ -186,6 +187,9 @@ def sync_saved_query_to_dag(# name is included in update_fields because Node.save() auto-syncs it from saved_querytarget.save(update_fields=["name", "type", "properties"])+ # After the save, so it reads fresh state under a row lock rather than riding along on the+ # whole-blob write above.+ clear_suspension_if_query_changed(target, saved_query.query)if reconcile:maybe_reconcile_dag(dag)return targetdiff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex e95a5a0318a4..b2ed40a8e77b 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -9,7 +9,7 @@ from django.db import modelsfrom django.db.models import OuterRef, Subqueryfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, extend_schema+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_fieldfrom rest_framework import filters, request, response, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import PermissionDenied@@ -20,16 +20,28 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.models import Team, Userfrom posthog.ph_client import feature_enabled_or_false+from posthog.rbac.user_access_control import AccessControlLevelfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.data_modeling.run_workflow import RunWorkflowInputs, Selectorfrom posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputs-from products.data_modeling.backend.facade.api import get_declared_target+from products.data_modeling.backend.facade.api import get_declared_target, resume_nodes, suspension_statefrom products.data_modeling.backend.facade.models import DAG, Edge, Node, NodeTypefrom products.warehouse_sources.backend.facade.models import sync_frequency_interval_to_sync_frequency+class NodeSuspensionSerializer(serializers.Serializer):+ at = serializers.DateTimeField(help_text="When the node was suspended.")+ reason = serializers.CharField(help_text="Error from the materialization that tripped suspension.")+ job_id = serializers.CharField(help_text="Materialization job that tripped suspension.")+++class NodeResumeSerializer(serializers.Serializer):+ resumed = serializers.BooleanField(help_text="False when the node was not suspended to begin with.")++class NodeSerializer(serializers.ModelSerializer):+ suspended = serializers.SerializerMethodField(read_only=True)upstream_count = serializers.SerializerMethodField(read_only=True)downstream_count = serializers.SerializerMethodField(read_only=True)last_run_at = serializers.SerializerMethodField(read_only=True)@@ -57,8 +69,10 @@ class NodeSerializer(serializers.ModelSerializer):"last_run_status","user_tag","sync_interval",+ "suspended",]read_only_fields = [+ "suspended","upstream_count","downstream_count","last_run_at",@@ -69,6 +83,16 @@ class NodeSerializer(serializers.ModelSerializer):"saved_query_id",]+ @extend_schema_field(+ serializers.DictField(+ child=NodeSuspensionSerializer(),+ help_text="Engines this node is suspended for after repeated materialization failures. "+ "Suspended engines are skipped by scheduled DAG runs until the node is resumed.",+ )+ )+ def get_suspended(self, node: Node) -> dict[str, Any]:+ return {engine: NodeSuspensionSerializer(entry).data for engine, entry in suspension_state(node).items()}+def get_upstream_count(self, node: Node) -> int:counts = self.context.get("node_counts")if counts and str(node.id) in counts:@@ -119,6 +143,11 @@ class NodePagination(PageNumberPagination):page_size = 1000+# Nodes expose warehouse view/table names, types, edges, and the error that suspended a+# materialization, so reading them needs the same warehouse access as reading the views themselves.+_READ_DENIED = "Reading data models requires data warehouse read access."++# TODO: consolidate graph traversal logic. similar implementations exist in:# - posthog/temporal/data_modeling/workflows/execute_dag.py (_get_edge_lookup, _get_downstream_lookup)# - products/data_modeling/backend/graph.py (Graph) — shared in-memory graph used by list endpoint@@ -213,9 +242,21 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):raise serializers.ValidationError("Nodes belonging to a system-managed DAG cannot be deleted.")instance.delete()+ def _require_warehouse_access(self, *, level: AccessControlLevel, message: str) -> None:+ """`scope_object = "INTERNAL"` makes AccessControlPermission skip this viewset entirely, so+ warehouse RBAC has to be re-applied by hand (warehouse_view inherits warehouse_objects)."""+ if not self.user_access_control.check_access_level_for_resource("warehouse_view", required_level=level):+ raise PermissionDenied(message)++ def retrieve(self, request, *args, **kwargs):+ self._require_warehouse_access(level="viewer", message=_READ_DENIED)+ return super().retrieve(request, *args, **kwargs)+def list(self, request, *args, **kwargs):from products.data_modeling.backend.facade.models import Graph+ self._require_warehouse_access(level="viewer", message=_READ_DENIED)+queryset = self.filter_queryset(self.get_queryset())page = self.paginate_queryset(queryset)nodes = page if page is not None else queryset@@ -280,6 +321,10 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):node_ids.add(str(node.id))+ # ExecuteDAGWorkflow skips suspended nodes, so without this the request is a silent no-op+ # for exactly the nodes that need it most.+ resume_nodes(Node.objects.filter(team_id=self.team_id, id__in=node_ids), by="manual_run")+if _is_v2_backend_enabled(cast(User, req.user), self.team):inputs: ExecuteDAGInputs | RunWorkflowInputs = ExecuteDAGInputs(team_id=self.team_id,@@ -348,12 +393,9 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"""from products.data_modeling.backend.presentation.views.edge import EdgeSerializer- # NodeViewSet is `scope_object = "INTERNAL"`, so AccessControlPermission does not gate it on- # any resource. Lineage exposes warehouse view/table names, types, and edges — the same- # metadata the deleted `warehouse_view`-scoped upstream endpoint gated on. Re-apply that gate- # here so warehouse RBAC still governs the read (warehouse_view inherits warehouse_objects).- if not self.user_access_control.check_access_level_for_resource("warehouse_view", required_level="viewer"):- raise PermissionDenied("Reading lineage requires data warehouse read access.")+ # Lineage exposes the same metadata the deleted `warehouse_view`-scoped upstream endpoint+ # gated on.+ self._require_warehouse_access(level="viewer", message="Reading lineage requires data warehouse read access.")node_id = req.query_params.get("node_id")saved_query_id = req.query_params.get("saved_query_id")@@ -413,3 +455,19 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):start_node_materialization(node, is_v2=_is_v2_backend_enabled(cast(User, req.user), self.team))return response.Response(status=status.HTTP_200_OK)++ @extend_schema(request=None, responses={200: NodeResumeSerializer})+ @action(methods=["POST"], detail=True)+ def resume(self, req: request.Request, *args, **kwargs) -> response.Response:+ """Resume a node suspended after repeated failed materializations.++ Scheduled runs skip a suspended node and its descendants, so it cannot succeed its way back+ on its own. Resuming also gives it a fresh failure window rather than re-suspending on the+ next failure.+ """+ # Resuming puts a model back on the materialization schedule, so it needs write access.+ self._require_warehouse_access(level="editor", message="Resuming a node requires data warehouse write access.")++ resumed = resume_nodes([self.get_object()], by="api")++ return response.Response({"resumed": bool(resumed)}, status=status.HTTP_200_OK)diff --git a/products/data_modeling/backend/test/test_node_suspension.py b/products/data_modeling/backend/test/test_node_suspension.pynew file mode 100644index 000000000000..4bc1f12e6dd9--- /dev/null+++ b/products/data_modeling/backend/test/test_node_suspension.py@@ -0,0 +1,117 @@+from datetime import timedelta+from uuid import uuid4++from posthog.test.base import BaseTest++from parameterized import parameterized++from products.data_modeling.backend.logic.node_frequency import get_declared_target, set_declared_target+from products.data_modeling.backend.logic.node_suspension import (+ mark_node_suspended,+ query_fingerprint,+ resume_nodes,+ suspension_reset_at,+ suspension_state,+)+from products.data_modeling.backend.logic.saved_query_dag_sync import sync_saved_query_to_dag+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.node import Node++ENGINE = "clickhouse"+++class TestSuspensionClearedOnQueryChange(BaseTest):+ def _suspended_node(self, *, fingerprint: str | None) -> tuple[DataWarehouseSavedQuery, Node]:+ saved_query = DataWarehouseSavedQuery.objects.create(+ name="suspended_model",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ )+ node = sync_saved_query_to_dag(saved_query)+ assert node is not None+ mark_node_suspended(node, engine=ENGINE, reason="boom", job_id=str(uuid4()), fingerprint=fingerprint)+ node.save()+ return saved_query, node++ @parameterized.expand(+ [+ ("query_changed", "SELECT 2", True),+ ("query_unchanged", "SELECT 1", False),+ ]+ )+ def test_sync_clears_suspension_only_when_the_query_changed(+ self, _name: str, new_query: str, expect_cleared: bool+ ) -> None:+ saved_query, node = self._suspended_node(fingerprint=query_fingerprint({"query": "SELECT 1"}))++ saved_query.query = {"query": new_query, "kind": "HogQLQuery"}+ saved_query.save()+ sync_saved_query_to_dag(saved_query)++ node.refresh_from_db()+ self.assertEqual(suspension_state(node) == {}, expect_cleared)++ def test_sync_clears_a_suspension_recorded_without_a_fingerprint(self) -> None:+ # Nothing to compare against, so an edit must free them or they stay suspended for good.+ saved_query, node = self._suspended_node(fingerprint=None)++ sync_saved_query_to_dag(saved_query)++ node.refresh_from_db()+ self.assertEqual(suspension_state(node), {})+++class TestResumeNodes(BaseTest):+ def test_resume_clears_state_and_records_a_reset_watermark(self) -> None:+ saved_query = DataWarehouseSavedQuery.objects.create(+ name="resumed_model",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ )+ node = sync_saved_query_to_dag(saved_query)+ assert node is not None+ mark_node_suspended(node, engine=ENGINE, reason="boom", job_id=str(uuid4()), fingerprint=None)+ node.save()++ resumed = resume_nodes([node], by="api")++ self.assertEqual(resumed, 1)+ node.refresh_from_db()+ self.assertEqual(suspension_state(node), {})+ # Without the watermark the next single failure re-suspends it.+ self.assertIsNotNone(suspension_reset_at(node, ENGINE))++ def test_resume_keeps_a_properties_change_committed_after_the_caller_read_the_node(self) -> None:+ # properties is a single JSON blob, so resuming off the caller's in-memory copy would drop+ # whatever a materialization committed to the same row in the meantime.+ saved_query = DataWarehouseSavedQuery.objects.create(+ name="raced_model",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ )+ node = sync_saved_query_to_dag(saved_query)+ assert node is not None+ mark_node_suspended(node, engine=ENGINE, reason="boom", job_id=str(uuid4()), fingerprint=None)+ node.save()++ stale = Node.objects.get(id=node.id)+ set_declared_target(Node.objects.get(id=node.id), timedelta(hours=1))++ self.assertEqual(resume_nodes([stale], by="api"), 1)++ node.refresh_from_db()+ self.assertEqual(suspension_state(node), {})+ self.assertEqual(get_declared_target(node), timedelta(hours=1))++ def test_resume_is_a_no_op_on_a_node_that_is_not_suspended(self) -> None:+ saved_query = DataWarehouseSavedQuery.objects.create(+ name="healthy_model",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ )+ node = sync_saved_query_to_dag(saved_query)+ assert node is not None++ self.assertEqual(resume_nodes([node], by="api"), 0)+ node.refresh_from_db()+ self.assertIsNone(suspension_reset_at(node, ENGINE))diff --git a/products/data_modeling/backend/tests/api/test_node_api.py b/products/data_modeling/backend/tests/api/test_node_api.pyindex 96fd9f47978d..df9c78196813 100644--- a/products/data_modeling/backend/tests/api/test_node_api.py+++ b/products/data_modeling/backend/tests/api/test_node_api.py@@ -1,5 +1,7 @@from datetime import timedelta+from uuid import uuid4+import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, patch@@ -9,8 +11,10 @@ from rest_framework import statusfrom posthog.models import Teamfrom products.data_modeling.backend.logic.node_frequency import set_declared_target+from products.data_modeling.backend.logic.node_suspension import mark_node_suspended, suspension_statefrom products.data_modeling.backend.models import DAG, Edge, Node, NodeTypefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.warehouse_sources.backend.tests.api._access_control_base import WarehouseAccessControlTestMixinclass TestNodeViewSet(APIBaseTest):@@ -234,6 +238,61 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)mock_client.start_workflow.assert_called_once()+ def _suspend(self, node: Node) -> None:+ mark_node_suspended(node, engine="clickhouse", reason="boom", job_id=str(uuid4()), fingerprint=None)+ node.save()++ def test_suspended_node_reports_its_state_and_can_be_resumed(self):+ self._suspend(self.view_node)++ detail = f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/"+ self.assertEqual(self.client.get(detail).json()["suspended"]["clickhouse"]["reason"], "boom")++ response = self.client.post(f"{detail}resume/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(self.client.get(detail).json()["suspended"], {})++ @patch("products.data_modeling.backend.presentation.views.node.sync_connect")+ def test_run_resumes_every_node_it_was_asked_to_run(self, mock_sync_connect):+ # A suspended node is skipped by ExecuteDAGWorkflow, so without this the button is a no-op.+ mock_sync_connect.return_value = AsyncMock()+ downstream = Node.objects.create(+ team=self.team,+ dag=self.dag,+ saved_query=DataWarehouseSavedQuery.objects.create(+ name="downstream_view", team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ ),+ type=NodeType.VIEW,+ )+ Edge.objects.create(team=self.team, dag=self.dag, source=self.view_node, target=downstream)+ self._suspend(self.view_node)+ self._suspend(downstream)++ response = self.client.post(+ f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/run/",+ {"direction": "downstream"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.view_node.refresh_from_db()+ downstream.refresh_from_db()+ self.assertEqual(suspension_state(self.view_node), {})+ self.assertEqual(suspension_state(downstream), {})++ @patch("products.data_modeling.backend.logic.node_materialization.sync_connect")+ def test_materialize_resumes_the_node(self, mock_sync_connect):+ mock_sync_connect.return_value = AsyncMock()+ self._suspend(self.view_node)++ response = self.client.post(+ f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/materialize/",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.view_node.refresh_from_db()+ self.assertEqual(suspension_state(self.view_node), {})+@patch("products.data_modeling.backend.presentation.views.node.feature_enabled_or_false", return_value=True)@patch("products.data_modeling.backend.presentation.views.node.sync_connect")def test_run_uses_execute_dag_when_v2_enabled(self, mock_sync_connect, mock_feature_flag):@@ -547,6 +606,69 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(self.view_node.dag_id, self.dag.id)+class TestNodeAccessControl(WarehouseAccessControlTestMixin):+ # NodeViewSet is scope_object = "INTERNAL", so AccessControlPermission does not gate it on any+ # resource — the actions re-apply warehouse RBAC by hand. warehouse_view inherits from+ # warehouse_objects, so grant at the umbrella.+ resource = "warehouse_objects"++ def setUp(self):+ super().setUp()+ self.dag = DAG.objects.create(team=self.team, name=f"posthog_{self.team.id}")+ self.node = Node.objects.create(+ team=self.team,+ dag=self.dag,+ saved_query=DataWarehouseSavedQuery.objects.create(+ name="suspended_view", team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ ),+ type=NodeType.VIEW,+ )+ mark_node_suspended(self.node, engine="clickhouse", reason="boom", job_id=str(uuid4()), fingerprint=None)+ self.node.save()++ def _list_url(self) -> str:+ return f"/api/environments/{self.team.id}/data_modeling_nodes/"++ @parameterized.expand(+ [+ ("viewer", status.HTTP_403_FORBIDDEN),+ ("editor", status.HTTP_200_OK),+ ]+ )+ def test_resume_requires_warehouse_write_access(self, access_level, expected_status):+ user = self.viewer_user if access_level == "viewer" else self.editor_user+ self._create_access_control(user, access_level=access_level)+ self.client.force_login(user)++ response = self.client.post(f"{self._list_url()}{self.node.id}/resume/")++ self.assertEqual(response.status_code, expected_status)+ self.node.refresh_from_db()+ self.assertEqual(suspension_state(self.node) == {}, expected_status == status.HTTP_200_OK)++ @parameterized.expand(+ [+ ("list_granted", False, "viewer", status.HTTP_200_OK),+ ("list_denied", False, None, status.HTTP_403_FORBIDDEN),+ ("retrieve_granted", True, "viewer", status.HTTP_200_OK),+ ("retrieve_denied", True, None, status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_reading_nodes_requires_warehouse_read_access(self, _name, detail, access_level, expected_status):+ # The serialized `suspended` state carries the raw materialization error, so a project member+ # denied warehouse access must not be able to read nodes at all.+ if access_level is None:+ self._create_project_default(access_level="none")+ else:+ self._create_access_control(self.viewer_user, access_level=access_level)+ self.client.force_login(self.viewer_user)++ response = self.client.get(f"{self._list_url()}{self.node.id}/" if detail else self._list_url())++ self.assertEqual(response.status_code, expected_status)++class TestEdgeViewSet(APIBaseTest):def setUp(self):super().setUp()diff --git a/products/data_modeling/frontend/generated/api.schemas.ts b/products/data_modeling/frontend/generated/api.schemas.tsindex 72793c0071cd..d01256ce8199 100644--- a/products/data_modeling/frontend/generated/api.schemas.ts+++ b/products/data_modeling/frontend/generated/api.schemas.ts@@ -104,6 +104,20 @@ export const NodeTypeEnumApi = {Endpoint: 'endpoint',} as const+export interface NodeSuspensionApi {+ /** When the node was suspended. */+ at: string+ /** Error from the materialization that tripped suspension. */+ reason: string+ /** Materialization job that tripped suspension. */+ job_id: string+}++/**+ * Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed.+ */+export type NodeApiSuspended = { [key: string]: NodeSuspensionApi }+export interface NodeApi {readonly id: string/** @maxLength 2048 */@@ -128,6 +142,8 @@ export interface NodeApi {readonly user_tag: string | null/** @nullable */readonly sync_interval: string | null+ /** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */+ readonly suspended: NodeApiSuspended}export interface PaginatedNodeListApi {@@ -139,6 +155,11 @@ export interface PaginatedNodeListApi {results: NodeApi[]}+/**+ * Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed.+ */+export type PatchedNodeApiSuspended = { [key: string]: NodeSuspensionApi }+export interface PatchedNodeApi {readonly id?: string/** @maxLength 2048 */@@ -163,6 +184,13 @@ export interface PatchedNodeApi {readonly user_tag?: string | null/** @nullable */readonly sync_interval?: string | null+ /** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */+ readonly suspended?: PatchedNodeApiSuspended+}++export interface NodeResumeApi {+ /** False when the node was not suspended to begin with. */+ resumed: boolean}export type DataModelingDagsListParams = {diff --git a/products/data_modeling/frontend/generated/api.ts b/products/data_modeling/frontend/generated/api.tsindex e2c40dabf3e2..952c25b0727d 100644--- a/products/data_modeling/frontend/generated/api.ts+++ b/products/data_modeling/frontend/generated/api.ts@@ -16,6 +16,7 @@ import type {DataModelingNodesListParams,EdgeApi,NodeApi,+ NodeResumeApi,PaginatedDAGListApi,PaginatedEdgeListApi,PaginatedNodeListApi,@@ -362,6 +363,28 @@ export const dataModelingNodesMaterializeCreate = async (})}+export const getDataModelingNodesResumeCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/data_modeling_nodes/${id}/resume/`+}++/**+ * Resume a node suspended after repeated failed materializations.+ *+ * Scheduled runs skip a suspended node and its descendants, so it cannot succeed its way back+ * on its own. Resuming also gives it a fresh failure window rather than re-suspending on the+ * next failure.+ */+export const dataModelingNodesResumeCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<NodeResumeApi> => {+ return apiMutator<NodeResumeApi>(getDataModelingNodesResumeCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getDataModelingNodesRunCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/data_modeling_nodes/${id}/run/`}diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.pyindex be23e5790e16..3d992475bd03 100644--- a/products/data_warehouse/backend/presentation/views/saved_query.py+++ b/products/data_warehouse/backend/presentation/views/saved_query.py@@ -10,7 +10,7 @@ from django.db.models.functions import Castimport structlogimport posthoganalyticsfrom asgiref.sync import async_to_sync-from drf_spectacular.utils import extend_schema_field+from drf_spectacular.utils import extend_schema, extend_schema_fieldfrom rest_framework import exceptions, filters, request, response, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.pagination import PageNumberPagination@@ -946,6 +946,10 @@ class DataWarehouseSavedQueryFolderViewSet(TeamAndOrgViewSetMixin, AccessControlreturn response.Response(status=status.HTTP_204_NO_CONTENT)+class SavedQueryResumeSerializer(serializers.Serializer):+ resumed = serializers.BooleanField(help_text="False when the query's materialization was not suspended.")++class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):"""Create, Read, Update and Delete Warehouse Tables.@@ -1131,6 +1135,20 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSereturn response.Response(status=status.HTTP_200_OK)+ @extend_schema(request=None, responses={200: SavedQueryResumeSerializer})+ @action(methods=["POST"], detail=True, required_scopes=["warehouse_view:write"])+ def resume(self, request: request.Request, *args, **kwargs) -> response.Response:+ """Resume materialization suspended after repeated failures.++ Scheduled runs skip a suspended model and everything downstream of it, so it cannot succeed+ its way back on its own.+ """+ from products.data_modeling.backend.facade.api import resume_saved_query++ resumed = resume_saved_query(self.get_object())++ return response.Response({"resumed": bool(resumed)}, status=status.HTTP_200_OK)+@action(methods=["POST"],detail=True,diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.pyindex d17dece0a40e..1c4f9359cd5c 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py@@ -14,6 +14,7 @@ from parameterized import parameterizedfrom posthog.models import ActivityLogfrom posthog.models.activity_logging.activity_log import Detail+from products.data_modeling.backend.facade.api import mark_node_suspended, suspension_statefrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPathfrom products.data_modeling.backend.facade.models import (DAG,@@ -1935,6 +1936,42 @@ class TestSavedQuery(APIBaseTest):self.assertIn("Running", returned_statuses)self.assertIn("Cancelled", returned_statuses)+ def test_resume_clears_suspension_for_every_node_of_the_query(self):+ # Key access is the point of this surface: the node-level resume is on an INTERNAL viewset,+ # which no API key can reach.+ api_key = self.create_personal_api_key_with_scopes(["warehouse_view:write"])+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")++ saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="suspended_view",+ query={"kind": "HogQLQuery", "query": "select event as event from events LIMIT 100"},+ created_by=self.user,+ )+ # One saved query can back several nodes when it landed in duplicate DAGs.+ nodes = [+ Node.objects.create(+ team=self.team,+ dag=DAG.objects.create(team=self.team, name=f"dag_{i}"),+ saved_query=saved_query,+ type=NodeType.MAT_VIEW,+ )+ for i in range(2)+ ]+ for node in nodes:+ mark_node_suspended(node, engine="clickhouse", reason="boom", job_id=str(uuid.uuid4()))+ node.save()++ response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query.id}/resume/"+ )++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json(), {"resumed": True})+ for node in nodes:+ node.refresh_from_db()+ self.assertEqual(suspension_state(node), {})+@patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)def test_materialize_and_revert_are_rate_limited(self, _rate_limit_enabled_mock):api_key = self.create_personal_api_key_with_scopes(["warehouse_view:write"])diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex f1b42d007337..692938774e7e 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -1137,6 +1137,11 @@ export interface PatchedDataWarehouseSavedQueryApi {readonly user_access_level?: string | null}+export interface SavedQueryResumeApi {+ /** False when the query's materialization was not suspended. */+ resumed: boolean+}+export interface DataWarehouseSavedQueryDraftApi {readonly id: stringreadonly created_at: stringdiff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex 717a74f03260..99a3a66f260b 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -58,6 +58,7 @@ import type {QueryTabStateListParams,ResetPasswordResponseApi,SavedQueryColumnAnnotationsListParams,+ SavedQueryResumeApi,TableApi,ViewLinkApi,ViewLinkValidationApi,@@ -1596,6 +1597,27 @@ export const warehouseSavedQueriesMaterializeCreate = async (})}+export const getWarehouseSavedQueriesResumeCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${id}/resume/`+}++/**+ * Resume materialization suspended after repeated failures.+ *+ * Scheduled runs skip a suspended model and everything downstream of it, so it cannot succeed+ * its way back on its own.+ */+export const warehouseSavedQueriesResumeCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<SavedQueryResumeApi> => {+ return apiMutator<SavedQueryResumeApi>(getWarehouseSavedQueriesResumeCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getWarehouseSavedQueriesRevertMaterializationCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/warehouse_saved_queries/${id}/revert_materialization/`}diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex 6f3ce24435fd..4cb4584bcef8 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -487,6 +487,9 @@ tools:warehouse-saved-queries-descendants-create:operation: warehouse_saved_queries_descendants_createenabled: false+ warehouse-saved-queries-resume-create:+ operation: warehouse_saved_queries_resume_create+ enabled: falsewarehouse-saved-queries-resume-schedules-create:operation: warehouse_saved_queries_resume_schedules_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 060c3c7d28f5..7621a6ae8d3c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -39494,6 +39494,20 @@ export namespace Schemas {specificity_rejection?: SpecificityMetadata | null;}+ export interface NodeSuspension {+ /** When the node was suspended. */+ at: string;+ /** Error from the materialization that tripped suspension. */+ reason: string;+ /** Materialization job that tripped suspension. */+ job_id: string;+ }++ /**+ * Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed.+ */+ export type NodeSuspended = {[key: string]: NodeSuspension};+/*** * `table` - Table* * `view` - View@@ -39534,6 +39548,13 @@ export namespace Schemas {readonly user_tag: string | null;/** @nullable */readonly sync_interval: string | null;+ /** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */+ readonly suspended: NodeSuspended;+ }++ export interface NodeResume {+ /** False when the node was not suspended to begin with. */+ resumed: boolean;}/**@@ -49828,6 +49849,11 @@ export namespace Schemas {tile?: MoveTileTile;}+ /**+ * Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed.+ */+ export type PatchedNodeSuspended = {[key: string]: NodeSuspension};+export interface PatchedNode {readonly id?: string;/** @maxLength 2048 */@@ -49852,6 +49878,8 @@ export namespace Schemas {readonly user_tag?: string | null;/** @nullable */readonly sync_interval?: string | null;+ /** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */+ readonly suspended?: PatchedNodeSuspended;}/**@@ -60422,6 +60450,11 @@ export namespace Schemas {block_consent_modals?: boolean;}+ export interface SavedQueryResume {+ /** False when the query's materialization was not suspended. */+ resumed: boolean;+ }+/*** Distinct creators across all scanners on the team — feeds the `Created by` filter dropdown.*/