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(data-warehouse): split slack $channels sync via _fetch_all_channels (#57156)

Marcus Hofa3e6b33483d9
diff --git a/posthog/temporal/data_imports/sources/slack/slack.py b/posthog/temporal/data_imports/sources/slack/slack.py
index 9978505e93b1..79bc9bb004d1 100644
--- a/posthog/temporal/data_imports/sources/slack/slack.py
+++ b/posthog/temporal/data_imports/sources/slack/slack.py
@@ -88,23 +88,6 @@ class SlackCursorPaginator(BasePaginator):
def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:
- if name == "$channels":
- return {
- "name": "$channels",
- "table_name": "$channels",
- "write_disposition": "replace",
- "endpoint": {
- "data_selector": "channels",
- "path": "conversations.list",
- "params": {
- "types": "public_channel,private_channel",
- "limit": 999,
- "exclude_archived": "false",
- },
- },
- "table_format": "delta",
- }
-
if name == "$users":
return {
"name": "$users",
@@ -363,12 +346,19 @@ def slack_source(
db_incremental_field_last_value: Optional[Any] = None,
incremental_field: str | None = None,
channel_id: str | None = None,
+ authed_user: str | None = None,
) -> SourceResponse:
items: Callable[[], Iterable[Any] | AsyncIterable[Any]]
sort_mode: SortMode = "asc"
- if endpoint in ENDPOINTS:
- # Metadata endpoints ($channels, $users) — served via REST, no webhook support
+ if endpoint == "$channels":
+ # Bypass rest_api_resource: Slack's conversations.list pagination is buggy when
+ # public+private types are mixed, so we walk public and private separately and
+ # scope private channels to the installer (matches get_schemas behavior).
+ endpoint_config = ENDPOINTS[endpoint]
+ items = lambda: iter(_fetch_all_channels(access_token, authed_user))
+ elif endpoint in ENDPOINTS:
+ # $users — served via the generic REST framework
endpoint_config = ENDPOINTS[endpoint]
config: RESTAPIConfig = {
"client": {
diff --git a/posthog/temporal/data_imports/sources/slack/source.py b/posthog/temporal/data_imports/sources/slack/source.py
index ad6deb538e55..b89f75356549 100644
--- a/posthog/temporal/data_imports/sources/slack/source.py
+++ b/posthog/temporal/data_imports/sources/slack/source.py
@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Optional, cast
if TYPE_CHECKING:
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+ from posthog.models.integration import Integration
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
@@ -62,6 +63,10 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhook
def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
return WebhookSourceManager(inputs, inputs.logger)
+ @staticmethod
+ def _get_authed_user_id(integration: "Integration") -> str | None:
+ return (integration.config or {}).get("authed_user", {}).get("id")
+
def create_webhook(self, config: SlackSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:
return WebhookCreationResult(
success=False,
@@ -179,7 +184,7 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhook
msg_config = messages_endpoint_config()
webhook_flag_enabled = is_webhook_feature_flag_enabled(team_id)
- authed_user = (integration.config or {}).get("authed_user", {}).get("id")
+ authed_user = self._get_authed_user_id(integration)
channels = get_channels(access_token, authed_user)
for ch in channels:
if ch["id"] in ENDPOINTS:
@@ -247,4 +252,5 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhook
incremental_field=inputs.incremental_field,
channel_id=channel_id,
webhook_source_manager=webhook_source_manager,
+ authed_user=self._get_authed_user_id(integration),
)
diff --git a/posthog/temporal/data_imports/sources/slack/test_slack.py b/posthog/temporal/data_imports/sources/slack/test_slack.py
index 6e5511c789cc..51353e43fc12 100644
--- a/posthog/temporal/data_imports/sources/slack/test_slack.py
+++ b/posthog/temporal/data_imports/sources/slack/test_slack.py
@@ -5,7 +5,14 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from posthog.temporal.data_imports.sources.slack.slack import SlackResumeConfig, _channel_messages_generator
+from posthog.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
+from posthog.temporal.data_imports.sources.slack.slack import (
+ SlackResumeConfig,
+ _channel_messages_generator,
+ _fetch_all_channels,
+ _fetch_channels_by_type,
+ slack_source,
+)
def _make_response(payload: dict[str, Any]) -> MagicMock:
@@ -155,3 +162,144 @@ class TestChannelMessagesGeneratorResumable:
call_kwargs = mock_get.call_args.kwargs
assert "cursor" not in call_kwargs["params"]
assert call_kwargs["params"]["oldest"] == "original_oldest"
+
+
+def _make_channel_page(channels: list[dict[str, Any]], next_cursor: str = "") -> dict[str, Any]:
+ return {
+ "ok": True,
+ "channels": channels,
+ "response_metadata": {"next_cursor": next_cursor},
+ }
+
+
+class TestFetchChannelsByType:
+ @parameterized.expand(
+ [
+ (
+ "public_with_authed_user_ignores_user_scoping",
+ "public_channel",
+ "U_INSTALLER",
+ "https://slack.com/api/conversations.list",
+ False,
+ ),
+ (
+ "private_with_authed_user_scopes_to_installer",
+ "private_channel",
+ "U_INSTALLER",
+ "https://slack.com/api/users.conversations",
+ True,
+ ),
+ (
+ "private_without_authed_user_omits_user_param",
+ "private_channel",
+ None,
+ "https://slack.com/api/users.conversations",
+ False,
+ ),
+ ]
+ )
+ def test_routes_to_expected_endpoint(
+ self,
+ _name: str,
+ channel_type: str,
+ authed_user: str | None,
+ expected_url: str,
+ expects_user_param: bool,
+ ) -> None:
+ responses = [_make_response(_make_channel_page([{"id": "X1", "name": "x"}]))]
+ with patch(
+ "posthog.temporal.data_imports.sources.slack.slack._slack_get",
+ side_effect=responses,
+ ) as mock_get:
+ channels = _fetch_channels_by_type("token", channel_type, authed_user=authed_user)
+
+ assert channels == [{"id": "X1", "name": "x"}]
+ assert mock_get.call_args.args[0] == expected_url
+ params = mock_get.call_args.kwargs["params"]
+ assert params["types"] == channel_type
+ if expects_user_param:
+ assert params["user"] == authed_user
+ else:
+ assert "user" not in params
+
+ def test_paginates_until_cursor_empty(self) -> None:
+ pages = [
+ _make_channel_page([{"id": "C1", "name": "a"}], next_cursor="page2"),
+ _make_channel_page([{"id": "C2", "name": "b"}], next_cursor=""),
+ ]
+ responses = [_make_response(p) for p in pages]
+ with patch(
+ "posthog.temporal.data_imports.sources.slack.slack._slack_get",
+ side_effect=responses,
+ ) as mock_get:
+ channels = _fetch_channels_by_type("token", "public_channel")
+
+ assert [c["id"] for c in channels] == ["C1", "C2"]
+ assert mock_get.call_count == 2
+ assert mock_get.call_args_list[1].kwargs["params"]["cursor"] == "page2"
+
+
+class TestFetchAllChannels:
+ def test_combines_public_and_private(self) -> None:
+ pages = [
+ _make_channel_page([{"id": "C1", "name": "general"}], next_cursor=""),
+ _make_channel_page([{"id": "G1", "name": "secret"}], next_cursor=""),
+ ]
+ responses = [_make_response(p) for p in pages]
+ with patch(
+ "posthog.temporal.data_imports.sources.slack.slack._slack_get",
+ side_effect=responses,
+ ) as mock_get:
+ channels = _fetch_all_channels("token", authed_user="U_INSTALLER")
+
+ assert [c["id"] for c in channels] == ["C1", "G1"]
+ assert mock_get.call_count == 2
+ first_url, second_url = mock_get.call_args_list[0].args[0], mock_get.call_args_list[1].args[0]
+ assert first_url == "https://slack.com/api/conversations.list"
+ assert second_url == "https://slack.com/api/users.conversations"
+ # public call must not carry user= scoping; private call must
+ assert "user" not in mock_get.call_args_list[0].kwargs["params"]
+ assert mock_get.call_args_list[1].kwargs["params"]["user"] == "U_INSTALLER"
+
+
+class TestSlackSourceChannelsEndpoint:
+ def _build_source(self, authed_user: str | None) -> Any:
+ return slack_source(
+ access_token="token",
+ endpoint="$channels",
+ team_id=1,
+ job_id="job-1",
+ webhook_source_manager=MagicMock(spec=WebhookSourceManager),
+ resumable_source_manager=MagicMock(spec=ResumableSourceManager),
+ authed_user=authed_user,
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "with_authed_user",
+ "U_INSTALLER",
+ [{"id": "C1", "name": "general"}, {"id": "G1", "name": "secret"}],
+ ),
+ (
+ "without_authed_user",
+ None,
+ [],
+ ),
+ ]
+ )
+ def test_uses_fetch_all_channels_and_threads_authed_user(
+ self,
+ _name: str,
+ authed_user: str | None,
+ sample: list[dict[str, Any]],
+ ) -> None:
+ with patch(
+ "posthog.temporal.data_imports.sources.slack.slack._fetch_all_channels",
+ return_value=sample,
+ ) as mock_fetch:
+ response = self._build_source(authed_user=authed_user)
+ items = list(response.items())
+
+ assert items == sample
+ mock_fetch.assert_called_once_with("token", authed_user)