: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(posthog-ai): patch saved insights at their stored query root (#124859)
Matt Pua94e4595ae569
diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.pyindex 829184e73278..af9da3efd8ab 100644--- a/ee/hogai/context/context.py+++ b/ee/hogai/context/context.py@@ -32,6 +32,7 @@ from posthog.sync import database_sync_to_asyncfrom products.notebooks.backend.facade import api as notebooks_facadefrom products.notebooks.backend.facade.widgets import reusable_widget_catalog_context+from products.product_analytics.backend.facade.api import viewable_saved_queriesfrom ee.hogai.context.dashboard.context import DashboardContext, DashboardInsightContextfrom ee.hogai.context.insight.context import InsightContext@@ -184,6 +185,11 @@ class AssistantContextManager(AssistantContextMixin):OrganizationMembership.Level.OWNER,)+ @database_sync_to_async+ def _get_viewable_saved_queries(self, short_ids: list[str]) -> dict[str, dict[str, Any]]:+ # The ids come from the client, so apply the same viewer check as reading an insight.+ return viewable_saved_queries(team=self._team, user=self._user, short_ids=short_ids)+@database_sync_to_asyncdef check_has_audit_logs_access(self) -> bool:"""@@ -261,6 +267,7 @@ class AssistantContextManager(AssistantContextMixin):# Build DashboardInsightContext models for this dashboardinsights_data: list[DashboardInsightContext] = []+ saved_queries = await self._get_viewable_saved_queries([insight.id for insight in dashboard.insights])for insight in dashboard.insights:filters_override = (insight.filtersOverride.model_dump(mode="json") if insight.filtersOverride else None@@ -278,6 +285,7 @@ class AssistantContextManager(AssistantContextMixin):short_id=insight.id,filters_override=filters_override,variables_override=variables_override,+ saved_query=saved_queries.get(insight.id),))diff --git a/ee/hogai/context/dashboard/context.py b/ee/hogai/context/dashboard/context.pyindex 478ad936b955..cc04c37fb124 100644--- a/ee/hogai/context/dashboard/context.py+++ b/ee/hogai/context/dashboard/context.py@@ -27,6 +27,7 @@ class DashboardInsightContext(BaseModel, Generic[AnyPydanticModelQuery]):filters_override: dict | None = Nonevariables_override: dict | None = Nonelayout: dict | None = None+ saved_query: dict | None = Noneclass DashboardContext:@@ -179,4 +180,5 @@ class DashboardContext:dashboard_filters=self.dashboard_filters,filters_override=data.filters_override,variables_override=data.variables_override,+ saved_query=data.saved_query,)diff --git a/ee/hogai/context/insight/context.py b/ee/hogai/context/insight/context.pyindex 72ffc7aed767..3c521587c4c5 100644--- a/ee/hogai/context/insight/context.py+++ b/ee/hogai/context/insight/context.py@@ -1,3 +1,6 @@+import json+from typing import Any+from posthog.event_usage import EventSourcefrom posthog.hogql_queries.apply_dashboard_filters import (apply_dashboard_filters_to_dict,@@ -46,6 +49,7 @@ class InsightContext:variables_override: dict | None = None,event_source: EventSource = EventSource.POSTHOG_AI,max_sql_result_chars: int | None = None,+ saved_query: dict[str, Any] | None = None,) -> None:self.team = teamself.user = user@@ -60,6 +64,7 @@ class InsightContext:self.dashboard_filters = dashboard_filtersself.filters_override = filters_overrideself.variables_override = variables_override+ self.saved_query = saved_query@propertydef insight_url(self) -> str | None:@@ -91,7 +96,8 @@ class InsightContext:) -> str:"""Execute query and format results."""effective_query = await self._get_effective_query()- query_schema = effective_query.model_dump_json(exclude_none=True)+ query_schema = self._format_query_schema(effective_query)+ effective_query_schema = self._format_effective_query_schema(effective_query)try:results = await execute_and_format_query(@@ -121,23 +127,52 @@ class InsightContext:insight_id=self.insight_id,insight_description=self.description,query_schema=query_schema,+ is_saved_query=self.saved_query is not None,+ effective_query_schema=effective_query_schema,results=results,insight_url=self.insight_url,)async def format_schema(self, prompt_template: str = INSIGHT_RESULT_TEMPLATE) -> str:"""Format insight as schema-only (no execution)."""- effective_query = await self._get_effective_query()- query_schema = effective_query.model_dump_json(exclude_none=True)+ query_schema = self._format_query_schema(await self._get_effective_query())return format_prompt_string(prompt_template,insight_name=self.name,insight_id=self.insight_id,insight_description=self.description,query_schema=query_schema,+ is_saved_query=self.saved_query is not None,insight_url=self.insight_url,)+ def _format_query_schema(self, effective_query: AnyPydanticModelQuery | AnyAssistantGeneratedQuery) -> str:+ if self.saved_query is not None:+ # query_patch edits the stored query, so show it with its wrapper instead of the unwrapped query.+ return json.dumps(self.saved_query, separators=(",", ":"))+ return effective_query.model_dump_json(exclude_none=True)++ def _format_effective_query_schema(+ self, effective_query: AnyPydanticModelQuery | AnyAssistantGeneratedQuery+ ) -> str | None:+ """The query that produced the results, when dashboard filters or variables make it differ from the saved query."""+ if self.saved_query is None:+ return None+ try:+ saved_query = validate_assistant_query(self.saved_query.get("source") or self.saved_query)+ except Exception:+ saved_query = None+ if saved_query is not None and self._comparable(saved_query) == self._comparable(effective_query):+ return None+ return effective_query.model_dump_json(exclude_none=True)++ @staticmethod+ def _comparable(query: AnyPydanticModelQuery | AnyAssistantGeneratedQuery) -> dict[str, Any]:+ # The frontend fills in schema defaults and a version that saved queries often omit.+ dumped = query.model_dump(mode="json", exclude_none=True, exclude_defaults=True)+ dumped.pop("version", None)+ return dumped+async def _get_effective_query(self):"""Apply dashboard filters/overrides if provided."""if not (self.dashboard_filters or self.filters_override or self.variables_override):diff --git a/ee/hogai/context/insight/prompts.py b/ee/hogai/context/insight/prompts.pyindex 074265d50a36..e5bee278025d 100644--- a/ee/hogai/context/insight/prompts.py+++ b/ee/hogai/context/insight/prompts.py@@ -14,11 +14,23 @@ This insight is not saved in the project, so it cannot be accessed via a URL. An{{/insight_url}}{{#query_schema}}+{{#is_saved_query}}+Saved query (query_patch paths start at the root of this object):+{{/is_saved_query}}+{{^is_saved_query}}Query schema:+{{/is_saved_query}}```json{{{query_schema}}}```{{/query_schema}}+{{#effective_query_schema}}++Query that produced the results below, with dashboard filters and variables applied (not a query_patch target):+```json+{{{effective_query_schema}}}+```+{{/effective_query_schema}}{{#results}}{{{results}}}diff --git a/ee/hogai/context/insight/test/test_context.py b/ee/hogai/context/insight/test/test_context.pyindex b2e5d0bc71cf..1ba258d2e7f3 100644--- a/ee/hogai/context/insight/test/test_context.py+++ b/ee/hogai/context/insight/test/test_context.py@@ -3,7 +3,7 @@ from unittest.mock import patchfrom parameterized import parameterized-from posthog.schema import AssistantTrendsEventsNode, AssistantTrendsQuery+from posthog.schema import AssistantTrendsEventsNode, AssistantTrendsQuery, DateRange, EventsNode, TrendsQueryfrom ee.hogai.context.insight.context import InsightContextfrom ee.hogai.tool_errors import MaxToolRetryableError@@ -208,6 +208,39 @@ class TestInsightContext(BaseTest):executed_query = call_args[0][1]self.assertIsNotNone(executed_query)+ @parameterized.expand(+ [+ ("dashboard_filter", {"date_from": "-7d"}, None, True),+ ("same_query", None, None, False),+ ("frontend_version_only", None, 4, False),+ ]+ )+ @patch("ee.hogai.context.insight.context.execute_and_format_query")+ async def test_execute_and_format_shows_effective_query_when_it_differs_from_saved(+ self, _name, dashboard_filters, version, expect_effective, mock_execute+ ):+ mock_execute.return_value = "Test Results"+ saved_query = {+ "kind": "InsightVizNode",+ "source": {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ "dateRange": {"date_from": "-30d"},+ },+ }+ query = TrendsQuery(+ series=[EventsNode(event="$pageview")], dateRange=DateRange(date_from="-30d"), version=version+ )+ context = InsightContext(+ team=self.team, query=query, user=self.user, dashboard_filters=dashboard_filters, saved_query=saved_query+ )++ result = await context.execute_and_format()++ self.assertIn('"dateRange":{"date_from":"-30d"}', result)+ self.assertEqual("Query that produced the results below" in result, expect_effective)+ self.assertEqual('"date_from":"-7d"' in result, expect_effective)+@patch("ee.hogai.context.insight.context.execute_and_format_query")async def test_execute_and_format_with_insight_model_id(self, mock_execute):mock_execute.return_value = "Test Results"diff --git a/ee/hogai/context/test/test_context.py b/ee/hogai/context/test/test_context.pyindex 9769ad170fe1..955a406b7e0b 100644--- a/ee/hogai/context/test/test_context.py+++ b/ee/hogai/context/test/test_context.py@@ -37,7 +37,13 @@ from posthog.schema import (TrendsQuery,)+from posthog.constants import AvailableFeaturefrom posthog.models.organization import OrganizationMembership+from posthog.models.user import User+from posthog.sync import database_sync_to_async++from products.access_control.backend.models.access_control import AccessControl+from products.product_analytics.backend.facade.models import Insightfrom ee.hogai.context import AssistantContextManagerfrom ee.hogai.context.context import DASHBOARD_CONTEXT_CHAR_BUDGET@@ -176,13 +182,33 @@ class TestAssistantContextManager(BaseTest):self.assertEqual(result, None)mock_capture_exception.assert_called_once()+ @parameterized.expand([("viewer", True), ("no_access", False)])@patch("ee.hogai.context.insight.context.execute_and_format_query")- async def test_format_ui_context_with_dashboard(self, mock_execute):+ async def test_format_ui_context_with_dashboard(self, _name, can_view, mock_execute):mock_execute.return_value = "Dashboard insight results"+ creator = await database_sync_to_async(User.objects.create_and_join)(+ self.organization, "[email protected]", None+ )+ saved = await Insight.objects.acreate(+ team=self.team,+ created_by=creator,+ query={"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": [], "interval": "day"}},+ )+ if not can_view:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ await self.organization.asave()+ await OrganizationMembership.objects.filter(user=self.user, organization=self.organization).aupdate(+ level=OrganizationMembership.Level.MEMBER+ )+ await AccessControl.objects.acreate(+ team=self.team, resource="insight", resource_id=str(saved.id), access_level="none"+ )# Create mock insightinsight = MaxInsightContext(- id="123",+ id=saved.short_id,name="Dashboard Insight",description="Test insight",query=TrendsQuery(series=[EventsNode(event="pageview")]),@@ -207,6 +233,8 @@ class TestAssistantContextManager(BaseTest):self.assertIn("## Dashboard name: Test Dashboard", result)self.assertIn("Description: Test dashboard description", result)self.assertIn("Dashboard insights:", result)+ # query_patch targets the stored query, so the attached context must show its wrapper.+ self.assertEqual('{"kind":"InsightVizNode","source":{' in result, can_view)# The insight execution is tested separately - just verify structure hereself.assertNotIn("# Insights", result)diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.pyindex 5824ce57bf42..7bfe3ea8045c 100644--- a/ee/hogai/core/runner.py+++ b/ee/hogai/core/runner.py@@ -619,6 +619,22 @@ class BaseAgentRunner(ABC):raise ValueError("Approval does not match a pending operation")self._resume_payload = Noneresume_value = None+ elif self._resume_payload["action"] == "reject" and self._resume_payload.get("feedback"):+ # Feedback is a new instruction, so it rejects the whole batch, or each remaining card re-prompts with the old request.+ rejections = {+ pending.interrupt_id: {**self._resume_payload, "proposal_id": pending_id}+ for task in snapshot.tasks+ if task.result is None+ for pending in task.interrupts+ if (pending_id := pending_approval_proposal_id(pending.value))+ }+ for pending_id in {rejection["proposal_id"] for rejection in rejections.values()} - {proposal_id}:+ # Saved with the selected card's status below; matches the "skipped" cards the frontend shows live.+ if pending_id in self._conversation.approval_decisions:+ self._conversation.approval_decisions[pending_id]["decision_status"] = (+ ApprovalDecisionStatus.AUTO_REJECTED+ )+ resume_value = rejectionselse:# A scalar resume targets the next interrupt, which may belong to a different approval card.resume_value = {approval_interrupt.interrupt_id: self._resume_payload}diff --git a/ee/hogai/core/test/test_runner.py b/ee/hogai/core/test/test_runner.pyindex 16bb497a5008..4d805083638e 100644--- a/ee/hogai/core/test/test_runner.py+++ b/ee/hogai/core/test/test_runner.py@@ -828,8 +828,8 @@ class TestRunnerClientToolCallInterrupt(BaseTest):self.assertTrue(any(getattr(m, "content", None) == "Please clarify your request" for m in messages))mock_graph.aupdate_state.assert_called_once()- @parameterized.expand([("approve",), ("reject",)])- async def test_response_targets_selected_parallel_approval(self, action: str) -> None:+ @parameterized.expand([("approve", None), ("reject", None), ("reject", "make them monthly")])+ async def test_response_targets_selected_parallel_approval(self, action: str, feedback: str | None) -> None:executed: list[str] = []def operation(name: str) -> Callable[[AssistantState], dict[str, object]]:@@ -864,11 +864,24 @@ class TestRunnerClientToolCallInterrupt(BaseTest):self.conversation.approval_decisions[approval.proposal_id] = {"decision_status": "pending"}await self.conversation.asave(update_fields=["approval_decisions"])runner._resume_payload = {"action": action, "proposal_id": approvals["second"].proposal_id}+ if feedback:+ runner._resume_payload["feedback"] = feedbackcommand = await runner._init_or_update_state()await graph.ainvoke(command, config)self.assertEqual(executed, ["second"] if action == "approve" else [])after = await graph.aget_state(config)remaining = [pending.value for task in after.tasks if task.result is None for pending in task.interrupts]+ if feedback:+ await self.conversation.arefresh_from_db()+ self.assertEqual(remaining, [])+ self.assertEqual(+ {+ name: self.conversation.approval_decisions[approval.proposal_id]["decision_status"]+ for name, approval in approvals.items()+ },+ {"first": "auto_rejected", "second": "rejected"},+ )+ returnself.assertEqual([request.proposal_id for request in remaining], [approvals["first"].proposal_id])await self.conversation.arefresh_from_db()self.assertEqual(diff --git a/ee/hogai/tools/read_data/test/test_tool.py b/ee/hogai/tools/read_data/test/test_tool.pyindex 35c6d45c3402..54bda81973d9 100644--- a/ee/hogai/tools/read_data/test/test_tool.py+++ b/ee/hogai/tools/read_data/test/test_tool.py@@ -1574,6 +1574,7 @@ class TestReadDataTool(BaseTest):mock_query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])mock_content = VisualizationArtifactContent(name="Allowed Insight", query=mock_query)mock_insight = MagicMock(spec=Insight)+ mock_insight.query = {"kind": "InsightVizNode", "source": mock_query.model_dump(exclude_none=True)}context_manager.artifacts = MagicMock()context_manager.artifacts.aget_visualization = AsyncMock(diff --git a/ee/hogai/tools/read_data/tool.py b/ee/hogai/tools/read_data/tool.pyindex cc1a37227990..85a84c1f09ab 100644--- a/ee/hogai/tools/read_data/tool.py+++ b/ee/hogai/tools/read_data/tool.py@@ -452,6 +452,7 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):insight_id=artifact_or_insight_id,insight_model_id=result.model.id if isinstance(result, ModelArtifactResult) else None,insight_short_id=result.model.short_id if isinstance(result, ModelArtifactResult) else None,+ saved_query=result.model.query if isinstance(result, ModelArtifactResult) else None,)# The agent wants to read the schema, just return it@@ -754,6 +755,7 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):short_id=insight.short_id,db_id=insight.id,layout=tile.layouts,+ saved_query=insight.query,))diff --git a/ee/hogai/tools/test/test_create_insight.py b/ee/hogai/tools/test/test_create_insight.pyindex 19d3135b3f8d..faf5438daa30 100644--- a/ee/hogai/tools/test/test_create_insight.py+++ b/ee/hogai/tools/test/test_create_insight.py@@ -33,6 +33,7 @@ from ee.hogai.chat_agent.schema_generator.nodes import SchemaGenerationExceptionfrom ee.hogai.context.context import AssistantContextManagerfrom ee.hogai.tool_errors import MaxToolRetryableErrorfrom ee.hogai.tools.create_insight import INSIGHT_TOOL_FAILURE_SYSTEM_REMINDER_PROMPT, CreateInsightTool+from ee.hogai.tools.read_data.tool import ReadDataToolfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import ArtifactRefMessage, AssistantNodeName, NodePath@@ -124,6 +125,40 @@ class TestCreateInsightTool(ClickhouseTestMixin, NonAtomicBaseTest):await insight.arefresh_from_db()self.assertEqual(insight.query, concurrent_query)+ @parameterized.expand([("insight",), ("dashboard",)])+ async def test_saved_update_accepts_patch_paths_from_read_data_schema(self, read_kind: str):+ insight = await Insight.objects.acreate(+ team=self.team,+ name="Wrapped chart",+ query={"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": [], "interval": "day"}},+ )+ dashboard = await Dashboard.objects.acreate(team=self.team, name="Board")+ await DashboardTile.objects.acreate(dashboard=dashboard, insight=insight)+ read_tool = await ReadDataTool.create_tool_class(+ team=self.team, user=self.user, state=AssistantState(messages=[])+ )+ read_args = (+ {"kind": "insight", "insight_id": insight.short_id}+ if read_kind == "insight"+ else {"kind": "dashboard", "dashboard_id": str(dashboard.id)}+ )+ read_output, _ = await read_tool._arun_impl({**read_args, "execute": False})+ schema = json.loads(read_output.split("```json\n")[1].split("\n```")[0])+ interval_path = "/source/interval" if "source" in schema else "/interval"++ tool = await self._create_tool()+ await tool._arun_impl(+ viz_title="Chart",+ viz_description="",+ query_description="Change interval",+ insight_type="trends",+ insight_id=insight.short_id,+ query_patch=json.dumps([{"op": "replace", "path": interval_path, "value": "week"}]),+ )+ await insight.arefresh_from_db()+ assert insight.query is not None+ self.assertEqual(insight.query["source"]["interval"], "week")+async def test_saved_update_rejects_changes_after_approval_preview(self):tool = await self._create_tool()original_query = {"kind": "TrendsQuery", "series": []}diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex 566c849af172..c9199ee27c88 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -3186,6 +3186,27 @@ describe('maxThreadLogic', () => {expect(visibleProposal()).toBe('new')})+ it('marks the rest of a pending batch as rejected when the user rejects one card with feedback', async () => {+ const streamSpy = mockStream()+ logic.actions.setConversation(MOCK_CONVERSATION)+ for (const id of ['first', 'second', 'third']) {+ logic.actions.addPendingApprovalData(approval(id, 'pending'))+ }+ logic.actions.setResolvedApprovalStatus('third', 'approved')+ logic.actions.setPendingApproval('first')++ await expectLogic(logic, () => {+ logic.actions.continueAfterRejection('first', 'monthly')+ }).toDispatchActions(['autoRejectPendingApprovals'])++ expect(logic.values.resolvedApprovalStatuses['second']?.status).toBe('auto_rejected')+ expect(logic.values.resolvedApprovalStatuses['third']?.status).toBe('approved')+ expect(streamSpy).toHaveBeenCalledWith(+ expect.objectContaining({ resume_payload: expect.objectContaining({ action: 'reject' }) }),+ expect.any(Object)+ )+ })+it('follows the server for approvals it returns and selects none at turn end without a selection', () => {logic.actions.addPendingApprovalData(approval('other', 'pending'))logic.actions.completeThreadGeneration()diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex f5aadea6f966..aab2b25483a8 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -390,6 +390,9 @@ export interface maxThreadLogicActions {appendSandboxEntry: (entry: LogEntry) => {entry: LogEntry}+ autoRejectPendingApprovals: () => {+ value: true+ }clearPendingApproval: () => {value: true}@@ -912,6 +915,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([setCancelLoading: (cancelLoading: boolean) => ({ cancelLoading }),setPendingApproval: (proposalId: string) => ({ proposalId }),clearPendingApproval: true,+ autoRejectPendingApprovals: true,appendSandboxEntry: (entry: LogEntry) => ({ entry }),prewarmSandbox: true,releaseSandboxPrewarm: true,@@ -2462,6 +2466,14 @@ export const maxThreadLogic = kea<maxThreadLogicType>([false // Don't add to thread - no human message to show)},+ autoRejectPendingApprovals: () => {+ // The backend rejects the whole batch on feedback, so every card still pending is rejected too.+ for (const approval of Object.values(values.pendingApprovalsData)) {+ if (approval.decision_status === 'pending' && !values.resolvedApprovalStatuses[approval.proposal_id]) {+ actions.setResolvedApprovalStatus(approval.proposal_id, 'auto_rejected')+ }+ }+ },continueAfterApproval: ({ proposalId }) => {actions.clearQueuedMessages()// Persist the approved status so the card can display it@@ -2490,6 +2502,9 @@ export const maxThreadLogic = kea<maxThreadLogicType>([// mounted to show the resolved state with feedback. The alreadyResolved check// in askMax prevents auto-rejection for resolved approvals.actions.setResolvedApprovalStatus(proposalId, 'rejected', feedback)+ if (feedback) {+ actions.autoRejectPendingApprovals()+ }// Resume the conversation with the rejection payloadactions.streamConversation({diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.pyindex 3652707a47da..b7d3493328fd 100644--- a/products/product_analytics/backend/facade/api.py+++ b/products/product_analytics/backend/facade/api.py@@ -255,6 +255,17 @@ def viewable_insights(*, team: Team, user: User, insight_ids: Collection[int]) -]+def viewable_saved_queries(*, team: Team, user: User, short_ids: Collection[str]) -> dict[str, dict[str, Any]]:+ """The stored queries of this team's live insights among ``short_ids`` that the user may view, by short ID."""+ if not short_ids:+ return {}+ access_control = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))+ insights = access_control.filter_queryset_by_access_level(+ Insight.objects.filter(team_id=team.id, short_id__in=short_ids, deleted=False), resource="insight"+ )+ return {short_id: query for short_id, query in insights.values_list("short_id", "query") if query}++def save_saved_insight_query(*, team: Team, user: User, insight_id: int, expected_query: dict[str, Any], query: dict[str, Any]) -> str | None: