: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(workflows): trigger on channel messages of a workspace connected in both regions (#88642)
Harley Alexandered68e3b2e184
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 459a2452f027..fbbdd11b765e 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -104,7 +104,7 @@ from products.slack_app.backend.slack_link_unfurl import (link_url_region,parse_posthog_resource_link,)-from products.slack_app.backend.slack_workflow_events import emit_slack_message_event+from products.slack_app.backend.slack_workflow_events import emit_slack_message_event, is_triggering_messagelogger = structlog.get_logger(__name__)@@ -547,6 +547,11 @@ def resolve_slack_user(# This keeps the slack manifest endpoint swappable between us.posthog.com and eu.posthog.com# without any other coordination.REGION_PROXY_HEADER = "X-PostHog-Region-Proxied"++# Marks a copy of a channel message forwarded only for the workflow-trigger emit. A workspace can+# be connected in both regions; the receiver runs the emit for its own projects and nothing else,+# so the sender's pipeline (thread follow-ups, mentions) stays the only one handling the event.+EMIT_ONLY_MIRROR_HEADER = "X-PostHog-Slack-Emit-Only"REGION_PROXY_TIMEOUT_SECONDS = 3# Tight budget: the workspace_claims endpoint is just a DB .exists(), and EU calls it inline# before deciding whether to proxy. Slack's webhook ack deadline is 3s total, so we want this@@ -598,28 +603,46 @@ def was_proxied(request: HttpRequest) -> bool:return request.headers.get(REGION_PROXY_HEADER) == "1"-def _proxy_event_to_region(request: HttpRequest, target_domain: str) -> requests.Response | None:- """Forward the original Slack event to the other region, tagged so the receiver does not hop again."""+def _is_emit_only_mirror(request: HttpRequest) -> bool:+ # Mirror copies also carry REGION_PROXY_HEADER, so `proxied` keeps guarding against re-hops.+ return request.headers.get(EMIT_ONLY_MIRROR_HEADER) == "1"+++def _proxy_target_url(request: HttpRequest, target_domain: str) -> str:parsed_url = urlparse(request.build_absolute_uri())# In dev the EU "region" is plain-HTTP localhost while the incoming URI is HTTPS (ngrok-# terminated TLS), so always pick the scheme by target domain rather than copying the# inbound one. Production talks HTTPS region-to-region.target_scheme = "http" if settings.DEBUG else "https"- target_url = urlunparse(parsed_url._replace(scheme=target_scheme, netloc=target_domain))+ return urlunparse(parsed_url._replace(scheme=target_scheme, netloc=target_domain))+++def _proxy_request_headers(request: HttpRequest) -> dict[str, str]:# Drop Host plus the host-identifying forwarded headers so the receiver computes its own# host from the new TCP connection rather than mirroring the sender's edge. X-Forwarded-For# is intentionally preserved so the original Slack client IP survives the inter-region hop.stripped = {"host", "x-forwarded-host", "forwarded"}headers = {key: value for key, value in request.headers.items() if key.lower() not in stripped}headers[REGION_PROXY_HEADER] = "1"+ return headers++def send_region_proxy_request(+ *,+ method: str,+ target_url: str,+ headers: dict[str, str],+ params: dict[str, list[str]] | None = None,+ body: bytes | None = None,+) -> requests.Response | None:+ """POST a Slack event payload to the other region and translate the outcome into logs."""try:response = requests.request(- method=request.method or "POST",+ method=method,url=target_url,headers=headers,- params=dict(request.GET.lists()) if request.GET else None,- data=request.body or None,+ params=params,+ data=body,timeout=REGION_PROXY_TIMEOUT_SECONDS,)if 200 <= response.status_code < 300:@@ -637,11 +660,76 @@ def _proxy_event_to_region(request: HttpRequest, target_domain: str) -> requestsreturn None+def _proxy_event_to_region(request: HttpRequest, target_domain: str) -> requests.Response | None:+ """Forward the original Slack event to the other region, tagged so the receiver does not hop again."""+ return send_region_proxy_request(+ method=request.method or "POST",+ target_url=_proxy_target_url(request, target_domain),+ headers=_proxy_request_headers(request),+ params=dict(request.GET.lists()) if request.GET else None,+ body=request.body or None,+ )++def _proxy_event_and_return_route(request: HttpRequest, target_domain: str) -> str:"""Forward and translate the upstream result into a routing outcome string."""return ROUTE_PROXIED if _proxy_event_to_region(request, target_domain) is not None else ROUTE_PROXY_FAILED+def _is_top_level_channel_post(event: dict[str, Any]) -> bool:+ """Whether a channel ``message`` starts a thread rather than replying inside one.++ Slack sets ``thread_ts`` on replies and to ``ts`` on the post that opened the thread. Top-level+ posts are the ones the follow-up pipeline discards before its region gate, so the mirror is what+ carries them across; a reply already reaches that gate and crosses through it.+ """+ thread_ts = event.get("thread_ts")+ return not isinstance(thread_ts, str) or thread_ts == event.get("ts")+++def _mirror_message_event_to_other_region(+ request: HttpRequest,+ event: dict,+ *,+ slack_team_id: str,+ incoming_host: str,+ other_domain: str,+) -> None:+ """Queue an emit-only copy of a top-level channel post for the other region.++ A workspace connected in both regions gets its events consumed by the region Slack delivers to,+ and the plain hand-off only fires when that region holds no connection, so the other region's+ workflow triggers would otherwise never see a top-level channel message. The claims probe and+ the cross-region POST run in a Celery task: top-level posts dominate wire volume and the webhook+ owes Slack an ack within three seconds, so this path spends no cross-region I/O inline.++ Only top-level posts are mirrored. A thread reply already reaches the follow-up pipeline's+ region gate and crosses through it, so mirroring one would make the other region emit it twice.+ """+ if not _is_top_level_channel_post(event):+ return+ if not is_triggering_message(event):+ return+ headers = _proxy_request_headers(request)+ headers[EMIT_ONLY_MIRROR_HEADER] = "1"+ # noqa reason: the task module imports this module's probe and transport, so a module-level+ # import here would be circular.+ from products.slack_app.backend.tasks import mirror_slack_message_event # noqa: PLC0415++ try:+ mirror_slack_message_event.delay(+ slack_team_id=slack_team_id,+ incoming_host=incoming_host,+ target_url=_proxy_target_url(request, other_domain),+ headers=headers,+ body=(request.body or b"").decode("utf-8"),+ )+ except Exception:+ # A broker failure must not 500 the shared webhook: Slack would redeliver, and the mention+ # pipeline would handle the copy again. A lost mirror costs the other region one message.+ logger.exception("slack_app_mirror_dispatch_failed", slack_team_id=slack_team_id)++def _workspace_claims_cache_key(slack_team_id: str, kinds: list[str]) -> str:kinds_token = ",".join(sorted(kinds))return f"slack_app:ws_claims:{slack_team_id}:{kinds_token}"@@ -2042,6 +2130,17 @@ def route_posthog_code_event_to_relevant_region(# posts the follow-up pipeline discards are the ones it exists for. Emitting here rather# than inside that pipeline keeps the two independent.if event_type == "message":+ # A mirror copy exists only to feed the receiving region's emit — the sender's pipeline+ # already handles the event itself, so running the drops below would double-handle it.+ if _is_emit_only_mirror(request):+ emit_slack_message_event(+ event,+ slack_team_id,+ event_id=event_id,+ is_ext_shared_channel=is_ext_shared_channel,+ )+ return ROUTE_HANDLED_LOCALLY+should_try_other_region = emit_slack_message_event(event,slack_team_id,@@ -2049,10 +2148,20 @@ def route_posthog_code_event_to_relevant_region(is_ext_shared_channel=is_ext_shared_channel,)# The emit sees only this region's connections, and the drops below end a top-level post- # before the pipeline's region gate could forward it. No US-precedence probe: for a- # channel trigger, whichever region holds the connection should run the workflow.- if should_try_other_region and not proxied and cross_region_routing_enabled():- return _proxy_event_and_return_route(request, other_domain)+ # before the pipeline's region gate could forward it. For a channel trigger, every+ # region holding a connection should run its workflows: with no local connection the+ # whole event defers to the other region, and with one the event is handled here and a+ # workspace connected over there as well gets an emit-only mirror.+ if not proxied and cross_region_routing_enabled():+ if should_try_other_region:+ return _proxy_event_and_return_route(request, other_domain)+ _mirror_message_event_to_other_region(+ request,+ event,+ slack_team_id=slack_team_id,+ incoming_host=incoming_host,+ other_domain=other_domain,+ )if event_type == "app_mention":ignore_reason = _app_mention_ignore_reason(event)@@ -2084,8 +2193,7 @@ def route_posthog_code_event_to_relevant_region()return ROUTE_HANDLED_LOCALLY# Top-level channel posts dominate the wire volume; drop before the pipeline's DB hits.- top_level_thread_ts = event.get("thread_ts")- if not isinstance(top_level_thread_ts, str) or top_level_thread_ts == event.get("ts"):+ if _is_top_level_channel_post(event):return ROUTE_HANDLED_LOCALLYslack_user_id_str = str(event.get("user") or "")diff --git a/products/slack_app/backend/slack_workflow_events.py b/products/slack_app/backend/slack_workflow_events.pyindex ddff96a7c8b8..da9c76862bcf 100644--- a/products/slack_app/backend/slack_workflow_events.py+++ b/products/slack_app/backend/slack_workflow_events.py@@ -58,6 +58,15 @@ def _event_properties(}+def is_triggering_message(event: dict[str, Any]) -> bool:+ """Whether a workflow trigger could fire on this message, and the emit would write it out.++ Exposed so the webhook can decide about a cross-region mirror without spending a probe or a+ hop on the subtypes (edits, joins, deletions) no trigger fires on.+ """+ return bool(settings.SLACK_WORKFLOW_TRIGGERS_ENABLED) and event.get("subtype") in _TRIGGERING_SUBTYPES++def emit_slack_message_event(event: dict[str, Any],slack_team_id: str,@@ -75,10 +84,7 @@ def emit_slack_message_event(Never raises. This runs inside the Slack event webhook, which owes Slack an ack within threeseconds and shares the handler with mention routing, so a failure here has to cost neither."""- if not settings.SLACK_WORKFLOW_TRIGGERS_ENABLED:- return False-- if event.get("subtype") not in _TRIGGERING_SUBTYPES:+ if not is_triggering_message(event):return Falsetry:diff --git a/products/slack_app/backend/tasks.py b/products/slack_app/backend/tasks.pynew file mode 100644index 000000000000..6492a018fb87--- /dev/null+++ b/products/slack_app/backend/tasks.py@@ -0,0 +1,31 @@+"""Celery tasks for the Slack app product."""++from celery import shared_task++from products.slack_app.backend.api import (+ SLACK_INTEGRATION_KIND,+ does_other_region_claim_workspace,+ send_region_proxy_request,+)+++@shared_task(ignore_result=True)+def mirror_slack_message_event(+ *, slack_team_id: str, incoming_host: str, target_url: str, headers: dict[str, str], body: str+) -> None:+ """Deliver an emit-only mirror of a channel message to the other region.++ Runs out of band so the Slack webhook acks within its budget instead of waiting on the claims+ probe and the cross-region POST. No retries: the receiver rejects Slack timestamps older than+ five minutes, and a lost mirror costs the other region one message, which the caller accepts.+ """+ claimed = does_other_region_claim_workspace(+ slack_team_id=slack_team_id,+ kinds=[SLACK_INTEGRATION_KIND],+ incoming_host=incoming_host,+ )+ if not claimed:+ return+ # The body rides as text because Celery serializes arguments to JSON. Slack signs the raw+ # bytes, and the payload is UTF-8 JSON, so the decode/encode round trip is byte-exact.+ send_region_proxy_request(method="POST", target_url=target_url, headers=headers, body=body.encode("utf-8"))diff --git a/products/slack_app/backend/tests/test_thread_message_routing.py b/products/slack_app/backend/tests/test_thread_message_routing.pyindex 15f409bbba5f..72246232e12b 100644--- a/products/slack_app/backend/tests/test_thread_message_routing.py+++ b/products/slack_app/backend/tests/test_thread_message_routing.py@@ -2,7 +2,7 @@ from unittest.mock import patchfrom django.apps import appsfrom django.core.cache import cache-from django.test import TestCase, override_settings+from django.test import SimpleTestCase, TestCase, override_settingsfrom django.test.client import RequestFactoryfrom django.utils import timezone@@ -183,15 +183,25 @@ class TestRouteThreadMessage(TestCase):@parameterized.expand([- ("owned here", "T_SLACK", None, False),- ("owned by the other region", "T_OTHER_REGION", None, True),- # Nothing to trigger on, so no reason to spend a hop looking for a region that wants it.- ("an edit, owned by the other region", "T_OTHER_REGION", "message_changed", False),+ # The claims probe runs inside the queued task, so the webhook queues a mirror for+ # every locally-owned top-level post and the task decides whether it leaves the region.+ ("owned here", "T_SLACK", None, False, True),+ ("owned by the other region", "T_OTHER_REGION", None, True, False),+ # Nothing to trigger on, so no reason to queue a task looking for a region that wants it.+ ("an edit, owned by the other region", "T_OTHER_REGION", "message_changed", False, False),+ ("an edit, owned here", "T_SLACK", "message_changed", False, False),])@override_settings(SLACK_WORKFLOW_TRIGGERS_ENABLED=True)- def test_top_level_post_reaches_the_region_owning_the_workspace(self, _name, slack_team_id, subtype, expect_proxy):- from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, ROUTE_PROXIED+ def test_top_level_post_reaches_every_region_holding_the_workspace(+ self, _name, slack_team_id, subtype, expect_full_proxy, expect_mirror_dispatch+ ):+ from products.slack_app.backend.api import (+ EMIT_ONLY_MIRROR_HEADER,+ REGION_PROXY_HEADER,+ ROUTE_HANDLED_LOCALLY,+ ROUTE_PROXIED,+ )# thread_ts == ts, so a top-level postevent = self._make_event(thread_ts="1001.0000")@@ -200,12 +210,73 @@ class TestRouteThreadMessage(TestCase):with (patch("products.slack_app.backend.api.cross_region_routing_enabled", return_value=True),patch("products.slack_app.backend.api._proxy_event_to_region") as mock_proxy,+ patch("products.slack_app.backend.tasks.mirror_slack_message_event.delay") as mock_delay,patch("products.slack_app.backend.slack_workflow_events.produce_internal_event"),):result = self._route(event, slack_team_id=slack_team_id)- assert result == (ROUTE_PROXIED if expect_proxy else ROUTE_HANDLED_LOCALLY)- assert mock_proxy.called is expect_proxy+ assert result == (ROUTE_PROXIED if expect_full_proxy else ROUTE_HANDLED_LOCALLY)+ assert mock_proxy.called is expect_full_proxy+ assert mock_delay.called is expect_mirror_dispatch+ if expect_mirror_dispatch:+ kwargs = mock_delay.call_args.kwargs+ assert kwargs["headers"][EMIT_ONLY_MIRROR_HEADER] == "1"+ # Without the proxy marker the receiver would treat the mirror as a fresh Slack+ # delivery and hop it back, so its absence is a routing-loop regression.+ assert kwargs["headers"][REGION_PROXY_HEADER] == "1"+ assert "eu.posthog.com" in kwargs["target_url"]++ @override_settings(SLACK_WORKFLOW_TRIGGERS_ENABLED=True)+ def test_emit_only_mirror_emits_for_local_projects_and_nothing_else(self):+ from products.slack_app.backend.api import (+ EMIT_ONLY_MIRROR_HEADER,+ REGION_PROXY_HEADER,+ ROUTE_HANDLED_LOCALLY,+ route_posthog_code_event_to_relevant_region,+ )++ event = self._make_event(thread_ts="1001.0000")+ request = self.factory.post(+ "/slack/event-callback/",+ HTTP_HOST="us.posthog.com",+ headers={REGION_PROXY_HEADER: "1", EMIT_ONLY_MIRROR_HEADER: "1"},+ )+ with (+ patch("products.slack_app.backend.api.cross_region_routing_enabled", return_value=True),+ patch("products.slack_app.backend.api._proxy_event_to_region") as mock_proxy,+ patch("products.slack_app.backend.slack_workflow_events.produce_internal_event") as mock_produce,+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,+ ):+ result = route_posthog_code_event_to_relevant_region(request, event, "T_SLACK")++ assert result == ROUTE_HANDLED_LOCALLY+ mock_produce.assert_called_once()+ assert mock_produce.call_args.args[0] == self.team.id+ mock_proxy.assert_not_called()+ mock_start.assert_not_called()++ @override_settings(SLACK_WORKFLOW_TRIGGERS_ENABLED=True)+ def test_thread_reply_crosses_once_via_region_gate_not_mirror(self):+ # A thread reply on a workspace held in both regions must cross exactly once. The follow-up+ # pipeline's region gate already forwards it to the region that also claims the workspace, so+ # adding an emit-only mirror would make that region emit the reply twice and trigger a+ # workflow twice. Deliver to EU (can defer) with the other region claiming the workspace.+ from products.slack_app.backend.api import ROUTE_PROXIED, route_posthog_code_event_to_relevant_region++ event = self._make_event() # thread_ts != ts, a reply+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ with (+ patch("products.slack_app.backend.api.cross_region_routing_enabled", return_value=True),+ patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=True),+ patch("products.slack_app.backend.api._proxy_event_to_region") as mock_proxy,+ patch("products.slack_app.backend.tasks.mirror_slack_message_event.delay") as mock_delay,+ patch("products.slack_app.backend.slack_workflow_events.produce_internal_event"),+ ):+ result = route_posthog_code_event_to_relevant_region(request, event, "T_SLACK")++ assert result == ROUTE_PROXIED+ mock_proxy.assert_called_once()+ mock_delay.assert_not_called()# --- Mapping + FF gate -------------------------------------------------@@ -456,3 +527,41 @@ class TestRouteThreadMessage(TestCase):assert first.kwargs["posthog_user"].id == self.user.idassert second.kwargs["untagged_followup"] is Trueassert second.kwargs["posthog_user"].id == self.user.id+++class TestMirrorSlackMessageEventTask(SimpleTestCase):+ """The queued mirror task owns the claims probe, so the webhook-side tests above cannot+ cover it: only the task decides whether a mirror actually leaves the region."""++ @parameterized.expand(+ [+ ("other region claims the workspace", True, True),+ ("other region does not claim it", False, False),+ # An unknown answer must not turn into cross-region traffic for every message.+ ("claims probe failed", None, False),+ ]+ )+ def test_sends_only_when_the_other_region_claims_the_workspace(self, _name, claimed, expect_sent):+ from products.slack_app.backend.tasks import mirror_slack_message_event++ with (+ patch(+ "products.slack_app.backend.tasks.does_other_region_claim_workspace",+ return_value=claimed,+ ),+ patch("products.slack_app.backend.tasks.send_region_proxy_request") as mock_send,+ ):+ mirror_slack_message_event(+ slack_team_id="T_SLACK",+ incoming_host="eu.posthog.com",+ target_url="https://us.posthog.com/slack/event-callback/",+ headers={"X-PostHog-Region-Proxied": "1", "X-PostHog-Slack-Emit-Only": "1"},+ body='{"type": "event_callback"}',+ )++ assert mock_send.called is expect_sent+ if expect_sent:+ kwargs = mock_send.call_args.kwargs+ assert kwargs["target_url"] == "https://us.posthog.com/slack/event-callback/"+ assert kwargs["headers"]["X-PostHog-Slack-Emit-Only"] == "1"+ assert kwargs["body"] == b'{"type": "event_callback"}'