: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
feat(slack): randomize ack emoji on @PostHog mentions (#60469)
Andrew Maguireef4e4425f3e4
diff --git a/posthog/temporal/ai/posthog_code_slack_mention.py b/posthog/temporal/ai/posthog_code_slack_mention.pyindex 8a4c8071a039..9ee013b3f069 100644--- a/posthog/temporal/ai/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/posthog_code_slack_mention.py@@ -17,7 +17,12 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat import Heartbeaterfrom products.slack_app.backend.models import SlackThreadTaskMapping-from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler+from products.slack_app.backend.slack_thread import (+ SlackThreadContext,+ SlackThreadHandler,+ ack_emoji_for,+ stale_ack_emojis_for,+)from products.tasks.backend.models import Taskfrom products.tasks.backend.repo_selection import (RepoSelectionRejectedError,@@ -1126,8 +1131,8 @@ def create_posthog_code_task_for_repo_activity()slack = SlackIntegration(integration)- # Refuse before the :seedling: reaction or the permalink fetch: a denied- # mention should not first ack-react and then refuse a second later.+ # Refuse before the ack reaction or the permalink fetch: a denied mention+ # should not first ack-react and then refuse a second later.if _block_if_team_over_quota(integration=integration,slack=slack,@@ -1140,7 +1145,10 @@ def create_posthog_code_task_for_repo_activity(user_message_ts = event.get("ts")if user_message_ts:- _safe_react(slack.client, channel, user_message_ts, "seedling")+ # Deterministic per ts so activity retries (maximum_attempts=3) land on+ # the same emoji and `_safe_react`'s `already_reacted` short-circuit+ # keeps the ack idempotent.+ _safe_react(slack.client, channel, user_message_ts, ack_emoji_for(user_message_ts))user_text = re.sub(r"<@[A-Z0-9]+>", "", event.get("text", "")).strip()title = user_text[:255] if user_text else "Task from Slack"@@ -1594,7 +1602,7 @@ def _set_followup_done_reaction(slack: Any, channel: str, user_message_ts: str |if not user_message_ts:return- for stale_emoji in ("eyes", "seedling"):+ for stale_emoji in stale_ack_emojis_for(user_message_ts):try:slack.client.reactions_remove(channel=channel, timestamp=user_message_ts, name=stale_emoji)except Exception:diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.pyindex c5b7e3ba8736..2095ab3a11db 100644--- a/products/slack_app/backend/slack_thread.py+++ b/products/slack_app/backend/slack_thread.py@@ -1,4 +1,5 @@import re+import hashlibfrom dataclasses import dataclassfrom typing import Any@@ -15,6 +16,102 @@ UPSTREAM_PROVIDER_FAILURE_MESSAGE = ()UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN = re.compile(r"\bapi error:\s*(?:429|5\d\d)\b", re.IGNORECASE)+# Legacy fixed ack emoji. Tasks ack'd before the deterministic pool landed used+# `:seedling:` exclusively; cleanup still tries to remove it so in-flight tasks+# at deploy time don't end up with a stale reaction. Can be dropped a release+# cycle after this lands.+_LEGACY_ACK_EMOJI = "seedling"++# Pool of fun, universally-available Slack emoji names used to acknowledge a mention+# before the bot starts the longer-running work. Anything in this pool is treated as+# an in-progress signal by `update_reaction` / `_set_followup_done_reaction` and is+# cleaned up when the bot reaches a terminal state. Keep these distinct from the+# stage-specific reactions (:mag: for searching, :hedgehog: for done, :x: for failed)+# and from "eyes" (the follow-up ack), so the cleanup pool stays unambiguous.+RANDOM_ACK_EMOJIS: tuple[str, ...] = (+ # Friendly greetings & thinking+ "seedling",+ "wave",+ "robot_face",+ "thinking_face",+ "nerd_face",+ "sunglasses",+ # Energy & magic+ "sparkles",+ "rocket",+ "zap",+ "crystal_ball",+ "mage",+ "star2",+ "dizzy",+ "rainbow",+ # Working / tinkering+ "hammer_and_wrench",+ "gear",+ "coffee",+ "keyboard",+ "telescope",+ "brain",+ "bulb",+ "compass",+ # Nature & luck+ "four_leaf_clover",+ "cherry_blossom",+ "sunflower",+ "herb",+ # Animal companions+ "owl",+ "otter",+ "penguin",+ "fox_face",+ "bee",+ "butterfly",+ "unicorn_face",+ "turtle",+ "panda_face",+ "koala",+ "hamster",+ # Play & whimsy+ "art",+ "balloon",+ "game_die",+ # Characters+ "ninja",+ "alien",+ "space_invader",+)+++def ack_emoji_for(message_ts: str) -> str:+ """Pick an emoji from the ack pool deterministically per Slack message ts.++ `create_posthog_code_task_for_repo_activity` retries up to 3 times. With a+ truly random pick, each retry could choose a different emoji and bypass+ `_safe_react`'s `already_reacted` short-circuit, piling extra reactions on+ the user's mention. Keying the choice on the message ts keeps every replay+ landing on the same emoji. `hashlib` (not `hash()`) is used so the choice+ is stable across worker processes — PYTHONHASHSEED randomization would+ otherwise diverge per replay.+ """+ digest = hashlib.sha256(message_ts.encode("utf-8")).digest()+ return RANDOM_ACK_EMOJIS[int.from_bytes(digest[:4], "big") % len(RANDOM_ACK_EMOJIS)]+++def stale_ack_emojis_for(message_ts: str) -> tuple[str, ...]:+ """Reactions a cleanup pass should try to remove from `message_ts`.++ `eyes` is the follow-up ack, the deterministic pool pick is the initial+ ack, and `_LEGACY_ACK_EMOJI` covers tasks ack'd before this pool landed.+ Keeping the set small (vs. iterating the full pool) avoids burning the+ `reactions.remove` rate limit on guaranteed-`no_reaction` calls. The+ legacy emoji is also a pool member, so we dedupe when the deterministic+ pick coincidentally lands on it.+ """+ emojis = ["eyes", ack_emoji_for(message_ts)]+ if _LEGACY_ACK_EMOJI not in emojis:+ emojis.append(_LEGACY_ACK_EMOJI)+ return tuple(emojis)+def _format_task_error(error: str) -> str:error = error.strip()@@ -117,7 +214,7 @@ class SlackThreadHandler:target_ts = self.context.user_message_ts or self.context.thread_tstry:client = self._get_client()- for stale in ("seedling", "eyes"):+ for stale in stale_ack_emojis_for(target_ts):try:client.reactions_remove(channel=self.context.channel, timestamp=target_ts, name=stale)except Exception:diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.pyindex a7f854842f1b..c1f19840f020 100644--- a/products/slack_app/backend/tests/test_slack_thread.py+++ b/products/slack_app/backend/tests/test_slack_thread.py@@ -5,10 +5,13 @@ from django.test import TestCasefrom parameterized import parameterizedfrom products.slack_app.backend.slack_thread import (+ RANDOM_ACK_EMOJIS,UPSTREAM_PROVIDER_FAILURE_MESSAGE,SlackThreadContext,SlackThreadHandler,_format_task_error,+ ack_emoji_for,+ stale_ack_emojis_for,)@@ -84,7 +87,7 @@ class TestSlackThreadHandler(TestCase):mock_client.chat_delete.assert_not_called()@patch.object(SlackThreadHandler, "_get_client")- def test_update_reaction_removes_seedling_and_eyes(self, mock_get_client):+ def test_update_reaction_clears_stale_ack_emojis(self, mock_get_client):mock_client = MagicMock()mock_get_client.return_value = mock_client@@ -97,12 +100,38 @@ class TestSlackThreadHandler(TestCase):handler = SlackThreadHandler(context)handler.update_reaction("hedgehog")- remove_calls = mock_client.reactions_remove.call_args_list- assert len(remove_calls) == 2- assert remove_calls[0].kwargs["name"] == "seedling"- assert remove_calls[1].kwargs["name"] == "eyes"+ removed_names = [call.kwargs["name"] for call in mock_client.reactions_remove.call_args_list]+ # Only the candidate ack reactions for this specific ts are removed (not the whole pool),+ # so cleanup stays cheap regardless of pool size.+ assert removed_names == list(stale_ack_emojis_for("1234.5678"))mock_client.reactions_add.assert_called_once_with(channel="C001", timestamp="1234.5678", name="hedgehog")+ def test_ack_emoji_for_is_deterministic_per_ts(self):+ # Same ts must always pick the same emoji — activity retries depend on this for+ # `_safe_react`'s `already_reacted` short-circuit to keep the ack idempotent.+ assert ack_emoji_for("1700000001.000100") == ack_emoji_for("1700000001.000100")+ assert ack_emoji_for("1700000001.000100") in RANDOM_ACK_EMOJIS+ # Different ts values should reach across the pool (sanity check, not a uniformity claim).+ reached = {ack_emoji_for(f"1700000000.{i:06d}") for i in range(500)}+ assert len(reached) >= len(RANDOM_ACK_EMOJIS) // 2++ def test_stale_ack_emojis_for_includes_legacy_seedling_and_eyes(self):+ # `seedling` was the fixed pre-pool ack; tasks ack'd before this code shipped+ # must still be cleanable. `eyes` is the follow-up ack.+ stale = stale_ack_emojis_for("1234.5678")+ assert "eyes" in stale+ assert "seedling" in stale+ assert ack_emoji_for("1234.5678") in stale++ def test_stale_ack_emojis_for_dedupes_when_pick_is_seedling(self):+ # `seedling` is both in the pool and the legacy ack — when the deterministic+ # pick coincidentally lands on it, the tuple should not contain a duplicate.+ seedling_ts = "1700000000.000005"+ assert ack_emoji_for(seedling_ts) == "seedling", "fixture ts no longer maps to seedling"+ stale = stale_ack_emojis_for(seedling_ts)+ assert stale == ("eyes", "seedling")+ assert stale.count("seedling") == 1+@patch.object(SlackThreadHandler, "_get_client")def test_post_pr_opened_posts_buttons(self, mock_get_client):mock_client = MagicMock()