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): trigger initial run when materializing on v2 teams (#73962)

Jovan Sakovic31daf087e667
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.py
index b327ec9e09e7..dbd734d2b35f 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py
@@ -183,11 +183,19 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
else:
DataWarehouseModelPath.objects.update_from_saved_query(self)
- def schedule_materialization(self, unpause: bool = False, reconcile: bool = True):
+ def schedule_materialization(
+ self, unpause: bool = False, reconcile: bool = True, trigger_immediate_run: bool = False
+ ):
"""
It will schedule the saved query workflow to run at the configured frequency.
If unpause is True, it will unpause the saved query workflow if it already exists.
+ trigger_immediate_run is for callers enabling materialization: on v2 it starts the first
+ materialization right away instead of waiting for the next scheduled DAG tick, matching
+ v1 schedule creation (which triggers immediately). Callers merely updating frequency
+ must leave it False. Best-effort: a failed start never disables materialization, since
+ the DAG schedule still covers the query.
+
If the workflow fails to schedule, it will disable materialization for this view.
This also guarantees model paths are properly created or updated.
"""
@@ -224,6 +232,10 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
if self.sync_frequency_interval is not None:
self.sync_frequency_interval = None
self.save(update_fields=["sync_frequency_interval"])
+ if trigger_immediate_run:
+ # Deferred to commit so the run sees the enable's writes (endpoints enable
+ # runs inside an atomic block); immediate under autocommit.
+ transaction.on_commit(self._start_immediate_materialization)
return
self.setup_model_paths()
@@ -250,6 +262,19 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
self.is_materialized = False
self.save(update_fields=["is_materialized"])
+ def _start_immediate_materialization(self) -> None:
+ from products.data_modeling.backend.logic.node_materialization import materialize_saved_query
+
+ try:
+ materialize_saved_query(self)
+ except Exception as e:
+ capture_exception(e, {"saved_query_id": self.id, "saved_query_name": self.name})
+ logger.exception(
+ "failed_to_start_initial_materialization",
+ team_id=self.team_id,
+ saved_query_id=str(self.id),
+ )
+
def revert_materialization(self):
from products.data_modeling.backend.logic.schedule_reconcile import (
apply_saved_query_frequency_target,
diff --git a/products/data_modeling/backend/test/test_schedule_materialization.py b/products/data_modeling/backend/test/test_schedule_materialization.py
index 1d9487d18dc3..c8fc8df9a46b 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.node import NodeType
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"
class TestScheduleMaterializationV2Guard(BaseTest):
@@ -32,10 +33,14 @@ class TestScheduleMaterializationV2Guard(BaseTest):
mock.patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,
mock.patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),
mock.patch.object(DataWarehouseSavedQuery, "setup_model_paths") as setup_paths,
+ mock.patch(f"{NODE_MAT}.sync_connect") as sync_connect,
+ self.captureOnCommitCallbacks(execute=True),
):
self.sq.schedule_materialization()
sync_wf.assert_not_called()
setup_paths.assert_not_called()
+ # a frequency-only call carries no enable intent, so it must not start a one-off run
+ sync_connect.assert_not_called()
self.sq.refresh_from_db()
assert self.sq.sync_frequency_interval is None
diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.py
index 3d992475bd03..b32870d7ef5b 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query.py
@@ -1222,7 +1222,7 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
# Enable materialization - this handles model path setup and schedule creation
# If this fails, it will set is_materialized = False
try:
- saved_query.schedule_materialization(unpause=should_unpause)
+ saved_query.schedule_materialization(unpause=should_unpause, trigger_immediate_run=True)
except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:
# The requested cadence can't be honored (e.g. finer than an upstream source
# delivers) — a request problem, not a server one.
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.py
index 1c4f9359cd5c..b98fcf9173d3 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -2075,6 +2075,25 @@ class TestSavedQueryRunV2Aware(APIBaseTest):
mock_trigger.assert_not_called()
mock_client.start_workflow.assert_not_called()
+ @patch("products.data_modeling.backend.logic.node_materialization.sync_connect")
+ @patch("products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids")
+ def test_materialize_on_v2_schedule_starts_initial_run(self, mock_v2_dags, mock_sync_connect):
+ saved_query, dag, _node = self._make_saved_query_with_node("v2_matview")
+ mock_v2_dags.return_value = {str(dag.id)}
+ mock_client = AsyncMock()
+ mock_sync_connect.return_value = mock_client
+
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query.id}/materialize",
+ )
+
+ self.assertEqual(response.status_code, 200, response.content)
+ mock_client.start_workflow.assert_called_once()
+ self.assertEqual(mock_client.start_workflow.call_args[0][0], "data-modeling-materialize-view")
+ saved_query.refresh_from_db()
+ self.assertTrue(saved_query.is_materialized)
+
@patch("products.data_warehouse.backend.presentation.views.saved_query.trigger_saved_query_schedule")
@patch("products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids")
def test_run_on_v1_triggers_saved_query_schedule(self, mock_v2_dags, mock_trigger):
diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.py
index 62146660670c..8338896ff1bb 100644
--- a/products/endpoints/backend/logic/materialization.py
+++ b/products/endpoints/backend/logic/materialization.py
@@ -206,6 +206,11 @@ class EndpointMaterializationService:
# is deferred to on_commit (tiered) or terminal (v1), so nothing rolls back after it fires.
with transaction.atomic():
saved_query = self._get_or_build_saved_query(version)
+ # No live saved query row means materialization is being stood up fresh (first
+ # enable, re-enable after disable, or a version bump). Only that case gets an
+ # immediate first run; a retained enable (e.g. a metadata-only endpoint update
+ # re-reconciling materialization) must not restart the workflow.
+ newly_materialized = saved_query._state.adding
self._configure_saved_query(saved_query, version, data_freshness_seconds, bucket_overrides)
version.enable_materialization(saved_query, bucket_overrides)
@@ -229,10 +234,12 @@ class EndpointMaterializationService:
},
)
- # NOTE: schedule_materialization only triggers an immediate run when it CREATES the
- # Temporal schedule; re-enabling an existing materialization just (re)syncs the schedule.
+ # NOTE: on v1, schedule_materialization only triggers an immediate run when it CREATES
+ # the Temporal schedule; re-enabling an existing materialization just (re)syncs it.
+ # trigger_immediate_run mirrors that on v2: first run only for a newly created saved
+ # query (deferred to on_commit, so it sees the version link above).
try:
- saved_query.schedule_materialization()
+ saved_query.schedule_materialization(trigger_immediate_run=newly_materialized)
except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:
# The chosen data freshness can't be honored (e.g. finer than an upstream import
# delivers) — a request problem, not a server one.
diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.py
index e1d4e893974b..cab2d401e923 100644
--- a/products/endpoints/backend/tests/test_endpoint_materialization.py
+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py
@@ -1780,7 +1780,7 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
observed: dict = {}
- def simulate_immediate_temporal_run(self_saved_query):
+ def simulate_immediate_temporal_run(self_saved_query, **kwargs):
# schedule_materialization() triggers an immediate run on a separate worker
# process, which sees only committed DB state. Capture whether the version is
# already linked, then run the real activity code that throws when it isn't.
@@ -1819,7 +1819,7 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
observed: dict = {}
- def capture_node_state(self_saved_query):
+ def capture_node_state(self_saved_query, **kwargs):
observed["node_exists"] = Node.objects.filter(saved_query_id=self_saved_query.id).exists()
with mock.patch.object(
@@ -1840,6 +1840,48 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
"The DAG node must exist before materialization is scheduled",
)
+ def test_immediate_run_only_on_newly_enabled_materialization(self):
+ endpoint = create_endpoint_with_version(
+ name="v2-initial-run",
+ team=self.team,
+ query=self.sample_hogql_query,
+ created_by=self.user,
+ is_active=True,
+ )
+
+ mock_client = mock.AsyncMock()
+ with (
+ mock.patch(
+ "products.data_modeling.backend.schedule.get_v2_saved_query_ids",
+ side_effect=lambda ids: set(ids),
+ ),
+ mock.patch(
+ "products.data_modeling.backend.logic.node_materialization.sync_connect",
+ return_value=mock_client,
+ ),
+ ):
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",
+ {"is_materialized": True, "data_freshness_seconds": 86400},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ mock_client.start_workflow.assert_called_once()
+ self.assertEqual(mock_client.start_workflow.call_args[0][0], "data-modeling-materialize-view")
+
+ mock_client.start_workflow.reset_mock()
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",
+ {"description": "metadata only"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ # a retained enable must not restart materialization: only a newly created
+ # saved query (first enable, re-enable, version bump) gets the initial run
+ mock_client.start_workflow.assert_not_called()
+
def test_unsatisfiable_freshness_returns_400(self):
endpoint = create_endpoint_with_version(
name="too-fresh",