: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
refactor(data-modeling): share the execute-dag schedule teardown (#81270)
Jovan Sakovice1fda913a1ff
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 9d407dca899b..63bb00cfa09e 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -23,6 +23,7 @@ _LAZY = {"get_saved_query_summary": "logic.saved_query_reads","saved_query_materialized_at": "logic.saved_query_freshness","start_node_materialization": "logic.node_materialization",+ "delete_dag_schedules": "logic.schedule_reconcile","apply_saved_query_frequency_anchor": "logic.schedule_reconcile","apply_saved_query_frequency_target": "logic.schedule_reconcile","tiered_schedules_enabled": "logic.schedule_reconcile",diff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.pyindex e9f81d8d8aa9..fdf987dd8798 100644--- a/products/data_modeling/backend/logic/schedule_reconcile.py+++ b/products/data_modeling/backend/logic/schedule_reconcile.py@@ -431,6 +431,49 @@ async def list_existing_schedule_ids(dag_id: str) -> set[str]:return await _list_execute_dag_schedule_ids(temporal, dag_id)[email protected](frozen=True, kw_only=True)+class DagScheduleTeardown:+ """`ok` is False when the listing or any delete failed, so Temporal may still hold a schedule+ for this DAG. `deleted` holds the ids that are confirmed gone.+ """++ ok: bool+ deleted: tuple[str, ...]+++@async_to_sync+async def delete_dag_schedules(dag_id: str) -> DagScheduleTeardown:+ """Delete every execute-dag schedule Temporal has for a DAG, from an authoritative listing+ (PostHogDagId search attribute) rather than an id formula, so a tier, legacy or off-scheme+ schedule cannot survive its DAG. NOT_FOUND means a concurrent delete won the race.++ Callers that own the DAG row must keep it when `ok` is False: the listing is the only way back+ to these schedules once the row is gone.+ """+ try:+ temporal = await async_connect()+ schedule_ids = await _list_execute_dag_schedule_ids(temporal, dag_id)+ except Exception as error:+ logger.exception("Failed to list execute-dag schedules", dag_id=dag_id)+ capture_exception(error)+ return DagScheduleTeardown(ok=False, deleted=())++ ok = True+ deleted: list[str] = []+ for schedule_id in sorted(schedule_ids):+ try:+ await a_delete_schedule(temporal, schedule_id=schedule_id)+ except Exception as error:+ if isinstance(error, RPCError) and error.status == RPCStatusCode.NOT_FOUND:+ continue+ ok = False+ logger.exception("Failed to delete execute-dag schedule", schedule_id=schedule_id, dag_id=dag_id)+ capture_exception(error)+ continue+ deleted.append(schedule_id)+ return DagScheduleTeardown(ok=ok, deleted=tuple(deleted))++@async_to_syncasync def _apply_reconciliation(*,diff --git a/products/data_modeling/backend/management/commands/consolidate_dags.py b/products/data_modeling/backend/management/commands/consolidate_dags.pyindex 7f18af326802..a7a600c027d3 100644--- a/products/data_modeling/backend/management/commands/consolidate_dags.py+++ b/products/data_modeling/backend/management/commands/consolidate_dags.py@@ -12,12 +12,10 @@ from django.utils import timezoneimport structlogfrom temporalio.client import Client-from temporalio.service import RPCError, RPCStatusCodefrom posthog.hogql.errors import BaseHogQLErrorfrom posthog.temporal.common.client import sync_connect-from posthog.temporal.common.schedule import delete_schedulefrom products.data_modeling.backend.logic.cohort_scheduling import is_tier_schedule_idfrom products.data_modeling.backend.logic.freshness import (@@ -39,6 +37,7 @@ from products.data_modeling.backend.logic.saved_query_dag_sync import (sync_saved_query_to_dag,)from products.data_modeling.backend.logic.schedule_reconcile import (+ delete_dag_schedules,delete_v1_saved_query_schedules,list_existing_schedule_ids,null_saved_query_intervals,@@ -585,7 +584,7 @@ class Command(BaseCommand):if orphaned_drops:return f"{len(orphaned_drops)} duplicate(s) never reached the target ({', '.join(orphaned_drops)})"- if not self._teardown_execute_dag_schedules(temporal, str(plan.dag.id)):+ if not self._teardown_execute_dag_schedules(str(plan.dag.id)):return "execute-dag schedule teardown failed; DAG kept so a re-run can retry it"plan.dag.delete()@@ -642,33 +641,13 @@ class Command(BaseCommand):f"(source declared {format_cadence(declared)})")- def _teardown_execute_dag_schedules(self, temporal: Client, dag_id: str) -> bool:- """Delete the execute-dag schedules Temporal actually has for this DAG, from an- authoritative listing (PostHogDagId search attribute) rather than an id formula, so an- off-scheme schedule cannot be orphaned by the DAG's deletion. NOT_FOUND means a concurrent- delete won the race; a listing or delete failure keeps the DAG for a re-run.- """- try:- schedule_ids = list_existing_schedule_ids(dag_id)- except Exception:- logger.exception("Failed to list execute-dag schedules", dag_id=dag_id)- self.stderr.write(f" FAILED to list execute-dag schedules for DAG {dag_id}")- return False- ok = True- for schedule_id in sorted(schedule_ids):- try:- delete_schedule(temporal, schedule_id=schedule_id)- self.stdout.write(f" deleted execute-dag schedule {schedule_id}")- except RPCError as error:- if error.status != RPCStatusCode.NOT_FOUND:- ok = False- logger.exception("Failed to delete execute-dag schedule", schedule_id=schedule_id)- self.stderr.write(f" FAILED to delete execute-dag schedule {schedule_id}")- except Exception:- ok = False- logger.exception("Failed to delete execute-dag schedule", schedule_id=schedule_id)- self.stderr.write(f" FAILED to delete execute-dag schedule {schedule_id}")- return ok+ def _teardown_execute_dag_schedules(self, dag_id: str) -> bool:+ teardown = delete_dag_schedules(dag_id)+ for schedule_id in teardown.deleted:+ self.stdout.write(f" deleted execute-dag schedule {schedule_id}")+ if not teardown.ok:+ self.stderr.write(f" FAILED to tear down execute-dag schedules for DAG {dag_id}")+ return teardown.okdef _finalize_target(self, target: DAG, temporal: Client) -> set[str]:"""Converge the target after the moves: seed declared targets from leftover v1 intervals,diff --git a/products/data_modeling/backend/test/test_consolidate_dags.py b/products/data_modeling/backend/test/test_consolidate_dags.pyindex 7b02f3a38f60..eccd0b3873a4 100644--- a/products/data_modeling/backend/test/test_consolidate_dags.py+++ b/products/data_modeling/backend/test/test_consolidate_dags.py@@ -17,6 +17,7 @@ from temporalio.client import ScheduleListActionStartWorkflowfrom products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_idfrom products.data_modeling.backend.logic.node_frequency import get_declared_target, set_declared_targetfrom products.data_modeling.backend.logic.saved_query_dag_sync import sync_saved_query_to_dag+from products.data_modeling.backend.logic.schedule_reconcile import DagScheduleTeardownfrom products.data_modeling.backend.models.dag import DAG, REVENUE_ANALYTICS_DAG_NAMEfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.edge import Edge@@ -52,13 +53,11 @@ def _listing_client(schedules_by_dag):@contextmanager-def _temporal_boundary(schedules_by_dag=None, v2_delete_error=None):- v2_delete = mock.Mock()- if v2_delete_error is not None:- v2_delete.side_effect = v2_delete_error+def _temporal_boundary(schedules_by_dag=None, v2_teardown_fails=False):+ v2_delete = mock.Mock(return_value=DagScheduleTeardown(ok=not v2_teardown_fails, deleted=()))with (mock.patch(f"{COMMAND}.sync_connect"),- mock.patch(f"{COMMAND}.delete_schedule", v2_delete),+ mock.patch(f"{COMMAND}.delete_dag_schedules", v2_delete),mock.patch(f"{RECONCILE}.delete_schedule") as v1_delete,mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_listing_client(schedules_by_dag or {}))@@ -413,7 +412,7 @@ class TestConsolidateDags(BaseTest):self._node(source, moved)schedules_by_dag = {str(target.id): [str(target.id)], str(source.id): [str(source.id)]}- with _temporal_boundary(schedules_by_dag=schedules_by_dag, v2_delete_error=RuntimeError("temporal down")):+ with _temporal_boundary(schedules_by_dag=schedules_by_dag, v2_teardown_fails=True):with self.assertRaisesRegex(CommandError, "incomplete"):self._run(apply=True)diff --git a/products/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.pyindex 6f2eb687a8c8..484e242ecc49 100644--- a/products/data_modeling/backend/test/test_schedule_reconcile.py+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py@@ -4,7 +4,10 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest import mock+from django.test import SimpleTestCase+from temporalio.client import ScheduleAlreadyRunningError, ScheduleListActionStartWorkflow+from temporalio.service import RPCError, RPCStatusCodefrom posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY@@ -19,6 +22,7 @@ from products.data_modeling.backend.logic.saved_query_dag_sync import promote_dafrom products.data_modeling.backend.logic.schedule_reconcile import (apply_saved_query_frequency_anchor,convert_dag_to_tiers,+ delete_dag_schedules,maybe_reconcile_dag,reconcile_dag_schedules,)@@ -30,6 +34,7 @@ from products.data_modeling.backend.test.helpers import (no_existing_schedules,saved_query_node as _saved_query_node,table_node as _table_node,+ temporal_listing,warehouse_source_node as _warehouse_source_node,)from products.warehouse_sources.backend.facade.models import DataWarehouseTable@@ -517,3 +522,55 @@ class TestPromoteDagViewNodesToMatview(BaseTest):stranded.refresh_from_db()assert stranded.type == NodeType.MAT_VIEW+++class TestDeleteDagSchedules(SimpleTestCase):+ def _run(self, schedule_ids, *, delete=None):+ temporal = temporal_listing(schedule_ids)+ with (+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=delete or mock.AsyncMock()) as deleter,+ ):+ return delete_dag_schedules("dag-1"), deleter++ def test_deletes_every_listed_schedule_whatever_its_id_scheme(self):+ # the listing is authoritative, so a tier, a bare legacy id and an off-scheme id all go+ teardown, deleter = self._run(["dag-1:3600", "dag-1", "dag-1-legacy"])++ assert teardown.ok+ assert teardown.deleted == ("dag-1", "dag-1-legacy", "dag-1:3600")+ assert deleter.await_count == 3++ def test_already_deleted_schedule_is_not_a_failure(self):+ delete = mock.AsyncMock(side_effect=RPCError("gone", RPCStatusCode.NOT_FOUND, b""))+ teardown, _ = self._run(["dag-1:3600"], delete=delete)++ assert teardown.ok+ assert teardown.deleted == ()++ def test_listing_failure_reports_not_ok_and_deletes_nothing(self):+ # the caller keys "may I drop the DAG row?" off ok: the listing is the only way back to+ # these schedules once the row is gone+ temporal = mock.Mock()+ temporal.list_schedules = mock.AsyncMock(side_effect=RuntimeError("temporal down"))+ with (+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as deleter,+ ):+ teardown = delete_dag_schedules("dag-1")++ assert not teardown.ok+ assert teardown.deleted == ()+ deleter.assert_not_awaited()++ def test_one_failed_delete_reports_not_ok_but_still_deletes_the_others(self):+ def _fail_the_tier(_temporal, schedule_id):+ if schedule_id == "dag-1:3600":+ raise RPCError("boom", RPCStatusCode.INTERNAL, b"")++ delete = mock.AsyncMock(side_effect=_fail_the_tier)+ teardown, deleter = self._run(["dag-1:3600", "dag-1:86400"], delete=delete)++ assert not teardown.ok+ assert teardown.deleted == ("dag-1:86400",)+ assert deleter.await_count == 2