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 webhook sync for tables that don't support it (#124202)

Daniel Snitkovskiy83f03b2f3e0b
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 bebd98e8810c..9685c0632e95 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -1140,6 +1140,13 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
"It requires a Postgres heap table or materialized view on PostgreSQL 13+."
)
+ # A webhook-mode table that no webhook event feeds never receives a row (e.g. Stripe
+ # BalanceTransaction), so a request must not move a table into that state.
+ if self._webhook_support_check_applies():
+ webhook_support_error = self._webhook_support_error_cached(instance)
+ if webhook_support_error is not None:
+ raise ValidationError(webhook_support_error)
+
# 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 self._webhook_only_check_applies():
@@ -1768,18 +1775,56 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
return False
return any(s.name == schema.name and s.supports_xmin for s in source_schemas)
+ def _webhook_support_error(self, schema: ExternalDataSchema) -> str | None:
+ """Why this table can't move to webhook sync, or None when the source advertises webhook
+ support for it. Runs discovery so a raw PATCH can't move a table that no webhook event feeds
+ into webhook sync."""
+ unsupported = f"{schema.name} doesn't support webhook sync. Pick another sync method."
+ source = schema.source
+ try:
+ source_inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
+ return f"Couldn't check whether {schema.name} supports webhook sync. {UNREADABLE_SOURCE_CONFIG_ERROR}"
+ if not source_inputs:
+ return unsupported
+ try:
+ source_impl = SourceRegistry.get_source(ExternalDataSourceType(source.source_type))
+ except Exception:
+ return unsupported
+ if not isinstance(source_impl, WebhookSource):
+ return unsupported
+ try:
+ config = source_impl.parse_config(source_inputs)
+ source_schemas = source_impl.get_schemas(
+ config,
+ schema.team_id,
+ names=[schema.name],
+ api_version=source_impl.resolve_api_version(self._effective_probe_api_version(schema, source_impl)),
+ )
+ except Exception as e:
+ message, is_expected_source_error = source_helpers._classify_refresh_schemas_error(source_impl, e)
+ if not is_expected_source_error:
+ capture_exception(e, {"source_type": source.source_type, "schema_id": str(schema.id)})
+ return f"Couldn't check whether {schema.name} supports webhook sync. {message} Try again."
+ if any(s.name == schema.name and s.supports_webhooks for s in source_schemas):
+ return None
+ return unsupported
+
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.
+ """Pre-run the webhook validations that reach the external source, caching the results.
+
+ `_is_webhook_only_schema` and `_webhook_support_error` call the source's `get_schemas`,
+ which is a network round-trip (e.g. Google Ads OAuth refresh + field query). update() runs these
+ same checks, 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 results 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)
+ if self._webhook_support_check_applies():
+ self._webhook_support_error_cached(instance)
def seed_webhook_only_check(self, webhook_only: bool) -> None:
"""Pre-fill the webhook-only cache when the caller already discovered this table (e.g.
@@ -1798,6 +1843,21 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
self.__dict__["_webhook_only_result"] = self._is_webhook_only_schema(schema)
return self.__dict__["_webhook_only_result"]
+ def _webhook_support_check_applies(self) -> bool:
+ # The frontend re-sends the current sync_type on every save. Checking only a change keeps an
+ # unrelated edit (e.g. pausing the table) working when the lookup fails on expired credentials.
+ data = self.initial_data if isinstance(self.initial_data, dict) else {}
+ return (
+ data.get("sync_type") == ExternalDataSchema.SyncType.WEBHOOK
+ and self.instance is not None
+ and self.instance.sync_type != ExternalDataSchema.SyncType.WEBHOOK
+ )
+
+ def _webhook_support_error_cached(self, schema: ExternalDataSchema) -> str | None:
+ if "_webhook_support_error_result" not in self.__dict__:
+ self.__dict__["_webhook_support_error_result"] = self._webhook_support_error(schema)
+ return self.__dict__["_webhook_support_error_result"]
+
def _maybe_create_webhook(self, schema: ExternalDataSchema) -> None:
source = schema.source
source_inputs = SourceInputsStore.load(source)
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
index 7fff1742b50a..90af331516ca 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
@@ -623,7 +623,7 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
# Defaults discovery already confirmed these tables aren't webhook-only; seed the
# cache so the warm step below doesn't re-probe the source once per schema.
schema_serializer.seed_webhook_only_check(False)
- # Do the webhook-only source-discovery call (e.g. Google Ads token refresh + field query)
+ # Do the webhook source-discovery calls (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.
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
index 2daed80ec0fc..e7bff27d61f4 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
@@ -1372,6 +1372,25 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
},
)
+ # A webhook-mode table that no webhook event feeds never receives a row.
+ webhook_unsupported = sorted(
+ {
+ schema["name"]
+ for schema in payload_schemas
+ if schema.get("sync_type") == ExternalDataSchema.SyncType.WEBHOOK
+ and not source_schemas_by_name[schema["name"]].supports_webhooks
+ }
+ )
+ if webhook_unsupported:
+ new_source_model.delete()
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={
+ "message": f"Webhook sync isn't available for: {', '.join(webhook_unsupported)}. "
+ "Pick another sync method."
+ },
+ )
+
# Refuse per-schema `sync_type=cdc` when source-level CDC is off — `_setup_cdc_resources`
# would be skipped, leaving the source with no replication slot/publication.
if not cdc_enabled:
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 f70f4e4deb07..7b8059876bd5 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
@@ -2111,7 +2111,7 @@ class TestExternalDataSchema(APIBaseTest):
)
table = DataWarehouseTable.objects.create(team=self.team)
schema = ExternalDataSchema.objects.create(
- name="BalanceTransaction",
+ name="Charge",
team=self.team,
source=source,
should_sync=True,
@@ -2618,7 +2618,7 @@ class TestExternalDataSchema(APIBaseTest):
assert response.status_code == 200
mock_get_or_create.assert_not_called()
- def test_update_schema_to_webhook_non_webhook_source_no_webhook_result(self):
+ def test_update_schema_to_webhook_non_webhook_source_rejected(self):
source = ExternalDataSource.objects.create(
team=self.team,
source_type=ExternalDataSourceType.POSTGRES,
@@ -2655,48 +2655,103 @@ class TestExternalDataSchema(APIBaseTest):
data={"sync_type": "webhook", "incremental_field": "id", "incremental_field_type": "integer"},
)
- assert response.status_code == 200
+ assert response.status_code == 400
mock_get_or_create.assert_not_called()
+ schema.refresh_from_db()
+ assert schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH
- def test_update_schema_to_webhook_non_webhook_schema_no_webhook_result(self):
+ @parameterized.expand(
+ [
+ (
+ "no_webhook_support",
+ "BalanceTransaction",
+ ExternalDataSchema.SyncType.FULL_REFRESH,
+ 400,
+ ExternalDataSchema.SyncType.FULL_REFRESH,
+ ),
+ (
+ "no_webhook_support_already_webhook",
+ "BalanceTransaction",
+ ExternalDataSchema.SyncType.WEBHOOK,
+ 200,
+ ExternalDataSchema.SyncType.WEBHOOK,
+ ),
+ (
+ "webhook_support",
+ "Charge",
+ ExternalDataSchema.SyncType.FULL_REFRESH,
+ 200,
+ ExternalDataSchema.SyncType.WEBHOOK,
+ ),
+ ]
+ )
+ def test_update_schema_to_webhook_requires_webhook_support(
+ self, _name, schema_name, from_sync_type, expected_status, expected_sync_type
+ ):
source = ExternalDataSource.objects.create(
- team=self.team, source_type=ExternalDataSourceType.STRIPE, job_inputs={"stripe_secret_key": "test_key"}
+ team=self.team,
+ source_type=ExternalDataSourceType.STRIPE,
+ job_inputs={"auth_method": {"selection": "api_key", "stripe_secret_key": "123"}},
)
schema = ExternalDataSchema.objects.create(
- name="CustomerBalanceTransaction",
+ name=schema_name,
team=self.team,
source=source,
should_sync=True,
status=ExternalDataSchema.Status.COMPLETED,
- sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ sync_type=from_sync_type,
)
- mock_non_webhook_schemas = [
- SourceSchema(
- name="CustomerBalanceTransaction",
- supports_incremental=False,
- supports_append=False,
- supports_webhooks=False,
- ),
- ]
+ mock_hog_fn_result = WebhookHogFunctionCreateResult(
+ hog_function_id=str(uuid.uuid4()),
+ webhook_url="https://test.com/webhook",
+ hog_function_created=False,
+ )
with (
mock.patch(
"products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",
return_value=False,
),
- mock.patch.object(StripeSource, "get_schemas", return_value=mock_non_webhook_schemas),
mock.patch(
- "products.warehouse_sources.backend.presentation.views.external_data_schema.get_or_create_webhook_hog_function"
- ) as mock_get_or_create,
+ "products.warehouse_sources.backend.presentation.views.external_data_schema.get_or_create_webhook_hog_function",
+ return_value=mock_hog_fn_result,
+ ),
):
response = self.client.patch(
f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",
data={"sync_type": "webhook", "incremental_field": "created", "incremental_field_type": "integer"},
)
- assert response.status_code == 200
- mock_get_or_create.assert_not_called()
+ assert response.status_code == expected_status, response.json()
+ schema.refresh_from_db()
+ assert schema.sync_type == expected_sync_type
+
+ def test_update_schema_to_webhook_reports_failed_lookup(self):
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type=ExternalDataSourceType.STRIPE,
+ job_inputs={"auth_method": {"selection": "api_key", "stripe_secret_key": "123"}},
+ )
+ schema = ExternalDataSchema.objects.create(
+ name="Charge",
+ team=self.team,
+ source=source,
+ should_sync=True,
+ status=ExternalDataSchema.Status.COMPLETED,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+
+ with mock.patch.object(StripeSource, "get_schemas", side_effect=TimeoutError("Read timed out")):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",
+ data={"sync_type": "webhook", "incremental_field": "created", "incremental_field_type": "integer"},
+ )
+
+ assert response.status_code == 400
+ assert "Couldn't check whether Charge supports webhook sync" in str(response.json())
+ schema.refresh_from_db()
+ assert schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH
class TestUpdateExternalDataSchema:
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index fe2a1502e69a..b5f7181fa9fc 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -927,6 +927,10 @@ class TestExternalDataSource(APIBaseTest):
[
("unknown_name", {"name": "SomeOtherSchema", "should_sync": True, "sync_type": "full_refresh"}),
("unknown_sync_type", {"name": STRIPE_CUSTOMER_RESOURCE_NAME, "should_sync": True, "sync_type": "full"}),
+ (
+ "webhook_without_webhook_support",
+ {"name": STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME, "should_sync": True, "sync_type": "webhook"},
+ ),
]
)
@patch(