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(slack-app): run an edited mention the app never handled (#108260)

Vojta Bartoša81a957cbbc5
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 85b1ef7ea37b..a481bb071369 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -152,6 +152,10 @@ SLACK_PLACEHOLDER_USER_ID = "U00"
# person forgot how it works.
ONBOARDING_DEDUPE_TTL_SECONDS = 60 * 10
+EDITED_MENTION_WINDOW_SECONDS = 60 * 60
+# Outlives the window, because an expired marker would let an edit start a second run.
+MESSAGE_HANDLED_MARKER_TTL_SECONDS = 2 * EDITED_MENTION_WINDOW_SECONDS
+
ROUTE_HANDLED_LOCALLY = "handled_locally"
ROUTE_PROXIED = "proxied"
ROUTE_PROXY_FAILED = "proxy_failed"
@@ -1332,6 +1336,10 @@ def _app_mention_ignore_reason(event: dict[str, Any]) -> str | None:
"""
if event.get("edited") or event.get("subtype") == "message_changed":
return "edit"
+ return _mention_content_ignore_reason(event)
+
+
+def _mention_content_ignore_reason(event: dict[str, Any]) -> str | None:
authorship = _app_authorship_ignore_reason(event)
if authorship:
return authorship
@@ -1340,6 +1348,46 @@ def _app_mention_ignore_reason(event: dict[str, Any]) -> str | None:
return None
+def _message_handled_cache_key(slack_team_id: str, event: dict[str, Any]) -> str | None:
+ channel = event.get("channel")
+ message_ts = event.get("ts")
+ if not isinstance(channel, str) or not channel or not isinstance(message_ts, str) or not message_ts:
+ return None
+ return f"slack_app:message_handled:v1:{slack_team_id}:{channel}:{message_ts}"
+
+
+def _mark_message_handled(slack_team_id: str, event: dict[str, Any], handled_as: str) -> None:
+ """Record that the pipeline acted on this message, so that a later edit of it starts nothing."""
+ cache_key = _message_handled_cache_key(slack_team_id, event)
+ if cache_key is not None:
+ cache.set(cache_key, handled_as, timeout=MESSAGE_HANDLED_MARKER_TTL_SECONDS)
+
+
+def _edited_mention_ignore_cause(event: dict[str, Any], slack_team_id: str) -> str | None:
+ """Why an edited ``app_mention`` must start nothing, or None when it must start a run.
+
+ The marker claim is atomic and comes last, so a second edit of the same message stops here.
+ """
+ # The envelope nests the message, so its top-level ``ts`` is the ts of the change.
+ if event.get("subtype") == "message_changed":
+ return "message_changed_envelope"
+ content_reason = _mention_content_ignore_reason(event)
+ if content_reason:
+ return content_reason
+ cache_key = _message_handled_cache_key(slack_team_id, event)
+ if cache_key is None:
+ return "no_message_ts"
+ try:
+ posted_at = float(event["ts"])
+ except ValueError:
+ return "no_message_ts"
+ if time.time() - posted_at > EDITED_MENTION_WINDOW_SECONDS:
+ return "too_old"
+ if not cache.add(cache_key, "edited_mention", timeout=MESSAGE_HANDLED_MARKER_TTL_SECONDS):
+ return f"handled_as_{cache.get(cache_key) or 'unknown'}"
+ return None
+
+
def _thread_message_event_has_files(event: dict[str, Any]) -> bool:
files = event.get("files")
return isinstance(files, list) and len(files) > 0
@@ -2266,10 +2314,26 @@ def route_posthog_code_event_to_relevant_region(
if event_type == "app_mention":
ignore_reason = _app_mention_ignore_reason(event)
+ drop_context: dict[str, Any] = {}
+ if ignore_reason == "edit":
+ edit_ignore_cause = _edited_mention_ignore_cause(event, slack_team_id)
+ if edit_ignore_cause is None:
+ ignore_reason = None
+ logger.info(
+ "slack_app_edited_mention_accepted",
+ slack_team_id=slack_team_id,
+ channel=event.get("channel"),
+ message_ts=event.get("ts"),
+ )
+ else:
+ drop_context = {"edit_ignore_cause": edit_ignore_cause}
+ elif ignore_reason == "path_mention":
+ drop_context = _path_mention_drop_properties(event)
+ elif ignore_reason is None:
+ # Marked before the later gates, so that an edit of a refused mention does not
+ # repeat the explanation.
+ _mark_message_handled(slack_team_id, event, "mention")
if ignore_reason:
- drop_context: dict[str, Any] = (
- _path_mention_drop_properties(event) if ignore_reason == "path_mention" else {}
- )
logger.info(
"slack_app_event_app_mention_ignored",
reason=ignore_reason,
@@ -2561,6 +2625,9 @@ def route_posthog_code_event_to_relevant_region(
):
return ROUTE_HANDLED_LOCALLY
+ if untagged_followup_mapping is not None:
+ _mark_message_handled(slack_team_id, event, "untagged_followup")
+
return _start_mention_workflow(
event,
mention_target,
@@ -3507,6 +3574,7 @@ def _report_slack_mention_received(
# ``posthog code slack mention dropped`` reports the same field, so the two sides
# add up to a funnel.
"slack_event_type": event.get("type"),
+ "slack_message_edited": bool(event.get("edited")),
# "im" marks an assistant DM; channel mentions carry "channel"/"group" or no type at all.
"slack_channel_type": event.get("channel_type"),
"posthog_user_identified": identified_distinct_id is not None,
diff --git a/products/slack_app/backend/tests/test_thread_message_routing.py b/products/slack_app/backend/tests/test_thread_message_routing.py
index 5d0b1d748dbc..d7d5d58c64aa 100644
--- a/products/slack_app/backend/tests/test_thread_message_routing.py
+++ b/products/slack_app/backend/tests/test_thread_message_routing.py
@@ -1,3 +1,5 @@
+import time
+
from unittest.mock import patch
from django.apps import apps
@@ -536,6 +538,64 @@ class TestRouteThreadMessage(TestCase):
if expect_workflow:
assert mock_start.call_args.kwargs["untagged_followup"] is True
+ # --- Edits that add the tag --------------------------------------------
+
+ @parameterized.expand(
+ [
+ ("never_seen_before_the_edit", None, 20, {}, None),
+ ("reply_dropped_with_followups_off", "untagged_reply_followups_off", 20, {}, None),
+ ("original_mention_already_handled", "mention", 20, {}, "handled_as_mention"),
+ ("untagged_reply_already_dispatched", "untagged_reply", 20, {}, "handled_as_untagged_followup"),
+ ("second_edit_of_the_same_message", "edited_mention", 20, {}, "handled_as_edited_mention"),
+ ("posted_before_the_window", None, 2 * 60 * 60, {}, "too_old"),
+ ("message_changed_envelope", None, 20, {"subtype": "message_changed"}, "message_changed_envelope"),
+ ]
+ )
+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
+ def test_edited_mention_runs_only_when_the_message_was_never_handled(
+ self, _name, earlier, posted_seconds_ago, edit_overrides, expected_ignore_cause
+ ):
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, SLACK_MENTION_DROPPED_EVENT
+
+ now = time.time()
+ untagged_reply = self._make_event(user="U_ALICE", ts=f"{now - posted_seconds_ago:.6f}")
+ mention = {**untagged_reply, "type": "app_mention", "text": "<@U0BOT> check the export filter logic"}
+ edited_mention = {**mention, "edited": {"user": "U_ALICE", "ts": f"{now:.6f}"}, **edit_overrides}
+ earlier_events = {
+ "untagged_reply": untagged_reply,
+ "untagged_reply_followups_off": untagged_reply,
+ "mention": mention,
+ "edited_mention": edited_mention,
+ }
+ if earlier == "untagged_reply_followups_off":
+ self._set_creator_mode(UntaggedFollowupMode.NEVER)
+
+ with (
+ patch(
+ "products.slack_app.backend.api._start_mention_workflow", return_value=ROUTE_HANDLED_LOCALLY
+ ) as mock_start,
+ patch("products.slack_app.backend.api.posthoganalytics.capture") as mock_capture,
+ ):
+ if earlier is not None:
+ self._route(earlier_events[earlier])
+ mock_start.reset_mock()
+ mock_capture.reset_mock()
+ result = self._route(edited_mention)
+
+ assert result == ROUTE_HANDLED_LOCALLY
+ assert mock_start.called is (expected_ignore_cause is None)
+ if expected_ignore_cause is None:
+ assert mock_start.call_args.kwargs.get("untagged_followup", False) is False
+ else:
+ drops = [
+ call.kwargs["properties"]
+ for call in mock_capture.call_args_list
+ if call.kwargs["event"] == SLACK_MENTION_DROPPED_EVENT
+ ]
+ assert [(drop["drop_reason"], drop.get("edit_ignore_cause")) for drop in drops] == [
+ ("ignored:edit", expected_ignore_cause)
+ ]
+
class TestMirrorSlackMessageEventTask(SimpleTestCase):
"""The queued mirror task owns the claims probe, so the webhook-side tests above cannot