: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(integrations): page slack listings to the end instead of stopping at ten pages (#101950)
Daniel Marchuk1af2779379cc
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 46346f8e98a4..c8d74d91ca1a 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -61,6 +61,7 @@ from posthog.models.user import Userfrom posthog.models.user_integration import GitHubInstallRequest, UserIntegrationfrom posthog.models.utils import hash_key_valuefrom posthog.rate_limit import GitHubRepositoryRefreshThrottle+from posthog.team_notifications.slack import is_shared_channelfrom products.access_control.backend.models.access_control import AccessControlfrom products.batch_exports.backend.models import BatchExport, BatchExportDestination@@ -126,6 +127,216 @@ class TestSlackIntegration:assert channels[3]["id"] == "CP123"assert channels[3]["name"] == "d_private_channel"+ @patch("posthog.models.integration.slack.WebClient")+ def test_list_channels_keeps_only_the_fields_the_api_serves(self, mock_webclient_class):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client+ mock_client.conversations_list.return_value = {+ "channels": [+ {+ "id": "C123",+ "name": "a_channel",+ "is_private": False,+ "is_ext_shared": False,+ "topic": {"value": "x" * 200, "creator": "U1", "last_set": 1},+ "purpose": {"value": "y" * 400, "creator": "U1", "last_set": 1},+ "shared_team_ids": ["T1"],+ "previous_names": ["old_name"],+ }+ ],+ "response_metadata": {"next_cursor": ""},+ }+ mock_client.users_conversations.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}++ channels = SlackIntegration(self.integration).list_channels(True, "test_user_id")++ assert set(channels[0]) == {+ "id",+ "name",+ "is_private",+ "is_member",+ "is_ext_shared",+ "is_pending_ext_shared",+ "is_shared",+ "is_private_without_access",+ }++ @patch("posthog.models.integration.slack.WebClient")+ def test_list_public_channels_keeps_every_shared_flag(self, mock_webclient_class):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client+ mock_client.conversations_list.return_value = {+ "channels": [+ {+ "id": "C123",+ "name": "shared_with_another_org",+ "is_private": False,+ "is_ext_shared": False,+ "is_pending_ext_shared": False,+ "is_shared": True,+ "purpose": {"value": "z" * 400, "creator": "U1", "last_set": 1},+ }+ ],+ "response_metadata": {"next_cursor": ""},+ }++ channels = SlackIntegration(self.integration).list_public_channels()++ # team_notifications reads all three flags to keep an internal message out of a channel+ # shared beyond the workspace. A dropped flag reads as not shared.+ assert is_shared_channel(channels[0])++ @patch("posthog.models.integration.slack.WebClient")+ def test_list_channels_follows_the_cursor_past_ten_pages(self, mock_webclient_class):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client++ # Slack returns fewer channels than the requested limit whenever it likes, so a workspace+ # needs more pages than its channel count suggests. A page-count cap drops the remainder+ # with no error, and the channel it drops reads to the user as "the app is not in it".+ pages = 15++ def conversations_list(cursor=None, **kwargs):+ page = int(cursor or 0)+ return {+ "channels": [+ {"id": f"C{page}", "name": f"channel_{page:02d}", "is_private": False, "is_ext_shared": False}+ ],+ "response_metadata": {"next_cursor": str(page + 1) if page + 1 < pages else ""},+ }++ mock_client.conversations_list.side_effect = conversations_list+ mock_client.users_conversations.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}++ channels = SlackIntegration(self.integration).list_channels(True, "test_user_id")++ assert len(channels) == pages+ assert channels[-1]["name"] == "channel_14"++ @patch("posthog.models.integration.slack.WebClient")+ def test_list_channels_records_a_listing_it_had_to_cut_short(self, mock_webclient_class):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client++ # A cap that stops a listing early is the failure this whole change is about: the caller+ # cannot tell a partial list from a complete one, so the cap has to leave a trail.+ mock_client.conversations_list.side_effect = lambda cursor=None, **kwargs: {+ "channels": [+ {"id": f"C{cursor or 0}", "name": f"channel_{cursor or 0}", "is_private": False, "is_ext_shared": False}+ ],+ "response_metadata": {"next_cursor": str(int(cursor or 0) + 1)},+ }+ mock_client.users_conversations.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}++ with patch("posthog.models.integration.slack.SLACK_LISTING_MAX_REQUESTS", 3):+ with patch("posthog.models.integration.slack.slack_listing_truncated_counter") as mock_counter:+ channels = SlackIntegration(self.integration).list_channels(True, "test_user_id")++ assert len(channels) == 3+ mock_counter.labels.assert_called_once_with(kind="channels_public_channel")+ mock_counter.labels.return_value.inc.assert_called_once()++ @patch("posthog.models.integration.slack.WebClient")+ def test_list_channels_keeps_its_pages_when_slack_rate_limits_mid_walk(self, mock_webclient_class):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client++ # These endpoints are rate limited per workspace and the client does not retry. Raising+ # would hand the caller no channels at all, which is worse than the short list it used to+ # get, and nothing is cached to fall back on.+ first_page = {+ "channels": [{"id": "C1", "name": "a_channel", "is_private": False, "is_ext_shared": False}],+ "response_metadata": {"next_cursor": "1"},+ }+ rate_limited = SlackApiError("ratelimited", {"ok": False, "error": "ratelimited"})+ mock_client.conversations_list.side_effect = [first_page, rate_limited]+ mock_client.users_conversations.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}++ channels = SlackIntegration(self.integration).list_channels(True, "test_user_id")++ assert [channel["id"] for channel in channels] == ["C1"]++ @patch("posthog.models.integration.slack.WebClient")+ def test_get_channel_by_id_keeps_the_channel_when_membership_cannot_be_proven(self, mock_webclient_class):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client++ # An unfinished member scan means membership is unproven, not disproven. Hiding the channel+ # here is the same silent empty result this change exists to remove.+ mock_client.conversations_info.return_value = {+ "channel": {+ "id": "C123",+ "name": "huge_channel",+ "is_private": False,+ "is_ext_shared": False,+ "num_members": 50000,+ }+ }+ mock_client.conversations_members.return_value = {+ "members": ["U1"],+ "response_metadata": {"next_cursor": "keep-going"},+ }++ channel = SlackIntegration(self.integration).get_channel_by_id("C123", True, "test_user_id")++ assert channel is not None+ assert channel["id"] == "C123"+ assert channel["name"] == "huge_channel"++ @patch("posthog.models.integration.slack.WebClient")+ def test_get_channel_by_id_masks_a_private_name_it_cannot_prove_access_to(self, mock_webclient_class):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client++ # Keeping the channel is about availability, not access. An unfinished scan cannot prove the+ # connecting user is in a private channel, so the name stays masked.+ mock_client.conversations_info.return_value = {+ "channel": {+ "id": "CP123",+ "name": "secret_leadership_channel",+ "is_private": True,+ "is_ext_shared": False,+ "num_members": 50000,+ }+ }+ mock_client.conversations_members.return_value = {+ "members": ["U1"],+ "response_metadata": {"next_cursor": "keep-going"},+ }++ channel = SlackIntegration(self.integration).get_channel_by_id("CP123", True, "test_user_id")++ assert channel is not None+ assert channel["name"] == PRIVATE_CHANNEL_WITHOUT_ACCESS+ assert channel["is_private_without_access"] is True++ @patch("posthog.models.integration.slack.WebClient")+ def test_get_channel_by_id_finds_a_member_past_the_first_page(self, mock_webclient_class):+ mock_client = MagicMock()+ mock_webclient_class.return_value = mock_client++ # conversations.members returns at most 1000 ids per call whatever limit is asked for, so a+ # bigger limit does not reach member 1001. Without following the cursor the connecting user+ # reads as a non-member and the channel resolves to nothing.+ mock_client.conversations_info.return_value = {+ "channel": {+ "id": "C123",+ "name": "big_channel",+ "is_private": False,+ "is_ext_shared": False,+ "num_members": 1500,+ }+ }+ mock_client.conversations_members.side_effect = [+ {"members": [f"U{i}" for i in range(1000)], "response_metadata": {"next_cursor": "1000"}},+ {"members": ["test_user_id"], "response_metadata": {"next_cursor": ""}},+ ]++ channel = SlackIntegration(self.integration).get_channel_by_id("C123", True, "test_user_id")++ assert channel is not None+ assert channel["id"] == "C123"+@patch("posthog.models.integration.slack.WebClient")def test_list_users_excludes_ineligible_members(self, mock_webclient_class):mock_client = MagicMock()@@ -245,13 +456,16 @@ class TestSlackIntegration:"channel": {"id": "C123", "name": "general", "is_private": True, "is_ext_shared": False, "num_members": 10}}- mock_client.conversations_members.return_value = {"members": ["test_user_id", "U2", "U3"]}+ mock_client.conversations_members.return_value = {+ "members": ["test_user_id", "U2", "U3"],+ "response_metadata": {"next_cursor": ""},+ }slack = SlackIntegration(self.integration)channel = slack.get_channel_by_id("C123", True, "test_user_id")mock_client.conversations_info.assert_called_once_with(channel="C123", include_num_members=True)- mock_client.conversations_members.assert_called_once_with(channel="C123", limit=11)+ mock_client.conversations_members.assert_called_once_with(channel="C123", limit=1000, cursor=None)assert channel is not Noneassert channel["id"] == "C123"@@ -268,13 +482,16 @@ class TestSlackIntegration:"channel": {"id": "C123", "name": "general", "is_private": True, "is_ext_shared": False, "num_members": 10}}- mock_client.conversations_members.return_value = {"members": ["test_user_id", "U2", "U3"]}+ mock_client.conversations_members.return_value = {+ "members": ["test_user_id", "U2", "U3"],+ "response_metadata": {"next_cursor": ""},+ }slack = SlackIntegration(self.integration)channel = slack.get_channel_by_id("C123", False, "test_user_id")mock_client.conversations_info.assert_called_once_with(channel="C123", include_num_members=True)- mock_client.conversations_members.assert_called_once_with(channel="C123", limit=11)+ mock_client.conversations_members.assert_called_once_with(channel="C123", limit=1000, cursor=None)assert channel is not Noneassert channel["id"] == "C123"@@ -291,13 +508,16 @@ class TestSlackIntegration:"channel": {"id": "C123", "name": "general", "is_private": False, "is_ext_shared": False, "num_members": 10}}- mock_client.conversations_members.return_value = {"members": ["test_user_id", "U2", "U3"]}+ mock_client.conversations_members.return_value = {+ "members": ["test_user_id", "U2", "U3"],+ "response_metadata": {"next_cursor": ""},+ }slack = SlackIntegration(self.integration)channel = slack.get_channel_by_id("C123", True, "test_user_id")mock_client.conversations_info.assert_called_once_with(channel="C123", include_num_members=True)- mock_client.conversations_members.assert_called_once_with(channel="C123", limit=11)+ mock_client.conversations_members.assert_called_once_with(channel="C123", limit=1000, cursor=None)assert channel is not Noneassert channel["id"] == "C123"@@ -314,13 +534,16 @@ class TestSlackIntegration:"channel": {"id": "C123", "name": "general", "is_private": False, "is_ext_shared": False, "num_members": 10}}- mock_client.conversations_members.return_value = {"members": ["test_user_id", "U2", "U3"]}+ mock_client.conversations_members.return_value = {+ "members": ["test_user_id", "U2", "U3"],+ "response_metadata": {"next_cursor": ""},+ }slack = SlackIntegration(self.integration)channel = slack.get_channel_by_id("C123", False, "test_user_id")mock_client.conversations_info.assert_called_once_with(channel="C123", include_num_members=True)- mock_client.conversations_members.assert_called_once_with(channel="C123", limit=11)+ mock_client.conversations_members.assert_called_once_with(channel="C123", limit=1000, cursor=None)assert channel is not Noneassert channel["id"] == "C123"diff --git a/posthog/models/integration/__init__.py b/posthog/models/integration/__init__.pyindex 8e68dd65e319..d0636ed91a35 100644--- a/posthog/models/integration/__init__.py+++ b/posthog/models/integration/__init__.py@@ -123,9 +123,9 @@ from .refresh_tracking import ()from .slack import (PRIVATE_CHANNEL_WITHOUT_ACCESS,- SLACK_CHANNELS_MAX_PAGES,SLACK_CHANNELS_PAGE_SIZE,SLACK_INTEGRATION_KINDS,+ SLACK_LISTING_MAX_REQUESTS,SlackIntegration,SlackIntegrationError,SlackRequestSignature,@@ -190,7 +190,7 @@ __all__ = ["SlackIntegrationError","SLACK_INTEGRATION_KINDS","SLACK_CHANNELS_PAGE_SIZE",- "SLACK_CHANNELS_MAX_PAGES",+ "SLACK_LISTING_MAX_REQUESTS","SlackIntegration","SlackRequestSignature","sign_slack_request",diff --git a/posthog/models/integration/slack.py b/posthog/models/integration/slack.pyindex c39fb46d112a..02ea5c8e3439 100644--- a/posthog/models/integration/slack.py+++ b/posthog/models/integration/slack.py@@ -15,7 +15,9 @@ if TYPE_CHECKING:from django.http import HttpRequest+import structlogfrom opentelemetry import trace+from prometheus_client import Counterfrom rest_framework.request import Requestfrom slack_sdk.errors import SlackApiError@@ -26,6 +28,13 @@ from posthog.models.instance_setting import get_instance_settingsfrom . import modeltracer = trace.get_tracer(__name__)+logger = structlog.get_logger(__name__)++slack_listing_truncated_counter = Counter(+ "slack_listing_truncated",+ "Slack listings that hit a safety cap and dropped the remainder, by listing kind",+ labelnames=["kind"],+)PRIVATE_CHANNEL_WITHOUT_ACCESS = "PRIVATE_CHANNEL_WITHOUT_ACCESS"@@ -35,11 +44,43 @@ class SlackIntegrationError(Exception):pass+class SlackMembershipUnknown(SlackIntegrationError):+ """A membership check ran out of budget or hit a rate limit before it could answer.++ Distinct from "not a member": the caller must not turn this into an empty result, because a+ channel that resolves to nothing reads to the user as "the app is not in that channel".+ """+++def _is_rate_limited(error: SlackApiError) -> bool:+ response = getattr(error, "response", None)+ if response is None:+ return False+ return bool(response.get("error") == "ratelimited")++SLACK_INTEGRATION_KINDS: tuple[str, ...] = ("slack",)SLACK_CHANNELS_PAGE_SIZE = 1000-SLACK_CHANNELS_MAX_PAGES = 10+# Slack returns fewer items than the requested limit whenever it likes, so a page count is not an+# item count. A listing stops on whichever cap it reaches first. On short pages that is the request+# count, well short of the item cap, and the request count stays low because the listing runs+# inside a request a person waits on, where a few hundred sequential calls to a rate-limited Slack+# endpoint fail on latency before they finish. _record_truncation logs the items collected and the+# requests made, so the log says which cap stopped the listing.+# The item cap also bounds memory: a listing holds every channel it has collected, and both+# listings run inside one request.+SLACK_LISTING_MAX_ITEMS = 20000++SLACK_LISTING_MAX_REQUESTS = 100++# conversations.members returns at most 1000 ids per call, whatever limit is asked for.+SLACK_MEMBERS_PAGE_SIZE = 1000++# A membership check runs inside a request a person is waiting on, so it gets a much tighter budget+# than a listing. Ten calls covers every channel short of the largest Slack allows.+SLACK_MEMBERS_MAX_REQUESTS = 10class SlackIntegration:@@ -101,19 +142,61 @@ class SlackIntegration:"""return sorted(self._list_channels_by_type("public_channel"), key=lambda x: x["name"])+ def _is_channel_member(self, channel_id: str, authed_user: str | None) -> bool:+ """Slack caps conversations.members at 1000 ids per call whatever limit is asked for, so a+ member past the first page needs the cursor followed rather than a bigger limit."""+ cursor = None+ requests = 0+ seen = 0++ while requests < SLACK_MEMBERS_MAX_REQUESTS:+ requests += 1+ try:+ res = self.client.conversations_members(+ channel=channel_id, limit=SLACK_MEMBERS_PAGE_SIZE, cursor=cursor+ )+ except SlackApiError as e:+ if not _is_rate_limited(e):+ raise+ self._record_truncation("channel_members_rate_limited", collected=seen, requests=requests)+ raise SlackMembershipUnknown() from e+ members = res["members"]+ seen += len(members)+ if authed_user in members:+ return True+ cursor = (res.get("response_metadata") or {}).get("next_cursor")+ if not cursor:+ return False++ self._record_truncation("channel_members", collected=seen, requests=requests)+ raise SlackMembershipUnknown()+def get_channel_by_id(self, channel_id: str, should_include_private_channels: bool = False, authed_user: str | None = None) -> dict | None:try:response = self.client.conversations_info(channel=channel_id, include_num_members=True)channel = response["channel"]- members_response = self.client.conversations_members(channel=channel_id, limit=channel["num_members"] + 1)- isMember = authed_user in members_response["members"]- if not isMember:+ membership_unknown = False+ try:+ is_member = self._is_channel_member(channel_id, authed_user)+ except SlackMembershipUnknown:+ # The scan could not finish, so membership is unproven rather than disproven. Return+ # the channel: the picker shows it and flags that the app may not be in it, which is+ # recoverable, while hiding it is the silent empty result this change exists to stop.+ membership_unknown = True+ is_member = True+ if not is_member:return None- isPrivateWithoutAccess = channel["is_private"] and not should_include_private_channels+ # A private name is only shown to someone proven to be in the channel. Unproven is not+ # proven, so an unfinished scan masks the name the way a caller without access sees it.+ # The listing cannot surface this channel either, because it lists only the private+ # channels the connecting user is in.+ isPrivateWithoutAccess = channel["is_private"] and (+ not should_include_private_channels or membership_unknown+ )return {"id": channel["id"],@@ -128,24 +211,68 @@ class SlackIntegration:return Noneraise+ @staticmethod+ def _trim_channel(channel: dict) -> dict:+ # A Slack channel payload carries topic, purpose, shared team ids and more, about five times+ # the size of what the callers read. A listing holds every channel at once, so keep only the+ # fields they use.+ #+ # Every SHARED_CHANNEL_FLAGS entry has to survive. A dropped flag reads as absent, which+ # reads as not shared, and team_notifications uses that to decide whether a channel matched+ # by name may receive an internal message.+ return {+ "id": channel["id"],+ "name": channel["name"],+ "is_private": channel["is_private"],+ "is_member": channel.get("is_member", True),+ "is_ext_shared": channel["is_ext_shared"],+ "is_pending_ext_shared": channel.get("is_pending_ext_shared", False),+ "is_shared": channel.get("is_shared", False),+ "is_private_without_access": channel.get("is_private_without_access", False),+ }++ @staticmethod+ def _trim_user(member: dict) -> dict:+ # Same reason as _trim_channel. Runs after the workspace and DM checks, which read fields+ # this drops.+ return {+ "id": member["id"],+ "name": member.get("name", ""),+ "real_name": member.get("real_name"),+ "profile": {"display_name": (member.get("profile") or {}).get("display_name")},+ }+def list_users(self) -> list[dict]:"""Human workspace members the bot can DM, as raw Slack member payloads."""- max_page = SLACK_CHANNELS_MAX_PAGESusers: list[dict] = []cursor = None-- while max_page > 0:- max_page -= 1- res = self.client.users_list(limit=SLACK_CHANNELS_PAGE_SIZE, cursor=cursor)+ requests = 0+ fetched = 0++ while requests < SLACK_LISTING_MAX_REQUESTS:+ requests += 1+ try:+ res = self.client.users_list(limit=SLACK_CHANNELS_PAGE_SIZE, cursor=cursor)+ except SlackApiError as e:+ if not _is_rate_limited(e):+ raise+ self._record_truncation("users_rate_limited", collected=fetched, requests=requests)+ return users+ fetched += len(res["members"])users.extend(- member+ self._trim_user(member)for member in res["members"]if self._belongs_to_workspace(member) and self._is_dmable_user(member))- cursor = res["response_metadata"]["next_cursor"]- if not cursor:+ cursor = (res.get("response_metadata") or {}).get("next_cursor")+ # Cap on members fetched, not members kept, so a workspace full of bots and guests+ # cannot page forever.+ if not cursor or fetched >= SLACK_LISTING_MAX_ITEMS:break+ if cursor:+ self._record_truncation("users", collected=fetched, requests=requests)+return usersdef get_user_by_id(self, user_id: str) -> dict | None:@@ -194,37 +321,68 @@ class SlackIntegration:should_include_private_channels: bool = False,authed_user: str | None = None,) -> list[dict]:- max_page = SLACK_CHANNELS_MAX_PAGES- channels = []+ channels: list[dict] = []cursor = None-- while max_page > 0:- max_page -= 1- if type == "public_channel":- res = self.client.conversations_list(- exclude_archived=True, types=type, limit=SLACK_CHANNELS_PAGE_SIZE, cursor=cursor- )- else:- res = self.client.users_conversations(- exclude_archived=True,- types=type,- limit=SLACK_CHANNELS_PAGE_SIZE,- cursor=cursor,- user=authed_user,- )-+ requests = 0++ while requests < SLACK_LISTING_MAX_REQUESTS:+ requests += 1+ try:+ if type == "public_channel":+ res = self.client.conversations_list(+ exclude_archived=True, types=type, limit=SLACK_CHANNELS_PAGE_SIZE, cursor=cursor+ )+ else:+ res = self.client.users_conversations(+ exclude_archived=True,+ types=type,+ limit=SLACK_CHANNELS_PAGE_SIZE,+ cursor=cursor,+ user=authed_user,+ )+ except SlackApiError as e:+ # These endpoints are rate limited per workspace and the client does not retry, so a+ # long walk can run into a 429 part way. Keep the pages already collected: a short+ # list is what the caller got before this change, while raising here would replace it+ # with no channels at all, and nothing is cached to fall back on.+ if not _is_rate_limited(e):+ raise+ self._record_truncation(f"channels_{type}_rate_limited", collected=len(channels), requests=requests)+ return channels++ if type != "public_channel":for channel in res["channels"]:if channel["is_private"] and not should_include_private_channels:channel["name"] = PRIVATE_CHANNEL_WITHOUT_ACCESSchannel["is_private_without_access"] = True- channels.extend(res["channels"])- cursor = res["response_metadata"]["next_cursor"]- if not cursor:+ channels.extend(self._trim_channel(channel) for channel in res["channels"])+ cursor = (res.get("response_metadata") or {}).get("next_cursor")+ if not cursor or len(channels) >= SLACK_LISTING_MAX_ITEMS:break+ if cursor:+ self._record_truncation(f"channels_{type}", collected=len(channels), requests=requests)+return channels+ def _record_truncation(self, kind: str, *, collected: int, requests: int) -> None:+ """A cap stopped a listing with more to fetch, so the caller is holding a partial list.++ Nothing downstream can tell a partial list from a complete one, and a channel missing from+ it reads to the user as "the app is not in that channel". Leave a trail so the next report+ is answerable from our own data.+ """+ slack_listing_truncated_counter.labels(kind=kind).inc()+ logger.warning(+ "slack_listing_truncated",+ kind=kind,+ integration_id=self.integration.id,+ team_id=self.integration.team_id,+ collected=collected,+ requests=requests,+ )+@classmethoddef validate_request(cls, request: HttpRequest | Request):slack_config = cls.slack_config()