: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(insights): apply offset in the trending insights endpoint (#115193)
posthog[bot]5d6873f9f946
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex e3f6b13723d1..8653452da6d7 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -30,6 +30,7 @@ from rest_framework.renderers import BaseRendererfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.settings import api_settings+from rest_framework.utils.urls import replace_query_paramfrom rest_framework_csv import renderers as csvrenderersfrom posthog.schema import AccessControlFilterWarning, DataWarehouseSyncWarning, ProductKey, QueryStatus@@ -2020,8 +2021,11 @@ class InsightViewSet(try:days = int(request.GET.get("days", "7"))limit = min(int(request.GET.get("limit", "10")), 100)+ offset = int(request.GET.get("offset", "0"))except (ValueError, TypeError):- raise ValidationError("days and limit must be valid integers")+ raise ValidationError("days, limit and offset must be valid integers")+ if limit <= 0 or offset < 0:+ raise ValidationError("limit must be positive and offset must not be negative")cutoff_date = now() - timedelta(days=days)@@ -2035,13 +2039,16 @@ class InsightViewSet()).filter(view_count__gt=0)- .order_by("-view_count", "-last_modified_at")+ .order_by("-view_count", "-last_modified_at", "-id"))queryset = self._filter_queryset_by_access_level(queryset)- queryset = queryset[:limit]+ # Fetch one extra row to know if a next page exists without a separate count query.+ queryset = queryset[offset : offset + limit + 1]queryset = queryset.annotate(last_viewed_at=Max("insightviewed__last_viewed_at"))insights = list(queryset)+ has_next = len(insights) > limit+ insights = insights[:limit]# Batch fetch viewers once to avoid N+1 queriesviewers_by_insight = recent_viewers_by_insight(@@ -2058,8 +2065,19 @@ class InsightViewSet(# Wrap in the standard paginated envelope so the response shape matches the auto-generated# OpenAPI schema (drf-spectacular wraps `many=True` responses as `Paginated*List` when the# viewset has a paginator). This keeps the MCP-generated client and any other typed consumer- # happy. There's no real pagination — `limit` already caps the result set.- return Response({"count": len(data), "next": None, "previous": None, "results": data})+ # happy. `count` is the size of this page, not the total.+ page_url = request.build_absolute_uri()+ next_url = (+ replace_query_param(replace_query_param(page_url, "offset", offset + limit), "limit", limit)+ if has_next+ else None+ )+ previous_url = (+ replace_query_param(replace_query_param(page_url, "offset", max(offset - limit, 0)), "limit", limit)+ if offset > 0+ else None+ )+ return Response({"count": len(data), "next": next_url, "previous": previous_url, "results": data})@staticmethod@tracer.start_as_current_span("InsightViewSet._apply_search")diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.pyindex 2cd195f05092..0a19acd210d6 100644--- a/products/product_analytics/backend/tests/api/test_insight.py+++ b/products/product_analytics/backend/tests/api/test_insight.py@@ -2942,20 +2942,41 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):ids = [r["id"] for r in response.json()["results"]]assert ids == [kept_id]- def test_trending_insights_respects_limit(self) -> None:+ def test_trending_insights_pages_with_limit_and_offset(self) -> None:+ created_ids = []for short_id in ("trndL001", "trndL002", "trndL003"):insight_id, _ = self.dashboard_api.create_insight({"short_id": short_id})+ created_ids.append(insight_id)InsightViewed.objects.update_or_create(team=self.team, user=self.user, insight_id=insight_id, defaults={"last_viewed_at": timezone.now()})+ Insight.objects.filter(id__in=created_ids).update(last_modified_at=timezone.now())- response = self.client.get(f"/api/projects/{self.team.id}/insights/trending?limit=2")- body = response.json()- assert len(body["results"]) == 2- assert body["count"] == 2+ first = self.client.get(f"/api/projects/{self.team.id}/insights/trending?limit=2").json()+ assert len(first["results"]) == 2+ assert first["count"] == 2+ assert first["previous"] is None+ assert first["next"] is not None and "offset=2" in first["next"]++ second = self.client.get(f"/api/projects/{self.team.id}/insights/trending?limit=2&offset=2").json()+ assert len(second["results"]) == 1+ assert second["next"] is None+ assert second["previous"] is not None- def test_trending_insights_rejects_invalid_params(self) -> None:- response = self.client.get(f"/api/projects/{self.team.id}/insights/trending?days=abc")+ paged_ids = [r["id"] for r in first["results"] + second["results"]]+ assert sorted(paged_ids) == sorted(created_ids)++ @parameterized.expand(+ [+ ("non_integer_days", "days=abc"),+ ("non_integer_offset", "offset=abc"),+ ("negative_offset", "offset=-1"),+ ("negative_limit", "limit=-1"),+ ("zero_limit", "limit=0"),+ ]+ )+ def test_trending_insights_rejects_invalid_params(self, _name: str, query: str) -> None:+ response = self.client.get(f"/api/projects/{self.team.id}/insights/trending?{query}")assert response.status_code == status.HTTP_400_BAD_REQUESTdef test_get_recent_insights_with_feature_flag(self) -> None: