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(integrations): warn instead of silently substituting stale integration refs (#60441)

Meikel Ratz983d95b03b85
diff --git a/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx
index 793693697ec4..7f95471ceb68 100644
--- a/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx
+++ b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useEffect } from 'react'
import { IconExternal, IconTrash, IconX } from '@posthog/icons'
-import { LemonButton, LemonMenu, LemonSkeleton } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonMenu, LemonSkeleton } from '@posthog/lemon-ui'
import api from 'lib/api'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
@@ -40,19 +40,18 @@ export function IntegrationChoice({
const integrationsOfKind = integrations?.filter((x) => x.kind === kind)
const integrationKind = integrationsOfKind?.find((integration) => integration.id === value)
+ // The stored value points to an integration that's no longer available (deleted, or
+ // re-installed under a new ID). We deliberately do NOT auto-substitute here — that
+ // would silently mask the missing reference and let stale config keep flowing through
+ // saves. The UI surfaces a warning below instead so the user picks explicitly.
+ const valueIsMissing = !integrationsLoading && !!value && !!integrations && !integrationKind
+
useEffect(() => {
if (!integrationsLoading && !value && integrationsOfKind?.length) {
onChange?.(integrationsOfKind[0].id)
}
}, [integrationsLoading, onChange, integrationsOfKind?.length, value, integrationsOfKind])
- // Clear stale selection when the integration no longer exists (e.g. after disconnect)
- useEffect(() => {
- if (!integrationsLoading && value && integrations && !integrationKind) {
- onChange?.(null)
- }
- }, [integrationsLoading, value, integrations, integrationKind, onChange])
-
if (!kind) {
return null
}
@@ -172,6 +171,14 @@ export function IntegrationChoice({
<>
{integrationKind ? (
<IntegrationView schema={schema} integration={integrationKind} suffix={button} />
+ ) : valueIsMissing ? (
+ <div className="flex flex-col gap-2">
+ <LemonBanner type="warning">
+ The previously selected {kindName} connection (ID: {value}) is no longer available. Pick a
+ different connection or clear the selection — this connection will fail at runtime otherwise.
+ </LemonBanner>
+ {button}
+ </div>
) : (
button
)}
diff --git a/posthog/management/commands/backfill_workflows_slack_integration.py b/posthog/management/commands/backfill_workflows_slack_integration.py
new file mode 100644
index 000000000000..4f8ccc2f49a0
--- /dev/null
+++ b/posthog/management/commands/backfill_workflows_slack_integration.py
@@ -0,0 +1,144 @@
+import copy
+import time
+import logging
+from typing import Any
+
+from django.core.management.base import BaseCommand
+from django.db import transaction
+
+from posthog.models.hog_flow.hog_flow import HogFlow
+
+logger = logging.getLogger(__name__)
+
+
+# One-off backfill for team 2: the Slack integration was re-installed under a new
+# primary key (173069). 40 hogflows still reference the old integration row (54567),
+# which no longer exists, so their Slack steps fail at runtime. The UI auto-substitutes
+# on render but never writes the new id back to the stored config until the user saves.
+# Hard-coded by intent — this is not a generic remapper, just the one swap we need.
+TEAM_ID = 2
+OLD_INTEGRATION_ID = 54567
+NEW_INTEGRATION_ID = 173069
+
+
+def _rewrite_slack_workspace_in_actions(actions: Any) -> tuple[Any, list[str]]:
+ """Return (new_actions, changed_action_ids). actions is left untouched if no match.
+
+ Looks for `config.inputs.slack_workspace.value == OLD_INTEGRATION_ID` on any action
+ and rewrites it to NEW_INTEGRATION_ID. The integration id is stored as a literal
+ integer (no bytecode), so only the `value` needs swapping.
+ """
+ if not isinstance(actions, list):
+ return actions, []
+
+ changed_ids: list[str] = []
+ new_actions = copy.deepcopy(actions)
+
+ for action in new_actions:
+ if not isinstance(action, dict):
+ continue
+ inputs = (action.get("config") or {}).get("inputs") or {}
+ slack_workspace = inputs.get("slack_workspace")
+ if not isinstance(slack_workspace, dict):
+ continue
+ if slack_workspace.get("value") == OLD_INTEGRATION_ID:
+ slack_workspace["value"] = NEW_INTEGRATION_ID
+ changed_ids.append(str(action.get("id") or "<unknown>"))
+
+ return new_actions, changed_ids
+
+
+class Command(BaseCommand):
+ help = (
+ f"One-off: rewrite stale Slack integration {OLD_INTEGRATION_ID} → {NEW_INTEGRATION_ID} "
+ f"in HogFlow actions on team {TEAM_ID}."
+ )
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Run without making any changes to the database",
+ )
+
+ def handle(self, *args, **options):
+ start_time = time.time()
+ dry_run: bool = options["dry_run"]
+
+ if dry_run:
+ self.stdout.write(self.style.WARNING("Running in DRY RUN mode — no changes will be made"))
+
+ self.stdout.write(
+ f"Scanning HogFlows for team {TEAM_ID}, "
+ f"swapping slack_workspace {OLD_INTEGRATION_ID} → {NEW_INTEGRATION_ID}..."
+ )
+
+ # Team 2 has on the order of a few hundred hogflows. Pull them all in one go;
+ # no pagination required at this scale, and a single transaction keeps the
+ # write atomic for the team.
+ flows = list(HogFlow.objects.filter(team_id=TEAM_ID).order_by("id"))
+ total_count = len(flows)
+ self.stdout.write(f"Found {total_count} HogFlows on team {TEAM_ID}")
+
+ if total_count == 0:
+ return
+
+ updated_flows: list[HogFlow] = []
+ per_flow_changes: list[tuple[str, list[str], list[str]]] = []
+ error_count = 0
+
+ for flow in flows:
+ try:
+ new_actions, actions_changed = _rewrite_slack_workspace_in_actions(flow.actions)
+ draft_actions_changed: list[str] = []
+ new_draft = flow.draft
+ if isinstance(flow.draft, dict) and "actions" in flow.draft:
+ rewritten_draft_actions, draft_actions_changed = _rewrite_slack_workspace_in_actions(
+ flow.draft.get("actions")
+ )
+ if draft_actions_changed:
+ new_draft = {**flow.draft, "actions": rewritten_draft_actions}
+
+ if not actions_changed and not draft_actions_changed:
+ continue
+
+ flow.actions = new_actions
+ flow.draft = new_draft
+ updated_flows.append(flow)
+ per_flow_changes.append((str(flow.id), actions_changed, draft_actions_changed))
+ except Exception as e:
+ error_count += 1
+ logger.exception(
+ "Error processing HogFlow id=%s team_id=%s: %s",
+ flow.id,
+ flow.team_id,
+ e,
+ )
+
+ # Report planned changes before writing.
+ for flow_id, actions_changed, draft_actions_changed in per_flow_changes:
+ self.stdout.write(
+ f" {flow_id}: actions={actions_changed or '[]'} draft.actions={draft_actions_changed or '[]'}"
+ )
+
+ if updated_flows and not dry_run:
+ # bulk_update skips post_save, which means worker reloads won't happen
+ # automatically. That's fine for a one-off backfill — workers refresh their
+ # caches on their own ticking interval, and we'd rather not spam reload
+ # signals for every flow we touch.
+ with transaction.atomic():
+ HogFlow.objects.bulk_update(updated_flows, ["actions", "draft"], batch_size=200)
+
+ duration = time.time() - start_time
+ verb = "Would update" if dry_run else "Updated"
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"\nDone in {duration:.2f}s.\n"
+ f"Scanned: {total_count}\n"
+ f"{verb}: {len(updated_flows)}\n"
+ f"Errors: {error_count}"
+ )
+ )
+
+ if error_count > 0:
+ self.stdout.write(self.style.WARNING(f"Check logs for details on {error_count} errors"))
diff --git a/posthog/management/commands/test/test_backfill_workflows_slack_integration.py b/posthog/management/commands/test/test_backfill_workflows_slack_integration.py
new file mode 100644
index 000000000000..4e8125a71e4c
--- /dev/null
+++ b/posthog/management/commands/test/test_backfill_workflows_slack_integration.py
@@ -0,0 +1,156 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+
+from posthog.management.commands import backfill_workflows_slack_integration as backfill
+from posthog.management.commands.backfill_workflows_slack_integration import _rewrite_slack_workspace_in_actions
+from posthog.models import Team
+from posthog.models.hog_flow.hog_flow import HogFlow
+
+
+def _slack_action(action_id: str, slack_workspace_value: int | None) -> dict:
+ inputs: dict = {
+ "channel": {"value": "C123"},
+ }
+ if slack_workspace_value is not None:
+ inputs["slack_workspace"] = {"order": 0, "value": slack_workspace_value, "templating": "hog"}
+ return {
+ "id": action_id,
+ "name": "Slack",
+ "type": "function",
+ "config": {
+ "template_id": "template-slack",
+ "inputs": inputs,
+ },
+ }
+
+
+class TestRewriteSlackWorkspaceInActions(BaseTest):
+ def test_rewrites_matching_value(self):
+ actions = [_slack_action("a1", backfill.OLD_INTEGRATION_ID)]
+ new_actions, changed = _rewrite_slack_workspace_in_actions(actions)
+ assert changed == ["a1"]
+ assert new_actions[0]["config"]["inputs"]["slack_workspace"]["value"] == backfill.NEW_INTEGRATION_ID
+
+ def test_does_not_touch_non_matching_value(self):
+ actions = [_slack_action("a1", 99999)]
+ new_actions, changed = _rewrite_slack_workspace_in_actions(actions)
+ assert changed == []
+ assert new_actions[0]["config"]["inputs"]["slack_workspace"]["value"] == 99999
+
+ def test_handles_missing_slack_workspace_input(self):
+ actions = [_slack_action("a1", None)]
+ new_actions, changed = _rewrite_slack_workspace_in_actions(actions)
+ assert changed == []
+ assert "slack_workspace" not in new_actions[0]["config"]["inputs"]
+
+ def test_mixed_actions_only_changes_matches(self):
+ actions = [
+ _slack_action("match", backfill.OLD_INTEGRATION_ID),
+ _slack_action("nope", 99999),
+ {"id": "trigger", "type": "trigger", "config": {}},
+ {"id": "exit", "type": "exit", "config": {"reason": "default"}},
+ ]
+ new_actions, changed = _rewrite_slack_workspace_in_actions(actions)
+ assert changed == ["match"]
+ assert new_actions[0]["config"]["inputs"]["slack_workspace"]["value"] == backfill.NEW_INTEGRATION_ID
+ assert new_actions[1]["config"]["inputs"]["slack_workspace"]["value"] == 99999
+
+ def test_idempotent_when_already_migrated(self):
+ actions = [_slack_action("a1", backfill.NEW_INTEGRATION_ID)]
+ _, changed = _rewrite_slack_workspace_in_actions(actions)
+ assert changed == []
+
+ def test_non_list_actions_returned_unchanged(self):
+ new_actions, changed = _rewrite_slack_workspace_in_actions(None)
+ assert new_actions is None
+ assert changed == []
+
+ def test_deepcopy_does_not_mutate_input(self):
+ actions = [_slack_action("a1", backfill.OLD_INTEGRATION_ID)]
+ _rewrite_slack_workspace_in_actions(actions)
+ assert actions[0]["config"]["inputs"]["slack_workspace"]["value"] == backfill.OLD_INTEGRATION_ID
+
+
+class TestBackfillWorkflowsSlackIntegrationCommand(BaseTest):
+ """Tests patch the TEAM_ID constant to point at the test team so we don't need to
+ construct a Team row with a specific primary key."""
+
+ def setUp(self):
+ super().setUp()
+ self.other_team = Team.objects.create(organization=self.organization, name="Other team")
+
+ with patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers"):
+ self.target_flow = HogFlow.objects.create(
+ team=self.team,
+ name="Target flow",
+ status=HogFlow.State.ACTIVE,
+ actions=[
+ {"id": "trigger", "type": "trigger", "config": {}},
+ _slack_action("slack_step", backfill.OLD_INTEGRATION_ID),
+ ],
+ draft={
+ "actions": [
+ _slack_action("slack_step", backfill.OLD_INTEGRATION_ID),
+ ]
+ },
+ version=1,
+ )
+ self.untouched_flow = HogFlow.objects.create(
+ team=self.team,
+ name="Already migrated",
+ status=HogFlow.State.ACTIVE,
+ actions=[_slack_action("slack_step", backfill.NEW_INTEGRATION_ID)],
+ version=1,
+ )
+ self.other_team_flow = HogFlow.objects.create(
+ team=self.other_team,
+ name="Other team flow",
+ status=HogFlow.State.ACTIVE,
+ actions=[_slack_action("slack_step", backfill.OLD_INTEGRATION_ID)],
+ version=1,
+ )
+
+ def test_dry_run_does_not_modify_db(self):
+ with patch.object(backfill, "TEAM_ID", self.team.id):
+ call_command("backfill_workflows_slack_integration", "--dry-run")
+
+ self.target_flow.refresh_from_db()
+ assert self.target_flow.draft is not None
+ assert (
+ self.target_flow.actions[1]["config"]["inputs"]["slack_workspace"]["value"] == backfill.OLD_INTEGRATION_ID
+ )
+ assert (
+ self.target_flow.draft["actions"][0]["config"]["inputs"]["slack_workspace"]["value"]
+ == backfill.OLD_INTEGRATION_ID
+ )
+
+ def test_rewrites_only_target_team(self):
+ with (
+ patch.object(backfill, "TEAM_ID", self.team.id),
+ patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers"),
+ ):
+ call_command("backfill_workflows_slack_integration")
+
+ self.target_flow.refresh_from_db()
+ self.untouched_flow.refresh_from_db()
+ self.other_team_flow.refresh_from_db()
+
+ assert self.target_flow.draft is not None
+ assert (
+ self.target_flow.actions[1]["config"]["inputs"]["slack_workspace"]["value"] == backfill.NEW_INTEGRATION_ID
+ )
+ assert (
+ self.target_flow.draft["actions"][0]["config"]["inputs"]["slack_workspace"]["value"]
+ == backfill.NEW_INTEGRATION_ID
+ )
+ assert (
+ self.untouched_flow.actions[0]["config"]["inputs"]["slack_workspace"]["value"]
+ == backfill.NEW_INTEGRATION_ID
+ )
+ # Other team must remain untouched even with the matching old id.
+ assert (
+ self.other_team_flow.actions[0]["config"]["inputs"]["slack_workspace"]["value"]
+ == backfill.OLD_INTEGRATION_ID
+ )