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.

feat(data-warehouse): sync webhook events when schemas are enabled (#61481)

Daniel RC1f1c4b8618ae
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index ba329d31f8d3..8baa15a21d32 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5925,6 +5925,8 @@ export interface WebhookInfo {
schema_mapping?: Record<string, string>
inputs?: Record<string, WebhookInputValue>
external_status?: WebhookExternalStatus | null
+ // Desired provider events not yet on the webhook (manual setup, or created before a new table).
+ missing_events?: string[]
}
export interface DataModelingJob {
diff --git a/posthog/temporal/data_imports/sources/common/base.py b/posthog/temporal/data_imports/sources/common/base.py
index 10a3d3a693d8..7c3ac8b28a12 100644
--- a/posthog/temporal/data_imports/sources/common/base.py
+++ b/posthog/temporal/data_imports/sources/common/base.py
@@ -166,6 +166,15 @@ class WebhookCreationResult:
pending_inputs: list[str] = dataclasses.field(default_factory=list)
+class WebhookSyncResult:
+ """Outcome of reconciling an existing webhook's events — success plus an optional actionable
+ message. Distinct from WebhookCreationResult, which also carries create-only fields."""
+
+ success: bool
+ error: str | None = None
+
+
@dataclasses.dataclass
class WebhookDeletionResult:
success: bool
@@ -205,6 +214,22 @@ class WebhookSource(_BaseSource[ConfigType], Generic[ConfigType]):
"""
raise NotImplementedError()
+ def get_desired_webhook_events(self, config: ConfigType, eligible_schema_names: list[str]) -> list[str] | None:
+ """Events the webhook should subscribe to. ``None`` when the source has no
+ provider-side subscription to drift (e.g. Slack); such sources skip reconciliation."""
+ return None
+
+ def sync_webhook_events(
+ self,
+ config: ConfigType,
+ webhook_url: str,
+ team_id: int,
+ eligible_schema_names: list[str],
+ ) -> WebhookSyncResult:
+ """Reconcile the provider's subscribed events with the selected schemas. No-op default
+ for sources without a provider-side subscription; override where one exists (Stripe)."""
+ return WebhookSyncResult(success=True)
+
def webhook_inputs_updated(
self, config: ConfigType, webhook_url: str, team_id: int, inputs: dict[str, Any]
) -> tuple[bool, str | None]:
diff --git a/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py b/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py
index 76e0a43e83fc..4e428f374d4a 100644
--- a/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py
+++ b/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py
@@ -187,6 +187,23 @@ class TestRevenueCatSourceDeleteWebhook:
mock_delete.assert_called_once_with("k", "p", "https://example.com/h")
+class TestRevenueCatSourceSyncWebhookEvents:
+ """RevenueCat has no provider-side event subscription to reconcile — it inherits the
+ `WebhookSource` defaults, which are a no-op."""
+
+ def test_get_desired_webhook_events_is_none(self):
+ source = RevenueCatSource()
+ assert source.get_desired_webhook_events(_config("k", "p"), ["events"]) is None
+
+ def test_sync_webhook_events_is_noop_success(self):
+ source = RevenueCatSource()
+ result = source.sync_webhook_events(
+ _config("k", "p"), "https://example.com/h", team_id=1, eligible_schema_names=["events"]
+ )
+ assert result.success is True
+ assert result.error is None
+
+
class TestRevenueCatSourceExternalWebhookInfo:
@patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.get_external_webhook_info")
def test_delegates_to_api_client(self, mock_info):
diff --git a/posthog/temporal/data_imports/sources/slack/tests/test_slack_source.py b/posthog/temporal/data_imports/sources/slack/tests/test_slack_source.py
new file mode 100644
index 000000000000..9ddab8d26876
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/slack/tests/test_slack_source.py
@@ -0,0 +1,21 @@
+from unittest.mock import MagicMock
+
+from posthog.temporal.data_imports.sources.common.base import WebhookSource
+from posthog.temporal.data_imports.sources.slack.source import SlackSource
+
+
+class TestSlackSourceWebhookEventSync:
+ def test_does_not_override_reconcile_hooks(self):
+ # Slack configures webhooks manually — inheriting the base no-ops keeps reconcile away from it.
+ assert SlackSource.sync_webhook_events is WebhookSource.sync_webhook_events
+ assert SlackSource.get_desired_webhook_events is WebhookSource.get_desired_webhook_events
+
+ def test_get_desired_webhook_events_is_none(self):
+ assert SlackSource().get_desired_webhook_events(MagicMock(), ["messages"]) is None
+
+ def test_sync_webhook_events_is_noop_success(self):
+ result = SlackSource().sync_webhook_events(
+ MagicMock(), "https://example.com/h", team_id=1, eligible_schema_names=["messages"]
+ )
+ assert result.success is True
+ assert result.error is None
diff --git a/posthog/temporal/data_imports/sources/stripe/source.py b/posthog/temporal/data_imports/sources/stripe/source.py
index 7ed941dad3e4..151118ef5bd3 100644
--- a/posthog/temporal/data_imports/sources/stripe/source.py
+++ b/posthog/temporal/data_imports/sources/stripe/source.py
@@ -26,6 +26,7 @@ from posthog.temporal.data_imports.sources.common.base import (
WebhookCreationResult,
WebhookDeletionResult,
WebhookSource,
+ WebhookSyncResult,
)
from posthog.temporal.data_imports.sources.common.mixins import OAuthMixin
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
@@ -50,11 +51,13 @@ from posthog.temporal.data_imports.sources.stripe.stripe import (
StripePermissionError,
StripeResumeConfig,
StripeValidationError,
+ _all_known_webhook_events,
check_endpoint_permissions as check_stripe_endpoint_permissions,
create_webhook,
delete_webhook,
get_external_webhook_info,
stripe_source,
+ update_webhook_events,
validate_credentials as validate_stripe_credentials,
)
@@ -372,6 +375,24 @@ If automatic creation failed due to a permissions error and you're using a restr
api_key = self._get_api_key(config, team_id)
return create_webhook(api_key, config.stripe_account_id, webhook_url)
+ def get_desired_webhook_events(
+ self, config: StripeSourceConfig, eligible_schema_names: list[str]
+ ) -> list[str] | None:
+ # Every mappable event, not just the selected tables — auto-heals webhooks created
+ # before RESOURCE_TO_STRIPE_WEBHOOK_EVENT gained new resources.
+ return _all_known_webhook_events()
+
+ def sync_webhook_events(
+ self,
+ config: StripeSourceConfig,
+ webhook_url: str,
+ team_id: int,
+ eligible_schema_names: list[str],
+ ) -> WebhookSyncResult:
+ api_key = self._get_api_key(config, team_id)
+ desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []
+ return update_webhook_events(api_key, config.stripe_account_id, webhook_url, desired_events)
+
def get_external_webhook_info(
self, config: StripeSourceConfig, webhook_url: str, team_id: int
) -> ExternalWebhookInfo:
diff --git a/posthog/temporal/data_imports/sources/stripe/stripe.py b/posthog/temporal/data_imports/sources/stripe/stripe.py
index bb11c56f34a6..53f43d2563ea 100644
--- a/posthog/temporal/data_imports/sources/stripe/stripe.py
+++ b/posthog/temporal/data_imports/sources/stripe/stripe.py
@@ -21,6 +21,7 @@ from posthog.temporal.data_imports.sources.common.base import (
ExternalWebhookInfo,
WebhookCreationResult,
WebhookDeletionResult,
+ WebhookSyncResult,
)
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -545,16 +546,22 @@ def check_endpoint_permissions(
return results
-def create_webhook(api_key: str, stripe_account_id: str | None, webhook_url: str) -> WebhookCreationResult:
- logger = LOGGER.bind()
-
+def _all_known_webhook_events() -> list[str]:
+ """Every Stripe event whose prefix appears in RESOURCE_TO_STRIPE_WEBHOOK_EVENT.
+ Re-deriving on each reconcile is what auto-heals webhooks created before the map grew."""
hints = get_type_hints(WebhookEndpointService.CreateParams, include_extras=True)
enabled_events_type = hints["enabled_events"]
list_inner = get_args(enabled_events_type)[0]
possible_event_values: tuple[str] = get_args(list_inner)
prefixes_set = set(RESOURCE_TO_STRIPE_WEBHOOK_EVENT.values())
- filtered_events = [e for e in possible_event_values if any(e.startswith(f"{p}.") for p in prefixes_set)]
+ return [e for e in possible_event_values if any(e.startswith(f"{p}.") for p in prefixes_set)]
+
+
+def create_webhook(api_key: str, stripe_account_id: str | None, webhook_url: str) -> WebhookCreationResult:
+ logger = LOGGER.bind()
+
+ filtered_events = _all_known_webhook_events()
if not filtered_events:
return WebhookCreationResult(
@@ -638,6 +645,64 @@ def delete_webhook(api_key: str, stripe_account_id: str | None, webhook_url: str
return WebhookDeletionResult(success=False, error=f"Failed to delete webhook: {error_str}")
+def update_webhook_events(
+ api_key: str, stripe_account_id: str | None, webhook_url: str, desired_events: list[str]
+) -> WebhookSyncResult:
+ """Add `desired_events` to the matching Stripe endpoint, writing only on drift.
+ A 403 (missing webhook write scope) returns a failure result rather than raising, so
+ callers can enable the table and warn instead of hard-failing."""
+ logger = LOGGER.bind()
+
+ if not desired_events:
+ return WebhookSyncResult(success=True)
+
+ try:
+ client = StripeClient(
+ api_key,
+ stripe_account=stripe_account_id,
+ stripe_version="2024-09-30.acacia",
+ max_network_retries=2,
+ base_addresses=_stripe_base_addresses(),
+ http_client=_tracked_stripe_http_client(),
+ )
+
+ endpoints = client.webhook_endpoints.list(params={"limit": 100})
+
+ for endpoint in endpoints.auto_paging_iter():
+ if endpoint.url != webhook_url:
+ continue
+
+ current = set(endpoint.enabled_events or [])
+ # "*" already covers everything.
+ if "*" in current:
+ return WebhookSyncResult(success=True)
+
+ missing = [e for e in desired_events if e not in current]
+ if not missing:
+ return WebhookSyncResult(success=True)
+
+ # Merge, don't replace — never drop events the user added themselves.
+ merged = sorted(current | set(desired_events))
+ client.webhook_endpoints.update(endpoint.id, params={"enabled_events": merged}) # type: ignore
+ return WebhookSyncResult(success=True)
+
+ # No matching endpoint — nothing to reconcile (creation is handled elsewhere).
+ return WebhookSyncResult(success=True)
+ except stripe_lib.PermissionError as e:
+ logger.warning("No permission to update Stripe webhook events", error=str(e))
+ return WebhookSyncResult(
+ success=False,
+ error=(
+ "Your Stripe API key doesn't have permission to update webhooks. Add the 'Write' permission "
+ f"for 'Webhook endpoints' to your API key, or add these events manually: {', '.join(desired_events)}"
+ ),
+ )
+ except Exception as e:
+ error_str = _clean_stripe_error_message(str(e))
+ logger.warning("Failed to update Stripe webhook events", error=error_str)
+ return WebhookSyncResult(success=False, error=f"Failed to update webhook events automatically: {error_str}")
+
+
def get_external_webhook_info(api_key: str, stripe_account_id: str | None, webhook_url: str) -> ExternalWebhookInfo:
try:
client = StripeClient(
diff --git a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py
index de1b4720268b..c6154ab136bd 100644
--- a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py
+++ b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py
@@ -5,6 +5,7 @@ import pytest
from unittest import mock
import stripe as stripe_lib
+from parameterized import parameterized
from stripe._http_client import HTTPClient
from posthog.models.integration import Integration
@@ -838,3 +839,146 @@ class TestGetEndpointPermissions:
# Generic message — never leak the raw exception body to the UI.
assert result == {"Customer": "Stripe credentials are not available"}
assert "secret123" not in result["Customer"]
+
+
+class TestUpdateWebhookEvents:
+ """`update_webhook_events` reconciles a Stripe endpoint's enabled_events with the desired set."""
+
+ WEBHOOK_URL = "https://webhooks.us.posthog.com/public/webhooks/dwh/123"
+
+ def _mock_client_with_endpoint(self, *, url, enabled_events):
+ endpoint = mock.MagicMock()
+ endpoint.id = "we_123"
+ endpoint.url = url
+ endpoint.enabled_events = enabled_events
+
+ mock_client = mock.MagicMock()
+ mock_client.webhook_endpoints.list.return_value.auto_paging_iter.return_value = [endpoint]
+ return mock_client, endpoint
+
+ def test_drift_calls_update_with_merged_set(self):
+ from posthog.temporal.data_imports.sources.stripe.stripe import update_webhook_events
+
+ mock_client, endpoint = self._mock_client_with_endpoint(
+ url=self.WEBHOOK_URL, enabled_events=["charge.captured"]
+ )
+
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
+ result = update_webhook_events("rk_test", None, self.WEBHOOK_URL, ["charge.captured", "customer.created"])
+
+ assert result.success
+ mock_client.webhook_endpoints.update.assert_called_once()
+ args, kwargs = mock_client.webhook_endpoints.update.call_args
+ # Stripe SDK signature is update(endpoint_id, params={...}) — endpoint id positional,
+ # events nested under `params`. Asserting this exact shape guards against passing
+ # enabled_events as a bare kwarg (a silent TypeError that never actually updates).
+ assert args[0] == "we_123"
+ enabled = kwargs["params"]["enabled_events"]
+ assert "customer.created" in enabled
+ # Pre-existing events the user had are preserved.
+ assert "charge.captured" in enabled
+
+ @parameterized.expand(
+ [
+ # endpoint already carries everything desired
+ ("already in sync", WEBHOOK_URL, ["charge.captured", "customer.created"]),
+ # endpoint listens to all events
+ ("wildcard endpoint", WEBHOOK_URL, ["*"]),
+ # no endpoint matches our url
+ ("no matching endpoint", "https://other.example.com", ["charge.captured"]),
+ ]
+ )
+ def test_does_not_write_when_no_drift(self, _name, endpoint_url, enabled_events):
+ from posthog.temporal.data_imports.sources.stripe.stripe import update_webhook_events
+
+ mock_client, _ = self._mock_client_with_endpoint(url=endpoint_url, enabled_events=enabled_events)
+
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
+ result = update_webhook_events("rk_test", None, self.WEBHOOK_URL, ["charge.captured", "customer.created"])
+
+ assert result.success
+ mock_client.webhook_endpoints.update.assert_not_called()
+
+ def test_permission_error_returns_actionable_failure_without_raising(self):
+ from posthog.temporal.data_imports.sources.stripe.stripe import update_webhook_events
+
+ mock_client, _ = self._mock_client_with_endpoint(url=self.WEBHOOK_URL, enabled_events=["charge.captured"])
+ mock_client.webhook_endpoints.update.side_effect = stripe_lib.PermissionError(message="Forbidden")
+
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
+ result = update_webhook_events("rk_test", None, self.WEBHOOK_URL, ["customer.created"])
+
+ assert result.success is False
+ assert result.error is not None
+ assert "Write" in result.error
+ assert "customer.created" in result.error
+
+ def test_empty_desired_is_noop(self):
+ from posthog.temporal.data_imports.sources.stripe.stripe import update_webhook_events
+
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient") as mock_client_cls:
+ result = update_webhook_events("rk_test", None, "https://x", [])
+
+ assert result.success
+ mock_client_cls.assert_not_called()
+
+
+class TestAllKnownWebhookEvents:
+ """Guards the event-derivation the create + reconcile paths both depend on."""
+
+ def test_only_emits_events_under_mapped_prefixes(self):
+ from posthog.temporal.data_imports.sources.stripe.constants import RESOURCE_TO_STRIPE_WEBHOOK_EVENT
+ from posthog.temporal.data_imports.sources.stripe.stripe import _all_known_webhook_events
+
+ events = _all_known_webhook_events()
+
+ assert len(events) > 0
+ # Never subscribe to an event outside a mapped prefix — that's noise we'd drop anyway.
+ prefixes = set(RESOURCE_TO_STRIPE_WEBHOOK_EVENT.values())
+ for event in events:
+ assert any(event.startswith(f"{p}.") for p in prefixes), f"unmapped event leaked in: {event}"
+
+ def test_includes_revenue_critical_resource_events(self):
+ from posthog.temporal.data_imports.sources.stripe.stripe import _all_known_webhook_events
+
+ events = set(_all_known_webhook_events())
+ # The resources Revenue analytics depends on must always be covered. Disputes ride in via
+ # `charge.dispute.*` (the `dispute` prefix itself yields nothing — events are charge-scoped).
+ for expected in ["charge.captured", "customer.created", "invoice.created", "customer.subscription.created"]:
+ assert expected in events, f"missing critical event: {expected}"
+ assert any(e.startswith("charge.dispute.") for e in events)
+
+
+class TestCreateWebhook:
+ def test_creates_endpoint_with_full_known_event_set(self):
+ from posthog.temporal.data_imports.sources.stripe.stripe import _all_known_webhook_events, create_webhook
+
+ endpoint = mock.MagicMock()
+ endpoint.secret = "whsec_abc"
+ mock_client = mock.MagicMock()
+ mock_client.webhook_endpoints.create.return_value = endpoint
+
+ url = "https://webhooks.us.posthog.com/public/webhooks/dwh/123"
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
+ result = create_webhook("rk_test", None, url)
+
+ assert result.success
+ assert result.extra_inputs == {"signing_secret": "whsec_abc"}
+ _, kwargs = mock_client.webhook_endpoints.create.call_args
+ params = kwargs["params"]
+ assert params["url"] == url
+ # Refactor guard: create must still register exactly the full known event set.
+ assert params["enabled_events"] == _all_known_webhook_events()
+
+ def test_permission_error_returns_actionable_failure(self):
+ from posthog.temporal.data_imports.sources.stripe.stripe import create_webhook
+
+ mock_client = mock.MagicMock()
+ mock_client.webhook_endpoints.create.side_effect = Exception("403 Forbidden")
+
+ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):
+ result = create_webhook("rk_test", None, "https://x")
+
+ assert result.success is False
+ assert result.error is not None
+ assert "permission" in result.error.lower()
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.py
index 168c18bd4795..d8d803a6fc7a 100644
--- a/products/data_warehouse/backend/api/external_data_schema.py
+++ b/products/data_warehouse/backend/api/external_data_schema.py
@@ -40,6 +40,7 @@ from products.data_warehouse.backend.direct_postgres import hide_direct_postgres
from products.data_warehouse.backend.external_data_source.webhooks import (
create_and_register_webhook,
get_or_create_webhook_hog_function,
+ reconcile_webhook_events,
)
from products.data_warehouse.backend.postgres_helpers import (
get_postgres_source_location,
@@ -747,6 +748,31 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
f"Failed to register webhook on your source: {result.error or 'Unknown error'}. "
"You can set up the webhook manually from the Webhook tab."
)
+ else:
+ # Deferred to keep the provider call out of the surrounding transaction.
+ # Fully non-fatal: the table is already enabled by the time this runs, so any
+ # failure (bad creds, provider 403, network) must never propagate — it would
+ # otherwise 500 the post-commit hook on the bulk path, or roll back the enable
+ # on the single-update path. Data still flows once the user fixes provider events.
+ def reconcile() -> None:
+ try:
+ reconcile_result = reconcile_webhook_events(
+ source_impl, config, hog_fn_result, schema.team_id, [schema.name]
+ )
+ if not reconcile_result.success:
+ logger.warning(
+ "Failed to reconcile webhook events on schema enable",
+ error=reconcile_result.error,
+ schema_id=str(schema.id),
+ )
+ except Exception as e:
+ logger.warning(
+ "Error reconciling webhook events on schema enable",
+ error=str(e),
+ schema_id=str(schema.id),
+ )
+
+ self._run_temporal_side_effect(reconcile)
except ValidationError:
raise
except Exception as e:
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index d0db0d228b35..4e623c598383 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -2497,6 +2497,39 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
source_serializer = self.get_serializer(external_data_source, context=self.get_serializer_context())
return Response(source_serializer.data)
+ def _compute_missing_webhook_events(
+ self,
+ source: WebhookSource,
+ config: Any,
+ instance: ExternalDataSource,
+ external_status: ExternalWebhookInfo | None,
+ ) -> list[str]:
+ """Desired events not yet on the provider webhook — surfaced so manual-webhook users
+ (or keys lacking webhook-write scope) know what to add."""
+ if not external_status or not external_status.exists or external_status.error:
+ return []
+
+ eligible_schema_names = list(
+ ExternalDataSchema.objects.filter(
+ source=instance,
+ team_id=self.team_id,
+ sync_type=ExternalDataSchema.SyncType.WEBHOOK,
+ should_sync=True,
+ )
+ .exclude(deleted=True)
+ .values_list("name", flat=True)
+ )
+
+ desired = source.get_desired_webhook_events(config, eligible_schema_names)
+ if not desired:
+ return []
+
+ current = set(external_status.enabled_events or [])
+ if "*" in current:
+ return []
+
+ return sorted(e for e in desired if e not in current)
+
@action(methods=["GET"], detail=True)
def webhook_info(self, request: Request, *args: Any, **kwargs: Any) -> Response:
instance: ExternalDataSource = self.get_object()
@@ -2531,11 +2564,13 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
webhook_url = get_webhook_url(hog_function.id)
external_status: ExternalWebhookInfo | None = None
+ missing_events: list[str] = []
if instance.job_inputs:
try:
config = source.parse_config(instance.job_inputs)
external_status = source.get_external_webhook_info(config, webhook_url, self.team_id)
+ missing_events = self._compute_missing_webhook_events(source, config, instance, external_status)
except Exception as e:
capture_exception(e)
@@ -2563,6 +2598,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"schema_mapping": schema_mapping,
"inputs": webhook_inputs,
"external_status": dataclasses.asdict(external_status) if external_status else None,
+ "missing_events": missing_events,
},
)
diff --git a/products/data_warehouse/backend/api/test/test_external_data_schema.py b/products/data_warehouse/backend/api/test/test_external_data_schema.py
index 2258f9dde7ce..8ff615a0e89f 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_schema.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_schema.py
@@ -22,7 +22,7 @@ from posthog.api.test.test_user import create_user
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.utils import generate_random_token_personal
from posthog.temporal.common.schedule import describe_schedule
-from posthog.temporal.data_imports.sources.common.base import WebhookCreationResult
+from posthog.temporal.data_imports.sources.common.base import WebhookCreationResult, WebhookSyncResult
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.stripe.source import StripeSource
@@ -908,6 +908,158 @@ class TestExternalDataSchema(APIBaseTest):
mock_get_or_create.assert_called_once()
mock_create_webhook.assert_called_once()
+ def test_update_schema_to_webhook_existing_function_reconciles_events(self):
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_type=ExternalDataSourceType.STRIPE, job_inputs={"stripe_secret_key": "test_key"}
+ )
+ schema = ExternalDataSchema.objects.create(
+ name="Charge",
+ team=self.team,
+ source=source,
+ should_sync=True,
+ status=ExternalDataSchema.Status.COMPLETED,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+
+ mock_hog_function = mock.MagicMock()
+ mock_hog_function.id = uuid.uuid4()
+ mock_hog_function.inputs = {"schema_mapping": {"value": {}}, "source_id": {"value": "test-source-id"}}
+ # hog_function_created=False → existing webhook, so the reconcile path (not create) runs.
+ mock_hog_fn_result = WebhookHogFunctionCreateResult(
+ hog_function=mock_hog_function,
+ webhook_url="https://test.com/webhook",
+ hog_function_created=False,
+ )
+ mock_webhook_schemas = [
+ SourceSchema(name="Charge", supports_incremental=True, supports_append=True, supports_webhooks=True),
+ ]
+
+ with (
+ mock.patch(
+ "products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",
+ return_value=False,
+ ),
+ mock.patch(
+ "products.data_warehouse.backend.api.external_data_schema.get_or_create_webhook_hog_function",
+ return_value=mock_hog_fn_result,
+ ),
+ mock.patch.object(
+ StripeSource, "create_webhook", return_value=WebhookCreationResult(success=True)
+ ) as mock_create_webhook,
+ mock.patch.object(
+ StripeSource, "sync_webhook_events", return_value=WebhookSyncResult(success=True)
+ ) as mock_sync_events,
+ mock.patch.object(StripeSource, "get_schemas", return_value=mock_webhook_schemas),
+ ):
+ 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
+ # Existing webhook: reconcile events, never re-create.
+ mock_sync_events.assert_called_once()
+ mock_create_webhook.assert_not_called()
+
+ def test_update_schema_to_webhook_existing_function_reconcile_failure_does_not_block(self):
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_type=ExternalDataSourceType.STRIPE, job_inputs={"stripe_secret_key": "test_key"}
+ )
+ schema = ExternalDataSchema.objects.create(
+ name="Charge",
+ team=self.team,
+ source=source,
+ should_sync=True,
+ status=ExternalDataSchema.Status.COMPLETED,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+
+ mock_hog_function = mock.MagicMock()
+ mock_hog_function.id = uuid.uuid4()
+ mock_hog_function.inputs = {"schema_mapping": {"value": {}}, "source_id": {"value": "test-source-id"}}
+ mock_hog_fn_result = WebhookHogFunctionCreateResult(
+ hog_function=mock_hog_function,
+ webhook_url="https://test.com/webhook",
+ hog_function_created=False,
+ )
+ mock_webhook_schemas = [
+ SourceSchema(name="Charge", supports_incremental=True, supports_append=True, supports_webhooks=True),
+ ]
+
+ with (
+ mock.patch(
+ "products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",
+ return_value=False,
+ ),
+ mock.patch(
+ "products.data_warehouse.backend.api.external_data_schema.get_or_create_webhook_hog_function",
+ return_value=mock_hog_fn_result,
+ ),
+ mock.patch.object(
+ StripeSource,
+ "sync_webhook_events",
+ return_value=WebhookSyncResult(success=False, error="add Write permission"),
+ ),
+ mock.patch.object(StripeSource, "get_schemas", return_value=mock_webhook_schemas),
+ ):
+ 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"},
+ )
+
+ # Reconcile failure must not hard-fail the schema enable.
+ assert response.status_code == 200
+ schema.refresh_from_db()
+ assert schema.sync_type == ExternalDataSchema.SyncType.WEBHOOK
+
+ def test_update_schema_to_webhook_reconcile_raising_does_not_block(self):
+ # The dangerous case: sync_webhook_events RAISES (bad creds, OAuth expired, network)
+ # before any internal handling. This must never roll back the schema enable.
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_type=ExternalDataSourceType.STRIPE, job_inputs={"stripe_secret_key": "test_key"}
+ )
+ schema = ExternalDataSchema.objects.create(
+ name="Charge",
+ team=self.team,
+ source=source,
+ should_sync=True,
+ status=ExternalDataSchema.Status.COMPLETED,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+
+ mock_hog_function = mock.MagicMock()
+ mock_hog_function.id = uuid.uuid4()
+ mock_hog_function.inputs = {"schema_mapping": {"value": {}}, "source_id": {"value": "test-source-id"}}
+ mock_hog_fn_result = WebhookHogFunctionCreateResult(
+ hog_function=mock_hog_function,
+ webhook_url="https://test.com/webhook",
+ hog_function_created=False,
+ )
+ mock_webhook_schemas = [
+ SourceSchema(name="Charge", supports_incremental=True, supports_append=True, supports_webhooks=True),
+ ]
+
+ with (
+ mock.patch(
+ "products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",
+ return_value=False,
+ ),
+ mock.patch(
+ "products.data_warehouse.backend.api.external_data_schema.get_or_create_webhook_hog_function",
+ return_value=mock_hog_fn_result,
+ ),
+ mock.patch.object(StripeSource, "sync_webhook_events", side_effect=ValueError("Missing Stripe API key")),
+ mock.patch.object(StripeSource, "get_schemas", return_value=mock_webhook_schemas),
+ ):
+ 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
+ schema.refresh_from_db()
+ assert schema.sync_type == ExternalDataSchema.SyncType.WEBHOOK
+
def test_update_schema_to_incremental_does_not_trigger_webhook(self):
source = ExternalDataSource.objects.create(
team=self.team, source_type=ExternalDataSourceType.STRIPE, job_inputs={"stripe_secret_key": "test_key"}
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 08f4efa5a19d..5c1702a94e00 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
@@ -448,6 +448,77 @@ 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_webhook_reconcile_raising_does_not_500(self, _mock_workflow_exists):
+ # Webhook reconcile runs as a deferred post-commit hook in the bulk path, AFTER the
+ # atomic block. If it raised there it would 500 the request with the rows already
+ # committed. Guard that a raising reconcile is swallowed and the response stays 200.
+ from posthog.temporal.data_imports.sources.common.base import WebhookCreationResult
+ from posthog.temporal.data_imports.sources.common.schema import SourceSchema as _SourceSchema
+
+ from products.data_warehouse.backend.external_data_source.webhooks import WebhookHogFunctionCreateResult
+
+ source = self._create_external_data_source()
+ schema = ExternalDataSchema.objects.create(
+ name="Charge",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=True,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ )
+
+ mock_hog_function = MagicMock()
+ mock_hog_function.id = uuid.uuid4()
+ mock_hog_function.inputs = {"schema_mapping": {"value": {}}, "source_id": {"value": "test-source-id"}}
+ mock_hog_fn_result = WebhookHogFunctionCreateResult(
+ hog_function=mock_hog_function,
+ webhook_url="https://test.com/webhook",
+ hog_function_created=False,
+ )
+ mock_webhook_schemas = [
+ _SourceSchema(name="Charge", supports_incremental=True, supports_append=True, supports_webhooks=True),
+ ]
+
+ with (
+ patch(
+ "products.data_warehouse.backend.api.external_data_schema.get_or_create_webhook_hog_function",
+ return_value=mock_hog_fn_result,
+ ),
+ patch(
+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.sync_webhook_events",
+ side_effect=ValueError("Missing Stripe API key"),
+ ),
+ patch(
+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_schemas",
+ return_value=mock_webhook_schemas,
+ ),
+ patch(
+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook",
+ return_value=WebhookCreationResult(success=True),
+ ),
+ ):
+ 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_type": "webhook",
+ "incremental_field": "created",
+ "incremental_field_type": "integer",
+ }
+ ]
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ schema.refresh_from_db()
+ assert schema.sync_type == ExternalDataSchema.SyncType.WEBHOOK
+
@patch(
"posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
return_value=(True, None),
@@ -6862,6 +6933,63 @@ class TestWebhookInfo(APIBaseTest):
assert data["external_status"]["status"] == "enabled"
assert data["external_status"]["enabled_events"] == ["charge.created", "charge.updated"]
+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_desired_webhook_events")
+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_external_webhook_info")
+ def test_webhook_info_reports_missing_events(self, mock_get_info, mock_desired):
+ from posthog.temporal.data_imports.sources.common.base import ExternalWebhookInfo
+
+ mock_get_info.return_value = ExternalWebhookInfo(
+ exists=True,
+ status="enabled",
+ enabled_events=["charge.created"],
+ )
+ mock_desired.return_value = ["charge.created", "customer.created", "customer.updated"]
+
+ source = self._create_stripe_source()
+ self._create_hog_function(source)
+
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/webhook_info/")
+
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["missing_events"] == ["customer.created", "customer.updated"]
+
+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_desired_webhook_events")
+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_external_webhook_info")
+ def test_webhook_info_no_missing_events_when_in_sync(self, mock_get_info, mock_desired):
+ from posthog.temporal.data_imports.sources.common.base import ExternalWebhookInfo
+
+ mock_get_info.return_value = ExternalWebhookInfo(
+ exists=True,
+ status="enabled",
+ enabled_events=["charge.created", "customer.created"],
+ )
+ mock_desired.return_value = ["charge.created", "customer.created"]
+
+ source = self._create_stripe_source()
+ self._create_hog_function(source)
+
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/webhook_info/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["missing_events"] == []
+
+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_desired_webhook_events")
+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_external_webhook_info")
+ def test_webhook_info_wildcard_endpoint_has_no_missing_events(self, mock_get_info, mock_desired):
+ from posthog.temporal.data_imports.sources.common.base import ExternalWebhookInfo
+
+ mock_get_info.return_value = ExternalWebhookInfo(exists=True, status="enabled", enabled_events=["*"])
+ mock_desired.return_value = ["charge.created", "customer.created"]
+
+ source = self._create_stripe_source()
+ self._create_hog_function(source)
+
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/webhook_info/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["missing_events"] == []
+
@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_external_webhook_info")
def test_webhook_info_external_not_found(self, mock_get_info):
from posthog.temporal.data_imports.sources.common.base import ExternalWebhookInfo
diff --git a/products/data_warehouse/backend/external_data_source/test/test_webhooks.py b/products/data_warehouse/backend/external_data_source/test/test_webhooks.py
index abac89db1881..e4db27c3f703 100644
--- a/products/data_warehouse/backend/external_data_source/test/test_webhooks.py
+++ b/products/data_warehouse/backend/external_data_source/test/test_webhooks.py
@@ -4,12 +4,13 @@ import pytest
from unittest.mock import MagicMock, patch
from posthog.models import Organization, Team
-from posthog.temporal.data_imports.sources.common.base import WebhookCreationResult
+from posthog.temporal.data_imports.sources.common.base import WebhookCreationResult, WebhookSyncResult
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.data_warehouse.backend.external_data_source.webhooks import (
create_and_register_webhook,
get_or_create_webhook_hog_function,
+ reconcile_webhook_events,
)
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -375,3 +376,39 @@ class TestCreateAndRegisterWebhook:
result = create_and_register_webhook(webhook_source, config, hog_fn_result, team.id)
assert result.pending_inputs == []
+
+
+class TestReconcileWebhookEvents:
+ def test_delegates_to_sync_webhook_events(self):
+ _, team = _create_org_and_team()
+ _create_hog_function_template()
+ webhook_source = _make_webhook_source()
+ ext_source = _create_external_data_source(team)
+ schemas = _create_schemas(team, ext_source, ["Customers"])
+
+ hog_fn_result = get_or_create_webhook_hog_function(team, webhook_source, "source-123", schemas)
+ webhook_source.sync_webhook_events.return_value = WebhookSyncResult(success=True)
+
+ config = MagicMock()
+ result = reconcile_webhook_events(webhook_source, config, hog_fn_result, team.id, ["Customers"])
+
+ assert result.success is True
+ webhook_source.sync_webhook_events.assert_called_once_with(
+ config, hog_fn_result.webhook_url, team.id, ["Customers"]
+ )
+
+ def test_propagates_failure_without_raising(self):
+ _, team = _create_org_and_team()
+ _create_hog_function_template()
+ webhook_source = _make_webhook_source()
+ ext_source = _create_external_data_source(team)
+ schemas = _create_schemas(team, ext_source, ["Customers"])
+
+ hog_fn_result = get_or_create_webhook_hog_function(team, webhook_source, "source-123", schemas)
+ webhook_source.sync_webhook_events.return_value = WebhookSyncResult(success=False, error="add Write permission")
+
+ config = MagicMock()
+ result = reconcile_webhook_events(webhook_source, config, hog_fn_result, team.id, ["Customers"])
+
+ assert result.success is False
+ assert result.error == "add Write permission"
diff --git a/products/data_warehouse/backend/external_data_source/webhooks.py b/products/data_warehouse/backend/external_data_source/webhooks.py
index 07919a72e52a..72ed428cf756 100644
--- a/products/data_warehouse/backend/external_data_source/webhooks.py
+++ b/products/data_warehouse/backend/external_data_source/webhooks.py
@@ -8,6 +8,7 @@ from posthog.temporal.data_imports.sources.common.base import (
WebhookCreationResult,
WebhookDeletionResult,
WebhookSource,
+ WebhookSyncResult,
)
from posthog.temporal.data_imports.sources.common.config import Config
@@ -159,6 +160,17 @@ def create_and_register_webhook(
)
+def reconcile_webhook_events(
+ source: WebhookSource,
+ config: Config,
+ hog_fn_result: WebhookHogFunctionCreateResult,
+ team_id: int,
+ eligible_schema_names: list[str],
+) -> WebhookSyncResult:
+ """Reconcile a registered webhook's events with the selected schemas (no-op by default)."""
+ return source.sync_webhook_events(config, hog_fn_result.webhook_url, team_id, eligible_schema_names)
+
+
@dataclasses.dataclass
class WebhookDeletionSetupResult:
success: bool
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx
index af424979ad46..bc44cb9b5414 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookTab.tsx
@@ -1,6 +1,7 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
+import { IconCopy } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonCollapse, LemonSkeleton, LemonTable, LemonTag } from '@posthog/lemon-ui'
import { getColorVar } from 'lib/colors'
@@ -9,6 +10,7 @@ import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'
import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { SourceConfig, SourceFieldConfig } from '~/queries/schema/schema-general'
import { WebhookInfo } from '~/types'
@@ -136,6 +138,12 @@ export function WebhookTab({ id, tabId }: { id: string; tabId?: string }): JSX.E
tabId={tabId}
/>
)}
+ {!externalMissing && (webhookInfo.missing_events?.length ?? 0) > 0 && (
+ <WebhookMissingEventsSection
+ missingEvents={webhookInfo.missing_events!}
+ sourceName={sourceConfig?.label ?? source?.source_type ?? 'source'}
+ />
+ )}
<WebhookDetailsSection webhookInfo={webhookInfo} />
{mappedTables.length > 0 && <MappedTablesSection mappedTables={mappedTables} />}
<WebhookDeleteSection
@@ -325,6 +333,38 @@ function WebhookRecreateSection({
)
}
+function WebhookMissingEventsSection({
+ missingEvents,
+ sourceName,
+}: {
+ missingEvents: string[]
+ sourceName: string
+}): JSX.Element {
+ return (
+ <LemonBanner
+ type="warning"
+ action={{
+ icon: <IconCopy />,
+ children: 'Copy events',
+ onClick: () => void copyToClipboard(missingEvents.join('\n'), 'webhook events'),
+ }}
+ >
+ <p className="mb-2">
+ Some tables won't receive data until these events are added to your {sourceName} webhook. This happens
+ when the webhook was created manually, or before a newly added table was supported. Add them in your{' '}
+ {sourceName} dashboard, then refresh.
+ </p>
+ <div className="flex flex-wrap gap-1">
+ {missingEvents.map((event) => (
+ <LemonTag key={event} type="warning" className="text-xs">
+ {event}
+ </LemonTag>
+ ))}
+ </div>
+ </LemonBanner>
+ )
+}
+
function WebhookDetailsSection({ webhookInfo }: { webhookInfo: WebhookInfo }): JSX.Element {
const externalStatus = webhookInfo.external_status