: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
fix(data-modeling): bootstrap new teams onto tiered schedules (#76635)
Jovan Sakovic27329f7d6ac7
diff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.pyindex 946281cf2417..f4490488b98e 100644--- a/products/data_modeling/backend/logic/schedule_reconcile.py+++ b/products/data_modeling/backend/logic/schedule_reconcile.py@@ -37,7 +37,13 @@ from temporalio.service import RPCError, RPCStatusCodefrom posthog.exceptions_capture import capture_exceptionfrom posthog.ph_client import feature_enabled_or_falsefrom posthog.temporal.common.client import async_connect, sync_connect-from posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_update_schedule, delete_schedule+from posthog.temporal.common.schedule import (+ a_create_schedule,+ a_delete_schedule,+ a_update_schedule,+ delete_schedule,+ schedule_exists,+)from posthog.temporal.common.search_attributes import POSTHOG_DAG_ID_KEYfrom products.data_modeling.backend.logic.cohort_scheduling import (@@ -122,6 +128,63 @@ def _reconcile_dag_best_effort(dag: DAG) -> None:capture_exception(error)+def dag_has_live_v1_schedules(dag: DAG) -> bool:+ """Whether any of the DAG's schedulable saved queries still has a live v1 per-query schedule.++ Short-circuits on the first hit, so an unmigrated DAG — where the first query checked almost+ always has one — costs a single Temporal call.+ """+ temporal = sync_connect()+ for saved_query_id in schedulable_nodes(dag).values_list("saved_query_id", flat=True):+ if saved_query_id is None:+ continue+ if schedule_exists(temporal, schedule_id=str(saved_query_id)):+ return True+ return False+++def dag_can_bootstrap_to_tiers(dag: DAG) -> bool:+ """Whether this DAG can be born straight onto cadence tiers. Decides only — no side effects.++ Callers reach this only once the v2 lookup has said the DAG has no `execute-dag` schedule.+ Adding "and no live v1 schedules either" identifies a DAG that nothing has ever scheduled —+ a new team's first materialization — where seeding tiers cannot double-schedule anything.+ That is the one safe moment to do it: without this a fresh DAG mints a v1 per-query schedule+ (v2 is otherwise created only by the migration commands), so every new team is born on v1 and+ the v1 population grows on its own.++ A DAG carrying live v1 schedules is deliberately left alone — tiers next to them would+ materialize everything twice. It stays for a migration command to convert and sweep.+ """+ if not tiered_schedules_enabled(dag.team):+ return False+ return not dag_has_live_v1_schedules(dag)+++def bootstrap_dag_to_tiers(dag: DAG) -> None:+ """Seed the DAG's targets and queue the reconcile that creates its first tier schedules.++ Everything here is a side effect, and `transaction.on_commit` runs the callback immediately+ for callers that are not inside an atomic block — so call this only once+ `dag_can_bootstrap_to_tiers` has said yes, 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.+ """+ persist_seed_targets(dag)+ transaction.on_commit(lambda: _bootstrap_dag_best_effort(dag))+++def _bootstrap_dag_best_effort(dag: DAG) -> None:+ try:+ reconcile_dag_schedules(dag)+ except Exception as error:+ logger.exception("Freshness schedule bootstrap failed", dag_id=str(dag.id), team_id=dag.team_id)+ capture_exception(error)++def _warn_on_invalid_targets(dag: DAG, graph: FrequencyGraph | None = None) -> None:"""Surface declared targets that drifted outside their bounds; never blocks the mutation."""if graph is None:diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex dbd734d2b35f..9f6175f01e8d 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -205,8 +205,11 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,)from products.data_modeling.backend.logic.schedule_reconcile import (apply_saved_query_frequency_target,+ bootstrap_dag_to_tiers,+ dag_can_bootstrap_to_tiers,tiered_schedules_enabled,)+ from products.data_modeling.backend.models.node import Nodefrom products.data_modeling.backend.schedule import get_v2_saved_query_idsfrom products.data_warehouse.backend.facade.api import (saved_query_workflow_exists,@@ -219,13 +222,37 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,# 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.- if self.id in get_v2_saved_query_ids([self.id]):+ on_v2 = self.id in get_v2_saved_query_ids([self.id])+ dag_to_bootstrap = None+ if not on_v2:+ # Nothing creates a DAG's first v2 schedule outside the migration commands, so a+ # brand-new team would fall through to v1 forever. Bootstrap it instead — declined+ # unless the DAG has never been scheduled at all.+ node = (+ Node.objects.filter(team_id=self.team_id, saved_query_id=self.id)+ .select_related("dag", "dag__team")+ .first()+ )+ if node is not None and node.dag is not None and dag_can_bootstrap_to_tiers(node.dag):+ dag_to_bootstrap = node.dag+ on_v2 = True++ if on_v2:# Tiered v2: the interval is one-shot transport for frequency intent — consume# it into the node target(s) and reconcile. Validation raises before the# nulling below, so a rejected frequency stays visible for retry. A call with# no interval carries no frequency opinion and must not touch existing targets.if tiered_schedules_enabled(self.team) and self.sync_frequency_interval is not None:- apply_saved_query_frequency_target(self, self.sync_frequency_interval, reconcile=reconcile)+ # A bootstrap reconciles the whole DAG once below, once the target has landed,+ # so asking for a second pass here would only repeat it.+ apply_saved_query_frequency_target(+ self, self.sync_frequency_interval, reconcile=reconcile and dag_to_bootstrap is None+ )+ if dag_to_bootstrap is not None:+ # Last, so a frequency the validation above rejects leaves no seeded targets and+ # no schedules behind: on_commit fires immediately for the callers that are not+ # inside an atomic block, and two of the three are not.+ bootstrap_dag_to_tiers(dag_to_bootstrap)# On any v2 flavor the interval must end up NULL: a lingering value would let# a v1 per-query schedule be recreated, and on tiered teams the node target is# the only durable store of frequency intent.diff --git a/products/data_modeling/backend/test/test_schedule_materialization.py b/products/data_modeling/backend/test/test_schedule_materialization.pyindex c8fc8df9a46b..7b7d12ed367a 100644--- a/products/data_modeling/backend/test/test_schedule_materialization.py+++ b/products/data_modeling/backend/test/test_schedule_materialization.py@@ -3,6 +3,7 @@ from datetime import timedeltafrom posthog.test.base import BaseTestfrom unittest import mock+from products.data_modeling.backend.logic.cohort_scheduling import is_tier_schedule_idfrom products.data_modeling.backend.logic.freshness import UnsupportedFrequencyTargetErrorfrom products.data_modeling.backend.logic.node_frequency import get_declared_target, set_declared_targetfrom products.data_modeling.backend.models import DAG, Node@@ -15,6 +16,21 @@ RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"NODE_MAT = "products.data_modeling.backend.logic.node_materialization"+def _no_schedules():+ """A Temporal client whose schedule listing is empty — a DAG nothing has ever scheduled."""++ async def list_schedules(*_args, **_kwargs):+ async def gen():+ return+ yield # pragma: no cover - makes gen an async generator++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = list_schedules+ return temporal++class TestScheduleMaterializationV2Guard(BaseTest):def setUp(self):super().setUp()@@ -45,10 +61,13 @@ class TestScheduleMaterializationV2Guard(BaseTest):assert self.sq.sync_frequency_interval is Nonedef test_creates_v1_schedule_when_dag_not_on_v2(self):+ # an unmigrated v1 DAG: a live per-query schedule already covers this query, so the+ # bootstrap below must not fire and stack tiers on top of itwith (mock.patch(GET_V2_DAG_IDS, return_value=set()),mock.patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,- mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),+ mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=True),+ mock.patch(f"{RECONCILE}.schedule_exists", return_value=True),mock.patch.object(DataWarehouseSavedQuery, "setup_model_paths"),):self.sq.schedule_materialization()@@ -56,6 +75,82 @@ class TestScheduleMaterializationV2Guard(BaseTest):self.sq.refresh_from_db()assert self.sq.sync_frequency_interval == timedelta(hours=12)+ def test_virgin_dag_is_born_on_tiers_instead_of_minting_a_v1_schedule(self):+ # a brand-new team's DAG has no v2 schedule *and* no v1 schedules, so the v2 lookup says+ # "not on v2" and the query would get a per-query v1 schedule — that is how every new team+ # lands on v1 and why the v1 population grows on its own+ node = Node.objects.get(saved_query=self.sq)+ with (+ mock.patch(GET_V2_DAG_IDS, return_value=set()),+ mock.patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,+ mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),+ mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),+ mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_no_schedules())),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{NODE_MAT}.sync_connect"),+ self.captureOnCommitCallbacks(execute=True),+ ):+ self.sq.schedule_materialization()++ sync_wf.assert_not_called()+ create.assert_called_once()+ assert is_tier_schedule_id(create.call_args.kwargs["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++ def test_dag_with_a_v1_scheduled_sibling_is_not_treated_as_virgin(self):+ # adding a query to an unmigrated team's DAG must keep using v1 — bootstrapping tiers+ # here would double-schedule every query the sibling's v1 schedule already materializes+ sibling = DataWarehouseSavedQuery.objects.create(+ name="sibling",+ team=self.team,+ query={"query": "SELECT 2", "kind": "HogQLQuery"},+ sync_frequency_interval=timedelta(hours=12),+ )+ Node.objects.create(team=self.team, dag=self.dag, saved_query=sibling, type=NodeType.VIEW)+ with (+ mock.patch(GET_V2_DAG_IDS, return_value=set()),+ mock.patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,+ mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),+ # only the sibling still has a live v1 schedule+ mock.patch(+ f"{RECONCILE}.schedule_exists", side_effect=lambda _t, schedule_id: schedule_id == str(sibling.id)+ ),+ mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),+ mock.patch(f"{RECONCILE}.sync_connect"),+ mock.patch.object(DataWarehouseSavedQuery, "setup_model_paths"),+ ):+ self.sq.schedule_materialization()+ sync_wf.assert_called_once()++ def test_rejected_frequency_leaves_a_virgin_dag_unbootstrapped(self):+ # the bootstrap is all side effects, and on_commit fires immediately for the callers that+ # are not inside an atomic block — so seeding or scheduling before the frequency is+ # validated converts the DAG to v2 on a request that then 400s+ node = Node.objects.get(saved_query=self.sq)+ self.sq.sync_frequency_interval = timedelta(minutes=45)+ self.sq.save(update_fields=["sync_frequency_interval"])+ with (+ mock.patch(GET_V2_DAG_IDS, return_value=set()),+ mock.patch(f"{SERVICE}.sync_saved_query_workflow"),+ mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),+ mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),+ mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),+ mock.patch(f"{RECONCILE}.sync_connect"),+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_no_schedules())),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ self.captureOnCommitCallbacks(execute=True),+ self.assertRaises(UnsupportedFrequencyTargetError),+ ):+ self.sq.schedule_materialization()++ create.assert_not_called()+ node.refresh_from_db()+ assert get_declared_target(node) is None+def test_tiered_flag_writes_target_through_and_nulls_interval(self):node = Node.objects.get(saved_query=self.sq)with (diff --git a/products/data_modeling/backend/tests/test_managed_viewset_providers.py b/products/data_modeling/backend/tests/test_managed_viewset_providers.pyindex a846e1f7eefa..1320d7cb1c73 100644--- a/products/data_modeling/backend/tests/test_managed_viewset_providers.py+++ b/products/data_modeling/backend/tests/test_managed_viewset_providers.py@@ -1,5 +1,5 @@from posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import AsyncMock, Mock, patchfrom posthog.hogql.database.models import IntegerDatabaseField@@ -14,6 +14,7 @@ from products.data_modeling.backend.facade.models import (DataWarehouseManagedViewSet,DataWarehouseSavedQuery,)+from products.data_modeling.backend.logic.cohort_scheduling import is_tier_schedule_idfrom products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKindSCHEDULE_MATERIALIZATION = (@@ -23,6 +24,26 @@ SCHEDULE_MATERIALIZATION = (# about the provider mechanism, not about anything specific to engineering analytics.KIND = DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS+SERVICE = "products.data_warehouse.backend.logic.data_load.saved_query_service"+GET_V2_DAG_IDS = "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids"+RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"+NODE_MAT = "products.data_modeling.backend.logic.node_materialization"+++def _no_schedules():+ """A Temporal client whose schedule listing is empty — a DAG nothing has ever scheduled."""++ async def list_schedules(*_args, **_kwargs):+ async def gen():+ return+ yield # pragma: no cover - makes gen an async generator++ return gen()++ temporal = Mock()+ temporal.list_schedules = list_schedules+ return temporal+def _fake_view(name: str = "fake_provider_view", materialized: bool = True) -> ProvidedView:return ProvidedView(@@ -74,6 +95,34 @@ class TestManagedViewSetProviders(BaseTest):self.assertEqual(first_ids, second_ids)+ def test_provisioning_a_new_team_never_mints_v1_schedules(self):+ # Managed viewsets are how most new teams first materialize anything (a provider makes+ # several views at once), and their DAG is brand new — so without a birth-on-v2 path every+ # view here gets its own v1 per-query schedule. Views after the first must follow the+ # bootstrap too, even though its tier schedules are only created after commit.+ views = [_fake_view(name=f"provided_view_{i}") for i in range(3)]+ with (+ patch.dict(_expected_views_providers, clear=True),+ patch(GET_V2_DAG_IDS, return_value=set()),+ patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,+ patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),+ patch(f"{RECONCILE}.schedule_exists", return_value=False),+ patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),+ patch(f"{RECONCILE}.sync_connect"),+ patch(f"{RECONCILE}.async_connect", new=AsyncMock(return_value=_no_schedules())),+ patch(f"{RECONCILE}.a_create_schedule", new=AsyncMock()) as create,+ patch(f"{NODE_MAT}.sync_connect"),+ ):+ register_expected_views_provider(KIND, lambda team: views)+ viewset = self._viewset()+ with self.captureOnCommitCallbacks(execute=True):+ viewset.sync_views()++ sync_wf.assert_not_called()+ assert create.call_count > 0+ assert all(is_tier_schedule_id(call.kwargs["id"]) for call in create.call_args_list)+ assert [v.sync_frequency_interval for v in self._views(viewset)] == [None, None, None]+def test_sync_views_creates_nothing_for_empty_provider(self):with patch.dict(_expected_views_providers, clear=True):register_expected_views_provider(KIND, lambda team: [])