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.

chore(data-modeling): drop the bare whole-dag schedule guards (#118802)

Thiago Salvatoref0756650483d
diff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.py
index 77d001217be0..d1e91811f312 100644
--- a/products/data_modeling/backend/logic/schedule_reconcile.py
+++ b/products/data_modeling/backend/logic/schedule_reconcile.py
@@ -44,7 +44,6 @@ from products.data_modeling.backend.logic.cohort_scheduling import (
ScheduleReconcilePlan,
Tier,
bucket_into_cadence_tiers,
- is_tier_schedule_id,
plan_schedule_reconciliation,
tier_schedule_id,
)
@@ -82,13 +81,10 @@ logger = structlog.get_logger(__name__)
def maybe_reconcile_dag(dag: DAG) -> None:
- """Trigger hook for graph/target mutations: reconcile an already-tiered DAG, best-effort.
+ """Trigger hook for graph/target mutations: reconcile the DAG, best-effort.
Runs after commit so the reconcile reads the mutated graph, and never raises past the
- commit — the user's write already succeeded. Only DAGs already converted to cadence
- tiers are touched: `require_tiered` below leaves legacy single-schedule DAGs to the
- reconcile_freshness_schedules command, so a stray mutation cannot unschedule an
- unseeded DAG.
+ commit — the user's write already succeeded.
"""
transaction.on_commit(lambda: _reconcile_dag_best_effort(dag))
@@ -97,7 +93,7 @@ def _reconcile_dag_best_effort(dag: DAG) -> None:
try:
graph = build_frequency_graph(dag)
_warn_on_invalid_targets(dag, graph)
- reconcile_dag_schedules(dag, require_tiered=True, graph=graph)
+ reconcile_dag_schedules(dag, graph=graph)
except Exception as error:
logger.exception("Freshness schedule reconcile failed", dag_id=str(dag.id), team_id=dag.team_id)
capture_exception(error)
@@ -111,10 +107,6 @@ def bootstrap_dag_to_tiers(dag: DAG, *, requested_by: "DataWarehouseSavedQuery |
said the DAG has no `execute-dag` schedule, and only after whatever frequency validation the
caller does, never before.
- Reconciles without `require_tiered`, because this is the pass that creates the DAG's first
- tier schedules: `maybe_reconcile_dag` cannot stand in for it, since it declines a DAG that
- has no tier schedule yet.
-
`requested_by` is the saved query whose enable triggered this, and is marked not materialized
if the reconcile fails.
"""
@@ -258,18 +250,11 @@ def apply_saved_query_frequency_anchor(
return written
-def reconcile_dag_schedules(dag: DAG, *, require_tiered: bool = False, graph: FrequencyGraph | None = None) -> bool:
+def reconcile_dag_schedules(dag: DAG, *, graph: FrequencyGraph | None = None) -> None:
"""Make Temporal's schedules for this DAG match its nodes' effective cadences.
- Converging a covered DAG to zero schedules is refused only while it still has just legacy
- (non-tier) schedules AND schedulable nodes — an empty tier set there almost always means
- unseeded targets. A DAG with no schedulable nodes has nothing to seed, so its legacy schedule
- is swept rather than left firing no-op runs. Once tier schedules exist, an empty tier set is a
- deliberate wind-down (last target reverted/cleared) and those tiers are torn down. With
- `require_tiered`, a DAG that has no tiered schedule yet (legacy single schedule or nothing) is
- left untouched.
-
- Returns whether a reconcile was applied; False means a guard skipped it.
+ An empty tier set is a deliberate wind-down (last target reverted/cleared), so the DAG's
+ schedules are torn down.
"""
team = dag.team
if graph is None:
@@ -279,14 +264,12 @@ def reconcile_dag_schedules(dag: DAG, *, require_tiered: bool = False, graph: Fr
)
effective, _clamped = clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)
desired_tiers = bucket_into_cadence_tiers(effective, graph.declared_anchors)
- return _apply_reconciliation(
+ _apply_reconciliation(
dag_id=str(dag.id),
team_id=team.pk,
organization_id=str(team.organization_id),
team_timezone=team.timezone,
desired_tiers=desired_tiers,
- require_tiered=require_tiered,
- has_schedulable_nodes=bool(graph.nodes),
)
@@ -429,9 +412,7 @@ async def _apply_reconciliation(
organization_id: str,
team_timezone: str,
desired_tiers: dict[Tier, set[str]],
- require_tiered: bool = False,
- has_schedulable_nodes: bool = True,
-) -> bool:
+) -> None:
unsupported = sorted({tier.interval for tier in desired_tiers if tier.interval not in SCHEDULABLE_BUCKETS})
if unsupported:
tiers = ", ".join(format_cadence(interval) for interval in unsupported)
@@ -441,31 +422,6 @@ async def _apply_reconciliation(
temporal = await async_connect()
existing_ids = await _list_execute_dag_schedule_ids(temporal, dag_id)
- # `require_tiered` protects a DAG that still holds legacy (non-tier) schedules: tiering only
- # the seeded nodes would delete the whole-DAG schedule and leave the unseeded ones with no
- # scheduler. A DAG holding no schedule at all carries no such risk and has no scheduler to
- # lose, so it reconciles: that is a DAG whose views were all paused and one re-enabled.
- if require_tiered and existing_ids and not any(is_tier_schedule_id(schedule_id) for schedule_id in existing_ids):
- logger.debug("DAG not converted to cadence tiers yet, skipping reconcile", dag_id=dag_id)
- return False
- # An empty tier set on a DAG that still has only legacy (non-tier) schedules means an unseeded
- # conversion — protect it, but only when there is anything to seed: a DAG with no schedulable
- # nodes gets its legacy schedule swept instead of firing no-op runs forever. Once tier
- # schedules exist, empty desired is a deliberate wind-down (last target reverted/cleared/
- # "never"), so let the teardown sweep the stale tiers instead of leaving them firing
- # execute-dag on node_ids that no longer materialize.
- if (
- not desired_tiers
- and has_schedulable_nodes
- and existing_ids
- and not any(is_tier_schedule_id(schedule_id) for schedule_id in existing_ids)
- ):
- logger.warning(
- "Refusing to unschedule an unseeded DAG with only legacy schedules",
- dag_id=dag_id,
- existing_schedule_ids=sorted(existing_ids),
- )
- return False
plan = plan_schedule_reconciliation(dag_id, desired_tiers, existing_ids)
# Includes the schedule-type tag: get_v2_scheduled_dag_ids' unscoped sweep filters on
@@ -509,7 +465,6 @@ async def _apply_reconciliation(
except Exception as error:
logger.exception("Failed to delete stale schedule", schedule_id=schedule_id, dag_id=dag_id)
capture_exception(error)
- return True
async def _list_execute_dag_schedule_ids(temporal: Client, dag_id: str) -> set[str]:
diff --git a/products/data_modeling/backend/management/commands/set_schedule_anchor.py b/products/data_modeling/backend/management/commands/set_schedule_anchor.py
index 94a8696862d1..5bc325180fe8 100644
--- a/products/data_modeling/backend/management/commands/set_schedule_anchor.py
+++ b/products/data_modeling/backend/management/commands/set_schedule_anchor.py
@@ -151,15 +151,8 @@ class Command(BaseCommand):
):
set_declared_anchor(node, anchor)
written += 1
- # require_tiered makes reconcile skip an unconverted DAG; saying "reconciled" there
- # would tell the operator a pin took effect when it didn't
- if reconcile_dag_schedules(dag, require_tiered=True):
- self.stdout.write(f"DAG {dag.name} ({dag.id}): {past} {written} node(s), reconciled → {tier_line}")
- else:
- self.stdout.write(
- f"DAG {dag.name} ({dag.id}): {past} {written} node(s), but the DAG is not on cadence-tier "
- "schedules yet; anchors apply once it is converted (reconcile_freshness_schedules)"
- )
+ reconcile_dag_schedules(dag)
+ self.stdout.write(f"DAG {dag.name} ({dag.id}): {past} {written} node(s), reconciled → {tier_line}")
def _parse_anchor(self, at: str, on: str | None) -> int:
try:
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.py
index 88678d22587a..36c8f98985b3 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py
@@ -326,11 +326,10 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
node: Node | None = None
try:
- # 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.
+ # If this query's DAG runs on cadence tiers, those tiers materialize 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], tiered_only=True)
+ on_v2 = self.id in get_v2_saved_query_ids([self.id])
node = (
Node.objects.filter(team_id=self.team_id, saved_query_id=self.id)
.select_related("dag", "dag__team")
diff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.py
index 240603a7e4c3..384eb8d2afa7 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, is_tier_schedule_id
+from products.data_modeling.backend.logic.cohort_scheduling import dag_id_from_schedule_id
from products.data_modeling.backend.models.node import Node
# A schedule id is the bare DAG id, or "{dag_id}:{interval_seconds}" for a per-cadence-tier
@@ -55,15 +55,10 @@ 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, *, tiered_only: bool = False
+ 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.
- `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
@@ -90,19 +85,16 @@ async def get_v2_scheduled_dag_ids(
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, *, tiered_only: bool = False
+ candidate_ids: Collection[uuid.UUID] | None = None,
) -> 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`.
-
Optionally restrict the lookup to `candidate_ids` to keep the query bounded.
"""
if candidate_ids is not None:
@@ -120,12 +112,10 @@ 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}, tiered_only=tiered_only
- )
+ v2_dag_ids = get_v2_scheduled_dag_ids({dag_id for ids in dag_ids_by_saved_query.values() for dag_id in ids})
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(tiered_only=tiered_only)
+ v2_dag_ids = get_v2_scheduled_dag_ids()
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 1a2dd15e0bd7..78d1210d8dca 100644
--- a/products/data_modeling/backend/test/test_schedule_materialization.py
+++ b/products/data_modeling/backend/test/test_schedule_materialization.py
@@ -12,7 +12,6 @@ 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"
@@ -119,31 +118,6 @@ 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}.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/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.py
index 0a74f97a0819..a55da8b02fcd 100644
--- a/products/data_modeling/backend/test/test_schedule_reconcile.py
+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py
@@ -238,38 +238,7 @@ class TestReconcileDagSchedules(BaseTest):
delete.assert_called_once_with(temporal, schedule_id=created_ids[0])
self.assertNotEqual(created_ids[0], legacy_id)
- def test_refuses_to_unschedule_covered_dag_without_targets(self):
- # a covered DAG with no targets means unseeded conversion, not a wind-down —
- # converging to zero schedules would silently stop all materialization
- dag = DAG.get_or_create_default(self.team)
- source = _table_node(self.team, dag, "events", {"origin": "posthog"})
- endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)
- Edge.objects.create(team=self.team, dag=dag, source=source, target=endpoint)
-
- legacy_id = str(dag.id)
-
- async def fake_list_schedules(*_args, **_kwargs):
- async def gen():
- yield _listing(legacy_id)
-
- return gen()
-
- temporal = mock.Mock()
- temporal.list_schedules = fake_list_schedules
-
- with (
- mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),
- mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,
- mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,
- ):
- reconcile_dag_schedules(dag)
-
- create.assert_not_called()
- delete.assert_not_called()
-
def test_sweeps_legacy_schedule_when_dag_has_no_schedulable_nodes(self):
- # a DAG holding only source tables has nothing to seed, so the unseeded-conversion
- # guard must not apply: its legacy schedule just fires no-op execute-dag runs forever
dag = DAG.get_or_create_default(self.team)
_table_node(self.team, dag, "events", {"origin": "posthog"})
@@ -427,24 +396,6 @@ class TestMaybeReconcileDag(BaseTest):
temporal.list_schedules = fake_list_schedules
return temporal
- def test_untiered_dag_is_left_alone(self):
- # a legacy single-schedule DAG converts only via the conversion command: tiering the
- # seeded nodes here would delete the whole-DAG schedule the unseeded ones still ride
- dag = self._dag_with_target()
- with (
- mock.patch(
- f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=self._temporal_listing([str(dag.id)]))
- ),
- mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,
- mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()) as update,
- mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,
- ):
- with self.captureOnCommitCallbacks(execute=True):
- maybe_reconcile_dag(dag)
- create.assert_not_called()
- update.assert_not_called()
- delete.assert_not_called()
-
def test_dag_with_no_schedule_regains_a_tier(self):
dag = self._dag_with_target()
with (
diff --git a/products/data_modeling/backend/test/test_set_schedule_anchor.py b/products/data_modeling/backend/test/test_set_schedule_anchor.py
index 0195aa5d10a2..a94993d55c09 100644
--- a/products/data_modeling/backend/test/test_set_schedule_anchor.py
+++ b/products/data_modeling/backend/test/test_set_schedule_anchor.py
@@ -38,10 +38,10 @@ class TestSetScheduleAnchor(BaseTest):
Edge.objects.create(team=self.team, dag=self.dag, source=self.source, target=self.matview)
set_declared_target(self.matview, H1)
- def _run(self, *args, reconcile_applied=True):
+ def _run(self, *args):
out = StringIO()
with (
- mock.patch(f"{COMMAND}.reconcile_dag_schedules", return_value=reconcile_applied) as reconcile,
+ mock.patch(f"{COMMAND}.reconcile_dag_schedules") as reconcile,
):
call_command("set_schedule_anchor", "--team-id", str(self.team.pk), *args, stdout=out)
return out.getvalue(), reconcile
@@ -50,7 +50,7 @@ class TestSetScheduleAnchor(BaseTest):
output, reconcile = self._run("--dag-id", str(self.dag.id), "--at", "00:00")
self.matview.refresh_from_db()
self.assertEqual(get_declared_anchor(self.matview), 0)
- reconcile.assert_called_once_with(self.dag, require_tiered=True)
+ reconcile.assert_called_once_with(self.dag)
self.assertIn("1hour@00:00", output)
def test_saved_query_mode_anchors_only_the_named_query(self):
@@ -112,12 +112,6 @@ class TestSetScheduleAnchor(BaseTest):
self.assertIsNone(get_declared_anchor(self.matview))
self.assertIsNone(get_declared_anchor(downstream))
- def test_untiered_dag_stores_anchor_but_says_so_instead_of_claiming_reconcile(self):
- output, _reconcile = self._run("--dag-id", str(self.dag.id), "--at", "00:00", reconcile_applied=False)
- self.matview.refresh_from_db()
- self.assertEqual(get_declared_anchor(self.matview), 0)
- self.assertIn("not on cadence-tier schedules yet", output)
-
def test_a_refusal_on_one_dag_writes_nothing_anywhere(self):
# a --saved-query-names set spanning two DAGs must validate both before writing to either:
# the second DAG's weekly refusal must not leave the first already anchored and reconciled