: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(modeling): make management commands resumable and don't undo v2 progress (#61387)
andrew j. mcgeheee48fd8b909e2
diff --git a/products/data_modeling/backend/management/commands/backfill_missing_model_paths.py b/products/data_modeling/backend/management/commands/backfill_missing_model_paths.pyindex 923eb25643ef..1274b5684c7c 100644--- a/products/data_modeling/backend/management/commands/backfill_missing_model_paths.py+++ b/products/data_modeling/backend/management/commands/backfill_missing_model_paths.py@@ -26,6 +26,12 @@ class Command(BaseCommand):type=str,help="Comma separated list of team IDs to filter by",)+ parser.add_argument(+ "--start-after-team-id",+ default=None,+ type=int,+ help="Resume after this team ID (exclusive), following the team_id ordering used by this command",+ )parser.add_argument("--batch-size",default=50,@@ -59,6 +65,9 @@ class Command(BaseCommand):raise CommandError("team-ids must be a comma separated list of team IDs")queryset = queryset.filter(team_id__in=team_ids)+ if options.get("start_after_team_id") is not None:+ queryset = queryset.filter(team_id__gt=options["start_after_team_id"])+saved_queries = list(queryset.order_by("team_id", "id"))if not saved_queries:diff --git a/products/data_modeling/backend/management/commands/create_missing_saved_query_schedules.py b/products/data_modeling/backend/management/commands/create_missing_saved_query_schedules.pyindex 9465294aed4d..d42f75c77763 100644--- a/products/data_modeling/backend/management/commands/create_missing_saved_query_schedules.py+++ b/products/data_modeling/backend/management/commands/create_missing_saved_query_schedules.py@@ -6,6 +6,7 @@ from django.core.management.base import BaseCommand, CommandErrorimport structlogfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.schedule import partition_saved_queries_by_v2_schedulefrom products.data_warehouse.backend.data_load.saved_query_service import (saved_query_workflow_exists,sync_saved_query_workflow,@@ -30,6 +31,12 @@ class Command(BaseCommand):type=str,help="Comma separated list of team IDs to filter by",)+ parser.add_argument(+ "--start-after-saved-query-id",+ default=None,+ type=str,+ help="Resume after this saved query UUID (exclusive), following the id ordering used by this command",+ )parser.add_argument("--dry-run",action="store_true",@@ -59,11 +66,22 @@ class Command(BaseCommand):raise CommandError("team-ids must be a comma separated list of team IDs")queryset = queryset.filter(team_id__in=team_ids)- saved_queries = list(queryset)+ if options.get("start_after_saved_query_id") is not None:+ queryset = queryset.filter(id__gt=options["start_after_saved_query_id"])++ saved_queries = list(queryset.order_by("id"))if len(saved_queries) == 0:raise CommandError("No materialized saved queries found matching filters")+ # Never create a v1 schedule for a saved query whose DAG already runs on v2.+ saved_queries, on_v2 = partition_saved_queries_by_v2_schedule(saved_queries)+ if on_v2:+ logger.info(f"Skipping {len(on_v2)} saved queries on DAGs already migrated to v2")+ if not saved_queries:+ logger.info("All matching saved queries are on v2 DAGs, nothing to do")+ return+logger.info(f"Found {len(saved_queries)} materialized saved queries to check")missing = []diff --git a/products/data_modeling/backend/management/commands/delete_orphaned_saved_query_schedules.py b/products/data_modeling/backend/management/commands/delete_orphaned_saved_query_schedules.pyindex 08161d101a72..c080615ec30f 100644--- a/products/data_modeling/backend/management/commands/delete_orphaned_saved_query_schedules.py+++ b/products/data_modeling/backend/management/commands/delete_orphaned_saved_query_schedules.py@@ -43,6 +43,12 @@ class Command(BaseCommand):type=str,help="Comma-separated team IDs to filter orphans by (uses search attributes if available, falls back to describe)",)+ parser.add_argument(+ "--start-after-schedule-id",+ default=None,+ type=str,+ help="Resume after this schedule ID (exclusive), following the sorted schedule ID ordering used by this command",+ )parser.add_argument("--dry-run",action="store_true",@@ -88,6 +94,10 @@ class Command(BaseCommand):# Pass team_ids to use search attribute filtering in the listing queryorphans = await self._find_orphans_from_listing(temporal, team_ids=team_ids)+ start_after_schedule_id = options.get("start_after_schedule_id")+ if start_after_schedule_id:+ orphans = {sid for sid in orphans if sid > start_after_schedule_id}+if not orphans:logger.info("No orphaned schedules found")returndiff --git a/products/data_modeling/backend/management/commands/migrate_teams_to_dag_schedules.py b/products/data_modeling/backend/management/commands/migrate_teams_to_dag_schedules.pyindex 570fd4099ba4..9523fa93eefd 100644--- a/products/data_modeling/backend/management/commands/migrate_teams_to_dag_schedules.py+++ b/products/data_modeling/backend/management/commands/migrate_teams_to_dag_schedules.py@@ -41,6 +41,12 @@ class Command(BaseCommand):type=str,help="Comma separated list of team IDs to migrate",)+ parser.add_argument(+ "--start-after-team-id",+ default=None,+ type=int,+ help="Resume after this team ID (exclusive), following the team_id ordering used by this command",+ )parser.add_argument("--dry-run",action="store_true",@@ -56,6 +62,8 @@ class Command(BaseCommand):except ValueError:raise CommandError("team_ids must be a comma separated list of team IDs")dags = dags.filter(team_id__in=team_ids)+ if options.get("start_after_team_id") is not None:+ dags = dags.filter(team_id__gt=options["start_after_team_id"])dags = dags.order_by("team_id")total = dags.count()if total == 0:diff --git a/products/data_modeling/backend/management/commands/recover_saved_query_schedules.py b/products/data_modeling/backend/management/commands/recover_saved_query_schedules.pyindex b95ffc7c4093..8bfd0e58e68c 100644--- a/products/data_modeling/backend/management/commands/recover_saved_query_schedules.py+++ b/products/data_modeling/backend/management/commands/recover_saved_query_schedules.py@@ -23,13 +23,16 @@ Usage:# Limit number of queries to those created after datepython manage.py recover_saved_query_schedules --created-after '2025-10-01'++ # Resume after a previously processed saved query (exclusive)+ python manage.py recover_saved_query_schedules --start-after-saved-query-id <uuid>"""import loggingfrom datetime import UTC, datetime, timedeltafrom typing import Any-from django.core.management.base import BaseCommand+from django.core.management.base import BaseCommand, CommandErrorfrom django.db import transactionfrom django.db.models import Count, OuterRef, Q, Subquery@@ -38,6 +41,7 @@ from posthog.temporal.common.schedule import describe_schedule, schedule_exists,from products.data_modeling.backend.models.data_modeling_job import DataModelingJobfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.schedule import partition_saved_queries_by_v2_schedulelogger = logging.getLogger(__name__)@@ -75,6 +79,12 @@ class Command(BaseCommand):default="2025-10-01",help="Only process queries created after this date (YYYY-MM-DD). Default: 2025-10-01",)+ parser.add_argument(+ "--start-after-saved-query-id",+ type=str,+ default=None,+ help="Resume after this saved query UUID (exclusive), following the (created_at, id) ordering used by this command",+ )def handle(self, *args: Any, **options: Any) -> None:dry_run = options["dry_run"]@@ -82,6 +92,7 @@ class Command(BaseCommand):managed_viewset = options["managed_viewset"]limit = options["limit"]created_after = options["created_after"]+ start_after_saved_query_id = options["start_after_saved_query_id"]self.stdout.write(f"\n{'=' * 60}")self.stdout.write(f"Saved Query Schedule Recovery - {'DRY_RUN' if dry_run else 'LIVE'}")@@ -102,11 +113,28 @@ class Command(BaseCommand):returnself.stdout.write(f"\nProcessing team_id={target_team_id}")# get queries for the target team- queries = base_qs.filter(team_id=target_team_id).order_by("created_at")+ queries = base_qs.filter(team_id=target_team_id).order_by("created_at", "id")+ if start_after_saved_query_id:+ cursor = (+ DataWarehouseSavedQuery.objects.filter(id=start_after_saved_query_id, team_id=target_team_id)+ .values("created_at")+ .first()+ )+ if cursor is None:+ raise CommandError(f"No saved query found with id={start_after_saved_query_id}")+ cursor_created_at = cursor["created_at"]+ queries = queries.filter(+ Q(created_at__gt=cursor_created_at) | Q(created_at=cursor_created_at, id__gt=start_after_saved_query_id)+ )+ self.stdout.write(f"Resuming after saved query id={start_after_saved_query_id}")if limit:queries = queries[:limit]self.stdout.write(f"Limited to {limit} queries")queries = list(queries)+ # Never revive a v1 schedule for a saved query whose DAG already runs on v2.+ queries, on_v2 = partition_saved_queries_by_v2_schedule(queries)+ if on_v2:+ self.stdout.write(self.style.WARNING(f"Skipping {len(on_v2)} queries whose DAG already runs on v2"))self.stdout.write(f"Found {len(queries)} affected queries for team_id={target_team_id}\n")if not queries:self.stdout.write(self.style.SUCCESS("No queries to process for this team."))diff --git a/products/data_modeling/backend/management/commands/resync_data_modeling_schedules.py b/products/data_modeling/backend/management/commands/resync_data_modeling_schedules.pyindex 75efba6284b5..6ad3f40d6bd6 100644--- a/products/data_modeling/backend/management/commands/resync_data_modeling_schedules.py+++ b/products/data_modeling/backend/management/commands/resync_data_modeling_schedules.py@@ -10,6 +10,7 @@ import structlogimport temporaliofrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.schedule import get_v2_saved_query_idsfrom products.data_warehouse.backend.data_load.saved_query_service import sync_saved_query_workflowlogger = structlog.get_logger(__name__)@@ -28,6 +29,12 @@ class Command(BaseCommand):type=str,help="Comma separated list of team IDs to filter by",)+ parser.add_argument(+ "--start-after-saved-query-id",+ default=None,+ type=str,+ help="Resume after this saved query UUID (exclusive), following the id ordering used by this command",+ )parser.add_argument("--all",action="store_true",@@ -62,6 +69,15 @@ class Command(BaseCommand):raise CommandError("team_ids must be a comma separated list of team IDs")queryset = queryset.filter(team_id__in=team_ids)+ if options.get("start_after_saved_query_id") is not None:+ queryset = queryset.filter(id__gt=options["start_after_saved_query_id"])++ # Never refresh a v1 schedule for a saved query whose DAG already runs on v2.+ v2_ids = get_v2_saved_query_ids(list(queryset.values_list("id", flat=True)))+ if v2_ids:+ logger.info(f"Skipping {len(v2_ids)} saved queries on DAGs already migrated to v2")+ queryset = queryset.exclude(id__in=v2_ids)+queryset = queryset.order_by("id")total = queryset.count()diff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.pyindex 25713c5a59e3..50ba5f509a7f 100644--- a/products/data_modeling/backend/schedule.py+++ b/products/data_modeling/backend/schedule.py@@ -12,9 +12,82 @@ Frequency tiers:import uuidimport hashlib+from collections.abc import Collectionfrom datetime import timedelta+from typing import TYPE_CHECKING-from temporalio.client import ScheduleCalendarSpec, ScheduleRange, ScheduleSpec+from asgiref.sync import async_to_sync+from temporalio.client import ScheduleCalendarSpec, ScheduleListActionStartWorkflow, ScheduleRange, ScheduleSpec++from posthog.temporal.common.client import async_connect++from products.data_modeling.backend.models import Node++if TYPE_CHECKING:+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery++# v2 (DAG-based) schedules run this workflow; their schedule id is the DAG id. The v1 backend+# (`data-modeling-run`, one schedule per saved query) is frozen and being migrated away from.+DATA_MODELING_EXECUTE_DAG_WORKFLOW = "data-modeling-execute-dag"+++@async_to_sync+async def get_v2_scheduled_dag_ids() -> set[str]:+ """Return the IDs of DAGs that already have a v2 `data-modeling-execute-dag` Temporal schedule.++ A DAG appearing here has been migrated off the frozen v1 backend. Callers performing v1+ schedule operations must skip these DAGs' saved queries so they never re-create or revive a+ v1 schedule for a DAG already running on v2.+ """+ temporal = await async_connect()+ dag_ids: set[str] = set()+ # Pre-filter server-side so we don't page through every v1 `data-modeling-run` schedule;+ # keep the client-side check as a safety net since visibility data is eventually consistent.+ query = f"WorkflowType = '{DATA_MODELING_EXECUTE_DAG_WORKFLOW}'"+ async for listing in await temporal.list_schedules(query=query):+ action = listing.schedule.action if listing.schedule else None+ if (+ isinstance(action, ScheduleListActionStartWorkflow)+ and action.workflow == DATA_MODELING_EXECUTE_DAG_WORKFLOW+ ):+ dag_ids.add(listing.id)+ return dag_ids+++def get_v2_saved_query_ids(candidate_ids: Collection[uuid.UUID] | None = None) -> set[uuid.UUID]:+ """Return saved query IDs whose DAG already runs on a v2 schedule.++ Optionally restrict the lookup to `candidate_ids` to keep the query bounded. These saved+ queries must be skipped by v1 schedule commands so we never undo migration progress.+ """+ v2_dag_ids = get_v2_scheduled_dag_ids()+ if not v2_dag_ids:+ return set()++ nodes = Node.objects.filter(dag_id__in=v2_dag_ids, saved_query_id__isnull=False)+ if candidate_ids is not None:+ nodes = nodes.filter(saved_query_id__in=candidate_ids)+ return set(nodes.values_list("saved_query_id", flat=True))+++def partition_saved_queries_by_v2_schedule(+ saved_queries: list["DataWarehouseSavedQuery"],+) -> tuple[list["DataWarehouseSavedQuery"], list["DataWarehouseSavedQuery"]]:+ """Split saved queries into (v1_eligible, on_v2).++ A saved query is "on v2" when any DAG it belongs to already has a `data-modeling-execute-dag`+ schedule. v1 schedule commands should skip the on_v2 list so they do not undo migration progress.+ """+ if not saved_queries:+ return [], []++ v2_ids = get_v2_saved_query_ids([sq.id for sq in saved_queries])+ if not v2_ids:+ return list(saved_queries), []++ eligible = [sq for sq in saved_queries if sq.id not in v2_ids]+ on_v2 = [sq for sq in saved_queries if sq.id in v2_ids]+ return eligible, on_v2def _deterministic_int(entity_id: uuid.UUID, salt: str) -> int:diff --git a/products/data_modeling/backend/test/test_schedule.py b/products/data_modeling/backend/test/test_schedule.pyindex df34ed83e6a8..73ec0b480a70 100644--- a/products/data_modeling/backend/test/test_schedule.py+++ b/products/data_modeling/backend/test/test_schedule.py@@ -2,9 +2,22 @@ import uuidfrom collections import Counterfrom datetime import timedelta+import pytest+from posthog.test.base import BaseTest+from unittest import mock+from temporalio.client import ScheduleCalendarSpec-from products.data_modeling.backend.schedule import _deterministic_int, build_schedule_spec+from products.data_modeling.backend.models import Node+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 NodeType+from products.data_modeling.backend.schedule import (+ _deterministic_int,+ build_schedule_spec,+ get_v2_saved_query_ids,+ partition_saved_queries_by_v2_schedule,+)class TestDeterministicInt:@@ -236,3 +249,61 @@ class TestBuildScheduleSpecEdgeCases:def test_boundary_30d_is_monthly(self):spec = build_schedule_spec(uuid.uuid4(), timedelta(days=30))assert len(spec.calendars[0].day_of_month) == 1+++class TestV2ScheduleGuard(BaseTest):+ def _saved_query_on_dag(self, name: str, dag: DAG) -> DataWarehouseSavedQuery:+ sq = DataWarehouseSavedQuery.objects.create(+ name=name,+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ )+ Node.objects.create(team=self.team, dag=dag, saved_query=sq, type=NodeType.VIEW)+ return sq++ def setUp(self):+ super().setUp()+ self.v2_dag = DAG.objects.create(team=self.team, name="v2")+ self.v1_dag = DAG.objects.create(team=self.team, name="v1")+ self.sq_on_v2 = self._saved_query_on_dag("on_v2", self.v2_dag)+ self.sq_on_v1 = self._saved_query_on_dag("on_v1", self.v1_dag)++ def test_get_v2_saved_query_ids_returns_only_migrated_dag_queries(self):+ with mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ return_value={str(self.v2_dag.id)},+ ):+ result = get_v2_saved_query_ids([self.sq_on_v2.id, self.sq_on_v1.id])+ assert result == {self.sq_on_v2.id}++ def test_get_v2_saved_query_ids_empty_when_no_v2_schedules(self):+ with mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ return_value=set(),+ ):+ result = get_v2_saved_query_ids([self.sq_on_v2.id, self.sq_on_v1.id])+ assert result == set()++ def test_partition_splits_v1_eligible_from_v2(self):+ with mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ return_value={str(self.v2_dag.id)},+ ):+ eligible, on_v2 = partition_saved_queries_by_v2_schedule([self.sq_on_v2, self.sq_on_v1])+ assert [sq.id for sq in eligible] == [self.sq_on_v1.id]+ assert [sq.id for sq in on_v2] == [self.sq_on_v2.id]++ def test_partition_keeps_all_when_no_v2_schedules(self):+ with mock.patch(+ "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",+ return_value=set(),+ ):+ eligible, on_v2 = partition_saved_queries_by_v2_schedule([self.sq_on_v2, self.sq_on_v1])+ assert {sq.id for sq in eligible} == {self.sq_on_v2.id, self.sq_on_v1.id}+ assert on_v2 == []++ def test_partition_empty_input(self):+ eligible, on_v2 = partition_saved_queries_by_v2_schedule([])+ assert eligible == []+ assert on_v2 == []