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.

feat(data-modeling): clamp unsatisfiable cadences to their source floor (#69579)

Jovan Sakovic24e5f15b9c74
diff --git a/products/data_modeling/backend/logic/freshness.py b/products/data_modeling/backend/logic/freshness.py
index d883623580a9..d88fe96c96d9 100644
--- a/products/data_modeling/backend/logic/freshness.py
+++ b/products/data_modeling/backend/logic/freshness.py
@@ -175,6 +175,61 @@ def declared_target_bounds(
return source_floor, consumer_ceiling
+def nearest_schedulable_bucket_at_least(floor: timedelta) -> timedelta:
+ """The finest schedulable bucket no finer than `floor` — coarsen up to a runnable cadence.
+
+ A source delivering every 45min means running finer than 1hour recomputes identical data, so
+ the meaningful cadence is the smallest bucket >= the floor. Falls back to the coarsest bucket
+ when the floor is coarser than every bucket (nothing coarser is schedulable).
+ """
+ coarser_or_equal = [bucket for bucket in SCHEDULABLE_BUCKETS if bucket >= floor]
+ return min(coarser_or_equal) if coarser_or_equal else max(SCHEDULABLE_BUCKETS)
+
+
+class ClampedCadence:
+ """A node whose effective cadence was coarsened to what its ancestor sources can deliver."""
+
+ node_id: str
+ demanded: timedelta # cadence propagation or the seed asked for
+ source_floor: timedelta # slowest ancestor source
+ clamped_to: timedelta # the schedulable bucket it will actually run at
+
+
+def clamp_to_source_floor(
+ effective: dict[str, timedelta | None],
+ *,
+ edges: list[tuple[str, str]],
+ source_intervals: dict[str, timedelta],
+) -> tuple[dict[str, timedelta | None], list[ClampedCadence]]:
+ """Coarsen every node scheduled finer than its sources can deliver to the nearest bucket >= its
+ source floor, returning the adjusted cadences and the list of changes.
+
+ Clamping each node independently stays consistent because the floor spans the whole ancestor
+ cone (`declared_target_bounds`): a consumer that pulled an ancestor too fine shares that same
+ source and clamps to the same bucket. Streaming/best-effort sources have a zero floor and are
+ never clamped.
+ """
+ clamped: dict[str, timedelta | None] = {}
+ changes: list[ClampedCadence] = []
+ for node_id, cadence in effective.items():
+ if cadence is None:
+ clamped[node_id] = None
+ continue
+ source_floor, _consumer_ceiling = declared_target_bounds(
+ node_id=node_id, edges=edges, declared_targets={}, source_intervals=source_intervals
+ )
+ if is_finer_than(cadence, source_floor):
+ target = nearest_schedulable_bucket_at_least(source_floor)
+ clamped[node_id] = target
+ changes.append(
+ ClampedCadence(node_id=node_id, demanded=cadence, source_floor=source_floor, clamped_to=target)
+ )
+ else:
+ clamped[node_id] = cadence
+ return clamped, changes
+
+
def validate_declared_target(
*,
node_id: str,
diff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.py
index 28ef7102bdd0..60378005aeb5 100644
--- a/products/data_modeling/backend/logic/schedule_reconcile.py
+++ b/products/data_modeling/backend/logic/schedule_reconcile.py
@@ -43,15 +43,15 @@ from products.data_modeling.backend.logic.cohort_scheduling import (
)
from products.data_modeling.backend.logic.freshness import (
SCHEDULABLE_BUCKETS,
+ ClampedCadence,
InvalidTarget,
UnsupportedFrequencyTargetError,
+ clamp_to_source_floor,
compute_effective_cadences,
- declared_target_bounds,
find_invalid_targets,
format_cadence,
- is_finer_than,
)
-from products.data_modeling.backend.logic.node_frequency import FrequencyGraph, build_frequency_graph, seed_targets
+from products.data_modeling.backend.logic.node_frequency import build_frequency_graph, seed_targets
from products.data_modeling.backend.models.dag import DAG
from products.data_modeling.backend.schedule import (
DATA_MODELING_EXECUTE_DAG_WORKFLOW,
@@ -69,6 +69,7 @@ def reconcile_dag_schedules(dag: DAG) -> None:
effective = compute_effective_cadences(
nodes=graph.nodes, edges=graph.edges, declared_targets=graph.declared_targets
)
+ effective, _clamped = clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)
desired_tiers = bucket_into_cadence_tiers(effective)
_apply_reconciliation(
dag_id=str(dag.id),
@@ -79,24 +80,15 @@ def reconcile_dag_schedules(dag: DAG) -> None:
)
-class UnsatisfiableTier:
- """A node scheduled finer than its slowest ancestor source can actually deliver."""
-
- node_id: str
- effective: timedelta # cadence it would be scheduled at
- source_floor: timedelta # slowest cadence its sources can actually deliver
-
-
@dataclasses.dataclass
class DagSchedulePreview:
"""What reconcile would do for a DAG, computed read-only (no schedule writes)."""
- effective: dict[str, timedelta | None] # every schedulable node's resolved cadence
+ effective: dict[str, timedelta | None] # every schedulable node's resolved cadence (post-clamp)
desired_tiers: dict[timedelta, set[str]]
plan: ScheduleReconcilePlan
best_effort_source_ids: set[str] # sources whose freshness is not actually guaranteed
- unsatisfiable: list[UnsatisfiableTier] # effective finer than the source floor can honor
+ clamped: list[ClampedCadence] # nodes coarsened to what their sources can deliver
invalid_targets: list[InvalidTarget] # declared targets that drifted outside their bounds
unsupported_tiers: list[timedelta] # tiers reconcile would refuse (non-bucket cadence)
seeded: bool # whether targets were seeded in-memory from current cadence
@@ -113,6 +105,7 @@ def preview_dag_schedules(dag: DAG, *, seed: bool = False) -> DagSchedulePreview
graph = build_frequency_graph(dag)
declared = {**seed_targets(dag), **graph.declared_targets} if seed else graph.declared_targets
effective = compute_effective_cadences(nodes=graph.nodes, edges=graph.edges, declared_targets=declared)
+ effective, clamped = clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)
desired_tiers = bucket_into_cadence_tiers(effective)
existing_ids = _list_existing_schedule_ids(str(dag.id))
plan = plan_schedule_reconciliation(str(dag.id), desired_tiers, existing_ids)
@@ -121,7 +114,7 @@ def preview_dag_schedules(dag: DAG, *, seed: bool = False) -> DagSchedulePreview
desired_tiers=desired_tiers,
plan=plan,
best_effort_source_ids=graph.best_effort_source_ids,
- unsatisfiable=_find_unsatisfiable(graph, effective, declared),
+ clamped=clamped,
invalid_targets=find_invalid_targets(
edges=graph.edges, declared_targets=declared, source_intervals=graph.source_intervals
),
@@ -130,25 +123,6 @@ def preview_dag_schedules(dag: DAG, *, seed: bool = False) -> DagSchedulePreview
)
-def _find_unsatisfiable(
- graph: FrequencyGraph, effective: dict[str, timedelta | None], declared_targets: dict[str, timedelta]
-) -> list[UnsatisfiableTier]:
- """Flag nodes whose scheduled cadence is finer than their ancestor sources can deliver."""
- flagged: list[UnsatisfiableTier] = []
- for node_id, node_effective in effective.items():
- if node_effective is None:
- continue
- source_floor, _consumer_ceiling = declared_target_bounds(
- node_id=node_id,
- edges=graph.edges,
- declared_targets=declared_targets,
- source_intervals=graph.source_intervals,
- )
- if is_finer_than(node_effective, source_floor):
- flagged.append(UnsatisfiableTier(node_id=node_id, effective=node_effective, source_floor=source_floor))
- return flagged
-
-
@async_to_sync
async def _list_existing_schedule_ids(dag_id: str) -> set[str]:
temporal = await async_connect()
diff --git a/products/data_modeling/backend/management/commands/preview_freshness_schedules.py b/products/data_modeling/backend/management/commands/preview_freshness_schedules.py
index eb9afcdcf8f3..8b2030192fa2 100644
--- a/products/data_modeling/backend/management/commands/preview_freshness_schedules.py
+++ b/products/data_modeling/backend/management/commands/preview_freshness_schedules.py
@@ -76,11 +76,11 @@ class Command(BaseCommand):
def _print_warnings(self, preview: DagSchedulePreview, names: dict[str, str]) -> None:
wrote = False
- for tier in sorted(preview.unsatisfiable, key=lambda t: names.get(t.node_id, t.node_id)):
+ for clamp in sorted(preview.clamped, key=lambda c: names.get(c.node_id, c.node_id)):
wrote = True
self.stdout.write(
- f" ⚠ unsatisfiable: {names.get(tier.node_id, tier.node_id)} would run every {tier.effective} "
- f"but its sources only deliver every {tier.source_floor}"
+ f" ⚠ clamp: {names.get(clamp.node_id, clamp.node_id)} demanded every {clamp.demanded} "
+ f"but its sources only deliver every {clamp.source_floor} → will run {clamp.clamped_to}"
)
for interval in preview.unsupported_tiers:
wrote = True
diff --git a/products/data_modeling/backend/test/test_freshness.py b/products/data_modeling/backend/test/test_freshness.py
index f4b293b670f0..74dbc61482f3 100644
--- a/products/data_modeling/backend/test/test_freshness.py
+++ b/products/data_modeling/backend/test/test_freshness.py
@@ -10,6 +10,7 @@ from products.data_modeling.backend.logic.freshness import (
InvalidTarget,
UnsatisfiableFrequencyError,
UnsupportedFrequencyTargetError,
+ clamp_to_source_floor,
compute_effective_cadences,
declared_target_bounds,
find_invalid_targets,
@@ -18,6 +19,7 @@ from products.data_modeling.backend.logic.freshness import (
M5 = timedelta(minutes=5)
M15 = timedelta(minutes=15)
+M45 = timedelta(minutes=45)
H1 = timedelta(hours=1)
H6 = timedelta(hours=6)
DAY = timedelta(days=1)
@@ -228,3 +230,33 @@ class TestFindInvalidTargets(TestCase):
self.assertEqual(
find_invalid_targets(edges=edges, declared_targets=targets, source_intervals=source_intervals), expected
)
+
+
+class TestClampToSourceFloor(TestCase):
+ @parameterized.expand(
+ [
+ # finer than the 6h floor -> coarsened to the floor bucket
+ ("finer_than_floor", {"a": M15}, {"src": H6}, {"a": H6}, H6),
+ # floor is not a bucket (45min) -> clamp up to the nearest bucket (1h), never finer
+ ("non_bucket_floor_rounds_up", {"a": M15}, {"src": M45}, {"a": H1}, H1),
+ # already at the floor -> untouched
+ ("at_floor", {"a": H6}, {"src": H6}, {"a": H6}, None),
+ # coarser than the floor -> untouched
+ ("coarser_than_floor", {"a": DAY}, {"src": H6}, {"a": DAY}, None),
+ # streamed source imposes no floor -> never clamped
+ ("streamed_source", {"a": M15}, {"src": STREAMING}, {"a": M15}, None),
+ # unscheduled stays unscheduled
+ ("unscheduled_untouched", {"a": None}, {"src": H6}, {"a": None}, None),
+ ]
+ )
+ def test_clamp(self, _name, effective, source_intervals, expected_cadences, expected_clamped_to):
+ clamped, changes = clamp_to_source_floor(effective, edges=[("src", "a")], source_intervals=source_intervals)
+ self.assertEqual(clamped, expected_cadences)
+ if expected_clamped_to is None:
+ self.assertEqual(changes, [])
+ else:
+ self.assertEqual(len(changes), 1)
+ self.assertEqual(changes[0].node_id, "a")
+ self.assertEqual(changes[0].demanded, effective["a"])
+ self.assertEqual(changes[0].source_floor, source_intervals["src"])
+ self.assertEqual(changes[0].clamped_to, expected_clamped_to)
diff --git a/products/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.py
index 4d5d2b07f1f6..22f198a507fa 100644
--- a/products/data_modeling/backend/test/test_schedule_reconcile.py
+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py
@@ -2,22 +2,23 @@ from datetime import timedelta
import pytest
from posthog.test.base import BaseTest
-from unittest import TestCase, mock
+from unittest import mock
-from parameterized import parameterized
from temporalio.client import ScheduleListActionStartWorkflow
from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY
from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id
-from products.data_modeling.backend.logic.freshness import STREAMING, UnsupportedFrequencyTargetError
-from products.data_modeling.backend.logic.node_frequency import FrequencyGraph, set_declared_target
-from products.data_modeling.backend.logic.schedule_reconcile import _find_unsatisfiable, reconcile_dag_schedules
+from products.data_modeling.backend.logic.freshness import UnsupportedFrequencyTargetError
+from products.data_modeling.backend.logic.node_frequency import set_declared_target
+from products.data_modeling.backend.logic.schedule_reconcile import reconcile_dag_schedules
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.edge import Edge
from products.data_modeling.backend.models.node import Node, NodeType
from products.data_modeling.backend.schedule import DATA_MODELING_EXECUTE_DAG_WORKFLOW
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
M15 = timedelta(minutes=15)
H1 = timedelta(hours=1)
@@ -35,6 +36,27 @@ def _saved_query_node(team, dag, name, node_type):
return Node.objects.create(team=team, dag=dag, saved_query=saved_query, type=node_type)
+def _warehouse_source_node(team, dag, *, sync_frequency_interval):
+ table = DataWarehouseTable.objects.create(name="stripe_charges", team=team)
+ source = ExternalDataSource.objects.create(
+ team=team,
+ source_id="source_id",
+ connection_id="connection_id",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.STRIPE,
+ prefix="posthog_test_",
+ )
+ ExternalDataSchema.objects.create(
+ name="stripe_charges",
+ team=team,
+ source=source,
+ table=table,
+ sync_frequency_interval=sync_frequency_interval,
+ should_sync=True,
+ )
+ return _table_node(team, dag, "stripe_charges", {"origin": "warehouse", "warehouse_table_id": str(table.id)})
+
+
def _listing(schedule_id, workflow="data-modeling-execute-dag"):
action = mock.Mock(spec=ScheduleListActionStartWorkflow, workflow=workflow)
return mock.Mock(id=schedule_id, schedule=mock.Mock(action=action))
@@ -181,42 +203,34 @@ class TestReconcileDagSchedules(BaseTest):
reconcile_dag_schedules(dag)
connect.assert_not_called()
+ def test_clamps_a_target_finer_than_its_source_can_deliver(self):
+ # a matview target drifted below its source floor (e.g. the import later slowed to 6h):
+ # reconcile must schedule it at the source floor, not the wasteful finer cadence
+ dag = DAG.get_or_create_default(self.team)
+ source = _warehouse_source_node(self.team, dag, sync_frequency_interval=H6)
+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)
+ Edge.objects.create(team=self.team, dag=dag, source=source, target=matview)
+ set_declared_target(matview, M15)
-class TestFindUnsatisfiable(TestCase):
- @parameterized.expand(
- [
- # scheduled finer than the 6h source delivers -> flagged
- ("finer_than_source_floor", M15, H6, True),
- # exactly at the floor -> satisfiable
- ("at_floor", H6, H6, False),
- # coarser than the floor -> satisfiable
- ("coarser_than_floor", H6, H1, False),
- # streamed source imposes no floor -> satisfiable at any cadence
- ("streamed_source", M15, STREAMING, False),
- ]
- )
- def test_flags_node_finer_than_its_source(self, _name, effective, source_interval, flagged):
- graph = FrequencyGraph(
- nodes={"a"},
- edges=[("src", "a")],
- declared_targets={"a": effective},
- source_intervals={"src": source_interval},
- best_effort_source_ids=set(),
- )
- result = _find_unsatisfiable(graph, {"a": effective}, {"a": effective})
- if flagged:
- self.assertEqual(len(result), 1)
- self.assertEqual(result[0].node_id, "a")
- self.assertEqual(result[0].source_floor, source_interval)
- else:
- self.assertEqual(result, [])
-
- def test_unscheduled_node_is_never_flagged(self):
- graph = FrequencyGraph(
- nodes={"a"},
- edges=[("src", "a")],
- declared_targets={},
- source_intervals={"src": H6},
- best_effort_source_ids=set(),
- )
- self.assertEqual(_find_unsatisfiable(graph, {"a": None}, {}), [])
+ dag_id = str(dag.id)
+
+ async def fake_list_schedules(*_args, **_kwargs):
+ async def gen():
+ return
+ yield # pragma: no cover — empty async generator
+
+ return gen()
+
+ temporal = mock.Mock()
+ temporal.list_schedules = fake_list_schedules
+
+ module = "products.data_modeling.backend.logic.schedule_reconcile"
+ with (
+ mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=temporal)),
+ mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock()) as create,
+ ):
+ reconcile_dag_schedules(dag)
+
+ # clamped to the 6h source floor, not the declared 15min
+ create.assert_called_once()
+ self.assertEqual(create.call_args.kwargs["id"], tier_schedule_id(dag_id, H6))