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): stop a materialized view being skipped as ephemeral (#77350)

Jovan Sakovicc8913a388a5a
diff --git a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py b/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
index 629cd4bd326a..5b2065768f4d 100644
--- a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
+++ b/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
@@ -6,6 +6,7 @@ from temporalio import activity
from posthog.sync import database_sync_to_async_pool
from posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_context
+from products.data_modeling.backend.facade.api import promote_view_nodes_to_matview
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.data_warehouse.backend.facade.api import create_table_from_saved_query
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -45,6 +46,10 @@ def _update_saved_query_with_table(
saved_query_table.row_count = inputs.row_count
saved_query_table.save()
+ # The table is what makes the query a matview, so this is the one place that always knows the
+ # node type is stale — every other materialization entry point can leave it behind.
+ promote_view_nodes_to_matview(saved_query)
+
@dataclasses.dataclass
class PrepareQueryableTableResult:
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index a83ef5a712c0..9949e7e8d223 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -758,6 +758,45 @@ class TestPrepareQueryableTableActivity:
assert warehouse_table.row_count == 250
await database_sync_to_async(warehouse_table.delete)()
+ async def test_retypes_view_node_to_matview_once_a_table_is_linked(
+ self, activity_environment, ateam, asaved_query, anode, ajob
+ ):
+ # revert_materialization leaves the node typed VIEW; every scheduled DAG run then treats
+ # it as ephemeral and skips materialization without recording a job.
+ anode.type = NodeType.VIEW
+ await database_sync_to_async(anode.save)()
+
+ inputs = PrepareQueryableTableInputs(
+ team_id=ateam.pk,
+ job_id=str(ajob.id),
+ saved_query_id=str(asaved_query.id),
+ table_uri="s3://test-bucket/test_table",
+ file_uris=["s3://test-bucket/test_file.parquet"],
+ row_count=10,
+ )
+ warehouse_table = await database_sync_to_async(DataWarehouseTable.objects.create)(
+ team=ateam,
+ name="test_warehouse_table",
+ format="Delta",
+ )
+ with (
+ unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.prepare_queryable_table.prepare_s3_files_for_querying"
+ ) as mock_prepare,
+ unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.prepare_queryable_table.create_table_from_saved_query"
+ ) as mock_create_table,
+ ):
+ mock_prepare.return_value = "test-bucket/queryable_folder"
+ mock_create_table.return_value = CreateTableResult(
+ table=warehouse_table, storage_delta_mib=None, total_storage_mib=None
+ )
+ await activity_environment.run(prepare_queryable_table_activity, inputs)
+
+ await database_sync_to_async(anode.refresh_from_db)()
+ assert anode.type == NodeType.MAT_VIEW
+ await database_sync_to_async(warehouse_table.delete)()
+
class TestMaterializeViewActivity:
async def test_rejects_table_node_type(self, activity_environment, ateam, ajob, adag):
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index a55dffbfdc3c..b959ea9ab9cf 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -14,6 +14,7 @@ _LAZY = {
"UnsupportedFrequencyTargetError": "logic.freshness",
"HasDependentsError": "logic.saved_query_dag_sync",
"delete_node_from_dag": "logic.saved_query_dag_sync",
+ "promote_view_nodes_to_matview": "logic.saved_query_dag_sync",
"sync_saved_query_to_dag": "logic.saved_query_dag_sync",
"update_node_type": "logic.saved_query_dag_sync",
"is_saved_query_on_v2_schedule": "logic.node_materialization",
diff --git a/products/data_modeling/backend/logic/saved_query_dag_sync.py b/products/data_modeling/backend/logic/saved_query_dag_sync.py
index 76befa3151ad..864acdac87c0 100644
--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py
+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py
@@ -1,5 +1,7 @@
from typing import TYPE_CHECKING, TypedDict
+from django.db.models import QuerySet
+
import structlog
from posthog.hogql.database.database import Database
@@ -293,3 +295,36 @@ def update_node_type(saved_query: "DataWarehouseSavedQuery", type: NodeType) ->
nodes.update(type=type)
for dag in dags:
maybe_reconcile_dag(dag)
+
+
+def _promote_view_nodes(nodes: QuerySet[Node]) -> int:
+ """Retype the nodes in `nodes` that a table backs but the graph still calls ephemeral views.
+
+ `get_dag_structure` calls every VIEW node ephemeral, so a scheduled run reports success for one
+ without materializing it and without writing a job row — it just stops updating, silently. A
+ node ends up in that state because `revert_materialization` types it VIEW and, until the callers
+ below existed, only the `materialize` action ever typed it back.
+
+ Only VIEW nodes are touched: ENDPOINT nodes are a materializing type already and must keep
+ theirs. Views with no backing table are left alone, being genuinely ephemeral. No reconcile
+ follows, because tier membership keys off the node's frequency target, not its type.
+ """
+ return (
+ nodes.filter(type=NodeType.VIEW, saved_query__table_id__isnull=False)
+ .exclude(saved_query__deleted=True)
+ .update(type=NodeType.MAT_VIEW)
+ )
+
+
+def promote_view_nodes_to_matview(saved_query: "DataWarehouseSavedQuery") -> int:
+ """Repair one saved query's nodes, for the path that just linked its table."""
+ return _promote_view_nodes(Node.objects.filter(team_id=saved_query.team_id, saved_query=saved_query))
+
+
+def promote_dag_view_nodes_to_matview(dag: DAG) -> int:
+ """Repair a whole DAG's nodes, for the tier conversion that is about to sweep its v1 schedules.
+
+ v1 materializes a saved query whatever its node type, so a stranded node keeps running right up
+ until that sweep and only goes dark afterwards.
+ """
+ return _promote_view_nodes(Node.objects.filter(dag=dag))
diff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.py
index f4490488b98e..9f131ee5cf1e 100644
--- a/products/data_modeling/backend/logic/schedule_reconcile.py
+++ b/products/data_modeling/backend/logic/schedule_reconcile.py
@@ -215,24 +215,32 @@ def apply_saved_query_frequency_target(
callers batching many writes into one reconcile).
Returns the number of nodes written (0 = no DAG node, so a non-None target was stored nowhere).
+
+ Atomic because a saved query can still carry nodes in several DAGs while duplicates are being
+ consolidated away: without it, a target rejected by the third node stays written on the first
+ two, and their reconciles are already queued. One node per saved query is the end state, which
+ makes this a no-op then rather than something to unwind later.
"""
written = 0
- for node in Node.objects.filter(team=saved_query.team, saved_query=saved_query).select_related("dag", "dag__team"):
- if target is None:
- set_declared_target(node, None)
- else:
- graph = build_frequency_graph(node.dag)
- validate_declared_target(
- node_id=str(node.id),
- target=target,
- edges=graph.edges,
- declared_targets=graph.declared_targets,
- source_intervals=graph.source_intervals,
- )
- set_declared_target(node, target)
- written += 1
- if reconcile:
- maybe_reconcile_dag(node.dag)
+ with transaction.atomic():
+ for node in Node.objects.filter(team=saved_query.team, saved_query=saved_query).select_related(
+ "dag", "dag__team"
+ ):
+ if target is None:
+ set_declared_target(node, None)
+ else:
+ graph = build_frequency_graph(node.dag)
+ validate_declared_target(
+ node_id=str(node.id),
+ target=target,
+ edges=graph.edges,
+ declared_targets=graph.declared_targets,
+ source_intervals=graph.source_intervals,
+ )
+ set_declared_target(node, target)
+ written += 1
+ if reconcile:
+ maybe_reconcile_dag(node.dag)
return written
@@ -270,8 +278,17 @@ def convert_dag_to_tiers(dag: DAG, default: timedelta | None = None) -> int:
"""Seed per-node targets from the DAG's current cadence, then reconcile it to per-cadence tier
schedules. The shared conversion step both entry points (the v1 migrate command and
reconcile_freshness_schedules) run before clearing the now-redundant saved-query intervals.
+ Also repairs nodes a table backs but the graph still calls ephemeral views: v1 runs them
+ whatever their type, so they only go dark once the conversion's sweep removes their v1
+ schedule.
+
Returns how many targets were seeded.
"""
+ from products.data_modeling.backend.logic.saved_query_dag_sync import ( # noqa: PLC0415 — saved_query_dag_sync imports this module
+ promote_dag_view_nodes_to_matview,
+ )
+
+ promote_dag_view_nodes_to_matview(dag)
seeded = persist_seed_targets(dag, default=default)
reconcile_dag_schedules(dag)
return seeded
diff --git a/products/data_modeling/backend/logic/tier_membership.py b/products/data_modeling/backend/logic/tier_membership.py
index 11e16e27c96d..2852210196c1 100644
--- a/products/data_modeling/backend/logic/tier_membership.py
+++ b/products/data_modeling/backend/logic/tier_membership.py
@@ -26,6 +26,7 @@ from products.data_modeling.backend.logic.freshness import (
)
from products.data_modeling.backend.logic.node_frequency import build_frequency_graph
from products.data_modeling.backend.models.dag import DAG
+from products.data_modeling.backend.models.node import NodeType
from products.data_modeling.backend.schedule import DATA_MODELING_EXECUTE_DAG_WORKFLOW
@@ -61,6 +62,10 @@ CORRECTLY_UNSCHEDULED = "correctly_unscheduled" # no target and no live tier
# Reconcile refuses the *whole DAG* when any desired tier is not a schedulable bucket, so this must
# never be reported as stale_needs_reconcile: running reconcile would change nothing and raise.
UNSUPPORTED_TARGET = "unsupported_target"
+# Typed VIEW while a table backs the query, so `get_dag_structure` calls it ephemeral and every tier
+# run skips it — reporting success and writing no job. Outranks every tier verdict: the node can sit
+# in exactly the right tier and still never materialize, and reconcile cannot fix a node's type.
+EPHEMERAL_SKIPPED = "ephemeral_skipped"
def _interval_from_schedule_id(schedule_id: str) -> int | None:
@@ -159,6 +164,7 @@ def classify_node(
live_tiers: list[LiveTier],
expected_interval: int | None,
reconcile_blocked: bool = False,
+ has_backing_table: bool = False,
) -> NodeScheduleStatus:
"""Compare a node's live tier membership against what reconcile would schedule for it."""
live_intervals = [
@@ -168,7 +174,9 @@ def classify_node(
]
covered_live = bool(live_intervals)
- if covered_live and expected_interval is not None:
+ if node_type == NodeType.VIEW and has_backing_table:
+ verdict = EPHEMERAL_SKIPPED
+ elif covered_live and expected_interval is not None:
# A whole-DAG (interval None) schedule always satisfies expectation.
verdict = SCHEDULED if (None in live_intervals or expected_interval in live_intervals) else SCHEDULED_WRONG_TIER
elif covered_live and expected_interval is None:
diff --git a/products/data_modeling/backend/management/commands/check_node_tier_schedule.py b/products/data_modeling/backend/management/commands/check_node_tier_schedule.py
index 908e60685905..11a27e871a32 100644
--- a/products/data_modeling/backend/management/commands/check_node_tier_schedule.py
+++ b/products/data_modeling/backend/management/commands/check_node_tier_schedule.py
@@ -20,6 +20,7 @@ from asgiref.sync import async_to_sync
from posthog.temporal.common.client import async_connect
from products.data_modeling.backend.logic.tier_membership import (
+ EPHEMERAL_SKIPPED,
STALE_NEEDS_RECONCILE,
UNSUPPORTED_TARGET,
LiveTier,
@@ -94,6 +95,7 @@ class Command(BaseCommand):
live_tiers=live_by_dag.get(str(node.dag_id), []),
expected_interval=expected,
reconcile_blocked=blocked_by_dag.get(str(node.dag_id), False),
+ has_backing_table=node.saved_query is not None and node.saved_query.table_id is not None,
)
)
@@ -125,11 +127,13 @@ class Command(BaseCommand):
return []
if options["dag_id"]:
qs = qs.filter(dag_id=options["dag_id"])
- return list(qs.select_related("dag"))
+ return list(qs.select_related("dag", "saved_query"))
def _dag_nodes(self, team_id: int, dag_id: str) -> list[Node]:
return list(
- Node.objects.filter(team_id=team_id, dag_id=dag_id).exclude(type=NodeType.TABLE).select_related("dag")
+ Node.objects.filter(team_id=team_id, dag_id=dag_id)
+ .exclude(type=NodeType.TABLE)
+ .select_related("dag", "saved_query")
)
@staticmethod
@@ -166,9 +170,11 @@ class Command(BaseCommand):
expected = (
format_interval(status.expected_interval) if status.expected_interval is not None else "none (opt-out)"
)
- marker = " ⚠️" if status.verdict in (STALE_NEEDS_RECONCILE, UNSUPPORTED_TARGET) else ""
+ marker = " ⚠️" if status.verdict in (STALE_NEEDS_RECONCILE, UNSUPPORTED_TARGET, EPHEMERAL_SKIPPED) else ""
if status.verdict == UNSUPPORTED_TARGET:
marker += " — reconcile would REFUSE this whole DAG; fix the non-bucket target first"
+ if status.verdict == EPHEMERAL_SKIPPED:
+ marker += " — typed view over a live table; every tier run SKIPS it. Reconcile will not fix this"
self.stdout.write(
f"{status.name} [{status.node_type}] {status.node_id}\n"
f" live tier: {live} | reconcile would schedule: {expected} | verdict: {status.verdict}{marker}"
diff --git a/products/data_modeling/backend/test/test_check_node_tier_schedule.py b/products/data_modeling/backend/test/test_check_node_tier_schedule.py
index 513872c558d6..20aeea137251 100644
--- a/products/data_modeling/backend/test/test_check_node_tier_schedule.py
+++ b/products/data_modeling/backend/test/test_check_node_tier_schedule.py
@@ -4,9 +4,13 @@ from unittest.mock import patch
from django.core.management import call_command
from django.core.management.base import CommandError
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
from posthog.models import Organization, Team
+from products.data_modeling.backend.logic.tier_membership import EPHEMERAL_SKIPPED, SCHEDULED, LiveTier, classify_node
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.node import Node, NodeType
@@ -14,6 +18,43 @@ from products.data_modeling.backend.models.node import Node, NodeType
TEMPORAL_READ = "products.data_modeling.backend.management.commands.check_node_tier_schedule.Command._read_live_tiers"
+class TestClassifyNodeEphemeral(SimpleTestCase):
+ def _tier(self, node_id: str, seconds: int = 900) -> LiveTier:
+ return LiveTier(
+ schedule_id=f"dag:{seconds}",
+ interval_seconds=seconds,
+ covers_whole_dag=False,
+ node_ids=frozenset({node_id}),
+ )
+
+ def _classify(self, *, node_type: str, has_backing_table: bool) -> str:
+ return classify_node(
+ node_id="n1",
+ name="rep_sales_events",
+ node_type=node_type,
+ dag_id="d1",
+ dag_name="Default",
+ live_tiers=[self._tier("n1")],
+ expected_interval=900,
+ has_backing_table=has_backing_table,
+ ).verdict
+
+ def test_view_node_over_a_live_table_is_not_reported_as_scheduled(self):
+ # It sits in exactly the tier reconcile wants, so every tier comparison says "scheduled" —
+ # but execute_dag classes a view node ephemeral and skips it, so it never materializes.
+ assert self._classify(node_type=NodeType.VIEW, has_backing_table=True) == EPHEMERAL_SKIPPED
+
+ @parameterized.expand(
+ [
+ # a view with no table is a real ephemeral view, working as intended
+ ("ephemeral_view_without_table", NodeType.VIEW, False),
+ ("matview_with_table", NodeType.MAT_VIEW, True),
+ ]
+ )
+ def test_healthy_nodes_stay_scheduled(self, _name, node_type, has_backing_table):
+ assert self._classify(node_type=node_type, has_backing_table=has_backing_table) == SCHEDULED
+
+
class TestCheckNodeTierScheduleGuards(BaseTest):
"""The guards that must hold before the command reads live schedules out of Temporal."""
diff --git a/products/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.py
index 367071864161..c74bea4f5713 100644
--- a/products/data_modeling/backend/test/test_schedule_reconcile.py
+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py
@@ -11,16 +11,23 @@ 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 UnsupportedFrequencyTargetError
from products.data_modeling.backend.logic.node_frequency import set_declared_target
-from products.data_modeling.backend.logic.schedule_reconcile import maybe_reconcile_dag, reconcile_dag_schedules
+from products.data_modeling.backend.logic.saved_query_dag_sync import promote_dag_view_nodes_to_matview
+from products.data_modeling.backend.logic.schedule_reconcile import (
+ convert_dag_to_tiers,
+ maybe_reconcile_dag,
+ reconcile_dag_schedules,
+)
from products.data_modeling.backend.models.dag import DAG
from products.data_modeling.backend.models.edge import Edge
from products.data_modeling.backend.models.node import NodeType
from products.data_modeling.backend.schedule import DATA_MODELING_EXECUTE_DAG_WORKFLOW
from products.data_modeling.backend.test.helpers import (
+ no_existing_schedules,
saved_query_node as _saved_query_node,
table_node as _table_node,
warehouse_source_node as _warehouse_source_node,
)
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"
@@ -401,3 +408,47 @@ class TestMaybeReconcileDag(BaseTest):
with self.captureOnCommitCallbacks(execute=True):
maybe_reconcile_dag(dag)
capture.assert_called_once()
+
+
+class TestPromoteDagViewNodesToMatview(BaseTest):
+ def _backed(self, dag, name, node_type):
+ node = _saved_query_node(self.team, dag, name, node_type)
+ saved_query = node.saved_query
+ assert saved_query is not None
+ saved_query.table = DataWarehouseTable.objects.create(team=self.team, name=f"{name}_tbl", format="Delta")
+ saved_query.save()
+ return node
+
+ def test_retypes_only_table_backed_view_nodes(self):
+ dag = DAG.get_or_create_default(self.team)
+ stranded = self._backed(dag, "stranded", NodeType.VIEW)
+ endpoint = self._backed(dag, "endpoint_backed", NodeType.ENDPOINT)
+ ephemeral = _saved_query_node(self.team, dag, "ephemeral", NodeType.VIEW)
+
+ assert promote_dag_view_nodes_to_matview(dag) == 1
+
+ for node in (stranded, endpoint, ephemeral):
+ node.refresh_from_db()
+ assert stranded.type == NodeType.MAT_VIEW
+ # A view with no backing table is a real ephemeral view; retyping it would schedule
+ # materializations for something that has nothing to materialize.
+ assert ephemeral.type == NodeType.VIEW
+ assert endpoint.type == NodeType.ENDPOINT
+
+ def test_conversion_to_tiers_repairs_stranded_nodes(self):
+ # The v1 sweep that follows conversion is what makes a view-typed node go dark, so the
+ # repair has to happen as part of converting, not on some later pass.
+ dag = DAG.get_or_create_default(self.team)
+ stranded = self._backed(dag, "stranded", NodeType.VIEW)
+ set_declared_target(stranded, M15)
+
+ with (
+ mock.patch(f"{RECONCILE}.sync_connect", return_value=no_existing_schedules()),
+ mock.patch(f"{RECONCILE}.async_connect", return_value=no_existing_schedules()),
+ mock.patch(f"{RECONCILE}.a_create_schedule"),
+ ):
+ convert_dag_to_tiers(dag)
+
+ stranded.refresh_from_db()
+ assert stranded.type == NodeType.MAT_VIEW
diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.py
index e9b1dae1cba5..0f70fe8b2424 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query.py
@@ -1245,6 +1245,7 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
should_unpause = saved_query.sync_frequency_interval is None
previous_interval = saved_query.sync_frequency_interval
+ previously_materialized = saved_query.is_materialized
saved_query.sync_frequency_interval = sync_frequency_interval
saved_query.is_materialized = True
@@ -1261,7 +1262,13 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
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.
+ # delivers) — a request problem, not a server one. `schedule_materialization`
+ # deliberately re-raises these without applying its disable-on-failure contract, and
+ # this action is not inside an atomic block, so undo the enable by hand: otherwise the
+ # 400 leaves is_materialized=True behind and the UI reads the rejection as a success.
+ saved_query.sync_frequency_interval = previous_interval
+ saved_query.is_materialized = previously_materialized
+ saved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])
raise serializers.ValidationError(str(e))
# Refresh from DB to check if schedule_materialization set is_materialized = False on failure
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 6776037c3212..d42879234533 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -15,7 +15,7 @@ from parameterized import parameterized
from posthog.models import ActivityLog
from posthog.models.activity_logging.activity_log import Detail
-from products.data_modeling.backend.facade.api import mark_node_suspended, suspension_state
+from products.data_modeling.backend.facade.api import UnsatisfiableFrequencyError, mark_node_suspended, suspension_state
from products.data_modeling.backend.facade.modeling import DataWarehouseModelPath
from products.data_modeling.backend.facade.models import (
DAG,
@@ -244,6 +244,38 @@ class TestSavedQuery(APIBaseTest):
# But should still update the schedule
mock_sync.assert_called_once()
+ def test_materialize_leaves_nothing_persisted_when_the_frequency_is_rejected(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/",
+ {
+ "name": "event_view",
+ "query": {
+ "kind": "HogQLQuery",
+ "query": "select event as event from events LIMIT 100",
+ },
+ },
+ )
+ assert response.status_code == 201
+ saved_query_id = response.data["id"]
+
+ with patch.object(
+ DataWarehouseSavedQuery,
+ "schedule_materialization",
+ side_effect=UnsatisfiableFrequencyError(
+ "Requested freshness (1day) is less frequent than a downstream consumer requires "
+ "(tightest downstream target: 15min)"
+ ),
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}/materialize",
+ )
+
+ assert response.status_code == 400
+
+ saved_query = DataWarehouseSavedQuery.objects.get(id=saved_query_id)
+ assert saved_query.is_materialized is False
+ assert saved_query.sync_frequency_interval is None
+
def test_materialize_action_with_managed_viewset_fails(self):
"""Test that materializing a managed viewset query fails"""
managed_viewset = DataWarehouseManagedViewSet.objects.create(