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): keep materialization on when temporal is unreachable (#116509)

posthog[bot]81c382c94e26
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index b1064857cc52..984a1b6dba99 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -63,6 +63,7 @@ _LAZY = {
"MaterializationRunDirection": "facade.contracts",
"MaterializationRefusedError": "facade.contracts",
"IncrementalConfigRefusedError": "facade.contracts",
+ "SchedulingUnavailableError": "models.datawarehouse_saved_query",
"enable_saved_query_materialization": "logic.saved_query_materialization",
"disable_saved_query_materialization": "logic.saved_query_materialization",
"link_table_if_materializing": "logic.saved_query_dag_sync",
diff --git a/products/data_modeling/backend/logic/saved_query_materialization.py b/products/data_modeling/backend/logic/saved_query_materialization.py
index d4bf4cae44dc..355a85fd0116 100644
--- a/products/data_modeling/backend/logic/saved_query_materialization.py
+++ b/products/data_modeling/backend/logic/saved_query_materialization.py
@@ -36,7 +36,10 @@ from products.data_modeling.backend.logic.node_materialization import SavedQuery
from products.data_modeling.backend.logic.saved_query_dag_sync import materializes, update_node_type
from products.data_modeling.backend.logic.saved_query_reads import get_saved_query_columns
from products.data_modeling.backend.logic.schedule_reconcile import check_saved_query_frequency_target
-from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from products.data_modeling.backend.models.datawarehouse_saved_query import (
+ DataWarehouseSavedQuery,
+ SchedulingUnavailableError,
+)
from products.data_modeling.backend.models.node import Node, NodeType
logger = structlog.get_logger(__name__)
@@ -182,6 +185,13 @@ def _enable_materialization(
_store_incremental_config(saved_query, incremental_config, user)
_save_materialization(saved_query, is_materialized=True, sync_frequency_interval=sync_frequency_interval)
+ def restore_previous_state() -> None:
+ _save_materialization(
+ saved_query, is_materialized=previously_materialized, sync_frequency_interval=previous_interval
+ )
+ if incremental_config is not KEEP_INCREMENTAL_CONFIG:
+ _restore_incremental_config(saved_query, previous_incremental_config)
+
# If this fails, it will set is_materialized = False
try:
saved_query.schedule_materialization(trigger_immediate_run=True, triggered_by_id=user.pk)
@@ -192,12 +202,13 @@ def _enable_materialization(
# 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.
- _save_materialization(
- saved_query, is_materialized=previously_materialized, sync_frequency_interval=previous_interval
- )
- if incremental_config is not KEEP_INCREMENTAL_CONFIG:
- _restore_incremental_config(saved_query, previous_incremental_config)
+ restore_previous_state()
raise MaterializationRefusedError(LINEAGE_CHANGED_REFUSAL) from error
+ except SchedulingUnavailableError as error:
+ # Temporal was unreachable, so nothing changed on its side. Put the row back as it was:
+ # a query that was materialized keeps its schedule, and a new one stays off.
+ restore_previous_state()
+ raise MaterializationFailedError(MATERIALIZATION_FAILED_MESSAGE) from error
# Refresh from DB to check if schedule_materialization set is_materialized = False on failure
saved_query.refresh_from_db()
diff --git a/products/data_modeling/backend/management/commands/reenable_materialization.py b/products/data_modeling/backend/management/commands/reenable_materialization.py
new file mode 100644
index 000000000000..e97f2cf63b55
--- /dev/null
+++ b/products/data_modeling/backend/management/commands/reenable_materialization.py
@@ -0,0 +1,108 @@
+"""Turn materialization back on for saved queries that a failure to schedule switched off.
+
+schedule_materialization used to clear is_materialized on any error, a Temporal outage included,
+and nothing turns it back on. Give this command the saved query ids from the captured
+scheduling errors. It skips a query that is deleted or whose DAG node materializes again, and
+schedules the rest. A query that fails to schedule again goes back to off, so the summary
+reports it. The flag and the node go back on only after every Temporal call succeeds. A run that
+stops in the middle, by SIGKILL too, leaves the query in progress off, so the next run tries it
+again.
+
+ python manage.py reenable_materialization --ids-file ids.txt # dry-run
+ python manage.py reenable_materialization --ids-file ids.txt --apply
+ python manage.py reenable_materialization --saved-query-ids <id>,<id> --apply
+"""
+
+from pathlib import Path
+from typing import Any
+from uuid import UUID
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.db import transaction
+from django.db.models import Exists, OuterRef
+
+from products.data_modeling.backend.logic.saved_query_dag_sync import promote_view_nodes_to_matview
+from products.data_modeling.backend.logic.schedule_reconcile import reconcile_dag_schedules
+from products.data_modeling.backend.logic.tier_run_report import MATERIALIZING_TYPES
+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from products.data_modeling.backend.models.node import Node
+
+
+class SwitchedOffAgainError(Exception):
+ pass
+
+
+class Command(BaseCommand):
+ help = "Re-enable materialization for saved queries that a failure to schedule switched off"
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--saved-query-ids", type=str, default="", help="Comma-separated saved query ids")
+ parser.add_argument("--ids-file", type=Path, default=None, help="File with one saved query id per line")
+ parser.add_argument("--apply", action="store_true", default=False, help="Re-enable them (default: report only)")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ ids = self._parse_ids(options["saved_query_ids"], options["ids_file"])
+ apply: bool = options["apply"]
+
+ materializing_node = Node.objects.filter(saved_query_id=OuterRef("pk"), type__in=MATERIALIZING_TYPES)
+ candidates = list(
+ DataWarehouseSavedQuery.objects.filter(id__in=ids)
+ .exclude(deleted=True)
+ .exclude(Exists(materializing_node))
+ .order_by("team_id", "id")
+ )
+ self.stdout.write(f"{len(candidates)} of {len(ids)} saved query id(s) are live and have no materializing node.")
+ for saved_query in candidates:
+ self.stdout.write(f"team={saved_query.team_id} saved_query={saved_query.id} name={saved_query.name}")
+
+ if not apply:
+ self.stdout.write("Dry run. Re-run with --apply to re-enable them.")
+ return
+
+ reenabled = 0
+ failed = 0
+ for saved_query in candidates:
+ try:
+ self._reenable(saved_query)
+ except Exception as e:
+ saved_query.is_materialized = False
+ saved_query.save(update_fields=["is_materialized"])
+ self.stdout.write(f"failed saved_query={saved_query.id}: {e}")
+ failed += 1
+ else:
+ reenabled += 1
+
+ self.stdout.write(f"Re-enabled {reenabled}, failed {failed}.")
+
+ def _reenable(self, saved_query: DataWarehouseSavedQuery) -> None:
+ # The flag reaches the database only after every Temporal call. A run that stops before then
+ # leaves the query off for the next run, and no row lock waits on Temporal. Until then the flag
+ # is on in memory only, where the failure paths of schedule_materialization switch it off.
+ saved_query.is_materialized = True
+ # The default reconcile logs a failure and does not raise it, so a query that no tier runs
+ # counts as re-enabled. Reconcile below instead, where a failure raises.
+ saved_query.schedule_materialization(reconcile=False)
+ if not saved_query.is_materialized:
+ raise SwitchedOffAgainError("scheduling switched it off again")
+ nodes = Node.objects.filter(team_id=saved_query.team_id, saved_query=saved_query).select_related(
+ "dag", "dag__team"
+ )
+ for dag in {node.dag for node in nodes}:
+ reconcile_dag_schedules(dag)
+ with transaction.atomic():
+ saved_query.save(update_fields=["is_materialized"])
+ # A failed first enable leaves the node a VIEW, and a DAG run skips a VIEW node as ephemeral.
+ # The promotion reads the flag from the database, so it follows the save.
+ promote_view_nodes_to_matview(saved_query)
+
+ def _parse_ids(self, raw: str, ids_file: Path | None) -> set[UUID]:
+ tokens = [token.strip() for token in raw.split(",")]
+ if ids_file is not None:
+ tokens.extend(line.strip() for line in ids_file.read_text().splitlines())
+ try:
+ ids = {UUID(token) for token in tokens if token}
+ except ValueError as e:
+ raise CommandError(f"Invalid saved query id: {e}")
+ if not ids:
+ raise CommandError("Pass --saved-query-ids or --ids-file")
+ return ids
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.py
index 3fc9e3d42f54..c739df5a93d5 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py
@@ -115,6 +115,11 @@ class NoSchedulableDagError(Exception):
bootstrap one from."""
+class SchedulingUnavailableError(Exception):
+ """Raised when Temporal is unreachable, so the schedule state of a saved query is unknown.
+ The caller decides what to keep, because the saved query itself is not at fault."""
+
+
class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields, DeletedMetaFields):
class Status(models.TextChoices):
"""Possible states of this SavedQuery."""
@@ -309,9 +314,11 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
triggered_by_id is the person who enabled materialization, and is who hears about it if
that first run fails.
- A rejected frequency propagates to the caller. Any other failure disables
- materialization, because the alternative is a query that reports itself materialized
- while nothing is scheduled to materialize it.
+ A rejected frequency propagates to the caller. A Temporal outage propagates as
+ SchedulingUnavailableError and leaves is_materialized as it is: an outage says nothing
+ about the query, and the schedules that already back it keep running. Any other failure
+ disables materialization, because the alternative is a query that reports itself
+ materialized while nothing is scheduled to materialize it.
"""
from products.data_modeling.backend.logic.freshness import (
UnsatisfiableFrequencyError,
@@ -323,14 +330,23 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
bootstrap_dag_to_tiers,
)
from products.data_modeling.backend.models.node import Node
- from products.data_modeling.backend.schedule import get_v2_saved_query_ids
+ from products.data_modeling.backend.schedule import get_v2_saved_query_ids, is_transient_temporal_error
node: Node | None = None
try:
# 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])
+ # An unreachable Temporal is the exception: it goes to the caller, which knows whether
+ # a schedule already backs the query.
+ try:
+ on_v2 = self.id in get_v2_saved_query_ids([self.id])
+ except Exception as e:
+ if is_transient_temporal_error(e):
+ raise SchedulingUnavailableError(
+ f"Temporal is unavailable to schedule saved query {self.id}"
+ ) from e
+ raise
node = (
Node.objects.filter(team_id=self.team_id, saved_query_id=self.id)
.select_related("dag", "dag__team")
@@ -384,6 +400,10 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
# The query is fine — the requested frequency is not. Surface it to the caller
# instead of silently disabling materialization.
raise
+ except SchedulingUnavailableError as e:
+ capture_exception(e, {"saved_query_id": self.id, "team_id": self.team_id})
+ logger.warning("schedule_materialization_temporal_unavailable", saved_query_id=str(self.id))
+ raise
except Exception as e:
capture_exception(
e,
diff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.py
index 384eb8d2afa7..208e9690e609 100644
--- a/products/data_modeling/backend/schedule.py
+++ b/products/data_modeling/backend/schedule.py
@@ -25,6 +25,7 @@ from temporalio.client import (
ScheduleSpec,
)
from temporalio.common import SearchAttributePair, TypedSearchAttributes
+from temporalio.service import RPCError, RPCStatusCode
from posthog.temporal.common.client import async_connect
from posthog.temporal.common.search_attributes import (
@@ -41,6 +42,21 @@ from products.data_modeling.backend.models.node import Node
# schedule, optionally followed by ":{anchor}". Parsers must handle all three shapes.
DATA_MODELING_EXECUTE_DAG_WORKFLOW = "data-modeling-execute-dag"
+_TRANSIENT_RPC_STATUSES = (
+ RPCStatusCode.UNAVAILABLE,
+ RPCStatusCode.DEADLINE_EXCEEDED,
+ RPCStatusCode.RESOURCE_EXHAUSTED,
+)
+
+
+def is_transient_temporal_error(exc: BaseException) -> bool:
+ """True when Temporal could not answer at all, so a retry can succeed with no change on our side."""
+ if isinstance(exc, RPCError):
+ return exc.status in _TRANSIENT_RPC_STATUSES
+ # A failed connect (TLS handshake, DNS, refused) happens before any RPC, so the Rust bridge
+ # raises an untyped RuntimeError instead of an RPCError.
+ return isinstance(exc, RuntimeError) and str(exc).startswith("Failed client connect:")
+
def dag_schedule_search_attributes(*, team_id: int, organization_id: str, dag_id: str) -> TypedSearchAttributes:
return TypedSearchAttributes(
diff --git a/products/data_modeling/backend/test/test_reenable_materialization.py b/products/data_modeling/backend/test/test_reenable_materialization.py
new file mode 100644
index 000000000000..000802754668
--- /dev/null
+++ b/products/data_modeling/backend/test/test_reenable_materialization.py
@@ -0,0 +1,117 @@
+from datetime import timedelta
+from io import StringIO
+
+from posthog.test.base import BaseTest
+from unittest import mock
+
+from django.core.management import call_command
+
+from parameterized import parameterized
+from temporalio.service import RPCError, RPCStatusCode
+
+from products.data_modeling.backend.models import DAG, Node
+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from products.data_modeling.backend.models.node import NodeType
+from products.data_modeling.backend.test.helpers import no_existing_schedules
+
+GET_V2_DAG_IDS = "products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids"
+RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"
+
+
+class TestReenableMaterialization(BaseTest):
+ def _saved_query(
+ self,
+ name: str,
+ *,
+ node_type: NodeType | None = NodeType.VIEW,
+ deleted: bool = False,
+ ) -> DataWarehouseSavedQuery:
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ name=name,
+ team=self.team,
+ query={"query": "SELECT 1", "kind": "HogQLQuery"},
+ is_materialized=False,
+ sync_frequency_interval=timedelta(hours=12),
+ deleted=deleted,
+ )
+ if node_type is not None:
+ Node.objects.create(team=self.team, dag=self.dag, saved_query=saved_query, type=node_type)
+ return saved_query
+
+ def setUp(self):
+ super().setUp()
+ self.dag = DAG.objects.create(team=self.team, name="Default")
+
+ def test_dry_run_changes_nothing(self):
+ switched_off = self._saved_query("switched_off")
+ call_command("reenable_materialization", saved_query_ids=str(switched_off.id), stdout=StringIO())
+ switched_off.refresh_from_db()
+ assert switched_off.is_materialized is False
+
+ @parameterized.expand(
+ [
+ ("tier_created", None, True, NodeType.MAT_VIEW, "Re-enabled 1, failed 1."),
+ (
+ "tier_create_fails",
+ RPCError("connection reset", RPCStatusCode.UNAVAILABLE, b""),
+ False,
+ NodeType.VIEW,
+ "Re-enabled 0, failed 2.",
+ ),
+ ]
+ )
+ def test_apply_reenables_only_live_queries_that_can_be_scheduled(
+ self,
+ _name: str,
+ create_error: Exception | None,
+ expected_materialized: bool,
+ expected_node_type: NodeType,
+ expected_summary: str,
+ ):
+ switched_off = self._saved_query("switched_off")
+ deleted = self._saved_query("deleted", deleted=True)
+ nodeless = self._saved_query("nodeless", node_type=None)
+ already_materialized = self._saved_query("already_materialized", node_type=NodeType.MAT_VIEW)
+ out = StringIO()
+ with (
+ mock.patch(GET_V2_DAG_IDS, return_value={str(self.dag.id)}),
+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=no_existing_schedules())),
+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock(side_effect=create_error)) as create,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ call_command(
+ "reenable_materialization",
+ saved_query_ids=",".join(str(sq.id) for sq in (switched_off, deleted, nodeless, already_materialized)),
+ apply=True,
+ stdout=out,
+ )
+
+ for saved_query in (switched_off, deleted, nodeless, already_materialized):
+ saved_query.refresh_from_db()
+ node = Node.objects.get(saved_query=switched_off)
+ assert create.call_args.kwargs["schedule"].action.args[0]["node_ids"] == [str(node.id)]
+ assert switched_off.is_materialized is expected_materialized
+ assert node.type == expected_node_type
+ assert deleted.is_materialized is False
+ assert nodeless.is_materialized is False
+ assert already_materialized.is_materialized is False
+ assert "2 of 4 saved query id(s)" in out.getvalue()
+ assert expected_summary in out.getvalue()
+
+ @parameterized.expand([("ctrl_c", KeyboardInterrupt), ("exit", SystemExit)])
+ def test_interrupted_apply_leaves_the_query_off_for_the_next_run(
+ self, _name: str, interruption: type[BaseException]
+ ):
+ switched_off = self._saved_query("switched_off")
+ with (
+ mock.patch(GET_V2_DAG_IDS, return_value={str(self.dag.id)}),
+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=no_existing_schedules())),
+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock(side_effect=interruption)),
+ self.assertRaises(interruption),
+ ):
+ call_command(
+ "reenable_materialization", saved_query_ids=str(switched_off.id), apply=True, stdout=StringIO()
+ )
+
+ switched_off.refresh_from_db()
+ assert switched_off.is_materialized is False
diff --git a/products/data_modeling/backend/test/test_saved_query_materialization.py b/products/data_modeling/backend/test/test_saved_query_materialization.py
index 6f31ca0c4d7b..fa0a30f9811d 100644
--- a/products/data_modeling/backend/test/test_saved_query_materialization.py
+++ b/products/data_modeling/backend/test/test_saved_query_materialization.py
@@ -14,7 +14,10 @@ from products.data_modeling.backend.facade import api
from products.data_modeling.backend.logic.freshness import UnsatisfiableFrequencyError
from products.data_modeling.backend.logic.incremental import IncrementalConfig
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.datawarehouse_saved_query import (
+ DataWarehouseSavedQuery,
+ SchedulingUnavailableError,
+)
from products.data_modeling.backend.models.edge import Edge
from products.data_modeling.backend.models.node import Node, NodeType
from products.data_modeling.backend.test.helpers import warehouse_source_node
@@ -99,24 +102,30 @@ class TestEnableSavedQueryMaterialization(BaseTest):
assert self.saved_query.is_materialized is False
assert self.saved_query.sync_frequency_interval is None
- def test_a_cadence_refused_while_scheduling_restores_the_previous_materialization(self) -> None:
+ @parameterized.expand(
+ [
+ ("cadence_refused", UnsatisfiableFrequencyError("lineage moved"), api.MaterializationRefusedError),
+ ("temporal_unavailable", SchedulingUnavailableError("temporal down"), api.MaterializationFailedError),
+ ]
+ )
+ def test_a_scheduling_error_restores_the_previous_materialization(
+ self, _name: str, error: Exception, expected: type[Exception]
+ ) -> None:
self.saved_query.is_materialized = True
self.saved_query.sync_frequency_interval = timedelta(hours=12)
- self.saved_query.save(update_fields=["is_materialized", "sync_frequency_interval"])
+ self.saved_query.incremental_config = STORED_DAY_KEY
+ self.saved_query.save(update_fields=["is_materialized", "sync_frequency_interval", "incremental_config"])
with (
- patch.object(
- DataWarehouseSavedQuery,
- "schedule_materialization",
- side_effect=UnsatisfiableFrequencyError("lineage moved"),
- ),
- self.assertRaises(api.MaterializationRefusedError),
+ patch.object(DataWarehouseSavedQuery, "schedule_materialization", side_effect=error),
+ self.assertRaises(expected),
):
self._enable(timedelta(hours=1))
self.saved_query.refresh_from_db()
assert self.saved_query.is_materialized is True
assert self.saved_query.sync_frequency_interval == timedelta(hours=12)
+ assert self.saved_query.incremental_config == STORED_DAY_KEY
def test_a_schedule_that_disables_materialization_fails_without_logging_an_enable(self) -> None:
def disable_materialization(saved_query: DataWarehouseSavedQuery, **_kwargs: object) -> None:
diff --git a/products/data_modeling/backend/test/test_schedule_materialization.py b/products/data_modeling/backend/test/test_schedule_materialization.py
index 78d1210d8dca..a0d979f30922 100644
--- a/products/data_modeling/backend/test/test_schedule_materialization.py
+++ b/products/data_modeling/backend/test/test_schedule_materialization.py
@@ -3,6 +3,9 @@ from datetime import timedelta
from posthog.test.base import BaseTest
from unittest import mock
+from parameterized import parameterized
+from temporalio.service import RPCError, RPCStatusCode
+
from products.data_modeling.backend.logic.cohort_scheduling import is_tier_schedule_id
from products.data_modeling.backend.logic.freshness import UnsupportedFrequencyTargetError
from products.data_modeling.backend.logic.node_frequency import get_declared_target, set_declared_target
@@ -10,6 +13,7 @@ from products.data_modeling.backend.models import DAG, Node
from products.data_modeling.backend.models.datawarehouse_saved_query import (
DataWarehouseSavedQuery,
NoSchedulableDagError,
+ SchedulingUnavailableError,
)
from products.data_modeling.backend.models.node import NodeType
@@ -225,3 +229,18 @@ class TestScheduleMaterializationV2Guard(BaseTest):
self.sq.schedule_materialization()
self.sq.refresh_from_db()
assert self.sq.is_materialized is False
+
+ @parameterized.expand(
+ [
+ ("tls_handshake", RuntimeError("Failed client connect: Server connection error: invalid peer certificate")),
+ ("rpc_unavailable", RPCError("connection reset", RPCStatusCode.UNAVAILABLE, b"")),
+ ]
+ )
+ def test_temporal_outage_raises_and_keeps_materialization(self, _name: str, error: Exception):
+ self.sq.is_materialized = True
+ self.sq.save(update_fields=["is_materialized"])
+ with mock.patch(GET_V2_DAG_IDS, side_effect=error), self.assertRaises(SchedulingUnavailableError):
+ self.sq.schedule_materialization()
+ self.sq.refresh_from_db()
+ assert self.sq.is_materialized is True
+ assert self.sq.sync_frequency_interval == timedelta(hours=12)
diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.py
index 4ce4c0c0e0ea..1019fc98f70c 100644
--- a/products/endpoints/backend/logic/materialization.py
+++ b/products/endpoints/backend/logic/materialization.py
@@ -29,6 +29,7 @@ from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import Detail, log_activity
from products.data_modeling.backend.facade.api import (
+ SchedulingUnavailableError,
UnsatisfiableFrequencyError,
UnsupportedFrequencyTargetError,
is_materialization_fresh,
@@ -285,6 +286,9 @@ class EndpointMaterializationService:
# The chosen data freshness can't be honored (e.g. finer than an upstream import
# delivers) — a request problem, not a server one.
raise ValidationError(str(e))
+ except SchedulingUnavailableError as e:
+ # Raising unwinds the atomic block, so the endpoint keeps the state it had before.
+ raise APIException(f"Failed to schedule materialization for endpoint {endpoint.name}.") from e
# schedule_materialization applies a disable-on-failure contract rather than raising,
# so a failure to schedule shows up only as is_materialized flipping back. Checking it