: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
chore(data-modeling): add tier-schedule check and matview cleanup commands (#73898)
Jovan Sakovicfbddb76517d2
diff --git a/products/data_modeling/backend/logic/tier_membership.py b/products/data_modeling/backend/logic/tier_membership.pynew file mode 100644index 000000000000..11e16e27c96d--- /dev/null+++ b/products/data_modeling/backend/logic/tier_membership.py@@ -0,0 +1,199 @@+"""Answer "is this node actually on a cadence-tier schedule?" from the source of truth.++Neither the warehouse mirror nor the node's stored `target_seconds` is reliable for this: the+mirror lags on deletes, and a node can carry a target the last reconcile never wrote into a live+schedule. The only authoritative record of what a tier will materialize is the `node_ids` list in+the tier's Temporal schedule payload — which is Fernet-encrypted, so it must be read through a+codec-configured client (the standard PostHog Temporal client decodes it transparently).++This module reads those live `node_ids` and compares them against what reconcile *would* schedule+(`compute_effective_cadences`), so a node that has a target but is missing from every live tier is+reported as needing a reconcile rather than silently unscheduled.+"""++import dataclasses+from datetime import timedelta++from temporalio.client import Client, ScheduleActionStartWorkflow, ScheduleListActionStartWorkflow++from posthog.temporal.common.search_attributes import POSTHOG_DAG_ID_KEY++from products.data_modeling.backend.logic.cohort_scheduling import bucket_into_cadence_tiers, is_tier_schedule_id+from products.data_modeling.backend.logic.freshness import (+ SCHEDULABLE_BUCKETS,+ clamp_to_source_floor,+ compute_effective_cadences,+)+from products.data_modeling.backend.logic.node_frequency import build_frequency_graph+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.schedule import DATA_MODELING_EXECUTE_DAG_WORKFLOW++[email protected](frozen=True)+class LiveTier:+ """One execute-dag schedule for a DAG, as it exists in Temporal right now."""++ schedule_id: str+ interval_seconds: int | None # None = migration-era single schedule (no cadence tier)+ covers_whole_dag: bool # True when node_ids is unset — the schedule materializes every node+ node_ids: frozenset[str] | None # the exact set the tier will materialize; None when whole-DAG+++class NodeScheduleStatus:+ node_id: str+ name: str+ node_type: str+ dag_id: str+ dag_name: str+ live_intervals: list[int | None] # tiers whose live node_ids include this node (None = whole-DAG)+ expected_interval: int | None # what reconcile would put it on now (None = ride-downstream opt-out)+ verdict: str+ dag_reconcile_blocked: bool = False # a non-bucket tier anywhere in the DAG makes reconcile refuse it+++# Verdict values — a node's live scheduling vs what reconcile would currently schedule.+SCHEDULED = "scheduled" # on a live tier, matching expectation+SCHEDULED_WRONG_TIER = "scheduled_wrong_tier" # on a live tier, but at a different cadence than expected+STALE_NEEDS_RECONCILE = "stale_needs_reconcile" # has a target but no live tier covers it — reconcile+OVER_SCHEDULED = "over_scheduled" # on a live tier but reconcile would drop it (no effective cadence)+CORRECTLY_UNSCHEDULED = "correctly_unscheduled" # no target and no live tier — the opt-out, working+# Reconcile refuses the *whole DAG* when any desired tier is not a schedulable bucket, so this must+# never be reported as stale_needs_reconcile: running reconcile would change nothing and raise.+UNSUPPORTED_TARGET = "unsupported_target"+++def _interval_from_schedule_id(schedule_id: str) -> int | None:+ """Recover the tier's cadence (seconds) from its schedule id, or None for the legacy single schedule."""+ if is_tier_schedule_id(schedule_id):+ return int(schedule_id.rsplit(":", 1)[1])+ return None+++async def _decode_node_ids(temporal: Client, action: object) -> list[str] | None:+ """Read `node_ids` from a schedule's start-workflow args, decoding the encrypted payload.++ Returns None when the schedule carries no node_ids (a whole-DAG single schedule) or the args are+ shaped unexpectedly. `describe()` hands back raw Payloads; the client's data converter runs the+ Fernet codec on decode. We also accept already-decoded dicts so tests can mock without a codec.+ """+ if not isinstance(action, ScheduleActionStartWorkflow):+ return None+ args = list(action.args)+ if not args:+ return None+ first = args[0]+ if isinstance(first, dict):+ return first.get("node_ids")+ decoded = await temporal.data_converter.decode(args)+ if decoded and isinstance(decoded[0], dict):+ return decoded[0].get("node_ids")+ return None+++async def read_live_tiers(temporal: Client, dag_id: str) -> list[LiveTier]:+ """List a DAG's execute-dag schedules and read each one's live node set from Temporal."""+ tiers: list[LiveTier] = []+ schedules = await temporal.list_schedules(query=f"{POSTHOG_DAG_ID_KEY.name} = '{dag_id}'")+ async for listing in schedules:+ action = listing.schedule.action if listing.schedule else None+ if not (+ isinstance(action, ScheduleListActionStartWorkflow)+ and action.workflow == DATA_MODELING_EXECUTE_DAG_WORKFLOW+ ):+ continue+ described = await temporal.get_schedule_handle(listing.id).describe()+ node_ids = await _decode_node_ids(temporal, described.schedule.action)+ tiers.append(+ LiveTier(+ schedule_id=listing.id,+ interval_seconds=_interval_from_schedule_id(listing.id),+ covers_whole_dag=node_ids is None,+ node_ids=frozenset(node_ids) if node_ids is not None else None,+ )+ )+ return tiers+++def _desired_tiers(dag: DAG) -> dict[timedelta, set[str]]:+ """The tiers reconcile would want for this DAG: effective cadences → clamp to floor → buckets."""+ graph = build_frequency_graph(dag)+ effective = compute_effective_cadences(+ nodes=graph.nodes, edges=graph.edges, declared_targets=graph.declared_targets+ )+ effective, _clamped = clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)+ return bucket_into_cadence_tiers(effective)+++def expected_tier_by_node(dag: DAG) -> dict[str, int]:+ """What cadence (seconds) reconcile would currently schedule each schedulable node on.++ Mirrors `reconcile_dag_schedules` exactly (effective cadences → clamp to source floor → buckets)+ so a node absent from this map is one reconcile would leave unscheduled (the ride-downstream+ opt-out), not a bug.+ """+ return {+ node_id: int(interval.total_seconds())+ for interval, node_ids in _desired_tiers(dag).items()+ for node_id in node_ids+ }+++def dag_reconcile_would_refuse(dag: DAG) -> bool:+ """Whether reconcile would refuse this DAG outright because a desired tier is not a bucket.++ `_apply_reconciliation` raises `UnsupportedFrequencyTargetError` for the *whole* DAG when any+ desired tier falls outside `SCHEDULABLE_BUCKETS`, leaving every schedule untouched. Without+ this, such a node reads as `stale_needs_reconcile` — advice that would raise rather than fix.+ """+ return any(interval not in SCHEDULABLE_BUCKETS for interval in _desired_tiers(dag))+++def classify_node(+ *,+ node_id: str,+ name: str,+ node_type: str,+ dag_id: str,+ dag_name: str,+ live_tiers: list[LiveTier],+ expected_interval: int | None,+ reconcile_blocked: bool = False,+) -> NodeScheduleStatus:+ """Compare a node's live tier membership against what reconcile would schedule for it."""+ live_intervals = [+ tier.interval_seconds+ for tier in live_tiers+ if tier.covers_whole_dag or (tier.node_ids is not None and node_id in tier.node_ids)+ ]+ covered_live = bool(live_intervals)++ if covered_live and expected_interval is not None:+ # A whole-DAG (interval None) schedule always satisfies expectation.+ verdict = SCHEDULED if (None in live_intervals or expected_interval in live_intervals) else SCHEDULED_WRONG_TIER+ elif covered_live and expected_interval is None:+ verdict = OVER_SCHEDULED+ elif not covered_live and expected_interval is not None:+ # Reconcile is the remediation for stale_needs_reconcile, so only report it when reconcile+ # would actually run. A blocked DAG needs its unschedulable target fixed first.+ verdict = UNSUPPORTED_TARGET if reconcile_blocked else STALE_NEEDS_RECONCILE+ else:+ verdict = CORRECTLY_UNSCHEDULED++ return NodeScheduleStatus(+ node_id=node_id,+ name=name,+ node_type=node_type,+ dag_id=dag_id,+ dag_name=dag_name,+ live_intervals=sorted(live_intervals, key=lambda i: (i is None, i or 0)),+ expected_interval=expected_interval,+ verdict=verdict,+ dag_reconcile_blocked=reconcile_blocked,+ )+++def format_interval(seconds: int | None) -> str:+ if seconds is None:+ return "whole-DAG"+ return str(timedelta(seconds=seconds))diff --git a/products/data_modeling/backend/management/commands/check_node_tier_schedule.py b/products/data_modeling/backend/management/commands/check_node_tier_schedule.pynew file mode 100644index 000000000000..908e60685905--- /dev/null+++ b/products/data_modeling/backend/management/commands/check_node_tier_schedule.py@@ -0,0 +1,175 @@+"""Report whether a data-modeling node is actually materialized by a cadence-tier schedule.++Reads the live `node_ids` out of each execute-dag schedule's (encrypted) Temporal payload — the only+authoritative record of what a tier will run — and compares it against what a reconcile would+schedule for the node right now. Read-only. Run where the prod Temporal credentials live (the same+place `reconcile_freshness_schedules` runs), because it connects through the codec-configured client+to decrypt the payloads.++ python manage.py check_node_tier_schedule --team-id 2 --name managed_product_lifecycle+ python manage.py check_node_tier_schedule --team-id 2 --dag-id <uuid> # every node in a DAG+"""++import json+from typing import Any++from django.core.management.base import BaseCommand, CommandError, CommandParser++from asgiref.sync import async_to_sync++from posthog.temporal.common.client import async_connect++from products.data_modeling.backend.logic.tier_membership import (+ STALE_NEEDS_RECONCILE,+ UNSUPPORTED_TARGET,+ LiveTier,+ classify_node,+ dag_reconcile_would_refuse,+ expected_tier_by_node,+ format_interval,+ read_live_tiers,+)+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.node import Node, NodeType+++class Command(BaseCommand):+ help = "Show which cadence-tier schedule (if any) materializes a data-modeling node, from Temporal."++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team-id", type=int, required=True)+ selector = parser.add_mutually_exclusive_group()+ selector.add_argument("--node-id", help="Node UUID.")+ selector.add_argument("--saved-query-id", help="Saved query UUID (resolves to its node(s)).")+ selector.add_argument("--name", help="Node name (may match several across DAGs).")+ parser.add_argument(+ "--dag-id", help="Restrict to this DAG, or inspect all its nodes when no selector is given."+ )+ parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")++ def handle(self, *args: Any, **options: Any) -> None:+ team_id: int = options["team_id"]+ dag_id: str | None = options["dag_id"]++ selector_given = any(options[key] for key in ("node_id", "saved_query_id", "name"))+ nodes = self._resolve_nodes(team_id, options) if selector_given else []+ # A selector that matched nothing is a typo, not a request to dump the whole DAG.+ if selector_given and not nodes:+ raise CommandError(f"No node in team {team_id} matches that selector.")++ if nodes:+ node_list = list(nodes)+ dag_ids = {str(node.dag_id) for node in nodes}+ elif dag_id:+ node_list = self._dag_nodes(team_id, dag_id)+ dag_ids = {dag_id}+ else:+ raise CommandError("Pass --node-id, --saved-query-id or --name, or --dag-id to inspect a whole DAG.")++ # Resolve every DAG against the team *before* touching Temporal: schedule ids and tier node+ # counts are team data, and a --dag-id belonging to another team would otherwise print them.+ dags_by_id = {str(dag.id): dag for dag in DAG.objects.filter(team_id=team_id, id__in=dag_ids)}+ unknown = dag_ids - set(dags_by_id)+ if unknown:+ raise CommandError(f"DAG(s) {', '.join(sorted(unknown))} do not belong to team {team_id}.")++ live_by_dag = self._read_live_tiers(dag_ids)+ # Compute each DAG's expected tiers once — the frequency graph is per-DAG, not per-node.+ expected_by_dag = {known_id: expected_tier_by_node(dag) for known_id, dag in dags_by_id.items()}+ blocked_by_dag = {known_id: dag_reconcile_would_refuse(dag) for known_id, dag in dags_by_id.items()}++ statuses = []+ for node in node_list:+ dag = dags_by_id.get(str(node.dag_id))+ if dag is None:+ continue+ expected = expected_by_dag.get(str(node.dag_id), {}).get(str(node.id))+ statuses.append(+ classify_node(+ node_id=str(node.id),+ name=node.name,+ node_type=node.type,+ dag_id=str(node.dag_id),+ dag_name=dag.name,+ live_tiers=live_by_dag.get(str(node.dag_id), []),+ expected_interval=expected,+ reconcile_blocked=blocked_by_dag.get(str(node.dag_id), False),+ )+ )++ if options["json"]:+ self.stdout.write(+ json.dumps(+ {+ "tiers": {+ dag_id: [self._tier_dict(tier) for tier in tiers] for dag_id, tiers in live_by_dag.items()+ },+ "nodes": [status.__dict__ for status in statuses],+ },+ indent=2,+ )+ )+ return++ self._print_human(live_by_dag, dags_by_id, statuses)++ def _resolve_nodes(self, team_id: int, options: dict[str, Any]) -> list[Node]:+ qs = Node.objects.filter(team_id=team_id).exclude(type=NodeType.TABLE)+ if options["node_id"]:+ qs = qs.filter(id=options["node_id"])+ elif options["saved_query_id"]:+ qs = qs.filter(saved_query_id=options["saved_query_id"])+ elif options["name"]:+ qs = qs.filter(name=options["name"])+ else:+ return []+ if options["dag_id"]:+ qs = qs.filter(dag_id=options["dag_id"])+ return list(qs.select_related("dag"))++ def _dag_nodes(self, team_id: int, dag_id: str) -> list[Node]:+ return list(+ Node.objects.filter(team_id=team_id, dag_id=dag_id).exclude(type=NodeType.TABLE).select_related("dag")+ )++ @staticmethod+ @async_to_sync+ async def _read_live_tiers(dag_ids: set[str]) -> dict[str, list[LiveTier]]:+ temporal = await async_connect()+ return {dag_id: await read_live_tiers(temporal, dag_id) for dag_id in dag_ids}++ @staticmethod+ def _tier_dict(tier: LiveTier) -> dict[str, Any]:+ return {+ "schedule_id": tier.schedule_id,+ "interval_seconds": tier.interval_seconds,+ "covers_whole_dag": tier.covers_whole_dag,+ "node_count": None if tier.node_ids is None else len(tier.node_ids),+ }++ def _print_human(+ self,+ live_by_dag: dict[str, list[LiveTier]],+ dags_by_id: dict[str, DAG],+ statuses: list[Any],+ ) -> None:+ for dag_id, tiers in live_by_dag.items():+ dag_name = dags_by_id[dag_id].name if dag_id in dags_by_id else "?"+ self.stdout.write(f"\nDAG {dag_name} ({dag_id}) — {len(tiers)} live execute-dag schedule(s):")+ for tier in sorted(tiers, key=lambda t: (t.interval_seconds is None, t.interval_seconds or 0)):+ count = "whole DAG" if tier.node_ids is None else f"{len(tier.node_ids)} nodes"+ self.stdout.write(f" {format_interval(tier.interval_seconds):>10} {tier.schedule_id} ({count})")++ self.stdout.write("")+ for status in statuses:+ live = ", ".join(format_interval(i) for i in status.live_intervals) or "—"+ expected = (+ format_interval(status.expected_interval) if status.expected_interval is not None else "none (opt-out)"+ )+ marker = " ⚠️" if status.verdict in (STALE_NEEDS_RECONCILE, UNSUPPORTED_TARGET) else ""+ if status.verdict == UNSUPPORTED_TARGET:+ marker += " — reconcile would REFUSE this whole DAG; fix the non-bucket target first"+ self.stdout.write(+ f"{status.name} [{status.node_type}] {status.node_id}\n"+ f" live tier: {live} | reconcile would schedule: {expected} | verdict: {status.verdict}{marker}"+ )diff --git a/products/data_modeling/backend/management/commands/cleanup_orphaned_matview_tables.py b/products/data_modeling/backend/management/commands/cleanup_orphaned_matview_tables.pynew file mode 100644index 000000000000..9f00fe2c54e1--- /dev/null+++ b/products/data_modeling/backend/management/commands/cleanup_orphaned_matview_tables.py@@ -0,0 +1,210 @@+"""Finish the delete cascade for materialized saved queries that were only half-deleted.++The proper delete path (`delete_saved_query`) does four things: remove the DAG node+(`delete_node_from_dag`), soft-delete the query's joins, `revert_materialization()` (soft-delete the+backing table + null table_id + drop model paths + clear schedule/tier), and `soft_delete()` (rename+to POSTHOG_DELETED). A query soft-deleted another way — a manual `deleted=True` in a shell, bypassing+the model method — sets only that flag, leaving the table live (leaks into the "self-managed sources"+sidebar), the DAG node in place (a ghost node with no resolvable saved query), and the model paths /+joins dangling.++This finds those half-deleted matviews and runs the rest of the cascade, so each ends in the same+state a proper delete would have produced. Dry-run by default; --apply to mutate; --team-id to scope.++ python manage.py cleanup_orphaned_matview_tables # preview fleet-wide+ python manage.py cleanup_orphaned_matview_tables --team-id 2 --apply+"""++from typing import Any++from django.core.management.base import BaseCommand, CommandParser+from django.db.models import Q, QuerySet++import structlog++from products.data_modeling.backend.logic.saved_query_dag_sync import HasDependentsError, delete_node_from_dag+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.node import Node+from products.data_tools.backend.facade.models import DataWarehouseJoin+from products.warehouse_sources.backend.facade.models import DataWarehouseTable++logger = structlog.get_logger(__name__)++CLEANED = "cleaned"+SKIPPED_DEPENDENTS = "skipped_has_live_dependents"+SKIPPED_MANAGED = "skipped_managed_viewset"+SKIPPED_SHARED_TABLE = "skipped_table_shared_with_live_query"+SKIPPED_ERROR = "skipped_error"+++def table_shared_with_live_query(saved_query: DataWarehouseSavedQuery) -> bool:+ """Whether a live saved query points at this query's backing table. Checked at batch selection+ AND again inside the cascade: a live query can acquire the table in between, and reverting it+ then would soft-delete a table something uses.+ """+ if saved_query.table_id is None:+ return False+ return (+ DataWarehouseSavedQuery.objects.exclude(deleted=True)+ .filter(team_id=saved_query.team_id, table_id=saved_query.table_id)+ .exists()+ )+++def has_live_dependents(saved_query: DataWarehouseSavedQuery) -> bool:+ """Whether any live saved query depends on *any* of this query's nodes.++ `delete_node_from_dag` deletes every Node the query has, but the `HasDependentsError` guard it+ relies on only inspects one arbitrary node (`get_dependent_saved_queries` does a `.first()`). A+ query with nodes in several DAGs — the exact population `consolidate_dags` exists for — can+ therefore pass that guard while a real dependent sits in another DAG, and the cascade would+ delete its edge and revert the table underneath it. Check the full blast radius first.+ """+ nodes = Node.objects.filter(team_id=saved_query.team_id, saved_query=saved_query)+ return (+ Node.objects.filter(+ team_id=saved_query.team_id,+ incoming_edges__source__in=nodes,+ saved_query__isnull=False,+ )+ .exclude(saved_query__deleted=True)+ .exists()+ )+++def find_half_deleted_matviews(team_id: int | None = None) -> QuerySet[DataWarehouseSavedQuery]:+ """Saved queries soft-deleted by a path that bypassed the model method, with cleanup pending.++ The signature is `deleted=True` but `deleted_name IS NULL`: a proper `soft_delete()` always+ records `deleted_name` and renames to POSTHOG_DELETED, a raw `deleted=True` does neither. That+ filter is also what distinguishes these from properly-deleted queries that merely kept a ghost+ node — a separate, far larger population this must not touch. Managed-viewset rows are excluded+ because their viewset owns their lifecycle.++ Every signature row stays selected regardless of which leftovers (node, live table, joins,+ rename) it still has: the cascade's stages commit independently, so a run that failed partway+ can leave a row with no node and no live table but live joins or an unfreed name. `soft_delete`+ runs last in the cascade and records `deleted_name` — the terminal marker that removes the row+ from this population — and every earlier stage is a no-op once done, so re-running the command+ resumes any partial cleanup.++ Safety guard: a query whose table is *also* referenced by a live saved query is excluded, so+ the cascade can never soft-delete a table something uses. The guard lookup is scoped by+ `--team-id` too: unscoped it reads the whole fleet on a single-team run, and tables are+ team-owned so another team's rows can never be the ones at risk.+ """+ deleted = DataWarehouseSavedQuery.objects.filter(+ deleted=True, deleted_name__isnull=True, managed_viewset__isnull=True+ )+ live = DataWarehouseSavedQuery.objects.exclude(deleted=True)+ if team_id is not None:+ deleted = deleted.filter(team_id=team_id)+ live = live.filter(team_id=team_id)++ # Tables still referenced by a live query must never be touched.+ live_table_ids = set(live.filter(table_id__isnull=False).values_list("table_id", flat=True))+ keep_ids: list[Any] = [+ sq_id+ for sq_id, table_id in deleted.values_list("id", "table_id")+ if table_id is None or table_id not in live_table_ids+ ]+ return DataWarehouseSavedQuery.objects.filter(id__in=keep_ids)+++def cascade_delete(saved_query: DataWarehouseSavedQuery) -> str:+ """Run the parts of `delete_saved_query` that a bypassed soft-delete skipped.++ The stages commit independently, so ordering is the retry mechanism: every stage is a no-op+ once done, and `soft_delete` — whose `deleted_name` removes the row from+ `find_half_deleted_matviews` — must stay LAST, so a failure at any earlier stage leaves the+ row selected for the next run to resume.+ """+ # `delete_saved_query` refuses these outright: the managed viewset owns the lifecycle and+ # reconciles its own views, so tearing one down out-of-band leaves sync_views() to discover a+ # view it believes it owns already gone.+ if saved_query.managed_viewset is not None:+ return SKIPPED_MANAGED+ if table_shared_with_live_query(saved_query):+ return SKIPPED_SHARED_TABLE+ if has_live_dependents(saved_query):+ return SKIPPED_DEPENDENTS++ try:+ delete_node_from_dag(saved_query)+ except HasDependentsError:+ return SKIPPED_DEPENDENTS++ for join in DataWarehouseJoin.objects.filter(+ Q(team_id=saved_query.team_id)+ & (Q(source_table_name=saved_query.name) | Q(joining_table_name=saved_query.name))+ ).exclude(deleted=True):+ join.soft_delete()++ saved_query.revert_materialization() # soft-deletes the table, nulls table_id, drops model paths+ if saved_query.deleted_name is None: # complete the rename a bypassed delete skipped+ saved_query.soft_delete()+ return CLEANED+++class Command(BaseCommand):+ help = "Finish the delete cascade for materialized saved queries that were only half-deleted (deleted flag set, table/node left behind)."++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team-id", type=int, help="Scope to one team (default: all teams).")+ parser.add_argument("--apply", action="store_true", help="Actually run the cascade (default: dry-run).")++ def handle(self, *args: Any, **options: Any) -> None:+ team_id: int | None = options["team_id"]+ apply: bool = options["apply"]++ saved_queries = list(find_half_deleted_matviews(team_id))+ if not saved_queries:+ self.stdout.write("No half-deleted matviews found.")+ return++ node_dag = dict(+ Node.objects.filter(saved_query__in=saved_queries)+ .select_related("dag")+ .values_list("saved_query_id", "dag__name")+ )+ live_table_ids = {+ t.id+ for t in DataWarehouseTable.objects.exclude(deleted=True).filter(+ id__in=[sq.table_id for sq in saved_queries if sq.table_id]+ )+ }++ verb = "Cascading delete for" if apply else "Would cascade delete"+ self.stdout.write(f"{verb} {len(saved_queries)} half-deleted matview(s):")+ for sq in sorted(saved_queries, key=lambda s: (s.team_id, s.name)):+ leftovers = []+ if sq.id in node_dag:+ leftovers.append(f"node in DAG {node_dag[sq.id]!r}")+ if sq.table_id in live_table_ids:+ leftovers.append("live table")+ if not leftovers:+ leftovers.append("unfinished rename only")+ self.stdout.write(f" team {sq.team_id} {sq.name} ({', '.join(leftovers)})")++ if not apply:+ self.stdout.write("\nDry-run only. Re-run with --apply to cascade.")+ return++ # Per-item isolation: a fleet-wide run must not lose the work it already did (or the record+ # of what it did) because one query failed halfway down the list.+ outcomes: dict[str, int] = {CLEANED: 0, SKIPPED_DEPENDENTS: 0, SKIPPED_MANAGED: 0, SKIPPED_ERROR: 0}+ for sq in saved_queries:+ try:+ outcomes[cascade_delete(sq)] += 1+ except Exception as e:+ outcomes[SKIPPED_ERROR] += 1+ self.stderr.write(f" team {sq.team_id} {sq.name}: {type(e).__name__}: {e}")+ logger.exception(+ "cleanup_orphaned_matview_tables_failed", team_id=sq.team_id, saved_query_id=str(sq.id)+ )+ self.stdout.write(+ f"\nCleaned {outcomes[CLEANED]}; skipped — live dependents {outcomes[SKIPPED_DEPENDENTS]}, "+ f"managed viewset {outcomes[SKIPPED_MANAGED]}, errored {outcomes[SKIPPED_ERROR]}."+ )+ if outcomes[SKIPPED_ERROR]:+ self.stdout.write("Re-run to retry the failures — the cascade is idempotent per query.")diff --git a/products/data_modeling/backend/test/test_check_node_tier_schedule.py b/products/data_modeling/backend/test/test_check_node_tier_schedule.pynew file mode 100644index 000000000000..513872c558d6--- /dev/null+++ b/products/data_modeling/backend/test/test_check_node_tier_schedule.py@@ -0,0 +1,58 @@+import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command+from django.core.management.base import CommandError++from posthog.models import Organization, Team++from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.node import Node, NodeType++TEMPORAL_READ = "products.data_modeling.backend.management.commands.check_node_tier_schedule.Command._read_live_tiers"+++class TestCheckNodeTierScheduleGuards(BaseTest):+ """The guards that must hold before the command reads live schedules out of Temporal."""++ def _node(self, dag: DAG, name: str) -> Node:+ saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team, name=name, query={"kind": "HogQLQuery", "query": "select 1"}+ )+ return Node.objects.create(team=self.team, dag=dag, name=name, type=NodeType.MAT_VIEW, saved_query=saved_query)++ def test_dag_id_from_another_team_is_refused_before_reading_temporal(self):+ # Schedule ids and per-tier node counts are team data. Resolving --dag-id only for display+ # while still querying Temporal by that id would print another team's live schedules.+ other_team = Team.objects.create(organization=Organization.objects.create(name="other"), name="other")+ foreign_dag = DAG.objects.create(team=other_team, name="Default")++ with patch(TEMPORAL_READ) as read_live:+ with pytest.raises(CommandError, match="do not belong to team"):+ call_command(+ "check_node_tier_schedule", "--team-id", str(self.team.pk), "--dag-id", str(foreign_dag.id)+ )++ read_live.assert_not_called()++ def test_selector_matching_nothing_errors_instead_of_dumping_the_dag(self):+ # A typo'd --name used to fall through to "no selector given" and dump every node in the DAG,+ # which reads as a clean bill of health for a node that was never actually inspected.+ dag = DAG.objects.create(team=self.team, name="Default")+ self._node(dag, "real_view")++ with patch(TEMPORAL_READ) as read_live:+ with pytest.raises(CommandError, match="matches that selector"):+ call_command(+ "check_node_tier_schedule",+ "--team-id",+ str(self.team.pk),+ "--name",+ "typo_view",+ "--dag-id",+ str(dag.id),+ )++ read_live.assert_not_called()diff --git a/products/data_modeling/backend/test/test_cleanup_orphaned_matview_tables.py b/products/data_modeling/backend/test/test_cleanup_orphaned_matview_tables.pynew file mode 100644index 000000000000..b386460af8e3--- /dev/null+++ b/products/data_modeling/backend/test/test_cleanup_orphaned_matview_tables.py@@ -0,0 +1,147 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from products.data_modeling.backend.management.commands.cleanup_orphaned_matview_tables import (+ CLEANED,+ SKIPPED_DEPENDENTS,+ SKIPPED_MANAGED,+ SKIPPED_SHARED_TABLE,+ cascade_delete,+ find_half_deleted_matviews,+)+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_managed_viewset import DataWarehouseManagedViewSet+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_tools.backend.facade.models import DataWarehouseJoin+from products.warehouse_sources.backend.facade.models import DataWarehouseTable+++class TestFindHalfDeletedMatviews(BaseTest):+ def _table(self, name: str, deleted: bool = False) -> DataWarehouseTable:+ return DataWarehouseTable.objects.create(team=self.team, name=name, format="Parquet", deleted=deleted)++ def _saved_query(self, name: str, table: DataWarehouseTable | None, deleted: bool) -> DataWarehouseSavedQuery:+ return DataWarehouseSavedQuery.objects.create(+ team=self.team, name=name, query={"kind": "HogQLQuery", "query": "select 1"}, table=table, deleted=deleted+ )++ def _node(self, sq: DataWarehouseSavedQuery, dag_name: str = "Default") -> Node:+ dag, _ = DAG.objects.get_or_create(team=self.team, name=dag_name)+ return Node.objects.create(team=self.team, dag=dag, name=sq.name, type=NodeType.MAT_VIEW, saved_query=sq)++ def _found(self) -> set:+ return set(find_half_deleted_matviews().values_list("id", flat=True))++ def test_orphan_with_live_table_and_node_is_found(self):+ table = self._table("leaked_view")+ sq = self._saved_query("leaked_view", table, deleted=True)+ self._node(sq)+ assert self._found() == {sq.id}++ def test_node_only_orphan_is_found(self):+ # The post-table-cleanup state: table already soft-deleted, but the ghost node lingers.+ table = self._table("gone_view", deleted=True)+ sq = self._saved_query("gone_view", table, deleted=True)+ self._node(sq)+ assert self._found() == {sq.id}++ def test_table_shared_with_a_live_query_is_excluded(self):+ # Safety guard: a live query still points at the table — never cascade (would delete a live+ # table). The guard must also hold inside cascade_delete itself: a live query can acquire+ # the table between batch selection and the cascade reaching this row.+ table = self._table("shared_view")+ dead = self._saved_query("old_view", table, deleted=True)+ self._node(dead)+ self._saved_query("shared_view", table, deleted=False)+ assert self._found() == set()++ assert cascade_delete(dead) == SKIPPED_SHARED_TABLE+ table.refresh_from_db()+ dead.refresh_from_db()+ assert not table.deleted+ assert dead.table_id == table.id+ assert Node.objects.filter(saved_query=dead).exists()++ def test_partially_cleaned_row_stays_selected_until_soft_delete_completes(self):+ # The state a cascade crash leaves behind: node gone, table soft-deleted, but joins live+ # and the original name still occupied. The row must stay in the population so a re-run+ # resumes it — soft_delete's deleted_name is the terminal marker, not node/table presence.+ table = self._table("done_view", deleted=True)+ sq = self._saved_query("done_view", table, deleted=True)+ join = DataWarehouseJoin.objects.create(+ team=self.team,+ source_table_name="done_view",+ source_table_key="id",+ joining_table_name="events",+ joining_table_key="id",+ field_name="done_view",+ )+ assert self._found() == {sq.id}++ assert cascade_delete(sq) == CLEANED+ sq.refresh_from_db()+ join.refresh_from_db()+ assert sq.deleted_name == "done_view"+ assert sq.name.startswith("POSTHOG_DELETED_")+ assert join.deleted+ assert self._found() == set()++ def test_live_query_is_untouched(self):+ table = self._table("healthy_view")+ sq = self._saved_query("healthy_view", table, deleted=False)+ self._node(sq)+ assert self._found() == set()++ def test_managed_viewset_query_is_excluded(self):+ # The managed viewset owns its views' lifecycle; delete_saved_query refuses these outright,+ # so the cascade must never revert one out-of-band and leave sync_views() to discover it.+ viewset = DataWarehouseManagedViewSet.objects.create(team=self.team, kind="revenue_analytics")+ table = self._table("managed_view")+ sq = self._saved_query("managed_view", table, deleted=True)+ sq.managed_viewset = viewset+ sq.save()+ self._node(sq)++ assert self._found() == set()+ assert cascade_delete(sq) == SKIPPED_MANAGED++ def test_dependent_in_another_dag_blocks_the_cascade(self):+ # delete_node_from_dag deletes EVERY node of the query but its HasDependentsError guard only+ # inspects one arbitrary node, so a dependent living in a different DAG can slip past it and+ # have its edge cascade-deleted and its source table reverted underneath it.+ dead = self._saved_query("shared_upstream", self._table("shared_upstream"), deleted=True)+ self._node(dead, dag_name="Default") # created first, so .first() tends to pick it+ upstream_elsewhere = self._node(dead, dag_name="other_dag")++ live = self._saved_query("depends_on_it", None, deleted=False)+ dependent_node = self._node(live, dag_name="other_dag")+ Edge.objects.create(team=self.team, dag=dependent_node.dag, source=upstream_elsewhere, target=dependent_node)++ assert cascade_delete(dead) == SKIPPED_DEPENDENTS+ assert Node.objects.filter(saved_query=dead).count() == 2 # nothing deleted+ dead.refresh_from_db()+ assert dead.table_id is not None # table not reverted++ def test_one_failure_does_not_abort_the_batch(self):+ from django.core.management import call_command++ for name in ("first_view", "second_view"):+ sq = self._saved_query(name, self._table(name), deleted=True)+ self._node(sq, dag_name=f"dag_{name}")++ module = "products.data_modeling.backend.management.commands.cleanup_orphaned_matview_tables"+ with patch(f"{module}.cascade_delete", side_effect=[RuntimeError("boom"), "cleaned"]) as cascade:+ call_command("cleanup_orphaned_matview_tables", "--team-id", str(self.team.pk), "--apply")++ assert cascade.call_count == 2 # the second query still got its turn++ def test_properly_deleted_query_with_ghost_node_is_excluded(self):+ # deleted_name is set => it went through the real soft_delete(); a lingering node here is a+ # separate, much larger population this cleanup must not touch.+ sq = self._saved_query("POSTHOG_DELETED_x", None, deleted=True)+ sq.deleted_name = "old_name"+ sq.save()+ self._node(sq)+ assert self._found() == set()diff --git a/products/data_modeling/backend/test/test_tier_membership.py b/products/data_modeling/backend/test/test_tier_membership.pynew file mode 100644index 000000000000..6f79d0d34325--- /dev/null+++ b/products/data_modeling/backend/test/test_tier_membership.py@@ -0,0 +1,115 @@+import asyncio++from unittest import mock++from parameterized import parameterized+from temporalio.client import ScheduleActionStartWorkflow, ScheduleListActionStartWorkflow++from products.data_modeling.backend.logic.tier_membership import (+ CORRECTLY_UNSCHEDULED,+ OVER_SCHEDULED,+ SCHEDULED,+ SCHEDULED_WRONG_TIER,+ STALE_NEEDS_RECONCILE,+ UNSUPPORTED_TARGET,+ LiveTier,+ classify_node,+ read_live_tiers,+)+++def _tier(interval_seconds, node_ids):+ return LiveTier(+ schedule_id=f"dag:{interval_seconds}" if interval_seconds is not None else "dag",+ interval_seconds=interval_seconds,+ covers_whole_dag=node_ids is None,+ node_ids=frozenset(node_ids) if node_ids is not None else None,+ )+++class TestClassifyNode:+ @parameterized.expand(+ [+ # (live_tiers, expected_interval, expected_verdict)+ ("on the tier it should be on", [_tier(86400, {"n"})], 86400, SCHEDULED),+ ("covered by a whole-DAG schedule", [_tier(None, None)], 86400, SCHEDULED),+ ("scheduled but at the wrong cadence", [_tier(3600, {"n"})], 86400, SCHEDULED_WRONG_TIER),+ # The managed_product_lifecycle case: has a target, but no live tier lists it.+ ("has a target but no live tier covers it", [_tier(86400, {"other"})], 86400, STALE_NEEDS_RECONCILE),+ ("no tiers exist at all yet", [], 86400, STALE_NEEDS_RECONCILE),+ ("in a tier reconcile would drop", [_tier(86400, {"n"})], None, OVER_SCHEDULED),+ ("no target and no tier — the opt-out", [_tier(86400, {"other"})], None, CORRECTLY_UNSCHEDULED),+ ]+ )+ def test_verdict(self, _name, live_tiers, expected_interval, expected_verdict):+ status = classify_node(+ node_id="n",+ name="a_view",+ node_type="matview",+ dag_id="dag",+ dag_name="Default",+ live_tiers=live_tiers,+ expected_interval=expected_interval,+ )+ assert status.verdict == expected_verdict++ def test_blocked_dag_does_not_advise_a_reconcile_that_would_refuse(self):+ # reconcile raises UnsupportedFrequencyTargetError for the WHOLE DAG when a desired tier is+ # not a schedulable bucket, touching no schedule. Reporting stale_needs_reconcile there sends+ # an operator to run a reconcile that fixes nothing and takes the rest of the DAG with it.+ status = classify_node(+ node_id="n",+ name="a_view",+ node_type="matview",+ dag_id="dag",+ dag_name="Default",+ live_tiers=[],+ expected_interval=86400,+ reconcile_blocked=True,+ )+ assert status.verdict == UNSUPPORTED_TARGET+ assert status.dag_reconcile_blocked is True+++class TestReadLiveTiers:+ def _listing(self, schedule_id, workflow):+ action = mock.Mock(spec=ScheduleListActionStartWorkflow, workflow=workflow)+ return mock.Mock(id=schedule_id, schedule=mock.Mock(action=action))++ def _describe_returning(self, node_ids):+ # node_ids=None models a whole-DAG schedule (the arg dict has no node_ids key).+ payload = {"team_id": 2, "dag_id": "dag"} if node_ids is None else {"team_id": 2, "node_ids": node_ids}+ action = mock.Mock(spec=ScheduleActionStartWorkflow, args=[payload])+ described = mock.Mock(schedule=mock.Mock(action=action))+ return mock.AsyncMock(return_value=described)++ def test_reads_node_ids_and_ignores_non_execute_dag(self):+ listings = [+ self._listing("dag:86400", "data-modeling-execute-dag"),+ self._listing("dag", "data-modeling-execute-dag"), # legacy single schedule (whole DAG)+ self._listing("some-sq-id", "data-modeling-run"), # v1 — must be ignored+ ]+ describe_by_id = {+ "dag:86400": self._describe_returning(["n1", "n2"]),+ "dag": self._describe_returning(None),+ }++ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ for listing in listings:+ yield listing++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules+ temporal.get_schedule_handle = lambda sid: mock.Mock(describe=describe_by_id[sid])++ tiers = asyncio.run(read_live_tiers(temporal, "dag"))++ by_interval = {t.interval_seconds: t for t in tiers}+ assert set(by_interval) == {86400, None} # the v1 data-modeling-run schedule was skipped+ assert by_interval[86400].node_ids == frozenset({"n1", "n2"})+ assert by_interval[86400].covers_whole_dag is False+ assert by_interval[None].covers_whole_dag is True+ assert by_interval[None].node_ids is None