: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): delete the v1 schedule migration commands (#95128)
Jovan Sakovic6c70bf21d80f
diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.mdindex f3fe85d7df5c..f580aedc2998 100644--- a/products/customer_analytics/backend/COMPROMISES.md+++ b/products/customer_analytics/backend/COMPROMISES.md@@ -42,8 +42,6 @@ Shortcuts taken to ship the first version. Revisit when they bite.properties the workflow references — read-side usage isn't indexed, and one filtered query perview is cheap. If the added request latency bites, narrow to workflow-referenced properties ormake the step poll.-- **v2 materialization only.** v1 `run_workflow.py` is frozen and does not dispatch the sync; v1- teams get it after migrating to v2.## Account Track Rules schedulediff --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.pydeleted file mode 100644index f152dcc80bba..000000000000--- a/products/data_modeling/backend/management/commands/delete_orphaned_saved_query_schedules.py+++ /dev/null@@ -1,269 +0,0 @@-import sys-import asyncio-import logging-from uuid import UUID--from django.conf import settings-from django.core.management.base import BaseCommand, CommandError--import structlog-from asgiref.sync import sync_to_async--from posthog.temporal.common.client import async_connect-from posthog.temporal.common.schedule import a_delete_schedule-from posthog.temporal.common.search_attributes import POSTHOG_TEAM_ID_KEY--from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery--logger = structlog.get_logger(__name__)---def _get_valid_saved_query_ids(candidate_ids: set[str]) -> set[str]:- return {- str(pk)- for pk in DataWarehouseSavedQuery.objects.filter(id__in=candidate_ids)- .exclude(deleted=True)- .values_list("id", flat=True)- }---class Command(BaseCommand):- help = "Delete orphaned Temporal schedules for data modeling saved queries"-- def add_arguments(self, parser):- parser.add_argument(- "--schedule-ids",- default=None,- type=str,- help="Comma-separated schedule IDs for targeted deletion (skips listing all schedules)",- )- parser.add_argument(- "--team-ids",- default=None,- 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",- default=False,- help="Preview orphans without deleting",- )- parser.add_argument(- "--concurrency",- default=20,- type=int,- help="Max concurrent Temporal API calls (default: 20)",- )-- def handle(self, **options):- logger.setLevel(logging.INFO)- asyncio.run(self._run(options))-- async def _run(self, options):- dry_run = options["dry_run"]- concurrency = options["concurrency"]-- schedule_ids_arg = options.get("schedule_ids")- team_ids_arg = options.get("team_ids")-- team_ids: set[int] | None = None- if team_ids_arg:- try:- team_ids = {int(tid) for tid in team_ids_arg.split(",")}- except ValueError:- raise CommandError("--team-ids must be a comma-separated list of integers")-- temporal = await async_connect()-- # Step 1: Find orphans- skipped_wrong_team = 0- if schedule_ids_arg:- target_ids = {sid.strip() for sid in schedule_ids_arg.split(",") if sid.strip()}- orphans = await self._find_orphans_from_ids(target_ids)- # When using --schedule-ids with --team-ids, filter via describe fallback- if team_ids and orphans:- orphans, skipped_wrong_team = await self._filter_by_team(temporal, orphans, team_ids, concurrency)- else:- # Pass team_ids to use search attribute filtering in the listing query- orphans = 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")- return-- logger.info(f"Found {len(orphans)} orphaned schedule(s)")-- # Step 3: List orphans- for schedule_id in sorted(orphans):- logger.info("Orphaned schedule", schedule_id=schedule_id)-- if dry_run:- logger.info(f"DRY RUN: Would delete {len(orphans)} schedule(s)")- return-- # Step 4: Confirm- if not settings.TEST:- confirm = input(f"\n\tWill delete {len(orphans)} orphaned schedule(s). Proceed? (y/n) ")- if confirm.strip().lower() != "y":- logger.info("Aborting")- return-- # Step 5: Delete- deleted, failed = await self._delete_schedules(temporal, orphans, concurrency)-- logger.info(f"Done! Deleted: {deleted}, Failed: {failed}, Skipped (wrong team): {skipped_wrong_team}")-- async def _find_orphans_from_ids(self, target_ids: set[str]) -> set[str]:- """Check specific schedule IDs against Django — orphan if no valid saved query exists."""- orphans: set[str] = set()- valid_uuids: set[str] = set()-- for sid in target_ids:- if ":" in sid:- # "{dag_id}:{interval_seconds}" is a v2 cadence-tier execute-dag schedule,- # not a saved-query schedule — never sweep it as an orphan.- logger.warning("v2 cadence-tier schedule id, skipping", schedule_id=sid)- continue- try:- UUID(sid)- valid_uuids.add(sid)- except ValueError:- logger.warning("Invalid UUID, treating as orphan", schedule_id=sid)- orphans.add(sid)-- if valid_uuids:- existing = await sync_to_async(_get_valid_saved_query_ids)(valid_uuids)- for sid in valid_uuids:- if sid in existing:- logger.info("Has valid saved query, skipping", schedule_id=sid)- else:- orphans.add(sid)-- return orphans-- async def _find_orphans_from_listing(self, temporal, team_ids: set[int] | None = None) -> set[str]:- """List data-modeling-run schedules from Temporal and find orphans.-- If team_ids is provided, uses PostHogTeamId search attribute to pre-filter- schedules server-side (much faster than listing all + describe each).- """- schedule_ids: set[str] = set()- count = 0-- query = self._build_team_filter_query(team_ids) if team_ids else None- async for listing in await temporal.list_schedules(query=query):- if listing.schedule.action.workflow != "data-modeling-run":- continue- schedule_ids.add(listing.id)- count += 1- if count % 200 == 0:- sys.stderr.write(".")- sys.stderr.flush()-- if count >= 200:- sys.stderr.write("\n")-- logger.info(f"Found {len(schedule_ids)} data-modeling-run schedule(s) in Temporal")-- if not schedule_ids:- return set()-- # Batch check against Django- valid_ids = await sync_to_async(_get_valid_saved_query_ids)(schedule_ids)-- return schedule_ids - valid_ids-- @staticmethod- def _build_team_filter_query(team_ids: set[int]) -> str:- """Build a Temporal visibility query to filter schedules by PostHogTeamId."""- if len(team_ids) == 1:- return f"PostHogTeamId = {next(iter(team_ids))}"- return f"PostHogTeamId IN ({','.join(str(t) for t in sorted(team_ids))})"-- async def _filter_by_team(- self, temporal, orphans: set[str], team_ids: set[int], concurrency: int- ) -> tuple[set[str], int]:- """Filter orphans by team ID using describe() to extract team_id from payload.-- This is the fallback path used when search attributes are not available- (e.g. schedules created before search attributes were added).- """- import temporalio.converter-- from posthog.temporal.common.codec import EncryptionCodec-- codec = EncryptionCodec.from_settings(settings=settings)- payload_converter = temporalio.converter.default().payload_converter- semaphore = asyncio.Semaphore(concurrency)- results: dict[str, int | None] = {}-- async def describe_one(schedule_id: str) -> int | None:- async with semaphore:- try:- handle = temporal.get_schedule_handle(schedule_id)- desc = await handle.describe()- # Try search attributes first (fast path)- team_id_attr = desc.typed_search_attributes.get(POSTHOG_TEAM_ID_KEY)- if team_id_attr is not None:- return team_id_attr- # Fall back to decoding payload (slow path for old schedules)- raw_payloads = list(desc.schedule.action.args)- if not raw_payloads:- return None- decoded = await codec.decode(raw_payloads)- arg = payload_converter.from_payload(decoded[0])- if isinstance(arg, dict):- return arg.get("team_id")- except Exception:- logger.warning("Failed to describe schedule", schedule_id=schedule_id)- return None-- tasks = {sid: asyncio.create_task(describe_one(sid)) for sid in orphans}- for sid, task in tasks.items():- results[sid] = await task-- matched: set[str] = set()- skipped = 0- for sid, tid in results.items():- if tid is not None and tid in team_ids:- matched.add(sid)- else:- skipped += 1-- return matched, skipped-- async def _delete_schedules(self, temporal, orphans: set[str], concurrency: int) -> tuple[int, int]:- """Delete orphaned schedules with bounded concurrency."""- semaphore = asyncio.Semaphore(concurrency)- deleted = 0- failed = 0-- async def delete_one(schedule_id: str) -> bool:- async with semaphore:- try:- await a_delete_schedule(temporal, schedule_id)- logger.info("Deleted schedule", schedule_id=schedule_id)- return True- except Exception:- logger.exception("Failed to delete schedule", schedule_id=schedule_id)- return False-- tasks = [asyncio.create_task(delete_one(sid)) for sid in orphans]- for task in asyncio.as_completed(tasks):- if await task:- deleted += 1- else:- failed += 1-- return deleted, faileddiff --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.pydeleted file mode 100644index 6a30948544e3..000000000000--- a/products/data_modeling/backend/management/commands/migrate_teams_to_dag_schedules.py+++ /dev/null@@ -1,315 +0,0 @@-import time-from dataclasses import asdict-from datetime import timedelta-from itertools import groupby-from typing import cast--from django.conf import settings-from django.core.management.base import BaseCommand, CommandError-from django.db.models import QuerySet--import structlog-from temporalio.client import (- Schedule,- ScheduleActionStartWorkflow,- ScheduleOverlapPolicy,- SchedulePolicy,- ScheduleState,-)-from temporalio.common import RetryPolicy--from posthog.temporal.common.client import sync_connect-from posthog.temporal.common.schedule import create_schedule, schedule_exists-from posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputs--from products.data_modeling.backend.logic.schedule_reconcile import (- convert_dag_to_tiers,- delete_v1_saved_query_schedules,- null_saved_query_intervals,- tiered_schedules_enabled,-)-from products.data_modeling.backend.models import DAG, Node-from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-from products.data_modeling.backend.schedule import build_schedule_spec, dag_schedule_search_attributes--logger = structlog.get_logger(__name__)--BATCH_DELAY_SECONDS = 0.5---class Command(BaseCommand):- help = "Migrate teams from per-node v1 schedules to a single per-DAG v2 schedule"-- def add_arguments(self, parser):- parser.add_argument(- "--team-ids",- default=None,- 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",- default=False,- help="Only show what would be done without making changes",- )-- def handle(self, **options):- dags = DAG.objects.select_related("team")- if options.get("team_ids") is not None:- try:- team_ids = [int(tid) for tid in options["team_ids"].split(",")]- 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:- raise CommandError("No DAGs found matching filters")- logger.info(f"Found {total} DAG(s) to process")- if not options["dry_run"] and not settings.TEST:- confirm = input(f"\n\tWill migrate {total} DAGs to v2 schedules. Proceed? (y/n) ")- if confirm.strip().lower() != "y":- logger.info("Aborting")- return- migrated = 0- skipped = 0- failed = 0- processed = 0- dry_run = options["dry_run"]- # Group DAGs by team so a saved query shared across two of a team's DAGs is seeded from- # every DAG before any interval is nulled (see _migrate_team_tiered). DAGs are ordered by- # team_id, which groupby requires to keep each team's rows contiguous.- for _team_id, group in groupby(dags.iterator(), key=lambda dag: dag.team_id):- team_dags = list(group)- if tiered_schedules_enabled(team_dags[0].team):- outcomes = self._migrate_team_tiered(team_dags, dry_run=dry_run)- else:- outcomes = [self._migrate_dag_legacy(dag, dry_run=dry_run) for dag in team_dags]- for outcome in outcomes:- if outcome == "migrated":- migrated += 1- elif outcome == "skipped":- skipped += 1- else:- failed += 1- processed += 1- logger.info(f"Progress: {processed}/{total} (migrated={migrated}, skipped={skipped}, failed={failed})")- if not dry_run:- time.sleep(BATCH_DELAY_SECONDS)- if dry_run:- logger.info(f"Dry run complete. Would migrate: {migrated}, Would skip: {skipped}")- else:- logger.info(f"Done! Migrated: {migrated}, Skipped: {skipped}, Failed: {failed}")-- def _scheduled_nodes(self, dag: DAG) -> QuerySet[Node]:- """Materialized nodes in this DAG whose saved query still carries a v1 sync interval."""- return Node.objects.filter(- dag=dag,- saved_query__isnull=False,- saved_query__sync_frequency_interval__isnull=False,- saved_query__deleted=False,- ).select_related("saved_query")-- def _migrate_team_tiered(self, team_dags: list[DAG], *, dry_run: bool) -> list[str]:- """Migrate all of a team's v1 DAGs straight to per-cadence-tier v2 schedules.-- Two-phase so it stays correct when a saved query has schedulable nodes in two of the team's- DAGs: phase 1 seeds every DAG's node targets (never overwriting) while the shared- sync_frequency_interval is still intact; phase 2 sweeps the v1 schedules and nulls the- consumed intervals. Nulling per DAG mid-seed would leave the second DAG to re-seed from the- 1-day DAG default — a silent freshness regression. Mirrors reconcile_freshness_schedules.-- Idempotent by construction: seeding never overwrites an existing target, the reconcile- converges whatever schedules exist, and the v1 deletes tolerate NOT_FOUND.-- Returns one outcome ("migrated"/"skipped"/"failed") per DAG, in team_dags order.- """- outcomes: list[str] = []- seeded: list[tuple[DAG, list[Node]]] = []- # Phase 1 — seed every DAG before any interval is nulled.- for dag in team_dags:- try:- nodes = list(self._scheduled_nodes(dag))- if not nodes:- logger.info("No scheduled nodes found, skipping", dag_id=str(dag.id), team_id=dag.team_id)- outcomes.append("skipped")- continue- intervals = sorted(- {str(node.saved_query.sync_frequency_interval) for node in nodes if node.saved_query is not None}- )- if dry_run:- logger.info(- "Would migrate DAG to cadence tiers",- dag_id=str(dag.id),- dag_name=dag.name,- team_id=dag.team_id,- intervals=intervals,- scheduled_nodes=len(nodes),- )- outcomes.append("migrated")- continue- seeded_targets = convert_dag_to_tiers(dag)- logger.info(- "Migrated DAG to cadence tiers",- dag_id=str(dag.id),- team_id=dag.team_id,- seeded_targets=seeded_targets,- intervals=intervals,- )- seeded.append((dag, nodes))- outcomes.append("migrated")- except Exception:- logger.exception("Failed to migrate DAG", dag_id=str(dag.id), team_id=dag.team_id)- outcomes.append("failed")- if dry_run or not seeded:- return outcomes- # Phase 2 — every DAG is now seeded, so sweeping v1 schedules and nulling the consumed- # intervals can no longer strand another DAG's seed. Isolate the connect so a Temporal- # outage skips this team's sweep (idempotent, retried on re-run) instead of aborting the- # whole fleet run and leaving every later team unprocessed.- try:- temporal = sync_connect()- except Exception:- logger.exception(- "Failed to connect to Temporal for v1 sweep; leaving it for a re-run",- team_id=team_dags[0].team_id,- )- return outcomes- for dag, nodes in seeded:- try:- failed_schedule_ids = delete_v1_saved_query_schedules(- nodes, team_id=dag.team_id, dag_id=str(dag.id), temporal=temporal- )- # Null intervals only for queries whose v1 schedule actually went away: a failed- # delete keeps its interval so a re-run retries it.- deleted_sq_ids = [- str(node.saved_query_id)- for node in nodes- if node.saved_query_id is not None and str(node.saved_query_id) not in failed_schedule_ids- ]- cleared = null_saved_query_intervals(dag, only_saved_query_ids=deleted_sq_ids)- logger.info(- "Cleared sync_frequency_interval on saved queries",- dag_id=str(dag.id),- team_id=dag.team_id,- count=cleared,- )- except Exception:- logger.exception(- "Failed to sweep v1 schedules after tier conversion",- dag_id=str(dag.id),- team_id=dag.team_id,- )- return outcomes-- def _migrate_dag_legacy(self, dag: DAG, *, dry_run: bool) -> str:- """Migrate one DAG to a single per-DAG v2 schedule (pre-tiers path, flag off).-- Returns "migrated", "skipped", or "failed".- """- try:- return self._do_migrate_dag_legacy(dag, dry_run=dry_run)- except Exception:- logger.exception("Failed to migrate DAG", dag_id=str(dag.id), team_id=dag.team_id)- return "failed"-- def _do_migrate_dag_legacy(self, dag: DAG, *, dry_run: bool) -> str:- team = dag.team- scheduled_nodes = self._scheduled_nodes(dag)- if not scheduled_nodes.exists():- logger.info("No scheduled nodes found, skipping", dag_id=str(dag.id), team_id=team.pk)- return "skipped"- # check that all scheduled saved queries share the same sync frequency- distinct_intervals = scheduled_nodes.values_list("saved_query__sync_frequency_interval", flat=True).distinct()- intervals = list(distinct_intervals)- if len(intervals) != 1:- logger.warning(- "DAG has multiple sync frequencies, skipping",- dag_id=str(dag.id),- team_id=team.pk,- intervals=[str(i) for i in intervals],- )- return "skipped"- interval = cast(timedelta, intervals[0])- if dry_run:- logger.info(- "Would migrate DAG",- dag_id=str(dag.id),- dag_name=dag.name,- team_id=team.pk,- interval=str(interval),- scheduled_nodes=scheduled_nodes.count(),- )- return "migrated"- # create the v2 DAG schedule- temporal = sync_connect()- schedule_id = str(dag.id)- if schedule_exists(temporal, schedule_id=schedule_id):- logger.info("V2 schedule already exists, skipping creation", dag_id=str(dag.id), team_id=team.pk)- else:- inputs = ExecuteDAGInputs(- team_id=team.pk,- dag_id=str(dag.id),- node_ids=None,- duckgres_only=False,- )- spec = build_schedule_spec(- entity_id=dag.id,- interval=interval,- team_timezone=team.timezone,- )- schedule = Schedule(- action=ScheduleActionStartWorkflow(- "data-modeling-execute-dag",- asdict(inputs),- id=f"execute-dag-{dag.id}",- task_queue=str(settings.DATA_MODELING_TASK_QUEUE),- retry_policy=RetryPolicy(- initial_interval=timedelta(seconds=10),- maximum_interval=timedelta(seconds=60),- maximum_attempts=3,- non_retryable_error_types=["NondeterminismError", "CancelledError"],- ),- ),- spec=spec,- state=ScheduleState(note=f"DAG schedule for team {team.pk}"),- policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),- )- search_attributes = dag_schedule_search_attributes(- team_id=team.pk,- organization_id=str(team.organization_id),- dag_id=str(dag.id),- )- create_schedule(- temporal,- id=schedule_id,- schedule=schedule,- trigger_immediately=False,- search_attributes=search_attributes,- )- logger.info("Created v2 DAG schedule", dag_id=str(dag.id), team_id=team.pk, interval=str(interval))- # update the DAG only after schedule creation succeeded- dag.name = "Default"- dag.sync_frequency_interval = interval- dag.save(update_fields=["name", "sync_frequency_interval"])- logger.info("Renamed DAG", dag_id=str(dag.id), team_id=team.pk)- delete_v1_saved_query_schedules(scheduled_nodes, team_id=team.pk, dag_id=str(dag.id), temporal=temporal)- # null out sync_frequency_interval on migrated saved queries so v1 schedules are not re-created- migrated_sq_ids = [node.saved_query_id for node in scheduled_nodes if node.saved_query_id is not None]- DataWarehouseSavedQuery.objects.filter(id__in=migrated_sq_ids).update(sync_frequency_interval=None)- logger.info(- "Cleared sync_frequency_interval on saved queries",- dag_id=str(dag.id),- team_id=team.pk,- count=len(migrated_sq_ids),- )- return "migrated"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.pydeleted file mode 100644index 8bfd0e58e68c..000000000000--- a/products/data_modeling/backend/management/commands/recover_saved_query_schedules.py+++ /dev/null@@ -1,283 +0,0 @@-"""-Management command to recover saved query schedules affected by a production bug.--This command:-1. Finds saved queries with specific error messages and fields that indicate they were affected by INC-688 bug-2. Groups them by team_id and processes one team at a team to avoid thundering herd-3. For each query, checks if a Temporal schedule exists:- - If exists: retrieves the interval, updates sync_frequency_interval, and unpauses- - If not exists: logs for manual handling--Usage:- # Dry run for unmanaged queries (default)- python manage.py recover_saved_query_schedules --team-id 2 --dry-run-- # Dry run for managed viewset queries- python manage.py recover_saved_query_schedules --team-id 2 --managed-viewset-- # Live run- python manage.py recover_saved_query_schedules --team-id 2-- # Limit number of queries to process (for gradual recovery)- python manage.py recover_saved_query_schedules --limit 10-- # Limit number of queries to those created after date- python 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 logging-from datetime import UTC, datetime, timedelta-from typing import Any--from django.core.management.base import BaseCommand, CommandError-from django.db import transaction-from django.db.models import Count, OuterRef, Q, Subquery--from posthog.temporal.common.client import sync_connect-from posthog.temporal.common.schedule import describe_schedule, schedule_exists, unpause_schedule--from products.data_modeling.backend.models.data_modeling_job import DataModelingJob-from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-from products.data_modeling.backend.schedule import partition_saved_queries_by_v2_schedule--logger = logging.getLogger(__name__)---class Command(BaseCommand):- help = "Recover saved query schedules affected by production bug"-- def add_arguments(self, parser):- parser.add_argument(- "--team-id",- type=int,- help="Process only this team. If not provided, processes the team with most affected queries.",- )- parser.add_argument(- "--managed-viewset",- action="store_true",- default=False,- help="Process managed viewset queries instead of unmanaged queries.",- )- parser.add_argument(- "--dry-run",- action="store_true",- default=False,- help="Preview changes without making them.",- )- parser.add_argument(- "--limit",- type=int,- default=None,- help="Limit the number of queries to process (for gradual recovery).",- )- parser.add_argument(- "--created-after",- type=str,- 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"]- team_id = options["team_id"]- 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'}")- self.stdout.write(f"Query type: {'Managed Viewsets' if managed_viewset else 'Unmanaged Queries'}")- self.stdout.write(f"{'=' * 60}\n")-- # build the base queryset for affected queries- base_qs = self._get_affected_queries_queryset(managed_viewset, created_after)- # report on all affected queries grouped by team- self._report_affected_queries_by_team(base_qs)- # determine which team to process- if team_id:- target_team_id = team_id- else:- target_team_id = self._get_team_with_most_affected_queries(base_qs)- if target_team_id is None:- self.stdout.write(self.style.SUCCESS("\nNo affected queries found. Nothing to do."))- return- self.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", "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."))- return- # connect to temporal- temporal = sync_connect()- stats = {- "recovered": 0,- "no_schedule": 0,- "already_has_interval": 0,- "errors": 0,- }- for i, query in enumerate(queries, 1):- self.stdout.write(f"\n[{i}/{len(queries)}] Processing saved_query id={query.id}")- self.stdout.write(f" name: {query.name}")- self.stdout.write(f" team_id: {query.team_id}")- self.stdout.write(f" is_materialized: {query.is_materialized}")- self.stdout.write(f" table_id: {query.table_id}")- self.stdout.write(f" sync_frequency_interval: {query.sync_frequency_interval}")- latest_job_error = getattr(query, "latest_job_error", None)- self.stdout.write(f" latest_job_error: {latest_job_error[:100] if latest_job_error else None}...")- # skip if already has sync_frequency_interval set (idempotency)- if query.sync_frequency_interval is not None:- self.stdout.write(- self.style.WARNING(" -> SKIP: sync_frequency_interval already set (already recovered)")- )- stats["already_has_interval"] += 1- continue- try:- self._process_query(temporal, query, dry_run, stats)- except Exception as e:- self.stdout.write(self.style.ERROR(f" -> ERROR: {e}"))- stats["errors"] += 1- logger.exception(f"Error processing saved_query id={query.id}")- self.stdout.write(f"\n{'=' * 60}")- self.stdout.write("SUMMARY")- self.stdout.write(f"{'=' * 60}")- self.stdout.write(f"Total processed: {len(queries)}")- self.stdout.write(f"Recovered: {stats['recovered']}")- self.stdout.write(f"No schedule (needs manual handling): {stats['no_schedule']}")- self.stdout.write(f"Already had interval (skipped): {stats['already_has_interval']}")- self.stdout.write(f"Errors: {stats['errors']}")- if dry_run:- self.stdout.write(- self.style.WARNING("\nThis was a DRY RUN. No changes were made. Remove --dry-run to apply changes.")- )-- def _get_affected_queries_queryset(self, managed_viewset: bool, created_after: str):- """Build queryset for affected queries based on the bug conditions.-- Uses the error field from the latest DataModelingJob for each saved query,- which is more reliable than the saved query's latest_error field.- """- # Parse the date string to a timezone-aware datetime- created_after_dt = datetime.strptime(created_after, "%Y-%m-%d").replace(tzinfo=UTC)-- latest_job_error = (- DataModelingJob.objects.filter(saved_query=OuterRef("pk")).order_by("-created_at").values("error")[:1]- )- qs = DataWarehouseSavedQuery.objects.annotate(latest_job_error=Subquery(latest_job_error)).filter(- deleted=False,- created_at__gt=created_after_dt,- sync_frequency_interval__isnull=True, # this is a symptom of the bug- )- error_conditions = Q(latest_job_error__icontains="Query returned no results") | Q(- latest_job_error__icontains="You cannot call this from an async context"- )- qs = qs.filter(error_conditions)- if managed_viewset:- qs = qs.filter(managed_viewset_id__isnull=False)- else:- qs = qs.filter(managed_viewset_id__isnull=True)- return qs-- def _report_affected_queries_by_team(self, base_qs):- """Report affected queries grouped by team."""- team_counts = base_qs.values("team_id").annotate(count=Count("id")).order_by("-count")- self.stdout.write("Affected queries by team:")- self.stdout.write("-" * 40)- for entry in team_counts[:20]: # top 20- self.stdout.write(f" team_id={entry['team_id']}: {entry['count']} queries")- total = sum(entry["count"] for entry in team_counts)- self.stdout.write(f"\nTotal affected queries: {total}")-- def _get_team_with_most_affected_queries(self, base_qs) -> int | None:- """Return the team_id with the most affected queries."""- result = base_qs.values("team_id").annotate(count=Count("id")).order_by("-count").first()- return result["team_id"] if result else None-- def _process_query(self, temporal, query: DataWarehouseSavedQuery, dry_run: bool, stats: dict):- """Process a single saved query - check schedule and recover if possible."""- schedule_id = str(query.id)- # check if schedule exists- if not schedule_exists(temporal, schedule_id):- self.stdout.write(self.style.WARNING(" -> NO SCHEDULE EXISTS"))- self.stdout.write(" Manual handling needed:")- self.stdout.write(f" saved_query_id: {query.id}")- self.stdout.write(f" team_id: {query.team_id}")- self.stdout.write(f" name: {query.name}")- self.stdout.write(f" is_materialized: {query.is_materialized}")- self.stdout.write(f" table_id: {query.table_id}")- stats["no_schedule"] += 1- return- schedule_desc = describe_schedule(temporal, schedule_id)- # Get the interval from the schedule- if not schedule_desc.schedule.spec.intervals:- self.stdout.write(- self.style.WARNING(- " -> Schedule exists but has no intervals configured. 'Paused' is likely the correct state."- )- )- stats["no_schedule"] += 1- return- interval: timedelta = schedule_desc.schedule.spec.intervals[0].every- is_paused = schedule_desc.schedule.state.paused- self.stdout.write(" -> Schedule exists:")- self.stdout.write(f" interval: {interval}")- self.stdout.write(f" paused: {is_paused}")- if dry_run:- self.stdout.write(self.style.WARNING(" -> DRY RUN: Would update sync_frequency_interval and unpause"))- stats["recovered"] += 1- return- # update sync_frequency_interval on the saved query- with transaction.atomic():- # re-fetch with select_for_update to prevent race conditions- query_to_update = DataWarehouseSavedQuery.objects.select_for_update().get(id=query.id)- # double-check it hasn't been updated by another process- if query_to_update.sync_frequency_interval is not None:- self.stdout.write(self.style.WARNING(" -> SKIP: sync_frequency_interval was set by another process"))- stats["already_has_interval"] += 1- return- # update only the sync_frequency_interval field- query_to_update.sync_frequency_interval = interval- query_to_update.save(update_fields=["sync_frequency_interval"])- self.stdout.write(f" -> Updated sync_frequency_interval to {interval}")- # unpause the schedule if it's paused- if is_paused:- unpause_schedule(- temporal,- schedule_id=schedule_id,- note="Recovered by recover_saved_query_schedules management command",- )- self.stdout.write(self.style.SUCCESS(" -> Unpaused schedule"))- else:- self.stdout.write(" -> Schedule was not paused, no unpause needed")- stats["recovered"] += 1diff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.pyindex 47f490398911..4bbdd1310638 100644--- a/products/data_modeling/backend/schedule.py+++ b/products/data_modeling/backend/schedule.py@@ -36,12 +36,10 @@ from posthog.temporal.common.search_attributes import (from products.data_modeling.backend.logic.cohort_scheduling import dag_id_from_schedule_idfrom products.data_modeling.backend.models.dag import DAG-from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.node import Node-# v2 (DAG-based) schedules run this workflow; their schedule id is the bare DAG id, or-# "{dag_id}:{interval_seconds}" for a per-cadence-tier schedule. The v1 backend-# (`data-modeling-run`, one schedule per saved query) is frozen and being migrated away from.+# A schedule id is the bare DAG id, or "{dag_id}:{interval_seconds}" for a per-cadence-tier+# schedule, optionally followed by ":{anchor}". Parsers must handle all three shapes.DATA_MODELING_EXECUTE_DAG_WORKFLOW = "data-modeling-execute-dag"@@ -149,26 +147,6 @@ def get_v2_saved_query_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_v2--def _deterministic_int(entity_id: uuid.UUID, salt: str) -> int:"""SHA-256 based deterministic integer from entity_id + salt."""digest = hashlib.sha256(f"{entity_id}-{salt}".encode()).hexdigest()diff --git a/products/data_modeling/backend/test/test_delete_orphaned_saved_query_schedules.py b/products/data_modeling/backend/test/test_delete_orphaned_saved_query_schedules.pydeleted file mode 100644index c78b5afd60b2..000000000000--- a/products/data_modeling/backend/test/test_delete_orphaned_saved_query_schedules.py+++ /dev/null@@ -1,11 +0,0 @@-from asgiref.sync import async_to_sync--from products.data_modeling.backend.management.commands.delete_orphaned_saved_query_schedules import Command---class TestFindOrphansFromIds:- def test_tier_schedule_ids_are_never_orphans(self):- # "{dag_id}:{seconds}" is a live v2 cadence-tier schedule; treating it as an orphan- # (the non-UUID fallback) would delete active DAG scheduling on operator input- orphans = async_to_sync(Command()._find_orphans_from_ids)({"018f2a00-0000-0000-0000-000000000000:900"})- assert orphans == set()diff --git a/products/data_modeling/backend/test/test_migrate_teams_to_dag_schedules.py b/products/data_modeling/backend/test/test_migrate_teams_to_dag_schedules.pydeleted file mode 100644index 9a5fc10beb1d..000000000000--- a/products/data_modeling/backend/test/test_migrate_teams_to_dag_schedules.py+++ /dev/null@@ -1,180 +0,0 @@-from datetime import timedelta-from io import StringIO--import pytest-from posthog.test.base import BaseTest-from unittest import mock--from django.core.management import call_command--import temporalio.service--from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id-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.datawarehouse_saved_query import DataWarehouseSavedQuery-from products.data_modeling.backend.models.node import Node, NodeType-from products.data_modeling.backend.test.helpers import temporal_listing as _temporal_listing--M15 = timedelta(minutes=15)-DAY = timedelta(hours=24)--RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"-COMMAND = "products.data_modeling.backend.management.commands.migrate_teams_to_dag_schedules"---class TestMigrateTeamsToDagSchedulesTiered(BaseTest):- def _v1_dag_with_mixed_frequencies(self):- dag = DAG.objects.create(team=self.team, name="Default")- nodes = {}- for name, interval in (("fast", M15), ("slow", DAY)):- saved_query = DataWarehouseSavedQuery.objects.create(- name=name,- team=self.team,- query={"query": "SELECT 1", "kind": "HogQLQuery"},- sync_frequency_interval=interval,- )- nodes[name] = Node.objects.create(team=self.team, dag=dag, saved_query=saved_query, type=NodeType.VIEW)- return dag, nodes-- def _run(self, existing_schedule_ids, delete_side_effect=None):- create = mock.AsyncMock()- update = mock.AsyncMock()- v1_delete = mock.Mock(side_effect=delete_side_effect)- with (- mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=True),- mock.patch(f"{COMMAND}.sync_connect", return_value=mock.Mock()),- mock.patch(f"{RECONCILE}.delete_schedule", v1_delete),- mock.patch(- f"{RECONCILE}.async_connect",- new=mock.AsyncMock(return_value=_temporal_listing(existing_schedule_ids)),- ),- mock.patch(f"{RECONCILE}.a_create_schedule", create),- mock.patch(f"{RECONCILE}.a_update_schedule", update),- mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),- ):- call_command("migrate_teams_to_dag_schedules", "--team-ids", str(self.team.pk), stdout=StringIO())- return create, update, v1_delete-- def test_mixed_frequencies_migrate_to_separate_tiers(self):- # the single-schedule migration refused mixed-frequency DAGs entirely; tiers are the point- dag, nodes = self._v1_dag_with_mixed_frequencies()-- create, _update, v1_delete = self._run(existing_schedule_ids=[])-- created_ids = {call.kwargs["id"] for call in create.call_args_list}- self.assertEqual(created_ids, {tier_schedule_id(str(dag.id), M15), tier_schedule_id(str(dag.id), DAY)})- self.assertEqual(v1_delete.call_count, 2)-- # targets persisted from the v1 intervals; intervals nulled once consumed- for name, interval in (("fast", M15), ("slow", DAY)):- node = nodes[name]- node.refresh_from_db()- self.assertEqual(get_declared_target(node), interval)- assert node.saved_query is not None- node.saved_query.refresh_from_db()- self.assertIsNone(node.saved_query.sync_frequency_interval)-- def test_rerun_converges_instead_of_no_opping(self):- # the old command's cleanup was nested in the schedule-creation branch, so re-runs on- # half-migrated DAGs did nothing forever- dag, nodes = self._v1_dag_with_mixed_frequencies()- tier_ids = [tier_schedule_id(str(dag.id), M15), tier_schedule_id(str(dag.id), DAY)]- not_found = temporalio.service.RPCError("not found", temporalio.service.RPCStatusCode.NOT_FOUND, b"")-- create, update, v1_delete = self._run(existing_schedule_ids=tier_ids, delete_side_effect=not_found)-- create.assert_not_called()- self.assertEqual({call.kwargs["id"] for call in update.call_args_list}, set(tier_ids))- self.assertEqual(v1_delete.call_count, 2)- for node in nodes.values():- assert node.saved_query is not None- node.saved_query.refresh_from_db()- self.assertIsNone(node.saved_query.sync_frequency_interval)-- def test_transient_v1_delete_failure_keeps_interval_for_retry(self):- # a transient (non-NOT_FOUND) delete failure must keep that query's interval so a re-run- # retries, instead of orphaning a v1 schedule beside the tiers- dag, nodes = self._v1_dag_with_mixed_frequencies()- assert nodes["fast"].saved_query is not None- failed_id = str(nodes["fast"].saved_query.id)- transient = temporalio.service.RPCError("boom", temporalio.service.RPCStatusCode.UNAVAILABLE, b"")-- def delete(_temporal, *, schedule_id):- if schedule_id == failed_id:- raise transient-- self._run(existing_schedule_ids=[], delete_side_effect=delete)-- for name in ("fast", "slow"):- assert nodes[name].saved_query is not None- nodes[name].saved_query.refresh_from_db()- # failed delete keeps its interval (retryable); the successful one is cleared- self.assertEqual(nodes["fast"].saved_query.sync_frequency_interval, M15)- self.assertIsNone(nodes["slow"].saved_query.sync_frequency_interval)-- def test_query_in_two_dags_keeps_its_own_interval(self):- # a saved query with nodes in two of the team's DAGs must seed both from its own interval;- # nulling the shared interval per DAG mid-migration would leave the second node to re-seed- # from the DAG's 1-day default — a silent freshness regression- shared = DataWarehouseSavedQuery.objects.create(- name="shared",- team=self.team,- query={"query": "SELECT 1", "kind": "HogQLQuery"},- sync_frequency_interval=M15,- )- dag_a = DAG.objects.create(team=self.team, name="A", sync_frequency_interval=DAY)- dag_b = DAG.objects.create(team=self.team, name="B", sync_frequency_interval=DAY)- node_a = Node.objects.create(team=self.team, dag=dag_a, saved_query=shared, type=NodeType.VIEW)- node_b = Node.objects.create(team=self.team, dag=dag_b, saved_query=shared, type=NodeType.VIEW)-- self._run(existing_schedule_ids=[])-- node_a.refresh_from_db()- node_b.refresh_from_db()- self.assertEqual(get_declared_target(node_a), M15)- self.assertEqual(get_declared_target(node_b), M15)- shared.refresh_from_db()- self.assertIsNone(shared.sync_frequency_interval)-- def test_temporal_outage_in_sweep_does_not_abort_the_run(self):- # a connect failure during phase 2 must skip this team's v1 sweep (idempotent on re-run),- # not propagate out and abort the whole fleet run before later teams are processed- dag, nodes = self._v1_dag_with_mixed_frequencies()-- with (- mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=True),- mock.patch(f"{COMMAND}.sync_connect", side_effect=RuntimeError("temporal down")),- mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_temporal_listing([]))),- mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()),- mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()),- mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),- ):- # completes without raising — the outage is swallowed per team- call_command("migrate_teams_to_dag_schedules", "--team-ids", str(self.team.pk), stdout=StringIO())-- # phase 1 still seeded the targets; phase 2 was skipped, so intervals stay for the re-run- for name, interval in (("fast", M15), ("slow", DAY)):- node = nodes[name]- node.refresh_from_db()- self.assertEqual(get_declared_target(node), interval)- assert node.saved_query is not None- node.saved_query.refresh_from_db()- self.assertEqual(node.saved_query.sync_frequency_interval, interval)-- def test_flag_off_keeps_single_schedule_migration(self):- dag, _nodes = self._v1_dag_with_mixed_frequencies()-- with (- mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=False),- mock.patch(f"{COMMAND}.sync_connect", return_value=mock.Mock()),- mock.patch(f"{COMMAND}.schedule_exists", return_value=False),- mock.patch(f"{COMMAND}.create_schedule") as create,- mock.patch(f"{RECONCILE}.delete_schedule"),- ):- call_command("migrate_teams_to_dag_schedules", "--team-ids", str(self.team.pk), stdout=StringIO())-- # mixed frequencies are still refused on the legacy path — no schedule created- create.assert_not_called()- self.assertTrue(DAG.objects.filter(id=dag.id).exists())diff --git a/products/data_modeling/backend/test/test_schedule.py b/products/data_modeling/backend/test/test_schedule.pyindex 32bf55190847..e6dd438d10a4 100644--- a/products/data_modeling/backend/test/test_schedule.py+++ b/products/data_modeling/backend/test/test_schedule.py@@ -18,7 +18,6 @@ from products.data_modeling.backend.schedule import (build_schedule_spec,get_v2_saved_query_ids,get_v2_scheduled_dag_ids,- partition_saved_queries_by_v2_schedule,)@@ -330,29 +329,6 @@ class TestV2ScheduleGuard(BaseTest):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 == []-def _saved_query(self, name: str) -> DataWarehouseSavedQuery:return DataWarehouseSavedQuery.objects.create(name=name,diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.mdindex b42f6e3a29e9..d497dd4d2e60 100644--- a/products/managed_warehouse/backend/README.md+++ b/products/managed_warehouse/backend/README.md@@ -176,10 +176,10 @@ Follow these checklists to exercise the DuckLake copy workflows on a local checkRun `hogli start` (or `bin/start`) so Postgres, SeaweedFS, Temporal, and all DuckLake defaults are up. Make sure the `ducklake-data-modeling-copy-workflow` feature flag is enabled for the team you plan to use.2. **Trigger a model materialization from the app**- In the PostHog UI, open Data Warehouse → Views, pick (or create) a view, open the Materialization section, enable it if needed, and click **Sync now**. This schedules the `data-modeling-run` workflow for that team/view.+ In the PostHog UI, open Data Warehouse → Views, pick (or create) a view, open the Materialization section, enable it if needed, and click **Sync now**. This starts a `data-modeling-materialize-view` workflow for that view's DAG node.3. **Observe the data-modeling workflow**- Visit the Temporal UI at `http://localhost:8081/namespaces/default/workflows` and confirm a `data-modeling-run` execution appears. Wait for it to finish successfully.+ Visit the Temporal UI at `http://localhost:8081/namespaces/default/workflows` and confirm a `materialize-view-{node_id}` execution appears. Wait for it to finish successfully.4. **Verify the DuckLake copy workflow runs**Once the modeling workflow completes it automatically starts `ducklake-copy.data-modeling` as a child run. You should see it listed in the same Temporal UI; wait for the run to complete.