: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): stop serving deprecated dashboards to sessions (#72764)
Paul D'Ambra1b0cf3ca776b
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex b279acd5aca9..5ed3040b1882 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -2234,7 +2234,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):self.dashboard_api.soft_delete(dashboard_id, "dashboards")insight_json = self.dashboard_api.get_insight(insight_id=insight_id)- self.assertEqual(insight_json["dashboards"], [])+ self.assertEqual(insight_json["dashboard_tiles"], [])self.dashboard_api.soft_delete(insight_id, "insights")@@ -2289,11 +2289,9 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):insight_one_json = self.dashboard_api.get_insight(insight_id=insight_one_id)assert [t["dashboard_id"] for t in insight_one_json["dashboard_tiles"]] == [other_dashboard_id]- assert insight_one_json["dashboards"] == [other_dashboard_id]assert insight_one_json["deleted"] is Falseinsight_two_json = self.dashboard_api.get_insight(insight_id=insight_two_id)assert [t["dashboard_id"] for t in insight_two_json["dashboard_tiles"]] == []- assert insight_two_json["dashboards"] == []assert insight_two_json["deleted"] is Falsedef test_can_copy_tile_between_dashboards(self) -> None:@@ -2615,10 +2613,12 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):self.dashboard_api.soft_delete(dashboard_one_id, "dashboards")insight_after_dashboard_deletion = self.dashboard_api.get_insight(insight_id)- assert insight_after_dashboard_deletion["dashboards"] == [dashboard_two_id]+ assert [t["dashboard_id"] for t in insight_after_dashboard_deletion["dashboard_tiles"]] == [dashboard_two_id]dashboard_two_json = self.dashboard_api.get_dashboard(dashboard_two_id)- expected_dashboards_on_insight = dashboard_two_json["tiles"][0]["insight"]["dashboards"]+ expected_dashboards_on_insight = [+ t["dashboard_id"] for t in dashboard_two_json["tiles"][0]["insight"]["dashboard_tiles"]+ ]assert expected_dashboards_on_insight == [dashboard_two_id]@patch("products.dashboards.backend.api.dashboard.report_user_action")@@ -2835,7 +2835,6 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):"id": ANY,}],- "dashboards": [response.json()["id"]],"deleted": False,"derived_name": None,"description": None,@@ -4136,7 +4135,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):content_type="application/json",)self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["dashboards"], [dashboard1.pk])+ self.assertEqual([t["dashboard_id"] for t in response.json()["dashboard_tiles"]], [dashboard1.pk])self.assertTrue(DashboardTile.objects.filter(dashboard=dashboard1, insight=insight).exists())# Append to second dashboard — must include both IDs (full replacement)@@ -4146,7 +4145,9 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):content_type="application/json",)self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertCountEqual(response.json()["dashboards"], [dashboard1.pk, dashboard2.pk])+ self.assertCountEqual(+ [t["dashboard_id"] for t in response.json()["dashboard_tiles"]], [dashboard1.pk, dashboard2.pk]+ )self.assertTrue(DashboardTile.objects.filter(dashboard=dashboard1, insight=insight).exists())self.assertTrue(DashboardTile.objects.filter(dashboard=dashboard2, insight=insight).exists())@@ -4164,6 +4165,6 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):content_type="application/json",)self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["dashboards"], [dashboard1.pk])+ self.assertEqual([t["dashboard_id"] for t in response.json()["dashboard_tiles"]], [dashboard1.pk])self.assertTrue(DashboardTile.objects.filter(dashboard=dashboard1, insight=insight).exists())self.assertFalse(DashboardTile.objects.filter(dashboard=dashboard2, insight=insight, deleted=False).exists())diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex ec97ef61650f..5fd278ab99f9 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -14,10 +14,10 @@ from posthog.utils_cors import CORS_ALLOWED_TRACING_HEADERSlogger = structlog.get_logger(__name__)####-# Deprecated insight `dashboards` field: two-phase removal. While False (phase 1), every caller-# still receives the field and usage is metered by access method; flipping to True (phase 2)-# enforces the `include_dashboards` opt-in for non-first-party callers. Env-toggleable so the-# enforcement can be reverted without a code change.+# Deprecated insight `dashboards` field: session-authenticated callers always need to opt in with+# `include_dashboards`. While False, API-token callers still receive the field; flipping to True+# enforces the opt-in for them too. Env-toggleable so token enforcement can be reverted without a+# code change.INSIGHT_DASHBOARDS_OPT_IN_ENFORCED = get_from_env("INSIGHT_DASHBOARDS_OPT_IN_ENFORCED", False, type_cast=str_to_bool)####diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex d01b5ce3ebad..92ee93a4d3ba 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -7979,9 +7979,9 @@ export interface InsightApi {** DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.* A dashboard ID for each of the dashboards that this insight is displayed on.- * This field may be omitted from responses: once opt-in enforcement is enabled, API-token- * callers (personal API keys, OAuth) only receive it when passing the- * `include_dashboards=true` query parameter. Do not rely on it being present.+ * This field is omitted from session-authenticated responses unless `include_dashboards=true`+ * is passed. Once opt-in enforcement is enabled, API-token callers (personal API keys, OAuth)+ * must opt in the same way. Do not rely on it being present.** @deprecated*/diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex 31fd5b038117..ac578d1c0e07 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -349,11 +349,9 @@ DEPRECATED_DASHBOARDS_FIELD_USED_COUNTER = Counter()-# Access methods that are our own surfaces (web app, shared/exporter frontend) rather than-# external integrations. Unresolved auth ("no_authenticator") comes from the web app too. These-# keep receiving the deprecated `dashboards` field until the frontend fully migrates to-# dashboard_tiles, regardless of opt-in enforcement.-_FIRST_PARTY_ACCESS_METHODS = frozenset({"no_authenticator", "session", "sharing_token"})+# Access methods that still need the deprecated field without opting in. Shared/exporter views+# have their own frontend lifecycle, and unresolved auth is not a caller we can migrate safely.+_DEPRECATED_DASHBOARDS_FIELD_EXEMPT_ACCESS_METHODS = frozenset({"no_authenticator", "sharing_token"})def _dashboards_field_access_method(request: Request | None) -> str:@@ -377,25 +375,25 @@ def _is_internal_serialization_context(context: dict) -> bool:return context.get("request") is None-def _is_first_party_request(request: Request | None) -> bool:- return _dashboards_field_access_method(request) in _FIRST_PARTY_ACCESS_METHODS--def should_serve_deprecated_dashboards_field(context: dict) -> bool:"""The insight `dashboards` field is deprecated in favor of `dashboard_tiles`. Removal istwo-phase: while INSIGHT_DASHBOARDS_OPT_IN_ENFORCED is off, every caller still receives thefield and reads are metered by access method so remaining usage can drain; once enforced,- non-first-party callers must opt in with `?include_dashboards=true`.+ token callers must opt in with `?include_dashboards=true`. Session-authenticated requests+ already require the opt-in because the web app has migrated to `dashboard_tiles`."""if _is_internal_serialization_context(context):return Truerequest = context["request"]- if _is_first_party_request(request):- return Truequery_params = getattr(request, "query_params", None)if query_params is not None and str_to_bool(query_params.get(INCLUDE_DASHBOARDS_PARAM, "0")):return True+ access_method = _dashboards_field_access_method(request)+ if access_method == "session":+ return False+ if access_method in _DEPRECATED_DASHBOARDS_FIELD_EXEMPT_ACCESS_METHODS:+ return Truereturn not settings.INSIGHT_DASHBOARDS_OPT_IN_ENFORCED@@ -612,9 +610,9 @@ class InsightSerializer(InsightBasicSerializer):help_text="""DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.A dashboard ID for each of the dashboards that this insight is displayed on.- This field may be omitted from responses: once opt-in enforcement is enabled, API-token- callers (personal API keys, OAuth) only receive it when passing the- `include_dashboards=true` query parameter. Do not rely on it being present.+ This field is omitted from session-authenticated responses unless `include_dashboards=true`+ is passed. Once opt-in enforcement is enabled, API-token callers (personal API keys, OAuth)+ must opt in the same way. Do not rely on it being present.""",many=True,required=False,@@ -1050,6 +1048,10 @@ class InsightSerializer(InsightBasicSerializer):request=self.context["request"],)+ # Dashboard membership is mutated through separate querysets above, so the instance's+ # prefetched relation no longer reflects what was persisted. The response serializer must+ # reload it because session callers now derive membership exclusively from dashboard_tiles.+ getattr(instance, "_prefetched_objects_cache", {}).pop("dashboard_tiles", None)self.context["after_dashboard_changes"] = [describe_change(d) for d in dashboards if not d.deleted]@extend_schema_field(OpenApiTypes.ANY)@@ -1192,10 +1194,9 @@ class InsightSerializer(InsightBasicSerializer):# and avoid refreshing from the DB## `after_dashboard_changes` is only set (even to an empty list) when this request itself- # wrote `dashboards` (see _update_insight_dashboards), so a caller that isn't opted into- # the deprecated field for reads still needs to see the corrected value for the write it- # just made — including the "removed from all dashboards" case.- if "after_dashboard_changes" in self.context:+ # wrote `dashboards` (see _update_insight_dashboards). Correct the value only for callers+ # that opted into receiving the deprecated field.+ if "after_dashboard_changes" in self.context and should_serve_deprecated_dashboards_field(self.context):representation["dashboards"] = [described_dashboard["id"] for described_dashboard in self.context["after_dashboard_changes"]]diff --git a/products/product_analytics/backend/api/test/test_deprecated_dashboards_field.py b/products/product_analytics/backend/api/test/test_deprecated_dashboards_field.pyindex 22894e743d1d..767f58a8574c 100644--- a/products/product_analytics/backend/api/test/test_deprecated_dashboards_field.py+++ b/products/product_analytics/backend/api/test/test_deprecated_dashboards_field.py@@ -29,7 +29,14 @@ class TestShouldServeDeprecatedDashboardsField(SimpleTestCase):@parameterized.expand([- ("session_auth", SessionAuthentication(), {}, False, True),+ ("session_auth_requires_opt_in", SessionAuthentication(), {}, False, False),+ (+ "session_auth_with_opt_in",+ SessionAuthentication(),+ {"include_dashboards": "true"},+ False,+ True,+ ),("no_authenticator_is_first_party", None, {}, True, True),("sharing_token_is_first_party", SharingAccessTokenAuthentication(), {}, True, True),("personal_api_key_unenforced_phase", PersonalAPIKeyAuthentication(), {}, False, True),@@ -86,7 +93,18 @@ class TestDeprecatedDashboardsFieldAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["dashboards"] == [self.dashboard.id]- def test_session_auth_still_receives_deprecated_dashboards_field(self):+ def test_session_auth_does_not_receive_deprecated_dashboards_field(self):response = self.client.get(f"/api/projects/{self.team.id}/insights/{self.insight.id}/")assert response.status_code == status.HTTP_200_OK- assert response.json()["dashboards"] == [self.dashboard.id]+ assert "dashboards" not in response.json()+ assert [tile["dashboard_id"] for tile in response.json()["dashboard_tiles"]] == [self.dashboard.id]++ def test_session_auth_write_does_not_echo_deprecated_dashboards_field(self):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/insights/{self.insight.id}/",+ {"dashboards": []},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert "dashboards" not in response.json()diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.pyindex 2bd4143be3dc..3decb6611159 100644--- a/products/product_analytics/backend/api/test/test_insight.py+++ b/products/product_analytics/backend/api/test/test_insight.py@@ -774,7 +774,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):"favorited","filters","query",- "dashboards","dashboard_tiles","description","last_refresh",@@ -1352,7 +1351,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.dashboard_api.update_dashboard(deleted_dashboard_id, {"deleted": True})insight_json = self.dashboard_api.get_insight(insight_id)- assert insight_json["dashboards"] == [dashboard_id]assert insight_json["dashboard_tiles"] == [{"id": mock.ANY, "deleted": None, "dashboard_id": dashboard_id}]new_dashboard_id, _ = self.dashboard_api.create_dashboard({})@@ -1364,7 +1362,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)insight_json = self.dashboard_api.get_insight(insight_id)- assert insight_json["dashboards"] == [dashboard_id]assert insight_json["dashboard_tiles"] == [{"id": mock.ANY, "deleted": None, "dashboard_id": dashboard_id}]def test_insight_items_on_a_dashboard_ignore_deleted_dashboard_tiles(self) -> None:@@ -1386,19 +1383,16 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):tile.save()insight_json = self.dashboard_api.get_insight(insight_id)- assert insight_json["dashboards"] == []assert insight_json["dashboard_tiles"] == []insight_by_short_id = self.client.get(f"/api/projects/{self.team.pk}/insights?short_id={insight_json['short_id']}")- assert insight_by_short_id.json()["results"][0]["dashboards"] == []assert insight_by_short_id.json()["results"][0]["dashboard_tiles"] == []self.dashboard_api.add_insight_to_dashboard([dashboard_id], insight_id)insight_json = self.dashboard_api.get_insight(insight_id)- assert insight_json["dashboards"] == [dashboard_id]assert insight_json["dashboard_tiles"] == [{"id": mock.ANY, "deleted": False, "dashboard_id": dashboard_id}]def test_can_update_insight_with_inconsistent_dashboards(self) -> None:@@ -1425,7 +1419,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert DashboardTile.objects_including_soft_deleted.filter(dashboard_id=deleted_dashboard_id).exists()insight_json = self.dashboard_api.get_insight(insight_id)- assert insight_json["dashboards"] == [dashboard_id]assert insight_json["dashboard_tiles"] == [{"id": mock.ANY, "deleted": None, "dashboard_id": dashboard_id}]# accidentally include a deleted dashboard@@ -1437,7 +1430,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# confirm no updates happenedinsight_json = self.dashboard_api.get_insight(insight_id)- assert insight_json["dashboards"] == [dashboard_id]assert insight_json["dashboard_tiles"] == [{"id": mock.ANY, "deleted": None, "dashboard_id": dashboard_id}]def test_dashboards_relation_is_tile_soft_deletion_aware(self) -> None:@@ -1458,18 +1450,16 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):"dashboards": [dashboard_one_id],},)- assert on_update_insight_json["dashboards"] == [dashboard_one_id]+ assert "dashboards" not in on_update_insight_jsonassert on_update_insight_json["dashboard_tiles"] == [{"id": mock.ANY, "deleted": None, "dashboard_id": dashboard_one_id}]insight_json = self.dashboard_api.get_insight(insight_id)- assert insight_json["dashboards"] == [dashboard_one_id]assert insight_json["dashboard_tiles"] == [{"id": mock.ANY, "deleted": None, "dashboard_id": dashboard_one_id}]insights_list = self.dashboard_api.list_insights()assert insights_list["count"] == 1- assert [i["dashboards"] for i in insights_list["results"]] == [[dashboard_one_id]]assert [i["dashboard_tiles"] for i in insights_list["results"]] == [[{@@ -1728,7 +1718,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert original_tiles[0]["id"] == after_update_tiles[0]["id"] # tile has not been recreated in DBassert after_update_tiles[0]["layouts"] is not None # tile has not been recreated in DBassert original_tiles[0]["insight"]["id"] == after_update_tiles[0]["insight"]["id"]- assert sorted(original_tiles[0]["insight"]["dashboards"]) == sorted([dashboard_one_id, dashboard_two_id])assert sorted(t["dashboard_id"] for t in original_tiles[0]["insight"]["dashboard_tiles"]) == sorted([dashboard_one_id, dashboard_two_id])diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 9a3d6a4118e4..76761ba11446 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -7381,9 +7381,9 @@ export interface InsightApi {** DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.* A dashboard ID for each of the dashboards that this insight is displayed on.- * This field may be omitted from responses: once opt-in enforcement is enabled, API-token- * callers (personal API keys, OAuth) only receive it when passing the- * `include_dashboards=true` query parameter. Do not rely on it being present.+ * This field is omitted from session-authenticated responses unless `include_dashboards=true`+ * is passed. Once opt-in enforcement is enabled, API-token callers (personal API keys, OAuth)+ * must opt in the same way. Do not rely on it being present.** @deprecated*/@@ -7509,9 +7509,9 @@ export interface PatchedInsightApi {** DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.* A dashboard ID for each of the dashboards that this insight is displayed on.- * This field may be omitted from responses: once opt-in enforcement is enabled, API-token- * callers (personal API keys, OAuth) only receive it when passing the- * `include_dashboards=true` query parameter. Do not rely on it being present.+ * This field is omitted from session-authenticated responses unless `include_dashboards=true`+ * is passed. Once opt-in enforcement is enabled, API-token callers (personal API keys, OAuth)+ * must opt in the same way. Do not rely on it being present.** @deprecated*/diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 52e8b8f86b42..67ea0d12e29c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7566,9 +7566,9 @@ export namespace Schemas {** DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.* A dashboard ID for each of the dashboards that this insight is displayed on.- * This field may be omitted from responses: once opt-in enforcement is enabled, API-token- * callers (personal API keys, OAuth) only receive it when passing the- * `include_dashboards=true` query parameter. Do not rely on it being present.+ * This field is omitted from session-authenticated responses unless `include_dashboards=true`+ * is passed. Once opt-in enforcement is enabled, API-token callers (personal API keys, OAuth)+ * must opt in the same way. Do not rely on it being present.** @deprecated*/@@ -48963,9 +48963,9 @@ export namespace Schemas {** DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.* A dashboard ID for each of the dashboards that this insight is displayed on.- * This field may be omitted from responses: once opt-in enforcement is enabled, API-token- * callers (personal API keys, OAuth) only receive it when passing the- * `include_dashboards=true` query parameter. Do not rely on it being present.+ * This field is omitted from session-authenticated responses unless `include_dashboards=true`+ * is passed. Once opt-in enforcement is enabled, API-token callers (personal API keys, OAuth)+ * must opt in the same way. Do not rely on it being present.** @deprecated*/diff --git a/services/mcp/src/generated/product_analytics/api.ts b/services/mcp/src/generated/product_analytics/api.tsindex 6224bd36e4aa..fe921371969b 100644--- a/services/mcp/src/generated/product_analytics/api.ts+++ b/services/mcp/src/generated/product_analytics/api.ts@@ -215,7 +215,7 @@ export const InsightsCreateBody = /* @__PURE__ */ zod.array(zod.number()).optional().describe(- '\n DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.\n A dashboard ID for each of the dashboards that this insight is displayed on.\n This field may be omitted from responses: once opt-in enforcement is enabled, API-token\n callers (personal API keys, OAuth) only receive it when passing the\n `include_dashboards=true` query parameter. Do not rely on it being present.\n '+ '\n DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.\n A dashboard ID for each of the dashboards that this insight is displayed on.\n This field is omitted from session-authenticated responses unless `include_dashboards=true`\n is passed. Once opt-in enforcement is enabled, API-token callers (personal API keys, OAuth)\n must opt in the same way. Do not rely on it being present.\n '),description: zod.string().max(insightsCreateBodyDescriptionMax).nullish(),tags: zod.array(zod.unknown()).optional(),@@ -335,7 +335,7 @@ export const InsightsPartialUpdateBody = /* @__PURE__ */ zod.array(zod.number()).optional().describe(- '\n DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.\n A dashboard ID for each of the dashboards that this insight is displayed on.\n This field may be omitted from responses: once opt-in enforcement is enabled, API-token\n callers (personal API keys, OAuth) only receive it when passing the\n `include_dashboards=true` query parameter. Do not rely on it being present.\n '+ '\n DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.\n A dashboard ID for each of the dashboards that this insight is displayed on.\n This field is omitted from session-authenticated responses unless `include_dashboards=true`\n is passed. Once opt-in enforcement is enabled, API-token callers (personal API keys, OAuth)\n must opt in the same way. Do not rely on it being present.\n '),description: zod.string().max(insightsPartialUpdateBodyDescriptionMax).nullish(),tags: zod.array(zod.unknown()).optional(),