: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(integrations): use rapidfuzz for slack channel search (#61090)
Joshua Snyder012f9ace8c0b
diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 82d4421f34b4..2464ab90b604 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -30,6 +30,7 @@ from posthog.api.utils import actionfrom posthog.auth import SessionAuthenticationfrom posthog.domain_connect import discover_domain_connect, extract_root_domain_and_host, get_available_providersfrom posthog.exceptions_capture import capture_exception+from posthog.helpers.fuzzy_search import fuzzy_filterfrom posthog.models import Userfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.integration import (@@ -678,10 +679,16 @@ class IntegrationViewSet(@staticmethoddef _filter_slack_channels_for_search(channels: list[dict], search: str) -> list[dict]:visible = [channel for channel in channels if not channel.get("is_private_without_access")]- query = search.strip().lower()+ query = search.strip()if not query:return visible- return [channel for channel in visible if query in channel["name"].lower() or query in channel["id"].lower()]+ # Fuzzy-rank by name, then union in any channel whose id contains the query so pasting an id still resolves.+ ranked = fuzzy_filter(query, visible, key=lambda channel: channel["name"])+ ranked_ids = {channel["id"] for channel in ranked}+ id_matches = [+ channel for channel in visible if query.lower() in channel["id"].lower() and channel["id"] not in ranked_ids+ ]+ return ranked + id_matches@extend_schema(parameters=[SlackChannelsQuerySerializer],diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex e806c7b5fc8f..fa83e60154af 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -4,6 +4,7 @@ import jsonimport timeimport hashlibfrom datetime import timedelta+from urllib.parse import quoteimport pytestfrom unittest.mock import MagicMock, patch@@ -1183,8 +1184,8 @@ class TestIntegrationAPIKeyAccess:("", ["C1", "C2", "C3"], False),# Pagination beyond the dataset returns an empty page.("?limit=10&offset=10", [], False),- # Search + offset combine: "e" matches general+engineering in input order, offset=1 yields engineering.- ("?search=e&limit=1&offset=1", ["C3"], False),+ # Search + offset combine: "gen" fuzzy-matches general+engineering, offset=1 yields engineering.+ ("?search=gen&limit=1&offset=1", ["C3"], False),],ids=["default-no-params", "offset-past-end", "search-with-offset"],)@@ -1253,6 +1254,93 @@ class TestIntegrationAPIKeyAccess:assert [channel["id"] for channel in data["channels"]] == expected_idsassert data["has_more"] is expected_has_more+ @pytest.mark.parametrize(+ "search,expected_ids",+ [+ # "team-product" (C2) is a weaker fuzzy match on "product", so it ranks below the exact hit.+ ("product analytics", ["C1", "C2"]),+ ("product_analytics", ["C1", "C2"]),+ ("analytics product", ["C1", "C2"]),+ ("prod analy", ["C1"]),+ ("analytcs", ["C1"]),+ ("product-analytics", ["C1", "C2"]),+ ("team", ["C2", "C3"]),+ ("C2", ["C2"]),+ ("nonexistent channel", []),+ ],+ ids=[+ "spaces-match-hyphens",+ "underscores-match-hyphens",+ "reordered-tokens",+ "partial-tokens",+ "typo-tolerant",+ "exact-hyphenated",+ "shared-token-multi-match",+ "channel-id-paste",+ "no-match",+ ],+ )+ @patch("posthog.api.integration.SlackIntegration")+ def test_channels_action_fuzzy_search(+ self,+ mock_slack_class,+ search: str,+ expected_ids: list[str],+ client: HttpClient,+ ):+ slack_integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T_SEARCH",+ config={"authed_user": {"id": "test_user_id"}},+ sensitive_config={"access_token": "test-token-123"},+ created_by=self.user,+ )+ mock_slack_instance = MagicMock()+ mock_slack_instance.list_channels.return_value = [+ {+ "id": "C1",+ "name": "product-analytics",+ "is_private": False,+ "is_member": True,+ "is_ext_shared": False,+ "is_private_without_access": False,+ },+ {+ "id": "C2",+ "name": "team-product",+ "is_private": False,+ "is_member": True,+ "is_ext_shared": False,+ "is_private_without_access": False,+ },+ {+ "id": "C3",+ "name": "team-design",+ "is_private": False,+ "is_member": True,+ "is_ext_shared": False,+ "is_private_without_access": False,+ },+ ]+ mock_slack_class.return_value = mock_slack_instance++ key_value = f"test_key_slack_search_{search}".replace(" ", "_").replace("-", "_")+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scopes=["integration:read"],+ )++ response = client.get(+ f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/channels/?search={quote(search)}",+ HTTP_AUTHORIZATION=f"Bearer {key_value}",+ )+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert [channel["id"] for channel in data["channels"]] == expected_ids+def test_channels_action_with_missing_authed_user_returns_400(self, client: HttpClient):slack_integration = Integration.objects.create(team=self.team,diff --git a/posthog/helpers/fuzzy_search.py b/posthog/helpers/fuzzy_search.pynew file mode 100644index 000000000000..3fd915ae6f07--- /dev/null+++ b/posthog/helpers/fuzzy_search.py@@ -0,0 +1,73 @@+"""Core fuzzy-search helpers built on rapidfuzz.++Use these for typo-tolerant, separator- and order-insensitive matching of short+strings (channel names, labels, entity names) against an in-memory candidate+list — e.g. filtering a list fetched from a third-party API where Postgres+trigram search (see ``trigram_search.py``) isn't an option. For anything already+in the database, prefer a database-side search instead.+"""++from collections.abc import Callable, Iterable+from typing import TypeVar++from rapidfuzz import fuzz, process, utils++T = TypeVar("T")++# Scores run 0-100. 70 keeps reordered, partial-token and single-typo queries while dropping unrelated strings.+DEFAULT_SCORE_CUTOFF = 70.0++# WRatio blends ratio, partial-ratio and token-set scoring, so it tolerates separators, reordering and partial tokens.+_DEFAULT_SCORER = fuzz.WRatio+++def fuzzy_score(query: str, choice: str, *, scorer: Callable[..., float] = _DEFAULT_SCORER) -> float:+ """Similarity score (0-100) between ``query`` and ``choice``, case- and separator-insensitive."""+ return scorer(query, choice, processor=utils.default_process)+++def fuzzy_rank(+ query: str,+ choices: Iterable[str],+ *,+ score_cutoff: float = DEFAULT_SCORE_CUTOFF,+ limit: int | None = None,+ scorer: Callable[..., float] = _DEFAULT_SCORER,+) -> list[tuple[str, float]]:+ """Rank ``choices`` by similarity to ``query``, best first, dropping anything below ``score_cutoff``."""+ matches = process.extract(+ query,+ list(choices),+ scorer=scorer,+ processor=utils.default_process,+ score_cutoff=score_cutoff,+ limit=limit,+ )+ return [(choice, score) for choice, score, _ in matches]+++def fuzzy_filter(+ query: str,+ items: Iterable[T],+ key: Callable[[T], str],+ *,+ score_cutoff: float = DEFAULT_SCORE_CUTOFF,+ limit: int | None = None,+ scorer: Callable[..., float] = _DEFAULT_SCORER,+) -> list[T]:+ """Filter and rank arbitrary ``items`` by fuzzy match on ``key(item)``, best first.++ Items whose key scores below ``score_cutoff`` are dropped. Ties preserve the+ input order, so callers get a deterministic result.+ """+ items_list = list(items)+ keys = [key(item) for item in items_list]+ matches = process.extract(+ query,+ keys,+ scorer=scorer,+ processor=utils.default_process,+ score_cutoff=score_cutoff,+ limit=limit,+ )+ return [items_list[index] for _, _, index in matches]diff --git a/posthog/helpers/tests/test_fuzzy_search.py b/posthog/helpers/tests/test_fuzzy_search.pynew file mode 100644index 000000000000..870b3af0816d--- /dev/null+++ b/posthog/helpers/tests/test_fuzzy_search.py@@ -0,0 +1,74 @@+import pytest++from posthog.helpers.fuzzy_search import DEFAULT_SCORE_CUTOFF, fuzzy_filter, fuzzy_rank, fuzzy_score+++class TestFuzzyScore:+ @pytest.mark.parametrize(+ "query,choice",+ [+ ("product analytics", "product-analytics"),+ ("product_analytics", "product-analytics"),+ ("analytics product", "product-analytics"),+ ("Product Analytics", "product-analytics"),+ ],+ )+ def test_separator_and_case_insensitive_matches_score_high(self, query: str, choice: str):+ assert fuzzy_score(query, choice) >= DEFAULT_SCORE_CUTOFF++ def test_unrelated_strings_score_low(self):+ assert fuzzy_score("billing", "product-analytics") < DEFAULT_SCORE_CUTOFF+++class TestFuzzyRank:+ def test_ranks_best_match_first(self):+ ranked = fuzzy_rank("team", ["team-product", "team-design", "product-analytics"])+ assert [name for name, _ in ranked] == ["team-product", "team-design"]++ def test_drops_matches_below_cutoff(self):+ ranked = fuzzy_rank("xyzzy", ["team-product", "team-design"])+ assert ranked == []++ def test_limit_caps_results(self):+ ranked = fuzzy_rank("team", ["team-product", "team-design"], limit=1)+ assert len(ranked) == 1++ def test_lower_cutoff_is_more_permissive(self):+ names = ["team-product", "product-analytics"]+ strict = fuzzy_rank("product analytics", names, score_cutoff=90)+ loose = fuzzy_rank("product analytics", names, score_cutoff=50)+ assert [name for name, _ in strict] == ["product-analytics"]+ assert {name for name, _ in loose} == set(names)+++class TestFuzzyFilter:+ @pytest.fixture+ def items(self) -> list[dict]:+ return [+ {"id": "C1", "name": "product-analytics"},+ {"id": "C2", "name": "team-product"},+ {"id": "C3", "name": "team-design"},+ ]++ def test_ranks_items_best_first(self, items: list[dict]):+ result = fuzzy_filter("product analytics", items, key=lambda c: c["name"])+ assert result[0]["id"] == "C1"++ def test_tolerates_typos(self, items: list[dict]):+ result = fuzzy_filter("analytcs", items, key=lambda c: c["name"])+ assert [c["id"] for c in result] == ["C1"]++ def test_no_match_returns_empty(self, items: list[dict]):+ assert fuzzy_filter("nonexistent channel", items, key=lambda c: c["name"]) == []++ def test_ties_preserve_input_order(self, items: list[dict]):+ result = fuzzy_filter("team", items, key=lambda c: c["name"])+ assert [c["id"] for c in result] == ["C2", "C3"]++ def test_empty_query_matches_nothing(self, items: list[dict]):+ # Callers that want "show everything" on an empty query must short-circuit before calling.+ assert fuzzy_filter("", items, key=lambda c: c["name"]) == []++ def test_empty_input_returns_empty(self):+ assert fuzzy_filter("anything", [], key=lambda c: c["name"]) == []+ assert fuzzy_rank("anything", []) == []diff --git a/pyproject.toml b/pyproject.tomlindex 94d80edafe45..43f938f2fe67 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -117,6 +117,7 @@ dependencies = ["python-snappy~=0.7.3","python3-saml==1.16.0","pytz==2023.3",+ "rapidfuzz==3.14.5","redis==5.3.1","requests~=2.33.0","retry==0.9.2",diff --git a/uv.lock b/uv.lockindex d6740baa9ab0..67e49f3dccf8 100644--- a/uv.lock+++ b/uv.lock@@ -5366,6 +5366,7 @@ dependencies = [{ name = "python3-saml" },{ name = "pytz" },{ name = "pyyaml" },+ { name = "rapidfuzz" },{ name = "redis" },{ name = "requests" },{ name = "retry" },@@ -5633,6 +5634,7 @@ requires-dist = [{ name = "python3-saml", specifier = "==1.16.0" },{ name = "pytz", specifier = "==2023.3" },{ name = "pyyaml", specifier = "~=6.0.2" },+ { name = "rapidfuzz", specifier = "==3.14.5" },{ name = "redis", specifier = "==5.3.1" },{ name = "requests", specifier = "~=2.33.0" },{ name = "retry", specifier = "==0.9.2" },@@ -6722,6 +6724,25 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ad/3f/11dd4cd4f39e05128bfd20138faea57bec56f9ffba6185d276e3107ba5b2/questionary-2.1.0-py3-none-any.whl", hash = "sha256:44174d237b68bc828e4878c763a9ad6790ee61990e0ae72927694ead57bab8ec", size = 36747, upload-time = "2024-12-29T11:49:16.734Z" },]+[[package]]+name = "rapidfuzz"+version = "3.14.5"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/2c/21/ef6157213316e85790041254259907eb722e00b03480256c0545d98acd33/rapidfuzz-3.14.5.tar.gz", hash = "sha256:ba10ac57884ce82112f7ed910b67e7fb6072d8ef2c06e30dc63c0f604a112e0e", size = 57901753, upload-time = "2026-04-07T11:16:31.931Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d3/e3/574435c6aafb80254c191ef40d7aca2cb2bb97a095ec9395e9fa59ac307a/rapidfuzz-3.14.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0d3378f471ef440473a396ce2f8e97ee12f89a78b495540e0a5617bbfe895638", size = 1944601, upload-time = "2026-04-07T11:14:18.771Z" },+ { url = "https://files.pythonhosted.org/packages/d0/1f/fbad3102a255ecc112ce9a7e779bacab7fd14398217be8868dc9082ba363/rapidfuzz-3.14.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e910eebca9fd0eba245c0555e764597e8a0cccb673a92da2dc2397050725f48", size = 1164293, upload-time = "2026-04-07T11:14:20.534Z" },+ { url = "https://files.pythonhosted.org/packages/88/37/a3eb7ff6121ed3a5f199a8c38cc86c8e481816f879cb0e0b738b078c9a7e/rapidfuzz-3.14.5-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:01550fe5f60fd176aa66b7611289d46dc4aa4b1b904874c7b6d1d54e581c5ec1", size = 1371999, upload-time = "2026-04-07T11:14:22.63Z" },+ { url = "https://files.pythonhosted.org/packages/79/72/97a9728c711c7c1b06e107d3f0623880fb4ef90e147ed13c551a1730e7cc/rapidfuzz-3.14.5-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:48bee0b91bebfaec41e1081e351000659ab7570cc4598d617aa04d5bf827f9e6", size = 3145715, upload-time = "2026-04-07T11:14:24.508Z" },+ { url = "https://files.pythonhosted.org/packages/ed/54/d5caabbea233ac90c286c87c260e49d7641467e87438a18d858e41c82e91/rapidfuzz-3.14.5-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:7e580cb04ad849ae9b786fa21383c6b994b6e6c1444ad1cb9f22392759d72741", size = 1456304, upload-time = "2026-04-07T11:14:26.515Z" },+ { url = "https://files.pythonhosted.org/packages/fc/a7/2d1a81250ac8c01a0100c026018e76f0e7a097ff63e4c553e02a6938c6fb/rapidfuzz-3.14.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:09d6c9ba091854f07817055d795d604179c12a8f308ba4c7d56f3719dfea1646", size = 2389089, upload-time = "2026-04-07T11:14:28.635Z" },+ { url = "https://files.pythonhosted.org/packages/65/0d/c47c3872203ae88e6506997c0b576ad731f5261daa25d559be09c9756658/rapidfuzz-3.14.5-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:1e989f86113be66574113b9c7bdf4793f3f863d248e47d911b355e05ca6b6b10", size = 2493404, upload-time = "2026-04-07T11:14:30.577Z" },+ { url = "https://files.pythonhosted.org/packages/8f/2f/71e0a5a3130792146c8a200a2dd1e52aa16f7c1074012e17f2601eea9a90/rapidfuzz-3.14.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ebd1a18e2e47bc0b292a07e6ed9c3642f8aaa672d12253885f599b50807a4f9", size = 4251709, upload-time = "2026-04-07T11:14:32.451Z" },+ { url = "https://files.pythonhosted.org/packages/86/45/d39874901abacef325adb5b34ae416817c8486dfb4fb87c7a9b74ec5b072/rapidfuzz-3.14.5-cp312-cp312-win32.whl", hash = "sha256:9981d38a703b86f0e315a3cd229fd1906fe1d91c989ed121fb975b3c849f89f5", size = 1710069, upload-time = "2026-04-07T11:14:34.37Z" },+ { url = "https://files.pythonhosted.org/packages/85/0b/f65572c53de8a1c704bda707f63a447b67bdbe95d7cdc70d18885e191df5/rapidfuzz-3.14.5-cp312-cp312-win_amd64.whl", hash = "sha256:d8375e3da319593389727c3187ccaf3e0e84199accc530866b8e0f2b79af05e9", size = 1540630, upload-time = "2026-04-07T11:14:36.287Z" },+ { url = "https://files.pythonhosted.org/packages/5e/c3/143be3a578f989758cae516f3270d5cbb49783a7bfdf57cc27a670e00456/rapidfuzz-3.14.5-cp312-cp312-win_arm64.whl", hash = "sha256:478b59bb018a6780d73f33e38d0b3ec5e968a6c1ed42876b993dd456b7aa20e8", size = 813137, upload-time = "2026-04-07T11:14:38.289Z" },+]+[[package]]name = "redis"version = "5.3.1"