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): admin page showing each DAG tier and its last run (#73681)

Jovan Sakovic67105b9d5453
diff --git a/products/data_modeling/backend/admin.py b/products/data_modeling/backend/admin.py
new file mode 100644
index 000000000000..e549fd6a3cf9
--- /dev/null
+++ b/products/data_modeling/backend/admin.py
@@ -0,0 +1,66 @@
+from django.conf import settings
+from django.contrib import admin
+from django.http import Http404
+from django.shortcuts import render
+from django.urls import path, reverse
+from django.utils.html import format_html
+
+from products.data_modeling.backend.logic.tier_run_report import build_tier_runs, untargeted_nodes
+from products.data_modeling.backend.models.dag import DAG
+
+
+class DataModelingDAGAdmin(admin.ModelAdmin):
+ list_display = ("id", "name", "team_link", "sync_frequency_interval", "tiers_link")
+ list_display_links = ("id", "name")
+ list_select_related = ("team",)
+ search_fields = ("id", "name", "team__id", "team__name")
+ raw_id_fields = ("team", "created_by")
+ readonly_fields = ("id", "created_at", "updated_at", "tiers_link")
+
+ def get_urls(self):
+ return [
+ path(
+ "<path:object_id>/tiers/",
+ self.admin_site.admin_view(self.tiers_view),
+ name="data_modeling_dag_tiers",
+ ),
+ *super().get_urls(),
+ ]
+
+ @admin.display(description="Team")
+ def team_link(self, dag: DAG):
+ return format_html(
+ '<a href="{}">{} ({})</a>',
+ reverse("admin:posthog_team_change", args=[dag.team_id]),
+ dag.team.name,
+ dag.team_id,
+ )
+
+ @admin.display(description="Tiers")
+ def tiers_link(self, dag: DAG):
+ if not dag.pk:
+ return "—"
+ return format_html(
+ '<a href="{}">schedule tiers &amp; last run</a>', reverse("admin:data_modeling_dag_tiers", args=[dag.pk])
+ )
+
+ def tiers_view(self, request, object_id: str):
+ dag = self.get_object(request, object_id)
+ if dag is None:
+ raise Http404("No DAG with that id")
+
+ tiers = build_tier_runs(dag)
+ return render(
+ request,
+ "admin/data_modeling/dag_tiers.html",
+ {
+ **self.admin_site.each_context(request),
+ "title": f"Schedule tiers — {dag.name}",
+ "dag": dag,
+ "tiers": tiers,
+ "untargeted": untargeted_nodes(dag),
+ "temporal_ui_host": settings.TEMPORAL_UI_HOST,
+ "temporal_namespace": settings.TEMPORAL_NAMESPACE,
+ },
+ )
diff --git a/products/data_modeling/backend/logic/tier_run_report.py b/products/data_modeling/backend/logic/tier_run_report.py
new file mode 100644
index 000000000000..02a147b06ec8
--- /dev/null
+++ b/products/data_modeling/backend/logic/tier_run_report.py
@@ -0,0 +1,312 @@
+"""What each cadence tier of a DAG declares, and what its most recent run actually did.
+
+Answers "the daily tier holds N nodes — did they all run, and if not why not?" from Postgres
+alone. `DataModelingJob.parent_workflow_id` carries the tier's schedule id, so a run's job rows
+are attributable to the tier that produced them without asking Temporal.
+
+This is deliberately *not* a check that a node is in the live schedule's `node_ids` — that lives
+in Temporal, encrypted. A node reported `MISSING` here is either absent from the live tier or was
+skipped for a reason the run did not record; distinguishing those needs the Temporal read.
+"""
+
+import dataclasses
+from collections import defaultdict
+from datetime import datetime, timedelta
+
+from django.db import models
+
+from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id
+from products.data_modeling.backend.logic.freshness import format_cadence
+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.data_modeling_job import (
+ DataModelingJob,
+ DataModelingJobEngine,
+ DataModelingJobStatus,
+)
+from products.data_modeling.backend.models.edge import Edge
+from products.data_modeling.backend.models.node import Node, NodeType
+
+# node types a DAG run actually materializes; everything else is skipped and never gets a job row
+MATERIALIZING_TYPES = frozenset({NodeType.MAT_VIEW.value, NodeType.ENDPOINT.value})
+
+OK = "ok"
+FAILED = "failed"
+RUNNING = "running"
+CANCELLED = "cancelled"
+SUSPENDED = "suspended"
+BLOCKED = "blocked"
+MISSING = "missing"
+NOT_MATERIALIZING = "not_materializing"
+
+# worst first — drives display order within a tier
+STATUS_ORDER = (MISSING, FAILED, CANCELLED, SUSPENDED, BLOCKED, RUNNING, NOT_MATERIALIZING, OK)
+
+# only a Completed job proves the node materialized. Jobs default to Running, and a row left
+# Running by a dead workflow is only reaped by a later run of the same DAG, so treating anything
+# other than Completed as success would paint corpses green.
+_JOB_STATUS_TO_NODE_STATUS = {
+ DataModelingJobStatus.COMPLETED.value: OK,
+ DataModelingJobStatus.FAILED.value: FAILED,
+ DataModelingJobStatus.RUNNING.value: RUNNING,
+ DataModelingJobStatus.CANCELLED.value: CANCELLED,
+}
+
+
[email protected](frozen=True)
+class NodeRun:
+ node_id: str
+ name: str
+ node_type: str
+ saved_query_id: str | None
+ status: str
+ detail: str
+ job_id: str | None = None
+ workflow_id: str | None = None
+ workflow_run_id: str | None = None
+
+
[email protected](frozen=True)
+class TierRun:
+ interval: timedelta
+ schedule_id: str
+ parent_workflow_id: str | None
+ started_at: datetime | None
+ nodes: list[NodeRun]
+ # the matched run came from the DAG's pre-tier single schedule, not from this tier's own
+ run_is_legacy: bool = False
+
+ @property
+ def label(self) -> str:
+ return format_cadence(self.interval)
+
+ @property
+ def seconds(self) -> int:
+ """Anchor-safe tier identifier; `schedule_id` carries a colon."""
+ return int(self.interval.total_seconds())
+
+ @property
+ def counts(self) -> dict[str, int]:
+ counts = dict.fromkeys(STATUS_ORDER, 0)
+ for node in self.nodes:
+ counts[node.status] += 1
+ return counts
+
+ @property
+ def declared(self) -> int:
+ """Nodes on this tier a run is expected to materialize."""
+ return sum(1 for node in self.nodes if node.node_type in MATERIALIZING_TYPES)
+
+ @property
+ def ran(self) -> int:
+ return sum(1 for node in self.nodes if node.job_id is not None)
+
+
+def build_tier_runs(dag: DAG) -> list[TierRun]:
+ """One TierRun per declared cadence on `dag`, finest cadence first."""
+ nodes = _reportable_nodes(dag)
+ nodes_by_interval: dict[timedelta, list[Node]] = defaultdict(list)
+ for node in nodes:
+ target = get_declared_target(node)
+ if target is not None:
+ nodes_by_interval[target].append(node)
+
+ downstream = _downstream_lookup(dag)
+ # the runtime blocks on suspension DAG-wide, not per tier: get_dag_structure builds
+ # suspended_nodes over every executable node, so a suspended node in the daily tier skips its
+ # descendants in the hourly one. Seeding only from this tier would report those as unexplained.
+ suspensions = {str(node.id): _suspension_detail(node) for node in nodes}
+ names = {str(node.id): node.name for node in nodes}
+ return [
+ _build_tier(dag, interval, nodes_by_interval[interval], downstream, suspensions, names)
+ for interval in sorted(nodes_by_interval)
+ ]
+
+
+def untargeted_nodes(dag: DAG) -> list[Node]:
+ """Nodes carrying no declared target — they belong to no tier, so no schedule fires them."""
+ return [node for node in _reportable_nodes(dag) if get_declared_target(node) is None]
+
+
+def _reportable_nodes(dag: DAG) -> list[Node]:
+ """Every node a run could act on. Mirrors `schedulable_nodes`' exclusion of soft-deleted saved
+ queries — those keep their target but the scheduler never sees them, so reporting them would
+ manufacture permanent phantom rows. Source (TABLE) nodes are kept so the page can show them.
+ """
+ return list(
+ Node.objects.filter(team_id=dag.team_id, dag=dag)
+ .exclude(saved_query__deleted=True)
+ .select_related("saved_query")
+ )
+
+
+def _build_tier(
+ dag: DAG,
+ interval: timedelta,
+ nodes: list[Node],
+ downstream: dict[str, set[str]],
+ suspensions: dict[str, str],
+ names: dict[str, str],
+) -> TierRun:
+ schedule_id = tier_schedule_id(str(dag.id), interval)
+ parent_workflow_id, started_at, run_is_legacy = _latest_run(dag.team_id, str(dag.id), schedule_id)
+ jobs = _jobs_by_saved_query(dag.team_id, parent_workflow_id)
+
+ blocked_seeds = {node_id for node_id, suspension in suspensions.items() if suspension}
+ for node in nodes:
+ job = jobs.get(str(node.saved_query_id)) if node.saved_query_id else None
+ if job is not None and job.status == DataModelingJobStatus.FAILED:
+ blocked_seeds.add(str(node.id))
+
+ # execute_dag skips a node whose ancestor failed or is suspended, so attribute those before
+ # calling anything unexplained
+ blocked_by: dict[str, str] = {}
+ for seed in blocked_seeds:
+ for descendant in downstream.get(seed, ()):
+ blocked_by.setdefault(descendant, seed)
+
+ runs = [
+ _node_run(
+ node,
+ job=jobs.get(str(node.saved_query_id)) if node.saved_query_id else None,
+ suspension=suspensions[str(node.id)],
+ blocked_by=names.get(blocked_by.get(str(node.id), ""), blocked_by.get(str(node.id), "")),
+ )
+ for node in nodes
+ ]
+ runs.sort(key=lambda run: (STATUS_ORDER.index(run.status), run.name))
+ return TierRun(
+ interval=interval,
+ schedule_id=schedule_id,
+ parent_workflow_id=parent_workflow_id,
+ started_at=started_at,
+ nodes=runs,
+ run_is_legacy=run_is_legacy,
+ )
+
+
+def _node_run(node: Node, *, job: DataModelingJob | None, suspension: str, blocked_by: str) -> NodeRun:
+ def run(status: str, detail: str, job: DataModelingJob | None = None) -> NodeRun:
+ return NodeRun(
+ node_id=str(node.id),
+ name=node.name,
+ node_type=node.type,
+ saved_query_id=str(node.saved_query_id) if node.saved_query_id else None,
+ status=status,
+ detail=detail,
+ job_id=str(job.id) if job else None,
+ workflow_id=job.workflow_id if job else None,
+ workflow_run_id=job.workflow_run_id if job else None,
+ )
+
+ if node.type not in MATERIALIZING_TYPES:
+ return run(
+ NOT_MATERIALIZING,
+ "view node — a run marks it successful and materializes nothing"
+ if node.type == NodeType.VIEW.value
+ else "source node — nothing to materialize",
+ )
+
+ if job is not None:
+ status = _JOB_STATUS_TO_NODE_STATUS.get(job.status, FAILED)
+ detail = _first_line(job.error) or f"{job.rows_materialized or 0} rows"
+ if status == RUNNING:
+ detail = "still running, or a row left behind by a dead workflow"
+ return run(status, detail, job)
+
+ if suspension:
+ return run(SUSPENDED, suspension)
+ if blocked_by:
+ return run(BLOCKED, f"upstream {blocked_by} failed or is suspended")
+ return run(MISSING, "declared on this tier but the run produced no job")
+
+
+def _latest_run(team_id: int, dag_id: str, schedule_id: str) -> tuple[str | None, datetime | None, bool]:
+ """The most recent run whose jobs describe this tier, and whether it came from the legacy schedule.
+
+ A DAG that has not been reconciled onto tiers still runs everything under the single pre-tier
+ schedule `execute-dag-{dag_id}`, whose runs no tier prefix can match (a tier id continues with
+ `:`, never `-`). Without the fallback every node on such a DAG reports as never having run,
+ which is the opposite of the truth for most of the fleet.
+ """
+ tier = _latest_run_for_prefix(team_id, f"execute-dag-{schedule_id}-")
+ if tier is not None:
+ return *tier, False
+ legacy = _latest_run_for_prefix(team_id, f"execute-dag-{dag_id}-")
+ if legacy is not None:
+ return *legacy, True
+ return None, None, False
+
+
+def _latest_run_for_prefix(team_id: int, prefix: str) -> tuple[str, datetime] | None:
+ """The newest run under `prefix`, identified by its newest job.
+
+ Sound because both schedule-creation sites set `ScheduleOverlapPolicy.SKIP`, so one schedule
+ never has two runs in flight and consecutive runs' job timestamps cannot interleave.
+ """
+ latest = (
+ DataModelingJob.objects.filter(team_id=team_id, parent_workflow_id__startswith=prefix)
+ .order_by("-created_at")
+ .values("parent_workflow_id", "created_at")
+ .first()
+ )
+ if latest is None or latest["parent_workflow_id"] is None:
+ return None
+ parent_workflow_id: str = latest["parent_workflow_id"]
+ # the run's own start, not the last child's — a wide DAG starts children over a long window
+ started_at = DataModelingJob.objects.filter(team_id=team_id, parent_workflow_id=parent_workflow_id).aggregate(
+ first=models.Min("created_at")
+ )["first"]
+ return parent_workflow_id, started_at or latest["created_at"]
+
+
+def _jobs_by_saved_query(team_id: int, parent_workflow_id: str | None) -> dict[str, DataModelingJob]:
+ if parent_workflow_id is None:
+ return {}
+ # the duckgres shadow writes its own row per node in the same run; the serving engine is the
+ # one a reader cares about, so filter rather than relying on which row was written last
+ return {
+ str(job.saved_query_id): job
+ for job in DataModelingJob.objects.filter(
+ team_id=team_id, parent_workflow_id=parent_workflow_id, engine=DataModelingJobEngine.CLICKHOUSE
+ ).order_by("created_at")
+ }
+
+
+def _downstream_lookup(dag: DAG) -> dict[str, set[str]]:
+ """Transitive descendants per node, mirroring how execute_dag propagates a block."""
+ children: dict[str, list[str]] = defaultdict(list)
+ for source_id, target_id in Edge.objects.filter(team_id=dag.team_id, dag=dag).values_list("source_id", "target_id"):
+ children[str(source_id)].append(str(target_id))
+
+ downstream: dict[str, set[str]] = {}
+ for node_id in children:
+ seen: set[str] = set()
+ queue = list(children[node_id])
+ while queue:
+ current = queue.pop()
+ if current in seen:
+ continue
+ seen.add(current)
+ queue.extend(children.get(current, ()))
+ downstream[node_id] = seen
+ return downstream
+
+
+def _suspension_detail(node: Node) -> str:
+ """Why the serving engine skips this node, if it does.
+
+ Only the serving engine's marker blocks a run (`execute_dag` reads one engine's list), and the
+ duckgres shadow suspends independently and often — reporting its marker would turn healthy
+ nodes and their whole subtree into false `suspended` / `blocked` rows. Note a marker is written
+ whether or not `data-modeling-suspend-failing-nodes` is on for the team, so on a team without
+ that flag a marker here is decorative and the node still runs.
+ """
+ suspended = ((node.properties or {}).get("system") or {}).get("suspended") or {}
+ entry = suspended.get(DataModelingJobEngine.CLICKHOUSE.value)
+ return (entry or {}).get("reason", "unknown") if entry else ""
+
+
+def _first_line(error: str | None) -> str:
+ lines = (error or "").strip().splitlines()
+ return lines[0] if lines else ""
diff --git a/products/data_modeling/backend/templates/admin/data_modeling/dag_tiers.html b/products/data_modeling/backend/templates/admin/data_modeling/dag_tiers.html
new file mode 100644
index 000000000000..4be9227cc67f
--- /dev/null
+++ b/products/data_modeling/backend/templates/admin/data_modeling/dag_tiers.html
@@ -0,0 +1,108 @@
+{% extends "admin/base_site.html" %}
+
+{% block content %}
+<style>
+ .tier-summary { border-collapse: collapse; margin-bottom: 24px; }
+ .tier-summary th, .tier-summary td { padding: 6px 12px; border-bottom: 1px solid #ddd; text-align: left; }
+ .tier-nodes { border-collapse: collapse; width: 100%; margin-bottom: 32px; font-size: 12px; }
+ .tier-nodes th, .tier-nodes td { padding: 4px 10px; border-bottom: 1px solid #eee; text-align: left; vertical-align: top; }
+ .tier-nodes td.detail { color: #666; max-width: 640px; overflow-wrap: anywhere; }
+ .pill { padding: 1px 7px; border-radius: 9px; font-size: 11px; white-space: nowrap; }
+ .pill-ok { background: #e3f4e3; color: #1c631c; }
+ .pill-failed { background: #fbe0da; color: #8a2c12; }
+ .pill-suspended { background: #fbe6c2; color: #7a4a00; }
+ .pill-blocked { background: #ececec; color: #555; }
+ .pill-missing { background: #f2ddff; color: #5b1d80; }
+ .pill-running { background: #dceaf7; color: #1f4d75; }
+ .pill-cancelled { background: #fbe6c2; color: #7a4a00; }
+ .pill-not_materializing { background: #f5f5f5; color: #888; }
+ .tier-heading { margin-bottom: 4px; }
+ .tier-meta { color: #666; margin: 0 0 10px; }
+</style>
+
+<p class="tier-meta">
+ DAG <code>{{ dag.id }}</code> ·
+ team <a href="{% url 'admin:posthog_team_change' dag.team_id %}">{{ dag.team.name }} ({{ dag.team_id }})</a> ·
+ DAG interval {{ dag.sync_frequency_interval|default:"—" }}
+</p>
+
+<table class="tier-summary">
+ <tr>
+ <th>Tier</th><th>Schedule</th><th>Declared</th><th>Ran</th>
+ <th>OK</th><th>Failed</th><th>Running</th><th>Cancelled</th><th>Suspended</th><th>Blocked</th><th>No job</th>
+ <th>Non-materializing</th><th>Last run</th>
+ </tr>
+ {% for tier in tiers %}
+ <tr>
+ <td><a href="#tier-{{ tier.seconds }}"><strong>{{ tier.label }}</strong></a></td>
+ <td>
+ {% if temporal_ui_host %}
+ <a href="{{ temporal_ui_host }}/namespaces/{{ temporal_namespace }}/schedules/execute-dag-{{ tier.schedule_id }}" target="_blank" rel="noreferrer">schedule ↗</a>
+ {% else %}—{% endif %}
+ </td>
+ <td>{{ tier.declared }}</td>
+ <td>{{ tier.ran }}</td>
+ <td>{{ tier.counts.ok }}</td>
+ <td>{{ tier.counts.failed }}</td>
+ <td>{{ tier.counts.running }}</td>
+ <td>{{ tier.counts.cancelled }}</td>
+ <td>{{ tier.counts.suspended }}</td>
+ <td>{{ tier.counts.blocked }}</td>
+ <td>{{ tier.counts.missing }}</td>
+ <td>{{ tier.counts.not_materializing }}</td>
+ <td>
+ {% if tier.parent_workflow_id %}
+ {% if tier.run_is_legacy %}<strong>legacy</strong> {% endif %}{{ tier.started_at }}
+ {% if temporal_ui_host %}
+ <a href="{{ temporal_ui_host }}/namespaces/{{ temporal_namespace }}/workflows/{{ tier.parent_workflow_id }}" target="_blank" rel="noreferrer">↗</a>
+ {% endif %}
+ {% else %}never ran{% endif %}
+ </td>
+ </tr>
+ {% empty %}
+ <tr><td colspan="13">No node on this DAG declares a freshness target, so it has no tiers.</td></tr>
+ {% endfor %}
+</table>
+
+{% for tier in tiers %}
+<h2 class="tier-heading" id="tier-{{ tier.seconds }}">{{ tier.label }} — {{ tier.declared }} materializing node{{ tier.declared|pluralize }}</h2>
+<p class="tier-meta">
+ {% if tier.run_is_legacy %}
+ This DAG has no schedule for this tier. The statuses below come from its pre-tier
+ <strong>single DAG-wide schedule</strong>, <code>{{ tier.parent_workflow_id }}</code>, started
+ {{ tier.started_at }} — so the nodes may well be materializing, just not on a per-tier schedule.
+ {% elif tier.parent_workflow_id %}
+ Last run <code>{{ tier.parent_workflow_id }}</code> started {{ tier.started_at }}.
+ {% else %}
+ This tier has never produced a job. Either its schedule does not exist or it has not fired yet.
+ {% endif %}
+</p>
+<table class="tier-nodes">
+ <tr><th>Node</th><th>Type</th><th>Status</th><th>Detail</th><th>Run</th></tr>
+ {% for node in tier.nodes %}
+ <tr>
+ <td>{{ node.name }}</td>
+ <td>{{ node.node_type }}</td>
+ <td><span class="pill pill-{{ node.status }}">{{ node.status }}</span></td>
+ <td class="detail">{{ node.detail }}</td>
+ <td>
+ {% if node.workflow_id and temporal_ui_host %}
+ <a href="{{ temporal_ui_host }}/namespaces/{{ temporal_namespace }}/workflows/{{ node.workflow_id }}/{{ node.workflow_run_id }}" target="_blank" rel="noreferrer">workflow ↗</a>
+ {% else %}—{% endif %}
+ </td>
+ </tr>
+ {% endfor %}
+</table>
+{% endfor %}
+
+{% if untargeted %}
+<h2>No declared target ({{ untargeted|length }})</h2>
+<p class="tier-meta">These nodes belong to no tier, so no schedule fires them. Source tables are expected here; a matview or endpoint is not.</p>
+<table class="tier-nodes">
+ <tr><th>Node</th><th>Type</th></tr>
+ {% for node in untargeted %}
+ <tr><td>{{ node.name }}</td><td>{{ node.type }}</td></tr>
+ {% endfor %}
+</table>
+{% endif %}
+{% endblock %}
diff --git a/products/data_modeling/backend/test/test_dag_admin.py b/products/data_modeling/backend/test/test_dag_admin.py
new file mode 100644
index 000000000000..85d42fc6ab6a
--- /dev/null
+++ b/products/data_modeling/backend/test/test_dag_admin.py
@@ -0,0 +1,99 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+
+from django.contrib import admin
+from django.test import override_settings
+from django.urls import reverse
+
+from posthog.admin import register_all_admin
+
+from products.data_modeling.backend.logic.node_frequency import set_declared_target
+from products.data_modeling.backend.models.dag import DAG
+from products.data_modeling.backend.models.data_modeling_job import DataModelingJob, DataModelingJobStatus
+from products.data_modeling.backend.models.node import Node, NodeType
+from products.data_modeling.backend.test.helpers import saved_query_node
+
+# `posthog/apps.py` installs the lazy admin registry only `if not settings.TEST`, and that wrapper
+# is the sole caller of `register_all_admin()` — so under tests nothing ever registers a
+# product-local admin. (Autodiscovery itself is fine: this module is exactly what
+# `autodiscover_modules("admin")` imports for this app in a real process.)
+register_all_admin()
+
+
+@override_settings(TEMPORAL_UI_HOST="https://temporal.example.com", TEMPORAL_NAMESPACE="prod")
+class TestDataModelingDAGAdminTiers(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user.is_staff = True # is_superuser is a read-only alias for is_staff
+ self.user.save()
+ self.client.force_login(self.user)
+ self.dag = DAG.objects.create(team=self.team, name="Default")
+
+ def _node(self, name: str, target: timedelta | None) -> Node:
+ node = saved_query_node(self.team, self.dag, name, NodeType.MAT_VIEW)
+ if target is not None:
+ set_declared_target(node, target)
+ node.save()
+ return node
+
+ def test_the_admin_is_registered_through_the_real_registration_path(self):
+ # importing this module would also register it, but that would hide a duplicate
+ # registration elsewhere — which raises AlreadyRegistered and takes the whole admin down
+ assert admin.site.is_registered(DAG)
+
+ def test_tiers_page_renders_each_tier_with_temporal_links(self):
+ node = self._node("daily_model", timedelta(days=1))
+ self._node("hourly_model", timedelta(hours=1))
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=node.saved_query,
+ status=DataModelingJobStatus.COMPLETED,
+ parent_workflow_id=f"execute-dag-{self.dag.id}:86400-2026-07-25T03:00:00Z",
+ workflow_id="materialize-view-child",
+ workflow_run_id="run-1",
+ )
+
+ response = self.client.get(reverse("admin:data_modeling_dag_tiers", args=[self.dag.id]))
+ content = response.content.decode()
+
+ assert response.status_code == 200
+ assert "daily_model" in content
+ assert "1day" in content
+ # the summary table resolves counts through a dict lookup, which Django renders as "" on a
+ # miss rather than raising — so a renamed status constant would silently blank it
+ assert 'id="tier-86400"' in content and 'id="tier-3600"' in content
+ assert f"https://temporal.example.com/namespaces/prod/schedules/execute-dag-{self.dag.id}:86400" in content
+ assert "https://temporal.example.com/namespaces/prod/workflows/materialize-view-child/run-1" in content
+
+ def test_tiers_page_renders_for_a_dag_with_no_targets(self):
+ self._node("untargeted_model", None)
+
+ response = self.client.get(reverse("admin:data_modeling_dag_tiers", args=[self.dag.id]))
+ content = response.content.decode()
+
+ assert response.status_code == 200
+ assert "has no tiers" in content
+ assert "untargeted_model" in content
+
+ def test_an_unknown_dag_id_is_a_404_not_a_crash(self):
+ response = self.client.get(
+ reverse("admin:data_modeling_dag_tiers", args=["019f98c1-0000-0000-0000-000000000000"])
+ )
+
+ assert response.status_code == 404
+
+ def test_changelist_and_add_form_render(self):
+ # both call into the display helpers that reverse other admin URLs, and the add form is the
+ # only caller of tiers_link with an unsaved object
+ assert self.client.get(reverse("admin:data_modeling_dag_changelist")).status_code == 200
+ assert self.client.get(reverse("admin:data_modeling_dag_add")).status_code == 200
+
+ def test_tiers_page_requires_staff(self):
+ self.user.is_staff = False
+ self.user.save()
+
+ response = self.client.get(reverse("admin:data_modeling_dag_tiers", args=[self.dag.id]))
+
+ assert response.status_code == 302
+ assert "/admin/login/" in response["Location"]
diff --git a/products/data_modeling/backend/test/test_tier_run_report.py b/products/data_modeling/backend/test/test_tier_run_report.py
new file mode 100644
index 000000000000..b7dac5010bf1
--- /dev/null
+++ b/products/data_modeling/backend/test/test_tier_run_report.py
@@ -0,0 +1,329 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from products.data_modeling.backend.logic.node_frequency import set_declared_target
+from products.data_modeling.backend.logic.tier_run_report import (
+ BLOCKED,
+ CANCELLED,
+ FAILED,
+ MISSING,
+ NOT_MATERIALIZING,
+ OK,
+ RUNNING,
+ SUSPENDED,
+ build_tier_runs,
+ untargeted_nodes,
+)
+from products.data_modeling.backend.models.dag import DAG
+from products.data_modeling.backend.models.data_modeling_job import (
+ DataModelingJob,
+ DataModelingJobEngine,
+ DataModelingJobStatus,
+)
+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from products.data_modeling.backend.models.edge import Edge
+from products.data_modeling.backend.models.node import Node, NodeType
+from products.data_modeling.backend.test.helpers import saved_query_node, table_node
+
+DAILY = timedelta(days=1)
+HOURLY = timedelta(hours=1)
+
+
+class TestTierRunReport(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.dag = DAG.objects.create(team=self.team, name="Default")
+
+ def _node(self, name: str, target: timedelta | None, node_type: str = NodeType.MAT_VIEW) -> Node:
+ node = saved_query_node(self.team, self.dag, name, node_type)
+ if target is not None:
+ set_declared_target(node, target)
+ node.save()
+ return node
+
+ def _suspend(self, node: Node, *, engine: str = "clickhouse", reason: str = "Workflow was cancelled") -> None:
+ node.properties.setdefault("system", {}).setdefault("suspended", {})[engine] = {"reason": reason}
+ node.save()
+
+ def _job(
+ self,
+ node: Node,
+ *,
+ parent_workflow_id: str,
+ status: str,
+ error: str | None = None,
+ engine: str = DataModelingJobEngine.CLICKHOUSE,
+ ) -> DataModelingJob:
+ return DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=node.saved_query,
+ status=status,
+ error=error,
+ engine=engine,
+ parent_workflow_id=parent_workflow_id,
+ workflow_id=f"materialize-view-{self.dag.id}-{node.id}-2026-07-25T03:00:00+00:00",
+ workflow_run_id=f"run-{node.id}",
+ )
+
+ def _daily_parent(self, at: str = "2026-07-25T03:00:00Z") -> str:
+ return f"execute-dag-{self.dag.id}:86400-{at}"
+
+ def test_classifies_every_outcome_of_the_last_tier_run(self):
+ # the shape a real daily run produces: some nodes materialize, some fail, and the rest
+ # never get a job for three very different reasons that must not be conflated
+ ok = self._node("ok_model", DAILY)
+ failed = self._node("failed_model", DAILY)
+ blocked = self._node("blocked_model", DAILY)
+ suspended = self._node("suspended_model", DAILY)
+ self._node("missing_model", DAILY)
+ self._node("view_model", DAILY, node_type=NodeType.VIEW)
+
+ Edge.objects.create(team=self.team, dag=self.dag, source=failed, target=blocked)
+ self._suspend(suspended)
+
+ parent = self._daily_parent()
+ self._job(ok, parent_workflow_id=parent, status=DataModelingJobStatus.COMPLETED)
+ self._job(failed, parent_workflow_id=parent, status=DataModelingJobStatus.FAILED, error="boom\nsecond line")
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert tier.label == "1day"
+ assert tier.schedule_id == f"{self.dag.id}:86400"
+ assert tier.parent_workflow_id == parent
+ # ordered worst-first, which is what surfaces failures on a DAG with hundreds of nodes
+ assert [(node.name, node.status) for node in tier.nodes] == [
+ ("missing_model", MISSING),
+ ("failed_model", FAILED),
+ ("suspended_model", SUSPENDED),
+ ("blocked_model", BLOCKED),
+ ("view_model", NOT_MATERIALIZING),
+ ("ok_model", OK),
+ ]
+ assert tier.counts == {
+ MISSING: 1,
+ FAILED: 1,
+ CANCELLED: 0,
+ SUSPENDED: 1,
+ BLOCKED: 1,
+ RUNNING: 0,
+ NOT_MATERIALIZING: 1,
+ OK: 1,
+ }
+ # 5 materializing nodes declared, only 2 produced a job
+ assert (tier.declared, tier.ran) == (5, 2)
+
+ by_name = {node.name: node for node in tier.nodes}
+ assert by_name["failed_model"].detail == "boom"
+ assert "Workflow was cancelled" in by_name["suspended_model"].detail
+ assert "failed_model" in by_name["blocked_model"].detail
+ assert by_name["ok_model"].workflow_run_id == f"run-{ok.id}"
+
+ @parameterized.expand(
+ [
+ ("another tier's run", "execute-dag-{dag}:3600-2026-07-25T04:00:00Z"),
+ ("the legacy DAG-wide run", "execute-dag-{dag}-2026-07-24T03:00:00Z"),
+ ]
+ )
+ def test_a_job_outside_this_tiers_latest_run_is_not_evidence_it_ran(self, _name, parent_template):
+ # this tier DID run, so no fallback is in play — a job filed under any other parent must not
+ # make the node look materialized. Dropping the parent filter and keying jobs by saved query
+ # alone would report the tier as healthy when its own schedule never touched this node.
+ node = self._node("model", DAILY)
+ other = self._node("other", DAILY)
+ self._job(other, parent_workflow_id=self._daily_parent(), status=DataModelingJobStatus.COMPLETED)
+ self._job(
+ node,
+ parent_workflow_id=parent_template.format(dag=self.dag.id),
+ status=DataModelingJobStatus.COMPLETED,
+ )
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert {n.name: n.status for n in tier.nodes}["model"] == MISSING
+
+ def test_reports_only_the_most_recent_run_of_the_tier(self):
+ # an earlier run's failure must not be reported as the current state
+ node = self._node("model", DAILY)
+ self._job(
+ node,
+ parent_workflow_id=self._daily_parent("2026-07-24T03:00:00Z"),
+ status=DataModelingJobStatus.FAILED,
+ error="yesterday",
+ )
+ self._job(node, parent_workflow_id=self._daily_parent(), status=DataModelingJobStatus.COMPLETED)
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert tier.parent_workflow_id == self._daily_parent()
+ assert [node.status for node in tier.nodes] == [OK]
+
+ def test_tiers_are_ordered_by_cadence_and_split_by_target(self):
+ self._node("hourly_model", HOURLY)
+ self._node("daily_model", DAILY)
+
+ tiers = build_tier_runs(self.dag)
+
+ assert [(tier.label, tier.seconds) for tier in tiers] == [("1hour", 3600), ("1day", 86400)]
+ assert [[node.name for node in tier.nodes] for tier in tiers] == [["hourly_model"], ["daily_model"]]
+
+ def test_untargeted_nodes_are_reported_outside_every_tier(self):
+ table_node(self.team, self.dag, "source_table", {})
+ self._node("targeted", DAILY)
+ stray = self._node("no_target", None)
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert [node.name for node in tier.nodes] == ["targeted"]
+ assert {node.name for node in untargeted_nodes(self.dag)} == {"source_table", stray.name}
+
+ @parameterized.expand(
+ [
+ (DataModelingJobStatus.COMPLETED, OK),
+ (DataModelingJobStatus.FAILED, FAILED),
+ (DataModelingJobStatus.RUNNING, RUNNING),
+ (DataModelingJobStatus.CANCELLED, CANCELLED),
+ ]
+ )
+ def test_only_a_completed_job_reports_the_node_as_materialized(self, job_status, expected):
+ # jobs default to Running, and a preempted node is written Cancelled — reporting anything
+ # but Completed as ok would paint exactly the failures this page exists to find as green
+ node = self._node("model", DAILY)
+ self._job(node, parent_workflow_id=self._daily_parent(), status=job_status)
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert [n.status for n in tier.nodes] == [expected]
+
+ @parameterized.expand(
+ [
+ (NodeType.MAT_VIEW, MISSING, "declared on this tier but the run produced no job"),
+ (NodeType.ENDPOINT, MISSING, "declared on this tier but the run produced no job"),
+ (NodeType.VIEW, NOT_MATERIALIZING, "view node — a run marks it successful and materializes nothing"),
+ ]
+ )
+ def test_node_type_decides_whether_a_run_was_even_expected(self, node_type, expected_status, expected_detail):
+ # endpoints materialize on v2 DAGs just like matviews; views never do
+ self._node("model", DAILY, node_type=node_type)
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert (tier.nodes[0].status, tier.nodes[0].detail) == (expected_status, expected_detail)
+
+ @parameterized.expand([(None, "0 rows"), ("", "0 rows"), (" ", "0 rows"), ("\n", "0 rows"), ("boom\nx", "boom")])
+ def test_a_failed_job_shows_the_first_line_of_its_error_whatever_the_error_is(self, error, expected_detail):
+ # a whitespace-only error used to raise IndexError, taking the whole page down
+ node = self._node("model", DAILY)
+ self._job(node, parent_workflow_id=self._daily_parent(), status=DataModelingJobStatus.FAILED, error=error)
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert (tier.nodes[0].status, tier.nodes[0].detail) == (FAILED, expected_detail)
+
+ def test_falls_back_to_the_legacy_dag_wide_run_when_the_tier_has_none(self):
+ # a DAG not yet reconciled onto tiers runs everything under `execute-dag-{dag_id}`, which no
+ # tier prefix matches; without the fallback every node reports as never having run
+ node = self._node("model", DAILY)
+ legacy_parent = f"execute-dag-{self.dag.id}-2026-07-25T03:00:00Z"
+ self._job(node, parent_workflow_id=legacy_parent, status=DataModelingJobStatus.COMPLETED)
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert tier.run_is_legacy is True
+ assert tier.parent_workflow_id == legacy_parent
+ assert [n.status for n in tier.nodes] == [OK]
+
+ def test_a_tier_run_wins_over_an_older_legacy_run(self):
+ node = self._node("model", DAILY)
+ self._job(
+ node,
+ parent_workflow_id=f"execute-dag-{self.dag.id}-2026-07-24T03:00:00Z",
+ status=DataModelingJobStatus.COMPLETED,
+ )
+ self._job(node, parent_workflow_id=self._daily_parent(), status=DataModelingJobStatus.FAILED, error="boom")
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert tier.run_is_legacy is False
+ assert [n.status for n in tier.nodes] == [FAILED]
+
+ def test_a_failure_blocks_descendants_at_any_depth(self):
+ # execute_dag skips the whole cone below a failure, so stopping at direct children would
+ # report grandchildren as unexplained and send the operator after the wrong node
+ a, b, c = self._node("a", DAILY), self._node("b", DAILY), self._node("c", DAILY)
+ Edge.objects.create(team=self.team, dag=self.dag, source=a, target=b)
+ Edge.objects.create(team=self.team, dag=self.dag, source=b, target=c)
+ self._job(a, parent_workflow_id=self._daily_parent(), status=DataModelingJobStatus.FAILED, error="boom")
+
+ (tier,) = build_tier_runs(self.dag)
+ by_name = {n.name: n for n in tier.nodes}
+
+ assert (by_name["b"].status, by_name["c"].status) == (BLOCKED, BLOCKED)
+ assert "a" in by_name["c"].detail
+
+ def test_a_node_that_is_both_suspended_and_downstream_reports_its_own_suspension(self):
+ # suspension is the actionable cause; naming an upstream instead sends the operator away
+ upstream = self._node("upstream", DAILY)
+ both = self._node("both", DAILY)
+ Edge.objects.create(team=self.team, dag=self.dag, source=upstream, target=both)
+ self._suspend(both, reason="its own reason")
+ self._job(upstream, parent_workflow_id=self._daily_parent(), status=DataModelingJobStatus.FAILED, error="boom")
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert {n.name: n.status for n in tier.nodes}["both"] == SUSPENDED
+
+ def test_a_node_suspended_in_another_tier_blocks_its_descendants_here(self):
+ # execute_dag reads suspended_nodes for the whole DAG, so a suspension on the daily tier
+ # skips hourly descendants; seeding blocks only from this tier would call them unexplained
+ upstream = self._node("daily_upstream", DAILY)
+ downstream = self._node("hourly_downstream", HOURLY)
+ Edge.objects.create(team=self.team, dag=self.dag, source=upstream, target=downstream)
+ self._suspend(upstream)
+
+ hourly, _daily = build_tier_runs(self.dag)
+
+ assert {n.name: n.status for n in hourly.nodes}["hourly_downstream"] == BLOCKED
+
+ def test_only_the_serving_engine_counts_for_suspension_and_for_jobs(self):
+ # the duckgres shadow suspends independently and writes its own job row; neither should
+ # change what the clickhouse run is reported to have done
+ shadow_suspended = self._node("shadow_suspended", DAILY)
+ self._suspend(shadow_suspended, engine="duckgres", reason="shadow blew up")
+ shadow_only = self._node("shadow_only", DAILY)
+ served = self._node("served", DAILY)
+ parent = self._daily_parent()
+ self._job(shadow_only, parent_workflow_id=parent, status=DataModelingJobStatus.COMPLETED, engine="duckgres")
+ self._job(served, parent_workflow_id=parent, status=DataModelingJobStatus.COMPLETED)
+
+ (tier,) = build_tier_runs(self.dag)
+ by_name = {n.name: n.status for n in tier.nodes}
+
+ assert by_name["shadow_suspended"] == MISSING # not "suspended" — the CH run still ran it
+ assert by_name["shadow_only"] == MISSING # a shadow job is not evidence the node materialized
+ assert by_name["served"] == OK
+
+ def test_a_soft_deleted_saved_query_leaves_no_phantom_row(self):
+ # the scheduler excludes soft-deleted queries but the target stays on the node, so without
+ # the same exclusion the node would report missing on every page load forever
+ self._node("deleted_model", DAILY)
+ DataWarehouseSavedQuery.objects.filter(team=self.team, name="deleted_model").update(deleted=True)
+ self._node("live_model", DAILY)
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert [n.name for n in tier.nodes] == ["live_model"]
+ assert [n.name for n in untargeted_nodes(self.dag)] == []
+
+ def test_started_at_is_the_first_job_of_the_run_not_the_last(self):
+ # children start over a long window on a wide DAG; the last one is not when the run began
+ first, last = self._node("first", DAILY), self._node("last", DAILY)
+ parent = self._daily_parent()
+ first_job = self._job(first, parent_workflow_id=parent, status=DataModelingJobStatus.COMPLETED)
+ self._job(last, parent_workflow_id=parent, status=DataModelingJobStatus.COMPLETED)
+
+ (tier,) = build_tier_runs(self.dag)
+
+ assert tier.started_at == first_job.created_at