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(insights): dedupe saved-list search on the key, not whole rows (#103272)

posthog[bot]7f82e57601e9
diff --git a/posthog/helpers/trigram_search.py b/posthog/helpers/trigram_search.py
index a1fb139ffb0e..a535b06aa32a 100644
--- a/posthog/helpers/trigram_search.py
+++ b/posthog/helpers/trigram_search.py
@@ -103,7 +103,8 @@ def apply_trigram_search(
this way are flagged `_is_exact=1` and sort with the literal-substring matches.
When `include_tag_search=True`, rows whose tag names contain the term also match (as
- `exact`), and `.distinct()` dedups the tag-join fan-out.
+ `exact`). The tag join stays inside an `id__in` subquery, so the outer query keeps one row
+ per match without a `DISTINCT` over every selected column.
Word/full annotations are coalesced to 0.0 so a row with a NULL field matched only on
another field doesn't end up with a NULL `_search_score` (Postgres orders NULLS FIRST in
@@ -150,11 +151,7 @@ def apply_trigram_search(
_search_score=search_score,
)
- result = annotated.filter(exact_q | similar_q)
- if include_tag_search:
- result = result.distinct()
-
- return result.order_by("-_search_score", *tiebreakers)
+ return annotated.filter(exact_q | similar_q).order_by("-_search_score", *tiebreakers)
def drop_similar_when_exact_exists(queryset: QuerySet) -> QuerySet:
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index cdb182fb0e0e..18e369ac3784 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -6,7 +6,7 @@ from typing import Any, Union, cast
from django.conf import settings
from django.db import transaction
-from django.db.models import Count, F, Max, QuerySet
+from django.db.models import Count, Exists, F, Max, OuterRef, QuerySet
from django.db.models.query_utils import Q
from django.utils.functional import SimpleLazyObject
from django.utils.timezone import now
@@ -97,6 +97,7 @@ from posthog.models.activity_logging.activity_page import (
parse_activity_page_params,
)
from posthog.models.organization import Organization
+from posthog.models.tagged_item import TaggedItem
from posthog.models.team.team import Team
from posthog.models.utils import UUIDT
from posthog.permissions import TeamMemberStrictManagementPermission
@@ -2093,7 +2094,10 @@ class InsightViewSet(
if tags_filter:
tags_list = json.loads(tags_filter)
if tags_list:
- queryset = queryset.filter(tagged_items__tag__name__in=tags_list).distinct()
+ # A semi-join returns one row per insight, so the list needs no
+ # `.distinct()` sort over the wide insight JSON columns.
+ matching_tags = TaggedItem.objects.filter(insight_id=OuterRef("pk"), tag__name__in=tags_list)
+ queryset = queryset.filter(Exists(matching_tags))
elif key == "created_by":
created_by_filter = request.GET["created_by"]
if created_by_filter:
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index 676c905c0224..1ce7b442cf22 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -834,7 +834,13 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
f"({unsaved_no_dashboard.short_id}) must be excluded."
)
- def test_search_filter_does_not_duplicate_insights_with_multiple_matching_tags(self) -> None:
+ @parameterized.expand(
+ [
+ ("search", "search=needle"),
+ ("tags filter", 'tags=["needle-tag-a", "needle-tag-b", "needle-tag-c"]'),
+ ]
+ )
+ def test_list_does_not_duplicate_insights_with_multiple_matching_tags(self, _name: str, query: str) -> None:
from posthog.models.tag import Tag
from posthog.models.tagged_item import TaggedItem
@@ -845,13 +851,15 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
tag = Tag.objects.create(name=tag_name, team=self.team)
TaggedItem.objects.create(insight=insight, tag=tag)
- response = self.client.get(f"/api/projects/{self.team.id}/insights/?search=needle")
+ response = self.client.get(f"/api/projects/{self.team.id}/insights/?{query}")
assert response.status_code == status.HTTP_200_OK
- matching_short_ids = [r["short_id"] for r in response.json()["results"] if r["short_id"] == insight.short_id]
+ body = response.json()
+ matching_short_ids = [r["short_id"] for r in body["results"] if r["short_id"] == insight.short_id]
assert len(matching_short_ids) == 1, (
- f"search=needle must return the insight once even though three tags + the name match it; "
+ f"?{query} must return the insight once even though three tags match it; "
f"got {len(matching_short_ids)} copies."
)
+ assert body["count"] == 1, f"?{query} must count the insight once; got {body['count']}."
@parameterized.expand(
[