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-warehouse): reject schema syncs with no usable sync frequency (#104479)

Tom Owers6887d21289ec
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index f66d4a56a9c8..5442ae40f47a 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -199,18 +199,27 @@ def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:
instance.save(update_fields=["status", "updated_at"])
+# A schedule divides the sync time of day by the cadence, so a null interval cannot build one.
+NO_SYNC_FREQUENCY_ERROR = (
+ "This table has no sync frequency, so its sync cannot be scheduled. Set a sync frequency first."
+)
+
+
def _trigger_schema_sync(instance: ExternalDataSchema) -> None:
"""Trigger the schema's sync, creating its Temporal schedule first if it has none.
A schema can reach the UI with no schedule behind it (never created, or dropped), and
triggering one that isn't there raises NOT_FOUND. Retrying can't fix that, so recover the
- same way the source-level reload does instead of dead-ending a single table's sync.
+ same way the source-level reload does instead of dead-ending a single table's sync. Recovery
+ needs a cadence to build the schedule from, so a schema without one is reported to the caller.
"""
try:
trigger_external_data_workflow(instance)
except temporalio.service.RPCError as e:
if e.status != temporalio.service.RPCStatusCode.NOT_FOUND:
raise
+ if instance.sync_frequency_interval is None:
+ raise ValidationError(NO_SYNC_FREQUENCY_ERROR)
sync_external_data_job_workflow(instance, create=True, should_sync=instance.should_sync)
@@ -610,6 +619,16 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
return None
return api_version_deprecation_payload(schema.source.source_type, schema.api_version)
+ def validate_sync_frequency(self, value: str | None) -> str | None:
+ # "never" maps to a null interval, which the schedule builder cannot turn into a cadence.
+ # The choices still list it, so callers do send it. The message names should_sync because
+ # that is what stops a sync.
+ if value == "never":
+ raise ValidationError(
+ '"never" is not a sync frequency. To stop syncing this table, set should_sync to false.'
+ )
+ return value
+
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
instance = cast(Optional[ExternalDataSchema], self.instance)
override = attrs["api_version"] if "api_version" in attrs else (instance.api_version if instance else None)
@@ -1078,6 +1097,13 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
validated_data["sync_time_of_day"] = None
instance.sync_time_of_day = None
+ # A row can still carry a null interval from before that rejection. Turning the sync on, or
+ # moving its time of day, rebuilds the schedule, which a null interval cannot do. Turning
+ # the sync off only pauses the schedule, so it stays allowed.
+ if source.supports_scheduled_sync and instance.sync_frequency_interval is None:
+ if should_sync is True or was_sync_time_of_day_updated:
+ raise ValidationError({"sync_frequency": NO_SYNC_FREQUENCY_ERROR})
+
if source.supports_scheduled_sync and should_sync is True and sync_type is None and instance.sync_type is None:
raise ValidationError("Sync type must be set up first before enabling schema")
@@ -1773,6 +1799,10 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
data={"detail": "Couldn't start the sync. Try again in a few minutes."},
status=status.HTTP_400_BAD_REQUEST,
)
+ except ValidationError:
+ # A missing sync frequency is the caller's to fix, so let DRF render the 400 instead of
+ # logging it as a failure of ours.
+ raise
except Exception as e:
logger.exception(f"Could not trigger external data job for schema {instance.id}", exc_info=e)
raise
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
index 3744fa52bcaa..36c7b36e03f1 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
@@ -3364,6 +3364,33 @@ class TestTriggerFailureDoesNotPaintRunning(APIBaseTest):
schema.refresh_from_db()
assert schema.status == ExternalDataSchema.Status.RUNNING
+ @parameterized.expand([("reload",), ("resync",)])
+ @mock.patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_schema.sync_external_data_job_workflow"
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_schema.trigger_external_data_workflow"
+ )
+ def test_missing_schedule_without_a_sync_frequency_is_reported(self, endpoint, mock_trigger, mock_create_schedule):
+ # Recovery builds the schedule from the schema's own cadence, so a schema without one has
+ # nothing to recover with. Say so instead of crashing inside the schedule builder.
+ from temporalio.service import RPCError
+
+ schema = self._create_schema()
+ ExternalDataSchema.objects.filter(id=schema.id).update(sync_frequency_interval=None)
+ mock_trigger.side_effect = RPCError("schedule not found", RPCStatusCode.NOT_FOUND, b"")
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/{endpoint}/",
+ )
+
+ assert response.status_code == 400
+ assert "Set a sync frequency first" in str(response.json())
+ mock_create_schedule.assert_not_called()
+
+ schema.refresh_from_db()
+ assert schema.status == ExternalDataSchema.Status.FAILED
+
class TestExternalDataSchemaAPIKeyScopes(APIBaseTest):
def _make_api_key(self, scopes: list[str]) -> str:
@@ -3461,6 +3488,44 @@ class TestExternalDataSchemaSerializerValidation(APIBaseTest):
self.schema.refresh_from_db()
assert self.schema.sync_type is None
+ @parameterized.expand(
+ [
+ ("never_frequency", timedelta(hours=6), {"sync_frequency": "never"}, 400, "set should_sync to false"),
+ ("enable_without_frequency", None, {"should_sync": True}, 400, "Set a sync frequency first"),
+ ("retime_without_frequency", None, {"sync_time_of_day": "03:00:00"}, 400, "Set a sync frequency first"),
+ ("disable_without_frequency", None, {"should_sync": False}, 200, None),
+ ]
+ )
+ def test_schedule_needs_a_usable_sync_frequency(
+ self, _name, stored_interval, payload, expected_status, expected_message
+ ):
+ # A null interval builds no schedule: "never" maps to one, and rows written before it was
+ # rejected still carry one. Both used to crash the schedule builder. Disabling stays allowed
+ # because pausing needs no cadence, and it is how a table with no frequency is turned off.
+ ExternalDataSchema.objects.filter(id=self.schema.id).update(sync_frequency_interval=stored_interval)
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",
+ return_value=False,
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_schema.sync_external_data_job_workflow"
+ ) as mock_build_schedule,
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_schemas/{self.schema.id}/",
+ payload,
+ format="json",
+ )
+
+ assert response.status_code == expected_status, response.content
+ if expected_message is not None:
+ assert expected_message in str(response.json())
+ mock_build_schedule.assert_not_called()
+ self.schema.refresh_from_db()
+ assert self.schema.sync_frequency_interval == stored_interval
+
def test_update_absent_sync_type_preserves_existing_value(self):
response = self.client.patch(
f"/api/environments/{self.team.pk}/external_data_schemas/{self.schema.id}/",