: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): bulk upsert in /insights/viewed to remove n+1 (#58230)
posthog[bot]e28526f79139
diff --git a/posthog/api/insight.py b/posthog/api/insight.pyindex 0b3ba16ddc5c..233800b40887 100644--- a/posthog/api/insight.py+++ b/posthog/api/insight.py@@ -18,7 +18,7 @@ import structlogimport posthoganalyticsfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, extend_schema_view+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema_viewfrom loginas.utils import is_impersonated_sessionfrom opentelemetry import tracefrom prometheus_client import Counter@@ -49,6 +49,7 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.insight_metadata import generate_insight_metadatafrom posthog.api.insight_suggestions import get_insight_analysis, get_insight_suggestionsfrom posthog.api.insight_variable import map_stale_to_latest+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.monitoring import Feature, monitorfrom posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_paramfrom posthog.api.query_coalescer import QueryCoalescingMixin@@ -1191,6 +1192,20 @@ INSIGHT_ID_PATH_PARAMETER = OpenApiParameter()+INSIGHT_VIEWED_MAX_IDS = 2500+++class InsightViewedRequestSerializer(serializers.Serializer):+ insight_ids = serializers.ListField(+ child=serializers.IntegerField(),+ allow_empty=False,+ max_length=INSIGHT_VIEWED_MAX_IDS,+ help_text=(+ f"Insight IDs that were just viewed by the current user. At most {INSIGHT_VIEWED_MAX_IDS} ids per request."+ ),+ )++@extend_schema(tags=[ProductKey.PRODUCT_ANALYTICS])@extend_schema_view(list=extend_schema(@@ -2072,30 +2087,47 @@ When set, the specified dashboard's filters and date range override will be appl# Creates or updates InsightViewed objects for the user/insight combo(s)# Accepts an array of insight_ids# ******************************************+ @validated_request(+ request_serializer=InsightViewedRequestSerializer,+ responses={201: OpenApiResponse(description="Views recorded.")},+ description=(+ "Record that the current user has just viewed one or more insights. "+ "Submitted ids that do not belong to the current project or that point at deleted insights "+ "are silently dropped. Returns 201 on success regardless of how many ids were retained."+ ),+ )@action(methods=["POST"], detail=False, required_scopes=["insight:read"])- def viewed(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:+ def viewed(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:"""- Update insight view timestamps.+ Update insight view timestamps in bulk.Expects: {"insight_ids": [1, 2, 3, ...]}"""- insight_ids = request.data.get("insight_ids")-- if not insight_ids or not isinstance(insight_ids, list):- raise serializers.ValidationError({"insight_ids": "Must be a non-empty list of insight IDs"})-- insights = Insight.objects.filter(- id__in=insight_ids,- team__project_id=self.team.project_id,- deleted=False,+ insight_ids: list[int] = request.validated_data["insight_ids"]++ visible_insight_ids = list(+ Insight.objects.filter(+ id__in=insight_ids,+ team__project_id=self.team.project_id,+ deleted=False,+ ).values_list("id", flat=True))- viewed_at = now()- for insight in insights:- InsightViewed.objects.update_or_create(- team=self.team,- user=request.user,- insight=insight,- defaults={"last_viewed_at": viewed_at},+ if visible_insight_ids:+ viewed_at = now()+ user = cast(User, request.user)+ InsightViewed.objects.bulk_create(+ [+ InsightViewed(+ team=self.team,+ user=user,+ insight_id=insight_id,+ last_viewed_at=viewed_at,+ )+ for insight_id in visible_insight_ids+ ],+ update_conflicts=True,+ unique_fields=["team", "user", "insight"],+ update_fields=["last_viewed_at"],)return Response(status=status.HTTP_201_CREATED)diff --git a/posthog/api/test/test_insight.py b/posthog/api/test/test_insight.pyindex 0605e903869a..c6f347d058e8 100644--- a/posthog/api/test/test_insight.py+++ b/posthog/api/test/test_insight.py@@ -2815,31 +2815,32 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):).json()["id"]return cohort_one_id+ @parameterized.expand([("single_id", 1), ("bulk_ids", 3)])@freeze_time("2022-03-22T00:00:00.000Z")- def test_create_insight_viewed(self) -> None:+ def test_create_insight_viewed(self, _name: str, count: int) -> None:filter_dict = {"events": [{"id": "$pageview"}]}-- insight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),- team=self.team,- short_id="12345678",- )+ insights = [+ Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id=f"viewed{i}")+ for i in range(count)+ ]response = self.client.post(f"/api/projects/{self.team.id}/insights/viewed",- {"insight_ids": [insight.id]},+ {"insight_ids": [insight.id for insight in insights]},)self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(InsightViewed.objects.count(), count)- created_insight_viewed = InsightViewed.objects.all()[0]- self.assertEqual(created_insight_viewed.insight, insight)- self.assertEqual(created_insight_viewed.team, self.team)- self.assertEqual(created_insight_viewed.user, self.user)- self.assertEqual(- created_insight_viewed.last_viewed_at,- datetime(2022, 3, 22, 0, 0, tzinfo=ZoneInfo("UTC")),- )+ created_by_insight = {viewed.insight_id: viewed for viewed in InsightViewed.objects.all()}+ self.assertEqual(set(created_by_insight.keys()), {insight.id for insight in insights})+ for viewed in created_by_insight.values():+ self.assertEqual(viewed.team, self.team)+ self.assertEqual(viewed.user, self.user)+ self.assertEqual(+ viewed.last_viewed_at,+ datetime(2022, 3, 22, 0, 0, tzinfo=ZoneInfo("UTC")),+ )def test_update_insight_viewed(self) -> None:filter_dict = {"events": [{"id": "$pageview"}]}@@ -2886,6 +2887,102 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(response.status_code, status.HTTP_201_CREATED)self.assertEqual(InsightViewed.objects.count(), 0)+ @parameterized.expand(+ [+ ("missing", {}),+ ("empty_list", {"insight_ids": []}),+ ("not_a_list", {"insight_ids": "abc"}),+ ("non_int_element", {"insight_ids": ["abc", 1]}),+ ("over_max_length", {"insight_ids": list(range(1, 2502))}),+ ]+ )+ def test_insight_viewed_rejects_invalid_payloads(self, _name: str, payload: dict) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/insights/viewed",+ payload,+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(InsightViewed.objects.count(), 0)++ def test_bulk_upserts_existing_insight_viewed_rows(self) -> None:+ filter_dict = {"events": [{"id": "$pageview"}]}+ insights = [+ Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id=f"upsert{i}")+ for i in range(3)+ ]++ # Pre-create rows for the first two insights at T1.+ with freeze_time("2022-03-22T00:00:00.000Z"):+ self.client.post(+ f"/api/projects/{self.team.id}/insights/viewed",+ {"insight_ids": [insights[0].id, insights[1].id]},+ )++ # Submit all three at T2 — the first two should be UPDATEd, the third INSERTed.+ with freeze_time("2022-03-23T00:00:00.000Z"):+ response = self.client.post(+ f"/api/projects/{self.team.id}/insights/viewed",+ {"insight_ids": [insight.id for insight in insights]},+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(InsightViewed.objects.count(), 3)+ for viewed in InsightViewed.objects.all():+ self.assertEqual(viewed.last_viewed_at, datetime(2022, 3, 23, 0, 0, tzinfo=ZoneInfo("UTC")))++ def test_bulk_filters_unauthorized_and_deleted_insight_ids(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="other team")+ filter_dict = {"events": [{"id": "$pageview"}]}+ own_insight = Insight.objects.create(+ filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id="own1"+ )+ other_team_insight = Insight.objects.create(+ filters=Filter(data=filter_dict).to_dict(), team=other_team, short_id="other"+ )+ deleted_insight = Insight.objects.create(+ filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id="dead", deleted=True+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/insights/viewed",+ {"insight_ids": [own_insight.id, other_team_insight.id, deleted_insight.id]},+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(InsightViewed.objects.count(), 1)+ self.assertEqual(InsightViewed.objects.first().insight_id, own_insight.id) # type: ignore[union-attr]++ def test_bulk_insight_viewed_query_count_does_not_grow_with_insight_count(self) -> None:+ filter_dict = {"events": [{"id": "$pageview"}]}+ few = [+ Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id=f"few{i}")+ for i in range(2)+ ]+ many = [+ Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id=f"many{i}")+ for i in range(10)+ ]++ with capture_db_queries() as ctx_few:+ response = self.client.post(+ f"/api/projects/{self.team.id}/insights/viewed",+ {"insight_ids": [insight.id for insight in few]},+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ with capture_db_queries() as ctx_many:+ response = self.client.post(+ f"/api/projects/{self.team.id}/insights/viewed",+ {"insight_ids": [insight.id for insight in many]},+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ few_inserts = [q for q in ctx_few.captured_queries if 'INSERT INTO "posthog_insightviewed"' in q["sql"]]+ many_inserts = [q for q in ctx_many.captured_queries if 'INSERT INTO "posthog_insightviewed"' in q["sql"]]++ self.assertEqual(len(few_inserts), 1, f"expected exactly 1 INSERT for few, got {len(few_inserts)}")+ self.assertEqual(len(many_inserts), 1, f"expected exactly 1 INSERT for many, got {len(many_inserts)}")+def test_get_recently_viewed_insights(self) -> None:insight_1_id, _ = self.dashboard_api.create_insight({"short_id": "12345678"})diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 1b46fb52ea3a..96e47046adb0 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -7091,6 +7091,14 @@ export interface PaginatedTrendingInsightListApi {results: TrendingInsightApi[]}+export interface InsightViewedRequestApi {+ /**+ * Insight IDs that were just viewed by the current user. At most 2500 ids per request.+ * @maxItems 2500+ */+ insight_ids: number[]+}+export type ColumnConfigurationsListParams = {/*** Number of results to return per page.diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.tsindex e1d5667a0946..add35c543128 100644--- a/products/product_analytics/frontend/generated/api.ts+++ b/products/product_analytics/frontend/generated/api.ts@@ -17,6 +17,7 @@ import type {ElementApi,ElementsListParams,InsightApi,+ InsightViewedRequestApi,InsightsActivityRetrieveParams,InsightsAllActivityRetrieveParams,InsightsAnalyzeRetrieveParams,@@ -902,12 +903,11 @@ export const getInsightsViewedCreateUrl = (projectId: string, params?: InsightsV}/**- * Update insight view timestamps.-Expects: {"insight_ids": [1, 2, 3, ...]}+ * Record that the current user has just viewed one or more insights. Submitted ids that do not belong to the current project or that point at deleted insights are silently dropped. Returns 201 on success regardless of how many ids were retained.*/export const insightsViewedCreate = async (projectId: string,- insightApi?: NonReadonly<InsightApi>,+ insightViewedRequestApi: InsightViewedRequestApi,params?: InsightsViewedCreateParams,options?: RequestInit): Promise<void> => {@@ -915,6 +915,6 @@ export const insightsViewedCreate = async (...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(insightApi),+ body: JSON.stringify(insightViewedRequestApi),})}diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.tsindex 3a26cd296f71..b92ab02bc53f 100644--- a/products/product_analytics/frontend/generated/api.zod.ts+++ b/products/product_analytics/frontend/generated/api.zod.ts@@ -268,9 +268,13 @@ export const InsightsGenerateMetadataCreateBody = /* @__PURE__ */ zod.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')/**- * Update insight view timestamps.-Expects: {"insight_ids": [1, 2, 3, ...]}+ * Record that the current user has just viewed one or more insights. Submitted ids that do not belong to the current project or that point at deleted insights are silently dropped. Returns 201 on success regardless of how many ids were retained.*/-export const InsightsViewedCreateBody = /* @__PURE__ */ zod- .record(zod.string(), zod.unknown())- .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')+export const insightsViewedCreateBodyInsightIdsMax = 2500++export const InsightsViewedCreateBody = /* @__PURE__ */ zod.object({+ insight_ids: zod+ .array(zod.number())+ .max(insightsViewedCreateBodyInsightIdsMax)+ .describe('Insight IDs that were just viewed by the current user. At most 2500 ids per request.'),+})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a4b7938800c8..774ea0192959 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18401,6 +18401,14 @@ export namespace Schemas {values?: unknown;}+ export interface InsightViewedRequest {+ /**+ * Insight IDs that were just viewed by the current user. At most 2500 ids per request.+ * @maxItems 2500+ */+ insight_ids: number[];+ }+export interface InsightsToolCall {/** @maxLength 1000 */query: string;