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): scope v2 schedule lookup to candidate DAGs (#65464)

Jovan Sakovic40a0158faf14
diff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.py
index ade5fd0b55a5..19061ec50991 100644
--- a/products/data_modeling/backend/schedule.py
+++ b/products/data_modeling/backend/schedule.py
@@ -20,6 +20,7 @@ from asgiref.sync import async_to_sync
from temporalio.client import ScheduleCalendarSpec, ScheduleListActionStartWorkflow, ScheduleRange, ScheduleSpec
from posthog.temporal.common.client import async_connect
+from posthog.temporal.common.search_attributes import POSTHOG_DAG_ID_KEY
from products.data_modeling.backend.models import Node
@@ -32,19 +33,32 @@ DATA_MODELING_EXECUTE_DAG_WORKFLOW = "data-modeling-execute-dag"
@async_to_sync
-async def get_v2_scheduled_dag_ids() -> set[str]:
+async def get_v2_scheduled_dag_ids(candidate_dag_ids: Collection[str] | None = None) -> 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.
+
+ 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
+ limit once the schedule fleet is large. Pass None only for genuine full-namespace sweeps.
"""
+ if candidate_dag_ids is not None and not candidate_dag_ids:
+ return set()
+
temporal = await async_connect()
+ if candidate_dag_ids is not None:
+ # Filtering on a search attribute (PostHogDagId) is supported server-side; filtering on
+ # WorkflowType is not, so we still narrow to the execute-dag workflow client-side below.
+ quoted = ", ".join(f"'{dag_id}'" for dag_id in candidate_dag_ids)
+ schedules = await temporal.list_schedules(query=f"{POSTHOG_DAG_ID_KEY.name} IN ({quoted})")
+ else:
+ schedules = await temporal.list_schedules()
+
dag_ids: set[str] = set()
- # The schedule visibility store does not support filtering on WorkflowType (it raises
- # "cannot filter on WorkflowType"), unlike workflow visibility. So we list all schedules and
- # filter client-side on the action's workflow type.
- async for listing in await temporal.list_schedules():
+ async for listing in schedules:
action = listing.schedule.action if listing.schedule else None
if (
isinstance(action, ScheduleListActionStartWorkflow)
@@ -60,13 +74,29 @@ def get_v2_saved_query_ids(candidate_ids: Collection[uuid.UUID] | None = None) -
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.
"""
+ if candidate_ids is not None:
+ if not candidate_ids:
+ return set()
+ # Resolve the candidate saved queries to their DAGs first so the Temporal lookup is scoped
+ # to just those DAGs rather than listing every schedule in the namespace.
+ dag_id_by_saved_query = {
+ saved_query_id: str(dag_id)
+ for saved_query_id, dag_id in Node.objects.filter(
+ saved_query_id__in=candidate_ids, saved_query_id__isnull=False
+ ).values_list("saved_query_id", "dag_id")
+ if dag_id is not None
+ }
+ if not dag_id_by_saved_query:
+ return set()
+
+ v2_dag_ids = get_v2_scheduled_dag_ids(set(dag_id_by_saved_query.values()))
+ return {saved_query_id for saved_query_id, dag_id in dag_id_by_saved_query.items() if dag_id in v2_dag_ids}
+
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))
diff --git a/products/data_modeling/backend/test/test_schedule.py b/products/data_modeling/backend/test/test_schedule.py
index 66d7e91a0de3..bfe57d9bd5f5 100644
--- a/products/data_modeling/backend/test/test_schedule.py
+++ b/products/data_modeling/backend/test/test_schedule.py
@@ -345,3 +345,39 @@ class TestGetV2ScheduledDagIds:
assert captured["args"] == ()
assert "query" not in captured["kwargs"]
assert result == {"dag-on-v2"}
+
+ def test_scopes_listing_by_posthog_dag_id_when_candidates_given(self):
+ captured: dict = {}
+ listings = [
+ self._listing("dag-on-v2", "data-modeling-execute-dag"),
+ self._listing("sq-on-v1", "data-modeling-run"),
+ ]
+
+ async def fake_list_schedules(*args, **kwargs):
+ captured["kwargs"] = kwargs
+
+ async def gen():
+ for listing in listings:
+ yield listing
+
+ return gen()
+
+ temporal = mock.Mock()
+ temporal.list_schedules = fake_list_schedules
+ with mock.patch(
+ "products.data_modeling.backend.schedule.async_connect",
+ new=mock.AsyncMock(return_value=temporal),
+ ):
+ result = get_v2_scheduled_dag_ids({"dag-on-v2"})
+
+ # Server-side filtering on the PostHogDagId search attribute (allowed, unlike WorkflowType)
+ # keeps us from paginating the whole namespace.
+ assert captured["kwargs"]["query"] == "PostHogDagId IN ('dag-on-v2')"
+ assert result == {"dag-on-v2"}
+
+ def test_empty_candidates_skips_temporal(self):
+ connect = mock.AsyncMock()
+ with mock.patch("products.data_modeling.backend.schedule.async_connect", new=connect):
+ result = get_v2_scheduled_dag_ids(set())
+ assert result == set()
+ connect.assert_not_called()