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): commit bulk schema updates per-schema (#63957)

Marcus Hof0853da398960
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 21b34640f773..9c9c2e92c804 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -9,7 +9,7 @@ from urllib.parse import quote
from django.conf import settings
from django.core.exceptions import ValidationError as DjangoValidationError
-from django.db import transaction
+from django.db import connection, transaction
from django.db.models import Prefetch, Q
from django.utils import timezone
@@ -19,7 +19,7 @@ from dateutil import parser
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_field
from psycopg import OperationalError
from rest_framework import filters, serializers, status, viewsets
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import APIException, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
from sshtunnel import BaseSSHTunnelForwarderError
@@ -504,6 +504,32 @@ class ExternalDataSourceBulkUpdateSchemasSerializer(serializers.Serializer):
)
+def _validation_error_message(error: ValidationError) -> str:
+ # DRF normalizes ValidationError.detail to a list or dict (never a bare string).
+ detail = error.detail
+ if isinstance(detail, dict):
+ return " ".join(f"{field}: {value}" for field, value in detail.items())
+ return " ".join(str(item) for item in detail)
+
+
+class BulkSchemaSaveError(APIException):
+ default_code = "bulk_schema_save_failed"
+
+ def __init__(self, failures: dict[str, tuple[str, str]], *, only_validation_errors: bool) -> None:
+ # Pure input problems are the caller's to fix (400). A database/infra error is ours and is
+ # retryable (503); treat a mix as a server problem so it surfaces as retryable.
+ self.status_code = (
+ status.HTTP_400_BAD_REQUEST if only_validation_errors else status.HTTP_503_SERVICE_UNAVAILABLE
+ )
+ reasons = "; ".join(f"{name} ({reason})" for name, reason in failures.values())
+ super().__init__(
+ detail=(
+ f"These schemas in the batch could not be saved: {reasons}. "
+ "Any other schemas in the batch were saved successfully — retry the ones listed here."
+ )
+ )
+
+
class ExternalDataJobSerializers(serializers.ModelSerializer):
schema = serializers.SerializerMethodField(read_only=True)
status = serializers.SerializerMethodField(read_only=True)
@@ -3318,26 +3344,88 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
serializer_context = self.get_serializer_context()
updated_schemas: list[ExternalDataSchema] = []
- post_commit_actions: list[Callable[[], None]] = []
- update_serializer_context = {**serializer_context, "post_commit_actions": post_commit_actions}
+ # Each deferred action is paired with its schema so a post-commit failure can be attributed.
+ post_commit_actions: list[tuple[ExternalDataSchema, Callable[[], None]]] = []
+
+ # Validate every payload before writing anything, so a malformed request is rejected up
+ # front. Some checks only run inside the serializer's update() (during save() below), so
+ # this catches the common input errors but not all of them — the save loop handles the rest.
+ prepared: list[tuple[ExternalDataSchema, ExternalDataSchemaSerializer, list[Callable[[], None]]]] = []
+ for schema_update in schema_updates:
+ schema_id = schema_update["id"]
+ schema = source_schemas_by_id[schema_id]
+ schema_payload = {key: value for key, value in schema_update.items() if key != "id"}
+
+ schema_post_commit_actions: list[Callable[[], None]] = []
+ schema_serializer = ExternalDataSchemaSerializer(
+ schema,
+ data=schema_payload,
+ partial=True,
+ context={**serializer_context, "post_commit_actions": schema_post_commit_actions},
+ )
+ schema_serializer.is_valid(raise_exception=True)
+ prepared.append((schema, schema_serializer, schema_post_commit_actions))
+
+ # Commit each schema in its own transaction. A single atomic block around the whole batch
+ # meant one schema's failure rolled back every schema and failed the request, so the user
+ # got nothing applied. Isolating per schema keeps the ones that saved committed, attempts
+ # every schema so a single bad one can't block the rest, and reports the failures together.
+ failed_schemas: dict[str, tuple[str, str]] = {}
+ only_validation_errors = True
+ for schema, schema_serializer, schema_post_commit_actions in prepared:
+ try:
+ with transaction.atomic():
+ updated_schemas.append(schema_serializer.save())
+ except Exception as e:
+ if isinstance(e, ValidationError):
+ reason = _validation_error_message(e)
+ logger.warning(
+ "bulk_update_schemas validation error during save",
+ source_id=str(source.id),
+ schema_id=str(schema.id),
+ )
+ else:
+ only_validation_errors = False
+ reason = "a database error occurred while saving"
+ capture_exception(e)
+ logger.exception(
+ "bulk_update_schemas failed to persist schema",
+ source_id=str(source.id),
+ schema_id=str(schema.id),
+ )
+ failed_schemas[str(schema.id)] = (schema.name, reason)
+ # A dropped connection leaves Django holding a dead handle; reset it so the next
+ # schema reconnects instead of failing on the same broken connection.
+ if not connection.is_usable():
+ connection.close()
+ continue
- with transaction.atomic():
- for schema_update in schema_updates:
- schema_id = schema_update["id"]
- schema = source_schemas_by_id[schema_id]
- schema_payload = {key: value for key, value in schema_update.items() if key != "id"}
-
- schema_serializer = ExternalDataSchemaSerializer(
- schema,
- data=schema_payload,
- partial=True,
- context=update_serializer_context,
+ # Only run a schema's Temporal side effects once its own row is committed.
+ post_commit_actions.extend((schema, action) for action in schema_post_commit_actions)
+
+ post_commit_error: Exception | None = None
+ for action_schema, post_commit_action in post_commit_actions:
+ try:
+ post_commit_action()
+ except Exception as e:
+ # The row is already committed but its schedule still runs the old cadence. Capture +
+ # log every failure (with the schema id) so the drift is visible, and remember it so
+ # the request fails below — the caller must know the batch did not fully apply.
+ post_commit_error = e
+ capture_exception(e)
+ logger.warning(
+ "bulk_update_schemas saved the schema but its Temporal schedule update failed",
+ source_id=str(source.id),
+ schema_id=str(action_schema.id),
+ exc_info=e,
)
- schema_serializer.is_valid(raise_exception=True)
- updated_schemas.append(schema_serializer.save())
- for post_commit_action in post_commit_actions:
- post_commit_action()
+ # Report save failures first so a schedule-update failure can't mask which schemas didn't
+ # save, then fail the request on the schedule-update failure.
+ if failed_schemas:
+ raise BulkSchemaSaveError(failed_schemas, only_validation_errors=only_validation_errors)
+ if post_commit_error is not None:
+ raise post_commit_error
return Response(
ExternalDataSchemaSerializer(updated_schemas, many=True, context=serializer_context).data,
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index cefe4300a842..213b9a7a21f6 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -15,6 +15,7 @@ from django.utils import timezone
import psycopg
from parameterized import parameterized
from rest_framework import status
+from rest_framework.exceptions import ValidationError
from sshtunnel import BaseSSHTunnelForwarderError
from posthog.schema import (
@@ -452,6 +453,168 @@ class TestExternalDataSource(APIBaseTest):
assert mock_sync_external_data_job_workflow.call_args.kwargs == {"create": False, "should_sync": True}
assert mock_sync_external_data_job_workflow.call_args.args[0].id == schema.id
+ @parameterized.expand(
+ [
+ (
+ "db_error",
+ psycopg.OperationalError("the connection is closed"),
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ "database",
+ ),
+ (
+ "validation_error",
+ ValidationError("Table1 cannot be changed"),
+ status.HTTP_400_BAD_REQUEST,
+ "cannot be changed",
+ ),
+ ]
+ )
+ @patch(
+ "products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",
+ return_value=False,
+ )
+ def test_bulk_update_schemas_one_schema_failing_does_not_block_others(
+ self, _name, raised_exception, expected_status, expected_detail_substring, _mock_workflow_exists
+ ):
+ # Each schema commits in its own transaction. A failure on one schema — a database error
+ # mid-save, or a validation error raised inside update() — must not roll back or block the
+ # others: every schema is attempted, and the failures are reported per schema (503 for a
+ # database error, 400 when it is only validation) instead of 500ing the whole batch.
+ from products.data_warehouse.backend.api.external_data_schema import ExternalDataSchemaSerializer
+
+ source = self._create_external_data_source()
+ schemas = [
+ ExternalDataSchema.objects.create(
+ name=f"Table{i}",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=True,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+ for i in range(3)
+ ]
+ original_interval = schemas[1].sync_frequency_interval
+
+ original_update = ExternalDataSchemaSerializer.update
+ attempted = 0
+
+ def _failing_update(serializer_self, instance, validated_data):
+ nonlocal attempted
+ attempted += 1
+ if attempted == 2:
+ raise raised_exception
+ return original_update(serializer_self, instance, validated_data)
+
+ with (
+ patch.object(ExternalDataSchemaSerializer, "update", _failing_update),
+ patch("products.data_warehouse.backend.api.external_data_schema.sync_external_data_job_workflow"),
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",
+ data={"schemas": [{"id": str(s.id), "sync_frequency": "7day"} for s in schemas]},
+ format="json",
+ )
+
+ # Every schema is attempted despite the second one failing.
+ assert attempted == 3
+ # The failure is surfaced with the right status and names only the schema that failed.
+ assert response.status_code == expected_status
+ detail = response.json()["detail"]
+ assert "Table1" in detail
+ assert expected_detail_substring in detail
+ assert "Table0" not in detail
+ assert "Table2" not in detail
+
+ for schema in schemas:
+ schema.refresh_from_db()
+ # The schemas before and after the failure are committed...
+ assert sync_frequency_interval_to_sync_frequency(schemas[0].sync_frequency_interval) == "7day"
+ assert sync_frequency_interval_to_sync_frequency(schemas[2].sync_frequency_interval) == "7day"
+ # ...and the one that failed keeps its original frequency.
+ assert schemas[1].sync_frequency_interval == original_interval
+
+ def test_bulk_update_schemas_invalid_payload_rejected_before_any_write(self):
+ # The batch is validated up front (per-schema is_valid), so an invalid payload rejects the
+ # whole request with nothing written — even the valid schema listed alongside it is not
+ # committed. With per-schema commits, this preflight is what keeps a bad batch all-or-nothing.
+ source = self._create_external_data_source()
+ valid_schema = ExternalDataSchema.objects.create(
+ name="Valid",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=True,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+ invalid_schema = ExternalDataSchema.objects.create(
+ name="Invalid",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=True,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+ valid_original = valid_schema.sync_frequency_interval
+ invalid_original = invalid_schema.sync_frequency_interval
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",
+ data={
+ "schemas": [
+ {"id": str(valid_schema.id), "sync_frequency": "7day"},
+ {"id": str(invalid_schema.id), "sync_frequency": "not_a_real_frequency"},
+ ]
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ valid_schema.refresh_from_db()
+ invalid_schema.refresh_from_db()
+ # Nothing was persisted — the valid schema, listed first, was not committed.
+ assert valid_schema.sync_frequency_interval == valid_original
+ assert invalid_schema.sync_frequency_interval == invalid_original
+
+ @patch(
+ "products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",
+ return_value=False,
+ )
+ def test_bulk_update_schemas_fails_when_schedule_update_fails_after_save(self, _mock_workflow_exists):
+ # When a schema's row commits but its Temporal schedule update fails in the post-commit step,
+ # the request fails — the batch did not fully apply. The committed row stands (it can't be
+ # un-committed), and the failure is logged with the schema id.
+ source = self._create_external_data_source()
+ schema = ExternalDataSchema.objects.create(
+ name="Table0",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=True,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+
+ with (
+ patch(
+ "products.data_warehouse.backend.api.external_data_schema.sync_external_data_job_workflow",
+ side_effect=Exception("temporal unavailable"),
+ ),
+ patch("products.data_warehouse.backend.api.external_data_source.logger") as mock_logger,
+ ):
+ try:
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",
+ data={"schemas": [{"id": str(schema.id), "sync_frequency": "7day"}]},
+ format="json",
+ )
+ except Exception:
+ response = None
+
+ # The request did not succeed — it either raised or returned a server error.
+ assert response is None or response.status_code >= status.HTTP_500_INTERNAL_SERVER_ERROR
+ # The per-schema commit happened before the schedule update, so the row is still persisted...
+ schema.refresh_from_db()
+ assert sync_frequency_interval_to_sync_frequency(schema.sync_frequency_interval) == "7day"
+ # ...and the failure was logged with the schema id.
+ assert any(call.kwargs.get("schema_id") == str(schema.id) for call in mock_logger.warning.call_args_list)
+
@patch(
"products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",
return_value=False,