: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): run webhook-only check before bulk update txn (#65493)
Kyle Swankd6db4fb3deef
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.pyindex 57842ba35efa..2568cc9c58d3 100644--- a/products/data_warehouse/backend/api/external_data_schema.py+++ b/products/data_warehouse/backend/api/external_data_schema.py@@ -559,8 +559,8 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):# Reject non-webhook sync types for webhook-only schemas (e.g. Stripe Discount —# no API list endpoint, so anything other than webhook produces an empty sync).- if "sync_type" in data and sync_type != ExternalDataSchema.SyncType.WEBHOOK:- if self._is_webhook_only_schema(instance):+ if self._webhook_only_check_applies():+ if self._is_webhook_only_schema_cached(instance):raise ValidationError(f"{instance.name} can only be synced via webhooks — pick the Webhook sync method.")@@ -936,6 +936,31 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):return Falsereturn any(s.name == schema.name and s.supports_xmin for s in source_schemas)+ def warm_webhook_only_check(self, instance: ExternalDataSchema) -> None:+ """Pre-run the webhook-only validation that reaches the external source, caching the result.++ `_is_webhook_only_schema` calls the source's `get_schemas`, which is a network round-trip (e.g.+ Google Ads OAuth refresh + field query). update() runs this same check, but bulk_update_schemas+ wraps each update() in a transaction — making the call there held the DB connection idle-in-+ transaction long enough for the server to close it ("the connection is closed"). Calling this+ first (outside the transaction) does the network work up front; update() then reads the cached+ result and still raises per-schema, so failures stay isolated to one schema.+ """+ if self._webhook_only_check_applies():+ self._is_webhook_only_schema_cached(instance)++ def _webhook_only_check_applies(self) -> bool:+ # Single source of truth for when the webhook-only check runs, so update() and the+ # pre-transaction warm step can't drift apart and push the network call back into the+ # transaction. Reads `initial_data` (the raw request payload), like update() does.+ data = self.initial_data if isinstance(self.initial_data, dict) else {}+ return "sync_type" in data and data.get("sync_type") != ExternalDataSchema.SyncType.WEBHOOK++ def _is_webhook_only_schema_cached(self, schema: ExternalDataSchema) -> bool:+ if "_webhook_only_result" not in self.__dict__:+ self.__dict__["_webhook_only_result"] = self._is_webhook_only_schema(schema)+ return self.__dict__["_webhook_only_result"]+def _maybe_create_webhook(self, schema: ExternalDataSchema) -> None:source = schema.sourceif not source.job_inputs:diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex b4d8f667ca12..4e0872a52c20 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -3598,6 +3598,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixicontext={**serializer_context, "post_commit_actions": schema_post_commit_actions},)schema_serializer.is_valid(raise_exception=True)+ # Do the webhook-only source-discovery call (e.g. Google Ads token refresh + field query)+ # here, before the per-schema transaction below. Running it inside update()'s transaction+ # held the DB connection idle-in-transaction long enough for the server to close it.+ # update() reads the cached result, so it still validates and fails per-schema.+ schema_serializer.warm_webhook_only_check(schema)prepared.append((schema, schema_serializer, schema_post_commit_actions))# Commit each schema in its own transaction. A single atomic block around the whole batchdiff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex 59e1e3e9e5a6..fbde68b50d70 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@@ -9,6 +9,7 @@ from posthog.test.base import APIBaseTest, FuzzyIntfrom unittest.mock import MagicMock, Mock, PropertyMock, patchfrom django.conf import settings+from django.db import connectionfrom django.test import override_settingsfrom django.utils import timezone@@ -60,6 +61,7 @@ from posthog.temporal.data_imports.sources.stripe.constants import (from posthog.temporal.data_imports.sources.stripe.settings import ENDPOINTS as STRIPE_ENDPOINTSfrom products.data_tools.backend.models.join import DataWarehouseJoin+from products.data_warehouse.backend.api.external_data_schema import ExternalDataSchemaSerializerfrom products.data_warehouse.backend.api.external_data_source import (get_nonsensitive_and_sensitive_field_names,strip_sensitive_from_dict,@@ -499,6 +501,47 @@ 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+ @patch(+ "products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",+ return_value=False,+ )+ def test_bulk_update_schemas_runs_source_discovery_outside_transaction(self, _mock_workflow_exists):+ # `_is_webhook_only_schema` reaches the external source (e.g. Google Ads token refresh + field+ # query). It must run before the per-schema transaction opens — running it inside update()'s+ # transaction held the DB connection idle-in-transaction long enough for the server to close it.++ source = self._create_external_data_source()+ schema = ExternalDataSchema.objects.create(+ name="Customers",+ team_id=self.team.pk,+ source=source,+ should_sync=False,+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ )++ # The bulk loop opens a per-schema transaction (a nested savepoint) around update(). Compare the+ # savepoint depth at call time against the baseline before the request: equal ⇒ called from the+ # pre-transaction warm step (the fix); baseline + 1 ⇒ called inside update()'s transaction.+ baseline_savepoint_depth = len(connection.savepoint_ids)+ savepoint_depth_at_call: list[int] = []++ def record_savepoint_depth(_schema):+ savepoint_depth_at_call.append(len(connection.savepoint_ids))+ return False++ with patch.object(ExternalDataSchemaSerializer, "_is_webhook_only_schema", side_effect=record_savepoint_depth):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",+ data={"schemas": [{"id": str(schema.id), "should_sync": True, "sync_type": "full_refresh"}]},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ # Called exactly once (memoized across warm + update), outside the per-schema transaction.+ assert savepoint_depth_at_call == [baseline_savepoint_depth]+ schema.refresh_from_db()+ assert schema.should_sync is True+@parameterized.expand([(