Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(data-modeling): bootstrap dags that hold only a bare schedule (#102334)

Jovan Sakovic052583db6bbd
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.py
index e404464305b3..38e669477c49 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py
@@ -273,11 +273,11 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
node: Node | None = None
try:
- # If this query's DAG already runs on a v2 schedule, that schedule materializes it. Never
- # create or revive a per-query v1 schedule. This Temporal lookup stays inside the try so
- # that, if it fails, we honor the failure contract below rather than leaving
- # is_materialized=True with no schedule backing it.
- on_v2 = self.id in get_v2_saved_query_ids([self.id], team_id=self.team_id)
+ # If this query's DAG runs on cadence tiers, those tiers materialize it. A bare whole-DAG
+ # schedule does not count: reconcile refuses to add tiers beside one, so bootstrap sweeps it.
+ # This Temporal lookup stays inside the try so that, if it fails, we honor the failure
+ # contract below rather than leaving is_materialized=True with no schedule backing it.
+ on_v2 = self.id in get_v2_saved_query_ids([self.id], team_id=self.team_id, tiered_only=True)
node = (
Node.objects.filter(team_id=self.team_id, saved_query_id=self.id)
.select_related("dag", "dag__team")
@@ -285,7 +285,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
)
dag_to_bootstrap = None
if not on_v2:
- # Nothing creates a DAG's first schedule outside the migration commands, so a
+ # Nothing creates a DAG's first tier outside the migration commands, so a
# brand-new team has nothing to materialize it. Bootstrap it onto tiers instead.
if node is not None and node.dag is not None:
dag_to_bootstrap = node.dag
diff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.py
index 4bbdd1310638..48abfdacbbc6 100644
--- a/products/data_modeling/backend/schedule.py
+++ b/products/data_modeling/backend/schedule.py
@@ -34,7 +34,7 @@ from posthog.temporal.common.search_attributes import (
POSTHOG_TEAM_ID_KEY,
)
-from products.data_modeling.backend.logic.cohort_scheduling import dag_id_from_schedule_id
+from products.data_modeling.backend.logic.cohort_scheduling import dag_id_from_schedule_id, is_tier_schedule_id
from products.data_modeling.backend.models.dag import DAG
from products.data_modeling.backend.models.node import Node
@@ -55,13 +55,20 @@ def dag_schedule_search_attributes(*, team_id: int, organization_id: str, dag_id
@async_to_sync
-async def get_v2_scheduled_dag_ids(candidate_dag_ids: Collection[str] | None = None) -> set[str]:
+async def get_v2_scheduled_dag_ids(
+ candidate_dag_ids: Collection[str] | None = None, *, tiered_only: bool = False
+) -> 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.
+ `tiered_only` counts only cadence-tier schedules (`{dag_id}:{seconds}`), ignoring the bare
+ whole-DAG `{dag_id}` schedule the legacy migration left behind. A bare schedule fires the DAG
+ but honours no frequency target, so a caller about to apply one must treat such a DAG as not
+ yet on tiers and bootstrap it instead.
+
When `candidate_dag_ids` is given, the listing is scoped server-side to those DAGs via the
`PostHogDagId` search attribute so we never paginate every schedule in the namespace — a
single unscoped listing per saved-query operation is enough to exhaust the namespace rate
@@ -88,16 +95,19 @@ async def get_v2_scheduled_dag_ids(candidate_dag_ids: Collection[str] | None = N
if (
isinstance(action, ScheduleListActionStartWorkflow)
and action.workflow == DATA_MODELING_EXECUTE_DAG_WORKFLOW
+ and (not tiered_only or is_tier_schedule_id(listing.id))
):
dag_ids.add(dag_id_from_schedule_id(listing.id))
return dag_ids
def get_v2_saved_query_ids(
- candidate_ids: Collection[uuid.UUID] | None = None, *, team_id: int | None = None
+ candidate_ids: Collection[uuid.UUID] | None = None, *, team_id: int | None = None, tiered_only: bool = False
) -> set[uuid.UUID]:
"""Return saved query IDs whose DAG already runs on a v2 schedule.
+ `tiered_only` narrows "on v2" to DAGs with a cadence tier, as on `get_v2_scheduled_dag_ids`.
+
A saved query counts as on v2 when any DAG it belongs to has a v2 schedule, because it can sit
in several DAGs and one v1-scheduled placement does not make a v1 schedule safe to mint.
@@ -136,10 +146,12 @@ def get_v2_saved_query_ids(
if not dag_ids_by_saved_query:
return set()
- v2_dag_ids = get_v2_scheduled_dag_ids({dag_id for ids in dag_ids_by_saved_query.values() for dag_id in ids})
+ v2_dag_ids = get_v2_scheduled_dag_ids(
+ {dag_id for ids in dag_ids_by_saved_query.values() for dag_id in ids}, tiered_only=tiered_only
+ )
return {saved_query_id for saved_query_id, ids in dag_ids_by_saved_query.items() if ids & v2_dag_ids}
- v2_dag_ids = get_v2_scheduled_dag_ids()
+ v2_dag_ids = get_v2_scheduled_dag_ids(tiered_only=tiered_only)
if not v2_dag_ids:
return set()
diff --git a/products/data_modeling/backend/test/test_schedule_materialization.py b/products/data_modeling/backend/test/test_schedule_materialization.py
index 26173e07e80c..071154349341 100644
--- a/products/data_modeling/backend/test/test_schedule_materialization.py
+++ b/products/data_modeling/backend/test/test_schedule_materialization.py
@@ -12,6 +12,7 @@ from products.data_modeling.backend.models.datawarehouse_saved_query import (
NoSchedulableDagError,
)
from products.data_modeling.backend.models.node import NodeType
+from products.data_modeling.backend.test.helpers import temporal_listing
MODEL = "products.data_modeling.backend.models.datawarehouse_saved_query"
GET_V2_DAG_IDS = "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids"
@@ -121,6 +122,32 @@ class TestScheduleMaterializationV2Guard(BaseTest):
self.sq.refresh_from_db()
assert self.sq.sync_frequency_interval is None
+ def test_dag_with_only_a_bare_legacy_schedule_is_moved_onto_tiers(self):
+ # the retired migrate command left bare `{dag_id}` schedules behind on live DAGs
+ node = Node.objects.get(saved_query=self.sq)
+ self.sq.is_materialized = True
+ self.sq.save(update_fields=["is_materialized"])
+ bare = temporal_listing([str(self.dag.id)])
+ with (
+ mock.patch("products.data_modeling.backend.schedule.async_connect", new=mock.AsyncMock(return_value=bare)),
+ mock.patch(f"{RECONCILE}.sync_connect"),
+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=bare)),
+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,
+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ self.sq.schedule_materialization()
+
+ create.assert_called_once()
+ assert is_tier_schedule_id(create.call_args.kwargs["id"])
+ delete.assert_called_once()
+ assert delete.call_args.kwargs["schedule_id"] == str(self.dag.id)
+ node.refresh_from_db()
+ assert get_declared_target(node) == timedelta(hours=12)
+ self.sq.refresh_from_db()
+ assert self.sq.sync_frequency_interval is None
+ assert self.sq.is_materialized
+
def test_failed_bootstrap_retracts_the_materialized_claim(self):
# the reconcile runs after the caller's transaction commits, so a failure has no caller
# left to raise into: leaving is_materialized set would report a schedule that was
diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.py
index 7b3dad272a23..cd078f3df34b 100644
--- a/products/endpoints/backend/tests/test_endpoint.py
+++ b/products/endpoints/backend/tests/test_endpoint.py
@@ -1299,7 +1299,7 @@ class TestMaterializationPreview(ClickhouseTestMixin, APIBaseTest):
}
v2_dag_ids_patcher = mock.patch(
"products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",
- side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),
+ side_effect=lambda candidate_dag_ids=None, **_kwargs: set(candidate_dag_ids or []),
)
v2_dag_ids_patcher.start()
self.addCleanup(v2_dag_ids_patcher.stop)
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index 32b497437056..7bd3c765ffaf 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -75,7 +75,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
self.v2_dag_ids_patcher = mock.patch(
"products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",
- side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),
+ side_effect=lambda candidate_dag_ids=None, **_kwargs: set(candidate_dag_ids or []),
)
self.v2_dag_ids_patcher.start()
diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.py
index 184f93944034..2ca398610255 100644
--- a/products/endpoints/backend/tests/test_endpoint_materialization.py
+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py
@@ -54,7 +54,7 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
# The DAG node exists by scheduling time, so the v2 lookup would hit Temporal for real.
self.v2_dag_ids_patcher = mock.patch(
"products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",
- side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),
+ side_effect=lambda candidate_dag_ids=None, **_kwargs: set(candidate_dag_ids or []),
)
self.mock_v2_dag_ids = self.v2_dag_ids_patcher.start()
diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.py
index 3cadc949b106..0b455d46c676 100644
--- a/products/endpoints/backend/tests/test_insight_response_parity.py
+++ b/products/endpoints/backend/tests/test_insight_response_parity.py
@@ -52,7 +52,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
self.v2_dag_ids_patcher = mock.patch(
"products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",
- side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),
+ side_effect=lambda candidate_dag_ids=None, **_kwargs: set(candidate_dag_ids or []),
)
self.v2_dag_ids_patcher.start()