: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(cdp): stop deleted webhook sources and workflows from executing (#68953)
Luke Beltona2dd7494b3f7
diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.tsindex f93db6c9591b..da940bc3ad0f 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts@@ -15,6 +15,7 @@ import { template as incomingWebhookTemplate } from '~/cdp/templates/_sources/weimport { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, HogFunctionType } from '~/cdp/types'import { setupExpressApp } from '~/common/api/router'import { closeHub, createHub } from '~/common/utils/db/hub'+import { PostgresUse } from '~/common/utils/db/postgres'import { createCdpConsumerDeps } from '~/tests/helpers/cdp'import { forSnapshot } from '~/tests/helpers/snapshots'import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'@@ -203,6 +204,29 @@ describe('SourceWebhooksConsumer', () => {})})+ it('should 404 if the hog function is deleted', async () => {+ // Deletion via the django API is a soft delete that leaves `enabled` untouched+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogfunction SET deleted=true, updated_at = NOW() WHERE id = $1`,+ [hogFunction.id],+ 'testKey'+ )++ const res = await doPostRequest({+ body: {+ event: 'my-event',+ distinct_id: 'test-distinct-id',+ },+ })++ expect(res.status).toEqual(404)+ expect(res.body).toEqual({+ error: 'Not found',+ })+ expect(mockExecuteSpy).not.toHaveBeenCalled()+ })+it('should capture an event using internal capture', async () => {// Mock the monitoring service to verify events ARE captured for regular webhooksconst mockQueueInvocationResults = jest.spyOn(diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.tsindex 19f3f308908b..20e42ab92dff 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts@@ -106,11 +106,11 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf// Check for hog functionsconst hogFunction = await this.hogFunctionManager.getHogFunction(webhookId)- if (hogFunction?.type === 'source_webhook' && hogFunction?.enabled) {+ if (hogFunction?.type === 'source_webhook' && hogFunction.enabled && !hogFunction.deleted) {return { hogFunction }}- if (hogFunction?.type === 'warehouse_source_webhook' && hogFunction?.enabled) {+ if (hogFunction?.type === 'warehouse_source_webhook' && hogFunction.enabled && !hogFunction.deleted) {const templateId = hogFunction.template_id ?? 'template-warehouse-source-default'const template = await this.hogFunctionTemplateManager.getHogFunctionTemplate(templateId)if (template) {diff --git a/nodejs/src/cdp/services/managers/hog-function-manager.service.test.ts b/nodejs/src/cdp/services/managers/hog-function-manager.service.test.tsindex 73a91c98e3bf..3653e5e59152 100644--- a/nodejs/src/cdp/services/managers/hog-function-manager.service.test.ts+++ b/nodejs/src/cdp/services/managers/hog-function-manager.service.test.ts@@ -257,6 +257,23 @@ describe('HogFunctionManager', () => {expect(items).toEqual([])})++ it('does not return deleted functions when fetched by id', async () => {+ expect(await manager.getHogFunction(hogFunctions[0].id)).toMatchObject({ id: hogFunctions[0].id })++ // Soft-delete without disabling, as deletion via the django API leaves `enabled` untouched+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogfunction SET deleted=true, updated_at = NOW() WHERE id = $1`,+ [hogFunctions[0].id],+ 'testKey'+ )++ // This is normally dispatched by django+ manager['onHogFunctionsReloaded'](teamId1, [hogFunctions[0].id])++ expect(await manager.getHogFunction(hogFunctions[0].id)).toEqual(null)+ })})describe('Hogfunction Manager - Execution Order', () => {diff --git a/nodejs/src/cdp/services/managers/hog-function-manager.service.ts b/nodejs/src/cdp/services/managers/hog-function-manager.service.tsindex d8cd1054f5e0..c9d8433850e1 100644--- a/nodejs/src/cdp/services/managers/hog-function-manager.service.ts+++ b/nodejs/src/cdp/services/managers/hog-function-manager.service.ts@@ -211,7 +211,7 @@ export class HogFunctionManagerService {const response = await this.postgres.query<HogFunctionType>(PostgresUse.COMMON_READ,- `SELECT ${HOG_FUNCTION_FIELDS.join(', ')} FROM posthog_hogfunction WHERE id = ANY($1)`,+ `SELECT ${HOG_FUNCTION_FIELDS.join(', ')} FROM posthog_hogfunction WHERE id = ANY($1) AND deleted = FALSE`,[ids],'fetchHogFunctions')diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 0cb3cb134d09..4d3fd586bb09 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -82,6 +82,7 @@ post_delete:products.feature_flags.backend.local_evaluation.feature_flag_changedpost_delete:products.feature_flags.backend.models.feature_flag.refresh_flag_cache_on_updatespost_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_changepost_delete:products.surveys.backend.models.survey_changed+post_delete:products.workflows.backend.models.hog_flow.hog_flow.hog_flow_deletedpost_init:posthog.storage.gateway_credential_signal_handlers._snapshot_oauthpost_init:posthog.storage.gateway_credential_signal_handlers._snapshot_secret_keypost_init:posthog.storage.gateway_credential_signal_handlers._snapshot_user@@ -209,10 +210,10 @@ pre_save:posthog.storage.team_access_cache_signal_handlers.team_pre_save_auth_capre_save:posthog.storage.team_llm_gateway_policy_signal_handlers._capture_old_state_if_deferredpre_save:products.cohorts.backend.models.dependencies.cohort_pre_savepre_save:products.conversations.backend.signals.handle_comment_soft_delete-pre_save:products.signals.backend.receivers.capture_prior_status_for_pr_closepre_save:products.customer_analytics.backend.models.account._enforce_account_group_type_index_drift_policypre_save:products.event_definitions.backend.models.event_definition._capture_event_definition_old_namepre_save:products.feature_flags.backend.flag_version_sync.capture_cohort_definition_before_save+pre_save:products.signals.backend.receivers.capture_prior_status_for_pr_closepre_save:products.surveys.backend.models.pre_save_surveyuser_logged_in:posthog.models.activity_logging.signal_handlers.log_user_login_activityuser_logged_in:posthog.models.activity_logging.signal_handlers.post_logindiff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 0abbdbe82c1c..13dc15591545 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -3001,6 +3001,34 @@ class TestHogFlowAPI(APIBaseTest):assert response.json()["deleted"] == 0assert HogFlow.objects.filter(id=flow_id).exists()+ @parameterized.expand(+ [+ ("single_delete",),+ ("bulk_delete",),+ ]+ )+ def test_delete_publishes_reload_to_workers(self, delete_mode):+ flow_id = self._create_flow(name="Delete reload")+ self._archive_flow(flow_id)++ with (+ patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers") as mock_reload,+ self.captureOnCommitCallbacks(execute=True),+ ):+ if delete_mode == "single_delete":+ response = self.client.delete(f"/api/projects/{self.team.id}/hog_flows/{flow_id}")+ assert response.status_code == 204, response.content+ else:+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/bulk_delete",+ {"ids": [flow_id]},+ )+ assert response.status_code == 200, response.json()+ assert response.json()["deleted"] == 1++ assert not HogFlow.objects.filter(id=flow_id).exists()+ mock_reload.assert_called_once_with(team_id=self.team.id, hog_flow_ids=[flow_id])+def _base_hog_flow_with_variables(self, variables):trigger_action = {"id": "trigger_node",diff --git a/products/workflows/backend/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.pyindex bfc9f51ce19b..70682199fe40 100644--- a/products/workflows/backend/models/hog_flow/hog_flow.py+++ b/products/workflows/backend/models/hog_flow/hog_flow.py@@ -1,7 +1,7 @@from typing import TYPE_CHECKING, Final-from django.db import models-from django.db.models.signals import post_save+from django.db import models, transaction+from django.db.models.signals import post_delete, post_savefrom django.dispatch.dispatcher import receiverimport structlog@@ -99,6 +99,15 @@ def hog_flow_saved(sender, instance: HogFlow, created, **kwargs):reload_hog_flows_on_workers(team_id=instance.team_id, hog_flow_ids=[str(instance.id)])+@receiver(post_delete, sender=HogFlow)+def hog_flow_deleted(sender, instance: HogFlow, **kwargs):+ team_id = instance.team_id+ hog_flow_id = str(instance.id)+ # post_delete fires inside the delete transaction, so publish only after commit; otherwise a+ # worker could re-read the still-live row and cache it as active for another TTL.+ transaction.on_commit(lambda: reload_hog_flows_on_workers(team_id=team_id, hog_flow_ids=[hog_flow_id]))++@receiver(post_save, sender=Action)def action_saved_for_hog_flows(sender, instance: Action, created, **kwargs):from products.workflows.backend.tasks.hog_flows import refresh_affected_hog_flows # noqa: PLC0415