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): flag webhook sources missing event subscriptions (#104567)

jake sciottobdcb7801fe5c
diff --git a/posthog/temporal/health_checks/registry.py b/posthog/temporal/health_checks/registry.py
index 451e54d6d1d0..2dfd983439a3 100644
--- a/posthog/temporal/health_checks/registry.py
+++ b/posthog/temporal/health_checks/registry.py
@@ -20,6 +20,7 @@ HEALTH_CHECK_MODULES = [
"products.growth.backend.temporal.health_checks.sdk_outdated",
"products.cdp.backend.temporal.health_checks.ingestion_warnings",
"products.data_warehouse.backend.temporal.health_checks.materialized_view_failure",
+ "products.data_warehouse.backend.temporal.health_checks.webhook_subscription_stale",
"products.web_analytics.backend.temporal.health_checks.scroll_depth",
"products.web_analytics.backend.temporal.health_checks.authorized_urls",
"products.web_analytics.backend.temporal.health_checks.reverse_proxy",
diff --git a/products/data_warehouse/backend/temporal/health_checks/webhook_subscription_stale.py b/products/data_warehouse/backend/temporal/health_checks/webhook_subscription_stale.py
new file mode 100644
index 000000000000..791bd7dc6eb8
--- /dev/null
+++ b/products/data_warehouse/backend/temporal/health_checks/webhook_subscription_stale.py
@@ -0,0 +1,161 @@
+from django.db.models import Q
+
+import structlog
+
+from posthog.job_owners import JobOwners
+from posthog.models.health_issue import HealthIssue
+from posthog.temporal.health_checks.detectors import HealthExecutionPolicy
+from posthog.temporal.health_checks.framework import AlertContent, HealthCheck, Remediation
+from posthog.temporal.health_checks.models import HealthCheckResult
+
+from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+
+logger = structlog.get_logger(__name__)
+
+_MAX_LISTED = 20
+
+
+class WebhookSubscriptionStaleCheck(HealthCheck):
+ """Flag a webhook source that silently receives nothing because its provider endpoint is
+ subscribed to too narrow a set of events.
+
+ A webhook endpoint created before its source's resource-to-event map grew keeps its original,
+ narrower ``enabled_events`` forever, because the reconcile that would widen it only runs when a
+ user edits a schema. A table added later never receives a delivery and freezes at the
+ source-creation date, with no error anywhere. This check flags a webhook-synced schema that has
+ never landed data and whose own mapped events are entirely absent from the endpoint.
+ """
+
+ name = "webhook_subscription_stale"
+ kind = "webhook_subscription_stale"
+ owner = JobOwners.TEAM_DATA_STACK
+ policy = HealthExecutionPolicy(batch_size=50, max_concurrent=3)
+ schedule = "45 7 * * *"
+ active_since_days = 30
+ access_controlled_resource = "external_data_source"
+ remediation = Remediation(
+ human="""
+ The webhook on your source is subscribed to fewer event types than the connected tables
+ need, so some tables never receive data. Open the source (Data pipeline / Data warehouse →
+ Sources), go to the Webhook tab, and add the missing events — or delete and recreate the
+ webhook so it picks up the full set. Webhooks can't backfill, so after the events are
+ subscribed, run a one-time full refresh on the affected tables to load their history.
+ """,
+ agent="""
+ Confirm the gap with `external-data-sources-retrieve` and the source's webhook info, which
+ lists the endpoint's enabled events against the events the source wants. Have the user add
+ the missing events or recreate the webhook from the Webhook tab (webhook subscriptions
+ can't be changed over the API). Once the endpoint is subscribed, trigger a full refresh on
+ the affected schemas with `external-data-schemas-resync` to backfill the history webhooks
+ can't deliver. The check clears once a delivery lands and the schema syncs.
+ """,
+ )
+
+ @classmethod
+ def render_alert(cls, issue: HealthIssue) -> AlertContent:
+ name = issue.payload.get("pipeline_name") or issue.payload.get("source_type", "a webhook source")
+ return AlertContent(
+ title="Webhook source is missing event subscriptions",
+ summary=f"{name} has tables that never receive data because its webhook events are incomplete",
+ link="/health/pipeline-status",
+ )
+
+ def detect(self, team_ids: list[int]) -> dict[int, list[HealthCheckResult]]:
+ from products.cdp.backend.facade.models import HogFunction
+ from products.data_warehouse.backend.logic.external_data_source.webhooks import get_webhook_url
+ from products.warehouse_sources.backend.facade.source_management import SourceRegistry, WebhookSource
+
+ stale_schemas = (
+ ExternalDataSchema.objects.filter(
+ team_id__in=team_ids,
+ deleted=False,
+ should_sync=True,
+ sync_type=ExternalDataSchema.SyncType.WEBHOOK,
+ )
+ .filter(Q(table__isnull=True) | Q(table__row_count=0))
+ .select_related("source")
+ )
+
+ schemas_by_source: dict[str, list[ExternalDataSchema]] = {}
+ sources: dict[str, ExternalDataSource] = {}
+ for schema in stale_schemas:
+ source = schema.source
+ if source is None or not source.job_inputs:
+ continue
+ schemas_by_source.setdefault(str(source.pk), []).append(schema)
+ sources[str(source.pk)] = source
+
+ issues: dict[int, list[HealthCheckResult]] = {}
+
+ for source_pk, schemas in schemas_by_source.items():
+ source = sources[source_pk]
+ try:
+ source_impl = SourceRegistry.get_source(ExternalDataSourceType(source.source_type))
+ except Exception:
+ continue
+ if not isinstance(source_impl, WebhookSource):
+ continue
+
+ hog_function = HogFunction.objects.filter(
+ team_id=source.team_id,
+ type="warehouse_source_webhook",
+ inputs__source_id__value=source_pk,
+ deleted=False,
+ ).first()
+ if hog_function is None:
+ continue
+
+ webhook_url = get_webhook_url(hog_function.id)
+ try:
+ config = source_impl.parse_config(source.job_inputs)
+ api_version = source_impl.resolve_api_version(source.api_version)
+ external = source_impl.get_external_webhook_info(
+ config, webhook_url, source.team_id, api_version=api_version
+ )
+ except Exception as e:
+ logger.warning(
+ "webhook_subscription_stale: could not read webhook info",
+ source_id=source_pk,
+ error_type=type(e).__name__,
+ )
+ continue
+
+ if external is None or not external.exists or external.error:
+ continue
+ enabled = set(external.enabled_events or [])
+ if "*" in enabled:
+ continue
+
+ affected_schemas: list[str] = []
+ missing_events: set[str] = set()
+ for schema in schemas:
+ try:
+ desired = source_impl.get_desired_webhook_events(config, [schema.name]) or []
+ except Exception:
+ continue
+ key = source_impl.webhook_mapping_key(schema.name)
+ schema_events = [event for event in desired if event == key or event.startswith(f"{key}.")]
+ if schema_events and not any(event in enabled for event in schema_events):
+ affected_schemas.append(schema.name)
+ missing_events.update(schema_events)
+
+ if not affected_schemas:
+ continue
+
+ issues.setdefault(source.team_id, []).append(
+ HealthCheckResult(
+ severity=HealthIssue.Severity.WARNING,
+ payload={
+ "pipeline_type": "external_data_webhook",
+ "pipeline_id": source_pk,
+ "pipeline_name": source.prefix or source.source_type,
+ "source_type": source.source_type,
+ "affected_schemas": sorted(affected_schemas)[:_MAX_LISTED],
+ "missing_events": sorted(missing_events)[:_MAX_LISTED],
+ },
+ hash_keys=["pipeline_type", "pipeline_id"],
+ )
+ )
+
+ return issues
diff --git a/products/data_warehouse/backend/tests/test_webhook_subscription_stale_check.py b/products/data_warehouse/backend/tests/test_webhook_subscription_stale_check.py
new file mode 100644
index 000000000000..71da4f091761
--- /dev/null
+++ b/products/data_warehouse/backend/tests/test_webhook_subscription_stale_check.py
@@ -0,0 +1,145 @@
+import uuid
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest import mock
+
+from parameterized import parameterized
+
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.data_warehouse.backend.temporal.health_checks.webhook_subscription_stale import (
+ WebhookSubscriptionStaleCheck,
+)
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import ExternalWebhookInfo
+
+SOURCE_MGMT = "products.warehouse_sources.backend.facade.source_management"
+
+DESIRED_EVENTS = ["charge.succeeded", "customer.created", "invoice.paid"]
+
+
+class _FakeWebhookBase:
+ pass
+
+
+class _FakeStripeSource(_FakeWebhookBase):
+ def __init__(self, enabled_events: list[str] | None, exists: bool = True, error: str | None = None) -> None:
+ self._enabled_events = enabled_events
+ self._exists = exists
+ self._error = error
+
+ def parse_config(self, job_inputs: dict) -> dict:
+ return job_inputs
+
+ def resolve_api_version(self, pinned: str | None) -> str:
+ return pinned or "2020-08-27"
+
+ def webhook_mapping_key(self, schema_name: str) -> str:
+ return schema_name
+
+ def get_external_webhook_info(
+ self, config: Any, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> ExternalWebhookInfo:
+ return ExternalWebhookInfo(exists=self._exists, enabled_events=self._enabled_events, error=self._error)
+
+ def get_desired_webhook_events(self, config: Any, eligible_schema_names: list[str]) -> list[str]:
+ return DESIRED_EVENTS
+
+
+class TestWebhookSubscriptionStaleCheck(BaseTest):
+ def _create_webhook_source(self) -> ExternalDataSource:
+ source = ExternalDataSource.objects.create(
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ team=self.team,
+ source_type="Stripe",
+ job_inputs={"stripe_secret_key": "sk_test_x"},
+ )
+ HogFunction.objects.create(
+ team=self.team,
+ type="warehouse_source_webhook",
+ hog="return event",
+ inputs_schema=[{"key": "source_id", "type": "string"}],
+ inputs={"source_id": {"value": str(source.pk)}},
+ )
+ return source
+
+ def _table_with_rows(self, name: str, row_count: int) -> DataWarehouseTable:
+ return DataWarehouseTable.objects.create(
+ team=self.team, name=name, columns={"id": "String"}, row_count=row_count
+ )
+
+ def _create_webhook_schema(
+ self, source: ExternalDataSource, name: str, table: DataWarehouseTable | None = None
+ ) -> ExternalDataSchema:
+ return ExternalDataSchema.objects.create(
+ name=name,
+ team=self.team,
+ source=source,
+ sync_type=ExternalDataSchema.SyncType.WEBHOOK,
+ should_sync=True,
+ table=table,
+ )
+
+ def _detect(self, source_impl: _FakeStripeSource) -> list[dict]:
+ registry = mock.Mock()
+ registry.get_source.return_value = source_impl
+ with (
+ mock.patch(f"{SOURCE_MGMT}.SourceRegistry", registry),
+ mock.patch(f"{SOURCE_MGMT}.WebhookSource", _FakeWebhookBase),
+ ):
+ issues = WebhookSubscriptionStaleCheck().detect([self.team.id])
+ return [result.payload for result in issues.get(self.team.id, [])]
+
+ @parameterized.expand(
+ [
+ ("own_events_unsubscribed", ["invoice.paid"], True),
+ ("own_events_subscribed", ["charge.succeeded"], False),
+ ("wildcard", ["*"], False),
+ ]
+ )
+ def test_reports_only_when_a_schemas_own_events_are_missing(
+ self, _name: str, enabled_events: list[str], flagged: bool
+ ) -> None:
+ source = self._create_webhook_source()
+ self._create_webhook_schema(source, "charge")
+
+ payloads = self._detect(_FakeStripeSource(enabled_events))
+
+ if flagged:
+ assert len(payloads) == 1
+ assert payloads[0]["pipeline_id"] == str(source.pk)
+ assert payloads[0]["missing_events"] == ["charge.succeeded"]
+ assert payloads[0]["affected_schemas"] == ["charge"]
+ else:
+ assert payloads == []
+
+ def test_only_flags_schemas_whose_own_events_are_unsubscribed(self) -> None:
+ source = self._create_webhook_source()
+ self._create_webhook_schema(source, "charge")
+ self._create_webhook_schema(source, "customer")
+
+ payloads = self._detect(_FakeStripeSource(["charge.succeeded"]))
+
+ assert len(payloads) == 1
+ assert payloads[0]["affected_schemas"] == ["customer"]
+ assert payloads[0]["missing_events"] == ["customer.created"]
+
+ def test_row_count_gates_candidacy(self) -> None:
+ source = self._create_webhook_source()
+ self._create_webhook_schema(source, "charge", table=self._table_with_rows("charge_tbl", 0))
+ self._create_webhook_schema(source, "customer", table=self._table_with_rows("customer_tbl", 5))
+
+ payloads = self._detect(_FakeStripeSource([]))
+
+ assert len(payloads) == 1
+ assert payloads[0]["affected_schemas"] == ["charge"]
+ assert payloads[0]["missing_events"] == ["charge.succeeded"]
+
+ def test_unreadable_endpoint_is_skipped(self) -> None:
+ source = self._create_webhook_source()
+ self._create_webhook_schema(source, "charge")
+
+ assert self._detect(_FakeStripeSource(None, exists=False, error="cannot read webhook endpoint")) == []
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index b163cfdac741..8f60da2beaf3 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -867,6 +867,7 @@ warehouse_sources.ExternalDataSchema products.data_warehouse.backend.sql_warehou
warehouse_sources.ExternalDataSchema products.data_warehouse.backend.sync_status in-collection 1
warehouse_sources.ExternalDataSchema products.data_warehouse.backend.sync_status instance-many(select_related) 1
warehouse_sources.ExternalDataSchema products.data_warehouse.backend.temporal.health_checks.external_data_failure instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.temporal.health_checks.webhook_subscription_stale instance-many(select_related) 1
warehouse_sources.ExternalDataSchema products.engineering_analytics.backend.logic.sources instance-many(select_related) 1
warehouse_sources.ExternalDataSchema products.engineering_analytics.backend.management.commands.seed_engineering_analytics instance-single 1
warehouse_sources.ExternalDataSchema products.engineering_analytics.backend.management.commands.seed_engineering_analytics write(create) 1