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): concise freshness preview + cross-DAG duplication report (#69578)

Jovan Sakovic2f5919a0db38
diff --git a/products/data_modeling/backend/management/commands/preview_freshness_schedules.py b/products/data_modeling/backend/management/commands/preview_freshness_schedules.py
index 9bb90a391394..eb9afcdcf8f3 100644
--- a/products/data_modeling/backend/management/commands/preview_freshness_schedules.py
+++ b/products/data_modeling/backend/management/commands/preview_freshness_schedules.py
@@ -1,17 +1,21 @@
import uuid
+from collections import defaultdict
from django.core.management.base import BaseCommand, CommandError
+from products.data_modeling.backend.logic.freshness import format_cadence
from products.data_modeling.backend.logic.schedule_reconcile import DagSchedulePreview, preview_dag_schedules
from products.data_modeling.backend.models.dag import DAG
-from products.data_modeling.backend.models.node import Node
+from products.data_modeling.backend.models.node import Node, NodeType
class Command(BaseCommand):
help = (
"Dry-run: show the per-cadence-tier schedules a DAG would get from its nodes' freshness "
"targets, and the create/update/delete plan against its current schedules. Reads only — "
- "never creates, updates, or deletes a schedule, and touches no live read/write path."
+ "never creates, updates, or deletes a schedule, and touches no live read/write path. "
+ "Prints a compact summary by default (--verbose for per-node cadences), plus a team-level "
+ "cross-DAG duplication report to judge whether a redundant DAG is safe to drop."
)
def add_arguments(self, parser):
@@ -22,6 +26,11 @@ class Command(BaseCommand):
action="store_true",
help="Model the go-live plan: seed a target from current cadence for nodes without one (in memory, no write)",
)
+ parser.add_argument(
+ "--verbose",
+ action="store_true",
+ help="Print every node's effective cadence and each tier's members (default: tier counts only)",
+ )
def handle(self, *args, **options):
queryset = DAG.objects.filter(team_id=options["team_id"])
@@ -34,49 +43,73 @@ class Command(BaseCommand):
if not dags:
raise CommandError("No matching DAGs")
for dag in dags:
- self._preview(dag, seed=options["seed"])
+ self._preview(dag, seed=options["seed"], verbose=options["verbose"])
+ self._print_cross_dag_duplication(options["team_id"])
self.stdout.write("\n(dry run — no schedules were created, updated, or deleted)")
- def _preview(self, dag: DAG, *, seed: bool) -> None:
+ def _preview(self, dag: DAG, *, seed: bool, verbose: bool) -> None:
preview = preview_dag_schedules(dag, seed=seed)
names = {str(node_id): name for node_id, name in Node.objects.filter(dag=dag).values_list("id", "name")}
- seeded_note = " [targets seeded from current cadence]" if preview.seeded else ""
+ seeded_note = " [seeded]" if preview.seeded else ""
self.stdout.write(f"\nDAG {dag.name} ({dag.id}) — team {dag.team_id}{seeded_note}")
- self.stdout.write(" Effective cadences:")
- for node_id, interval in sorted(preview.effective.items(), key=lambda item: names.get(item[0], item[0])):
- cadence = str(interval) if interval is not None else "unscheduled"
- self.stdout.write(f" {names.get(node_id, node_id)}: {cadence}")
+ tiers = " ".join(
+ f"{format_cadence(interval)} x{len(node_ids)}"
+ for interval, node_ids in sorted(preview.desired_tiers.items())
+ )
+ unscheduled = sum(1 for cadence in preview.effective.values() if cadence is None)
+ tier_line = tiers or "(none)"
+ if unscheduled:
+ tier_line += f" unscheduled x{unscheduled}"
+ self.stdout.write(f" tiers: {tier_line}")
- self.stdout.write(" Desired tiers:")
- for interval, node_ids in sorted(preview.desired_tiers.items()):
- members = ", ".join(sorted(names.get(node_id, node_id) for node_id in node_ids))
- self.stdout.write(f" {interval}: {members}")
+ plan = preview.plan
+ self.stdout.write(
+ f" plan: CREATE {len(plan.to_create)}, UPDATE {len(plan.to_update)}, DELETE {len(plan.to_delete)}"
+ )
+
+ self._print_warnings(preview, names)
- self._print_plan(preview)
+ if verbose:
+ self._print_verbose(preview, names)
+ def _print_warnings(self, preview: DagSchedulePreview, names: dict[str, str]) -> None:
+ wrote = False
for tier in sorted(preview.unsatisfiable, key=lambda t: names.get(t.node_id, t.node_id)):
+ wrote = True
self.stdout.write(
f" ⚠ unsatisfiable: {names.get(tier.node_id, tier.node_id)} would run every {tier.effective} "
f"but its sources only deliver every {tier.source_floor}"
)
-
for interval in preview.unsupported_tiers:
+ wrote = True
self.stdout.write(f" ⚠ unsupported tier: {interval} is not a schedulable bucket — reconcile would refuse")
-
for invalid in sorted(preview.invalid_targets, key=lambda t: names.get(t.node_id, t.node_id)):
+ wrote = True
ceiling = str(invalid.consumer_ceiling) if invalid.consumer_ceiling is not None else "none"
self.stdout.write(
f" ⚠ invalid declared target: {names.get(invalid.node_id, invalid.node_id)} declares "
f"{invalid.declared} but its legal range is [{invalid.source_floor} … {ceiling}]"
)
-
if preview.best_effort_source_ids:
+ wrote = True
flagged = ", ".join(sorted(names.get(node_id, node_id) for node_id in preview.best_effort_source_ids))
self.stdout.write(f" ⚠ best-effort sources (freshness not guaranteed): {flagged}")
+ if not wrote:
+ self.stdout.write(" ⚠ none")
+
+ def _print_verbose(self, preview: DagSchedulePreview, names: dict[str, str]) -> None:
+ self.stdout.write(" Effective cadences:")
+ for node_id, interval in sorted(preview.effective.items(), key=lambda item: names.get(item[0], item[0])):
+ cadence = str(interval) if interval is not None else "unscheduled"
+ self.stdout.write(f" {names.get(node_id, node_id)}: {cadence}")
+
+ self.stdout.write(" Desired tiers:")
+ for interval, node_ids in sorted(preview.desired_tiers.items()):
+ members = ", ".join(sorted(names.get(node_id, node_id) for node_id in node_ids))
+ self.stdout.write(f" {interval}: {members}")
- def _print_plan(self, preview: DagSchedulePreview) -> None:
plan = preview.plan
self.stdout.write(" Plan vs current schedules:")
if not (plan.to_create or plan.to_update or plan.to_delete):
@@ -88,3 +121,38 @@ class Command(BaseCommand):
self.stdout.write(f" UPDATE {schedule_id} ({interval}, {len(node_ids)} nodes)")
for schedule_id in sorted(plan.to_delete):
self.stdout.write(f" DELETE {schedule_id}")
+
+ def _print_cross_dag_duplication(self, team_id: int) -> None:
+ """Which saved queries a team materializes in more than one DAG, and which are unique to
+ each DAG. A query in >1 DAG is materialized redundantly; a DAG whose queries all also live
+ elsewhere is safe to drop, one with unique queries is not."""
+ dags = list(DAG.objects.filter(team_id=team_id))
+ if len(dags) < 2:
+ return
+ dag_names = {dag.id: dag.name for dag in dags}
+ rows = (
+ Node.objects.filter(dag__in=dags)
+ .exclude(type=NodeType.TABLE)
+ .exclude(saved_query__deleted=True)
+ .values_list("dag_id", "saved_query_id")
+ )
+ dags_by_query: dict[object, set[object]] = defaultdict(set)
+ for dag_id, saved_query_id in rows:
+ if saved_query_id is not None:
+ dags_by_query[saved_query_id].add(dag_id)
+
+ if not dags_by_query:
+ return
+ double_materialized = sum(1 for owning in dags_by_query.values() if len(owning) > 1)
+ unique_per_dag: dict[object, int] = defaultdict(int)
+ for owning in dags_by_query.values():
+ if len(owning) == 1:
+ unique_per_dag[next(iter(owning))] += 1
+
+ self.stdout.write(f"\nTeam {team_id} cross-DAG duplication:")
+ self.stdout.write(f" {len(dags_by_query)} distinct saved queries across {len(dags)} DAGs")
+ self.stdout.write(f" in >1 DAG (double-materialized): {double_materialized}")
+ for dag in sorted(dags, key=lambda d: dag_names[d.id]):
+ unique = unique_per_dag.get(dag.id, 0)
+ note = "safe to drop" if unique == 0 else "unsafe to drop"
+ self.stdout.write(f" only in {dag_names[dag.id]} ({note}): {unique}")
diff --git a/products/data_modeling/backend/test/test_preview_freshness_schedules.py b/products/data_modeling/backend/test/test_preview_freshness_schedules.py
index 116c5c62a548..1c561b65eb95 100644
--- a/products/data_modeling/backend/test/test_preview_freshness_schedules.py
+++ b/products/data_modeling/backend/test/test_preview_freshness_schedules.py
@@ -78,8 +78,8 @@ class TestPreviewFreshnessSchedules(BaseTest):
delete.assert_not_called()
output = out.getvalue()
- self.assertIn("CREATE", output)
- self.assertIn("0:15:00", output)
+ self.assertIn("tiers: 15min", output)
+ self.assertIn("plan: CREATE 1", output)
self.assertIn("dry run", output)
def test_seed_mode_models_go_live_from_current_cadence(self):
@@ -108,9 +108,9 @@ class TestPreviewFreshnessSchedules(BaseTest):
create.assert_not_called()
delete.assert_not_called()
output = out.getvalue()
- self.assertIn("seeded from current cadence", output)
- self.assertIn("CREATE", output)
- self.assertIn("6:00:00", output)
+ self.assertIn("[seeded]", output)
+ self.assertIn("plan: CREATE 1", output)
+ self.assertIn("6hour", output)
def test_flags_unsupported_tier_and_invalid_declared_target(self):
# go-live audit: a 45min legacy cadence (seeded) must be flagged as unschedulable, and a
@@ -139,3 +139,43 @@ class TestPreviewFreshnessSchedules(BaseTest):
output = out.getvalue()
self.assertIn("unsupported tier: 0:45:00", output)
self.assertIn("invalid declared target: mv", output)
+
+ def test_verbose_flag_gates_per_node_detail(self):
+ # the per-node cadence wall is what floods the terminal; it must be verbose-only
+ dag = DAG.get_or_create_default(self.team)
+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})
+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)
+ Edge.objects.create(team=self.team, dag=dag, source=source, target=endpoint)
+ set_declared_target(endpoint, M15)
+
+ module = "products.data_modeling.backend.logic.schedule_reconcile"
+ summary, verbose = StringIO(), StringIO()
+ with mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=_no_existing_schedules())):
+ call_command("preview_freshness_schedules", "--team-id", str(self.team.pk), stdout=summary)
+ call_command("preview_freshness_schedules", "--team-id", str(self.team.pk), "--verbose", stdout=verbose)
+
+ self.assertNotIn("Effective cadences", summary.getvalue())
+ self.assertIn("Effective cadences", verbose.getvalue())
+ self.assertIn("0:15:00", verbose.getvalue())
+
+ def test_cross_dag_duplication_flags_unsafe_drop(self):
+ # one saved query materialized by two DAGs is double-materialized; a query unique to a DAG
+ # makes that DAG unsafe to drop, one whose queries all live elsewhere is safe
+ shared = DataWarehouseSavedQuery.objects.create(
+ name="shared_mv", team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"}
+ )
+ default_dag = DAG.objects.create(team=self.team, name="Default")
+ canonical_dag = DAG.objects.create(team=self.team, name="posthog_team")
+ Node.objects.create(team=self.team, dag=default_dag, saved_query=shared, type=NodeType.MAT_VIEW)
+ Node.objects.create(team=self.team, dag=canonical_dag, saved_query=shared, type=NodeType.MAT_VIEW)
+ _saved_query_node(self.team, default_dag, "only_in_default", NodeType.MAT_VIEW)
+
+ module = "products.data_modeling.backend.logic.schedule_reconcile"
+ out = StringIO()
+ with mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=_no_existing_schedules())):
+ call_command("preview_freshness_schedules", "--team-id", str(self.team.pk), stdout=out)
+
+ output = out.getvalue()
+ self.assertIn("in >1 DAG (double-materialized): 1", output)
+ self.assertIn("only in Default (unsafe to drop): 1", output)
+ self.assertIn("only in posthog_team (safe to drop): 0", output)