: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(phai): pass user to query runners (#68611)
Georgiy Tarasov34c32bc1cf87
diff --git a/ee/hogai/chat_agent/insights/nodes.py b/ee/hogai/chat_agent/insights/nodes.pyindex 5c6dc200494e..679b21ceaeba 100644--- a/ee/hogai/chat_agent/insights/nodes.py+++ b/ee/hogai/chat_agent/insights/nodes.py@@ -564,7 +564,9 @@ class InsightSearchNode(AssistantNode):) -> str:"""Execute query and format results with timing instrumentation."""try:- query_executor = AssistantQueryExecutor(team=self._team, utc_now_datetime=self._utc_now_datetime)+ query_executor = AssistantQueryExecutor(+ team=self._team, user=self._user, utc_now_datetime=self._utc_now_datetime+ )results, _ = await query_executor.arun_and_format_query(query_obj, debug_timing=True)return resultsexcept Exception as e:diff --git a/ee/hogai/chat_agent/memory/nodes.py b/ee/hogai/chat_agent/memory/nodes.pyindex 242771fda332..c37dac41ce58 100644--- a/ee/hogai/chat_agent/memory/nodes.py+++ b/ee/hogai/chat_agent/memory/nodes.py@@ -105,7 +105,7 @@ class MemoryInitializerContextMixin(AssistantContextMixin):) -> CacheMissResponse | QueryStatusResponse | CachedEventTaxonomyQueryResponse:def run_query() -> CacheMissResponse | QueryStatusResponse | CachedEventTaxonomyQueryResponse:runner = EventTaxonomyQueryRunner(- team=self._team, query=EventTaxonomyQuery(event=event, properties=[property])+ team=self._team, query=EventTaxonomyQuery(event=event, properties=[property]), user=self._user)return runner.run(ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,diff --git a/ee/hogai/chat_agent/query_planner/nodes.py b/ee/hogai/chat_agent/query_planner/nodes.pyindex 783a5a9e62a6..7e2cc3340943 100644--- a/ee/hogai/chat_agent/query_planner/nodes.py+++ b/ee/hogai/chat_agent/query_planner/nodes.py@@ -108,7 +108,7 @@ class QueryPlannerNode(TaxonomyUpdateDispatcherNodeMixin, AssistantNode):"react_property_filters": self._get_react_property_filters_prompt(),"react_human_in_the_loop": HUMAN_IN_THE_LOOP_PROMPT,"groups": self._team_group_types,- "events": format_events_yaml(events_in_context, self._team),+ "events": format_events_yaml(events_in_context, self._team, self._user),"project_datetime": self.project_now,"project_timezone": self.project_timezone,"project_name": self._team.name,diff --git a/ee/hogai/chat_agent/query_planner/toolkit.py b/ee/hogai/chat_agent/query_planner/toolkit.pyindex 3f0485f61bb3..4e349df22af1 100644--- a/ee/hogai/chat_agent/query_planner/toolkit.py+++ b/ee/hogai/chat_agent/query_planner/toolkit.py@@ -224,7 +224,7 @@ class TaxonomyAgentToolkit:else:query = EventTaxonomyQuery(actionId=event_name_or_action_id, maxPropertyValues=25)verbose_name = f"action with ID {event_name_or_action_id}"- runner = EventTaxonomyQueryRunner(query, self._team)+ runner = EventTaxonomyQueryRunner(query, self._team, user=self._user)with tags_context(product=Product.MAX_AI,feature=Feature.POSTHOG_AI,@@ -430,7 +430,7 @@ class TaxonomyAgentToolkit:team_id=self._team.pk,org_id=self._team.organization_id,):- response = ActorsPropertyTaxonomyQueryRunner(query, self._team).run(+ response = ActorsPropertyTaxonomyQueryRunner(query, self._team, user=self._user).run(ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,analytics_props={"source": EventSource.POSTHOG_AI},)diff --git a/ee/hogai/chat_agent/rag/nodes.py b/ee/hogai/chat_agent/rag/nodes.pyindex 66f69c9e3d4d..0717e9d9fe02 100644--- a/ee/hogai/chat_agent/rag/nodes.py+++ b/ee/hogai/chat_agent/rag/nodes.py@@ -124,6 +124,7 @@ class InsightRagContextNode(AssistantNode):runner = VectorSearchQueryRunner(team=self._team,query=VectorSearchQuery(embedding=embedding, embeddingVersion=LATEST_ACTIONS_EMBEDDING_VERSION),+ user=self._user,)with tags_context(product=Product.MAX_AI,@@ -178,7 +179,7 @@ class InsightRagContextNode(AssistantNode):Since this node is already blocking, we can pre-warm the taxonomy queries to avoid further delays.This will slightly reduce latency."""- TeamTaxonomyQueryRunner(TeamTaxonomyQuery(), self._team).run(+ TeamTaxonomyQueryRunner(TeamTaxonomyQuery(), self._team, user=self._user).run(ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,analytics_props={"source": EventSource.POSTHOG_AI},)diff --git a/ee/hogai/chat_agent/taxonomy/nodes.py b/ee/hogai/chat_agent/taxonomy/nodes.pyindex 6a297f7b8cb8..d1bd0d0b91a7 100644--- a/ee/hogai/chat_agent/taxonomy/nodes.py+++ b/ee/hogai/chat_agent/taxonomy/nodes.py@@ -108,7 +108,7 @@ class TaxonomyAgentNode(Generate the output format for events. Can be overridden by subclasses.Default implementation uses YAML format but it can be overridden to use XML format."""- return format_events_yaml(events_in_context, self._team)+ return format_events_yaml(events_in_context, self._team, self._user)def run(self, state: TaxonomyStateType, config: RunnableConfig) -> TaxonomyPartialStateType:"""Process the state and return filtering options."""diff --git a/ee/hogai/chat_agent/taxonomy/toolkit.py b/ee/hogai/chat_agent/taxonomy/toolkit.pyindex 11c6694e265b..13834816d1a9 100644--- a/ee/hogai/chat_agent/taxonomy/toolkit.py+++ b/ee/hogai/chat_agent/taxonomy/toolkit.py@@ -266,7 +266,7 @@ class TaxonomyAgentToolkit:else:query = EventTaxonomyQuery(actionId=action_id, maxPropertyValues=25, properties=properties)verbose_name = f"action with ID {action_id}"- runner = EventTaxonomyQueryRunner(query, self._team)+ runner = EventTaxonomyQueryRunner(query, self._team, user=self._user)with tags_context(product=Product.MAX_AI,feature=Feature.POSTHOG_AI,@@ -703,7 +703,7 @@ class TaxonomyAgentToolkit:team_id=self._team.pk,org_id=self._team.organization_id,):- return ActorsPropertyTaxonomyQueryRunner(query, self._team).run(+ return ActorsPropertyTaxonomyQueryRunner(query, self._team, user=self._user).run(ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,analytics_props={"source": EventSource.POSTHOG_AI},)diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.pyindex 798c1e5c7ad4..9ef6abf0ddae 100644--- a/ee/hogai/context/context.py+++ b/ee/hogai/context/context.py@@ -261,6 +261,7 @@ class AssistantContextManager(AssistantContextMixin):dashboard_ctx = DashboardContext(team=self._team,insights_data=insights_data,+ user=self._user,name=dashboard.name or f"Dashboard {dashboard.id}",description=dashboard.description,dashboard_id=str(dashboard.id) if dashboard.id else None,@@ -495,6 +496,7 @@ class AssistantContextManager(AssistantContextMixin):return InsightContext(team=self._team,+ user=self._user,query=insight.query,name=insight.name,description=insight.description,diff --git a/ee/hogai/context/dashboard/context.py b/ee/hogai/context/dashboard/context.pyindex 3c070b2305ba..45e8194f6215 100644--- a/ee/hogai/context/dashboard/context.py+++ b/ee/hogai/context/dashboard/context.py@@ -5,7 +5,7 @@ from typing import Genericfrom pydantic import BaseModelfrom posthog.exceptions_capture import capture_exception-from posthog.models import Team+from posthog.models import Team, Userfrom ee.hogai.context.insight.context import InsightContextfrom ee.hogai.utils.helpers import build_dashboard_url@@ -40,6 +40,8 @@ class DashboardContext:self,team: Team,insights_data: Sequence[DashboardInsightContext],+ *,+ user: User,name: str | None = None,description: str | None = None,dashboard_id: str | None = None,@@ -52,6 +54,7 @@ class DashboardContext:Args:team: Team instanceinsights_data: List of DashboardInsightContext models containing insight query and metadata+ user: User to execute insight queries asname: Dashboard namedescription: Dashboard descriptiondashboard_id: Dashboard ID@@ -59,6 +62,7 @@ class DashboardContext:max_concurrent_queries: Max concurrent insight queries (default: 5)"""self.team = team+ self.user = userself.name = nameself.description = descriptionself.dashboard_id = dashboard_id@@ -164,6 +168,7 @@ class DashboardContext:return InsightContext(team=self.team,query=data.query,+ user=self.user,name=data.name,description=data.description,insight_id=data.short_id,diff --git a/ee/hogai/context/dashboard/test/test_context.py b/ee/hogai/context/dashboard/test/test_context.pyindex 34cdae6d0999..bdfc8038ca6f 100644--- a/ee/hogai/context/dashboard/test/test_context.py+++ b/ee/hogai/context/dashboard/test/test_context.py@@ -14,6 +14,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=[],+ user=self.user,name="Empty Dashboard",description="A dashboard with no insights",dashboard_id="123",@@ -42,6 +43,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Test Dashboard",description="Dashboard description",dashboard_id="456",@@ -77,6 +79,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Multi-Insight Dashboard",dashboard_id="789",)@@ -113,6 +116,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Partially Failed Dashboard",dashboard_id="101",)@@ -130,6 +134,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=[],+ user=self.user,name="Schema Dashboard",description="Dashboard for schema test",dashboard_id="202",@@ -160,6 +165,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Schema Dashboard",dashboard_id="303",)@@ -192,6 +198,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Error Dashboard",dashboard_id="404",)@@ -206,6 +213,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=[],+ user=self.user,name="No ID Dashboard",)@@ -220,6 +228,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=[],+ user=self.user,dashboard_id="606",)@@ -233,6 +242,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=[],+ user=self.user,name="URL Test Dashboard",dashboard_id="12345",)@@ -256,6 +266,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="URL Test Dashboard",dashboard_id="67890",)@@ -281,6 +292,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Concurrent Dashboard",dashboard_id="707",max_concurrent_queries=5,@@ -310,6 +322,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Custom Template Dashboard",dashboard_id="808",)@@ -344,6 +357,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Mixed Dashboard",dashboard_id="789",)@@ -377,6 +391,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Cancelled Dashboard",dashboard_id="790",)@@ -409,6 +424,7 @@ class TestDashboardContext(BaseTest):dashboard_ctx = DashboardContext(team=self.team,insights_data=insights_data,+ user=self.user,name="Mixed Dashboard",dashboard_id="791",)diff --git a/ee/hogai/context/error_tracking/context.py b/ee/hogai/context/error_tracking/context.pyindex efef6d2ec0ca..3969cbd7b645 100644--- a/ee/hogai/context/error_tracking/context.py+++ b/ee/hogai/context/error_tracking/context.py@@ -5,7 +5,7 @@ from uuid import UUIDfrom posthog.schema import DateRange, ErrorTrackingOrderBy, ErrorTrackingQueryfrom posthog.hogql_queries.query_runner import get_query_runner-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.sync import database_sync_to_asyncfrom products.error_tracking.backend.facade import (@@ -28,10 +28,12 @@ class ErrorTrackingIssueContext:def __init__(self,team: Team,+ user: User,issue_id: str,issue_name: str | None = None,):self._team = team+ self._user = userself._issue_id = issue_idself._issue_name = issue_name@@ -88,7 +90,7 @@ class ErrorTrackingIssueContext:withLastEvent=False,)- runner = get_query_runner(query, self._team)+ runner = get_query_runner(query, self._team, user=self._user)result = runner.calculate()if result.results and len(result.results) > 0:diff --git a/ee/hogai/context/error_tracking/test/test_context.py b/ee/hogai/context/error_tracking/test/test_context.pyindex 40e5aa6f1ee3..2f3c911e97bc 100644--- a/ee/hogai/context/error_tracking/test/test_context.py+++ b/ee/hogai/context/error_tracking/test/test_context.py@@ -105,6 +105,7 @@ class TestErrorTrackingIssueContext(ClickhouseTestMixin, APIBaseTest):def _create_context(self, issue_id: str, issue_name: str | None = None) -> ErrorTrackingIssueContext:return ErrorTrackingIssueContext(team=self.team,+ user=self.user,issue_id=issue_id,issue_name=issue_name,)diff --git a/ee/hogai/context/insight/context.py b/ee/hogai/context/insight/context.pyindex dbd048252ee1..3257f7ac1776 100644--- a/ee/hogai/context/insight/context.py+++ b/ee/hogai/context/insight/context.py@@ -29,6 +29,8 @@ class InsightContext:self,team: Team,query: AnyPydanticModelQuery | AnyAssistantGeneratedQuery,+ *,+ user: User,name: str | None = None,description: str | None = None,insight_id: str | None = None,@@ -38,7 +40,6 @@ class InsightContext:dashboard_filters: dict | None = None,filters_override: dict | None = None,variables_override: dict | None = None,- user: User | None = None,):self.team = teamself.user = userdiff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex bcce3f489545..77f7f062d88a 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -150,7 +150,7 @@ class AssistantQueryExecutor:WAIT_TIME_S = 0.5- def __init__(self, team: Team, utc_now_datetime: datetime, user: Optional["User"] = None):+ def __init__(self, team: Team, utc_now_datetime: datetime, user: "User"):self._team = teamself._utc_now_datetime = utc_now_datetimeself._user = user@@ -620,10 +620,11 @@ def get_example_prompt(query: AnyPydanticModelQuery | AnyAssistantGeneratedQueryasync def execute_and_format_query(team: Team,query_model: AnyPydanticModelQuery | AnyAssistantGeneratedQuery,+ *,+ user: "User",execution_mode: Optional[ExecutionMode] = None,insight_id: Optional[int] = None,truncate_results: bool = True,- user: Optional["User"] = None,include_prompt_framing: bool = True,) -> str:"""diff --git a/ee/hogai/context/insight/test/test_context.py b/ee/hogai/context/insight/test/test_context.pyindex 3437d53cf8da..abdbf66e5462 100644--- a/ee/hogai/context/insight/test/test_context.py+++ b/ee/hogai/context/insight/test/test_context.py@@ -17,6 +17,7 @@ class TestInsightContext(BaseTest):context = InsightContext(team=self.team,query=query,+ user=self.user,name="Test Insight",description="Test Description",insight_id="test_id",@@ -38,7 +39,7 @@ class TestInsightContext(BaseTest):def test_initialization_with_minimal_parameters(self):query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query)+ context = InsightContext(team=self.team, query=query, user=self.user)self.assertEqual(context.team, self.team)self.assertEqual(context.query, query)@@ -52,7 +53,7 @@ class TestInsightContext(BaseTest):async def test_get_effective_query_no_filters(self):query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query)+ context = InsightContext(team=self.team, query=query, user=self.user)effective_query = await context._get_effective_query()@@ -72,6 +73,7 @@ class TestInsightContext(BaseTest):context = InsightContext(team=self.team,query=query,+ user=self.user,dashboard_filters=dashboard_filters,filters_override=filters_override,variables_override=variables_override,@@ -88,6 +90,7 @@ class TestInsightContext(BaseTest):context = InsightContext(team=self.team,query=query,+ user=self.user,name="Test Insight",description="Test Description",insight_id="test_id",@@ -107,7 +110,7 @@ class TestInsightContext(BaseTest):mock_execute.return_value = "Test Results"query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query)+ context = InsightContext(team=self.team, query=query, user=self.user)result = await context.execute_and_format()@@ -120,7 +123,7 @@ class TestInsightContext(BaseTest):custom_template = "Custom: {{{insight_name}}} - {{{results}}}"query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query, name="My Insight")+ context = InsightContext(team=self.team, query=query, user=self.user, name="My Insight")result = await context.execute_and_format(prompt_template=custom_template)@@ -133,7 +136,7 @@ class TestInsightContext(BaseTest):mock_execute.side_effect = Exception("Query failed")query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query)+ context = InsightContext(team=self.team, query=query, user=self.user)with self.assertRaises(MaxToolRetryableError) as exc:await context.execute_and_format()@@ -145,7 +148,7 @@ class TestInsightContext(BaseTest):mock_execute.side_effect = Exception("Query failed")query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query, name="Test Insight")+ context = InsightContext(team=self.team, query=query, user=self.user, name="Test Insight")result = await context.execute_and_format(return_exceptions=True)@@ -155,7 +158,12 @@ class TestInsightContext(BaseTest):async def test_format_schema_basic(self):query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])context = InsightContext(- team=self.team, query=query, name="Test Insight", description="Test Description", insight_id="test_id"+ team=self.team,+ query=query,+ user=self.user,+ name="Test Insight",+ description="Test Description",+ insight_id="test_id",)result = await context.format_schema()@@ -169,7 +177,7 @@ class TestInsightContext(BaseTest):async def test_format_schema_with_custom_template(self):custom_template = "Schema: {{{query_schema}}}"query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query)+ context = InsightContext(team=self.team, query=query, user=self.user)result = await context.format_schema(prompt_template=custom_template)@@ -178,7 +186,7 @@ class TestInsightContext(BaseTest):async def test_format_schema_without_optional_fields(self):query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query)+ context = InsightContext(team=self.team, query=query, user=self.user)result = await context.format_schema()@@ -190,7 +198,7 @@ class TestInsightContext(BaseTest):mock_execute.return_value = "Test Results"query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query, dashboard_filters={"date_from": "-7d"})+ context = InsightContext(team=self.team, query=query, user=self.user, dashboard_filters={"date_from": "-7d"})await context.execute_and_format()@@ -206,6 +214,7 @@ class TestInsightContext(BaseTest):context = InsightContext(team=self.team,query=query,+ user=self.user,insight_model_id=456,)@@ -217,7 +226,7 @@ class TestInsightContext(BaseTest):async def test_format_schema_applies_dashboard_filters(self):query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query, dashboard_filters={"date_from": "-7d"})+ context = InsightContext(team=self.team, query=query, user=self.user, dashboard_filters={"date_from": "-7d"})result = await context.format_schema()@@ -238,6 +247,7 @@ class TestInsightContext(BaseTest):context = InsightContext(team=self.team,query=query,+ user=self.user,dashboard_filters=dashboard_filters,filters_override=filters_override,variables_override=variables_override,@@ -249,13 +259,13 @@ class TestInsightContext(BaseTest):def test_insight_url_is_none_when_no_short_id(self):query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query)+ context = InsightContext(team=self.team, query=query, user=self.user)self.assertIsNone(context.insight_url)def test_insight_url_generated_from_short_id(self):query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- context = InsightContext(team=self.team, query=query, insight_short_id="abc123")+ context = InsightContext(team=self.team, query=query, user=self.user, insight_short_id="abc123")self.assertEqual(context.insight_url, f"/project/{self.team.id}/insights/abc123")@@ -267,6 +277,7 @@ class TestInsightContext(BaseTest):context = InsightContext(team=self.team,query=query,+ user=self.user,name="Test Insight",insight_id="display-id",insight_short_id="xyz789",@@ -284,6 +295,7 @@ class TestInsightContext(BaseTest):context = InsightContext(team=self.team,query=query,+ user=self.user,name="Test Insight",)diff --git a/ee/hogai/context/insight/test/test_query_executor.py b/ee/hogai/context/insight/test/test_query_executor.pyindex 0e083df21116..0a5100c73e52 100644--- a/ee/hogai/context/insight/test/test_query_executor.py+++ b/ee/hogai/context/insight/test/test_query_executor.py@@ -65,7 +65,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):def setUp(self):super().setUp()with freeze_time("2025-01-20T12:00:00Z"):- self.query_runner = AssistantQueryExecutor(self.team, datetime.now())+ self.query_runner = AssistantQueryExecutor(self.team, datetime.now(), user=self.user)@patch("ee.hogai.context.insight.query_executor.process_query_dict")async def test_run_and_format_query_trends(self, mock_process_query):@@ -779,7 +779,7 @@ class TestAssistantQueryExecutorAsync(NonAtomicBaseTest):def setUp(self):super().setUp()with freeze_time("2025-01-20T12:00:00Z"):- self.query_runner = AssistantQueryExecutor(self.team, datetime.now())+ self.query_runner = AssistantQueryExecutor(self.team, datetime.now(), user=self.user)async def test_runs_in_async_context(self):"""Test successful execution and formatting of funnels query"""@@ -805,7 +805,7 @@ class TestExecuteAndFormatQuery(NonAtomicBaseTest):def setUp(self):super().setUp()with freeze_time("2025-01-20T12:00:00Z"):- self.query_runner = AssistantQueryExecutor(self.team, datetime.now())+ self.query_runner = AssistantQueryExecutor(self.team, datetime.now(), user=self.user)@patch("ee.hogai.context.insight.query_executor.process_query_dict")async def test_includes_insight_schema_for_trends_query(self, mock_process_query):@@ -815,7 +815,7 @@ class TestExecuteAndFormatQuery(NonAtomicBaseTest):}query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- result = await execute_and_format_query(self.team, query)+ result = await execute_and_format_query(self.team, query, user=self.user)# Verify schema section is presentself.assertIn("```json", result)@@ -828,7 +828,7 @@ class TestExecuteAndFormatQuery(NonAtomicBaseTest):mock_process_query.return_value = {"results": [{"data": [1], "label": "test", "days": ["2025-01-01"]}]}query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")])- result = await execute_and_format_query(self.team, query)+ result = await execute_and_format_query(self.team, query, user=self.user)self.assertIn("kind", result)self.assertNotIn("breakdownFilter", result)@@ -840,7 +840,7 @@ class TestExecuteAndFormatQuery(NonAtomicBaseTest):# Create query with dateRange (which might have None values for date_from/date_to if not set)query = AssistantTrendsQuery(series=[AssistantTrendsEventsNode(name="$pageview")], breakdownFilter=None)- result = await execute_and_format_query(self.team, query)+ result = await execute_and_format_query(self.team, query, user=self.user)# The schema should not contain null valuesself.assertNotIn("null", result)@@ -853,7 +853,7 @@ class TestExecuteAndFormatQuery(NonAtomicBaseTest):# Create query with dateRange (which might have None values for date_from/date_to if not set)query = AssistantHogQLQuery(query="SELECT 1")- result = await execute_and_format_query(self.team, query)+ result = await execute_and_format_query(self.team, query, user=self.user)# The schema should not be presentself.assertNotIn("SELECT 1", result)diff --git a/ee/hogai/context/survey/context.py b/ee/hogai/context/survey/context.pyindex 03206bed46a2..f78311d9d08f 100644--- a/ee/hogai/context/survey/context.py+++ b/ee/hogai/context/survey/context.py@@ -1,7 +1,7 @@from posthog.schema import HogQLQueryfrom posthog.hogql_queries.query_runner import get_query_runner-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.sync import database_sync_to_asyncfrom products.surveys.backend.models import Survey@@ -20,10 +20,12 @@ class SurveyContext:def __init__(self,team: Team,+ user: User,survey_id: str,survey_name: str | None = None,):self._team = team+ self._user = userself._survey_id = survey_idself._survey_name = survey_name@@ -47,7 +49,7 @@ class SurveyContext:AND properties.$survey_id = '{self._survey_id}'""")- runner = get_query_runner(query, self._team)+ runner = get_query_runner(query, self._team, user=self._user)result = runner.calculate()if result.results and len(result.results) > 0:return result.results[0][0]diff --git a/ee/hogai/context/survey/test/test_context.py b/ee/hogai/context/survey/test/test_context.pyindex 4c2819686a8c..e6e397d78ea9 100644--- a/ee/hogai/context/survey/test/test_context.py+++ b/ee/hogai/context/survey/test/test_context.py@@ -37,7 +37,7 @@ class TestSurveyContext(BaseTest):)def test_format_questions_rating(self):- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))formatted = context.format_questions(self.survey)assert "How likely are you to recommend us?" in formatted@@ -47,7 +47,7 @@ class TestSurveyContext(BaseTest):assert "Optional: No" in formatteddef test_format_questions_open(self):- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))formatted = context.format_questions(self.survey)assert "What could we improve?" in formatted@@ -58,19 +58,19 @@ class TestSurveyContext(BaseTest):self.survey.questions = []self.survey.save()- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))formatted = context.format_questions(self.survey)assert formatted == "No questions defined."def test_format_targeting_url(self):- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))formatted = context.format_targeting(self.survey)assert "URL targeting: /pricing" in formatteddef test_format_targeting_wait_period(self):- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))formatted = context.format_targeting(self.survey)assert "Wait period: 30 seconds" in formatted@@ -79,13 +79,13 @@ class TestSurveyContext(BaseTest):self.survey.conditions = {}self.survey.save()- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))formatted = context.format_targeting(self.survey)assert formatted == "No specific targeting configured (shows to all users)."def test_get_status_draft(self):- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))status = context._get_status(self.survey)assert status == "draft"@@ -95,7 +95,7 @@ class TestSurveyContext(BaseTest):self.survey.start_date = timezone.now()self.survey.save()- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))status = context._get_status(self.survey)assert status == "active"@@ -106,7 +106,7 @@ class TestSurveyContext(BaseTest):self.survey.end_date = timezone.now()self.survey.save()- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))status = context._get_status(self.survey)assert status == "completed"@@ -114,13 +114,13 @@ class TestSurveyContext(BaseTest):self.survey.archived = Trueself.survey.save()- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))status = context._get_status(self.survey)assert status == "archived"@pytest.mark.asyncioasync def test_aget_survey(self):- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))survey = await context.aget_survey()assert survey is not None@@ -128,7 +128,7 @@ class TestSurveyContext(BaseTest):@pytest.mark.asyncioasync def test_aget_survey_not_found(self):- context = SurveyContext(team=self.team, survey_id="00000000-0000-0000-0000-000000000000")+ context = SurveyContext(team=self.team, user=self.user, survey_id="00000000-0000-0000-0000-000000000000")survey = await context.aget_survey()assert survey is None@@ -138,7 +138,7 @@ class TestSurveyContext(BaseTest):with patch.object(SurveyContext, "aget_response_count", new_callable=AsyncMock) as mock_count:mock_count.return_value = 42- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))result = await context.execute_and_format(self.survey)assert "Test NPS Survey" in result@@ -174,7 +174,7 @@ class TestSurveyContextChoiceQuestions(BaseTest):)def test_format_questions_single_choice(self):- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))formatted = context.format_questions(self.survey)assert "What feature do you use most?" in formatted@@ -182,7 +182,7 @@ class TestSurveyContextChoiceQuestions(BaseTest):assert "Choices: Dashboard, Insights, Session Replay" in formatteddef test_format_questions_multiple_choice(self):- context = SurveyContext(team=self.team, survey_id=str(self.survey.id))+ context = SurveyContext(team=self.team, user=self.user, survey_id=str(self.survey.id))formatted = context.format_questions(self.survey)assert "Which products interest you?" in formatteddiff --git a/ee/hogai/llm_traces_summaries/summarize_traces.py b/ee/hogai/llm_traces_summaries/summarize_traces.pyindex 6121a114938d..80c8fed7095c 100644--- a/ee/hogai/llm_traces_summaries/summarize_traces.py+++ b/ee/hogai/llm_traces_summaries/summarize_traces.py@@ -3,6 +3,7 @@ import structlogfrom posthog.schema import DateRangefrom posthog.models.team.team import Team+from posthog.models.user import Userfrom posthog.sync import database_sync_to_asyncfrom products.ai_observability.backend.models.llm_traces_summaries import LLMTraceSummary@@ -18,8 +19,9 @@ logger = structlog.get_logger(__name__)class LLMTracesSummarizer:- def __init__(self, team: Team):+ def __init__(self, team: Team, user: User | None = None):self._team = team+ self._user = userasync def summarize_traces_for_date_range(self, date_range: DateRange) -> None:"""Get, stringify, summarize, embed and store summaries for all traces in the date range."""@@ -30,7 +32,7 @@ class LLMTracesSummarizer:return Noneasync def _collect_and_stringify_traces_for_date_range(self, date_range: DateRange) -> dict[str, str]:- collector = LLMTracesSummarizerCollector(team=self._team)+ collector = LLMTracesSummarizerCollector(team=self._team, user=self._user)# Collect and stringify traces in-memorystringifier = LLMTracesSummarizerStringifier(team=self._team)stringified_traces: dict[str, str] = {} # trace_id -> stringified trace@@ -91,7 +93,7 @@ class LLMTracesSummarizer:summary_type: LLMTraceSummary.LLMTraceSummaryType,):"""Search all summarized traces withi the date range for the query and return the top similar traces."""- finder = LLMTracesSummarizerFinder(team=self._team)+ finder = LLMTracesSummarizerFinder(team=self._team, user=self._user)return finder.find_top_similar_traces_for_query(query=query,request_id=request_id,diff --git a/ee/hogai/llm_traces_summaries/tools/find_similar_traces.py b/ee/hogai/llm_traces_summaries/tools/find_similar_traces.pyindex 2ac2a7477513..0e0c30d4bde6 100644--- a/ee/hogai/llm_traces_summaries/tools/find_similar_traces.py+++ b/ee/hogai/llm_traces_summaries/tools/find_similar_traces.py@@ -15,6 +15,7 @@ from posthog.schema import (from posthog.event_usage import EventSourcefrom posthog.hogql_queries.document_embeddings_query_runner import DocumentEmbeddingsQueryRunnerfrom posthog.models.team.team import Team+from posthog.models.user import Userfrom products.ai_observability.backend.models.llm_traces_summaries import LLMTraceSummary@@ -30,9 +31,13 @@ logger = structlog.get_logger(__name__)class LLMTracesSummarizerFinder:def __init__(- self, team: Team, embedding_model_name: EmbeddingModelName = EmbeddingModelName.TEXT_EMBEDDING_3_LARGE_3072+ self,+ team: Team,+ user: User | None = None,+ embedding_model_name: EmbeddingModelName = EmbeddingModelName.TEXT_EMBEDDING_3_LARGE_3072,):self._team = team+ self._user = userself._embedding_model_name = embedding_model_namedef find_top_similar_traces_for_query(@@ -67,7 +72,7 @@ class LLMTracesSummarizerFinder:timestamp=embedding_timestamp,),)- runner = DocumentEmbeddingsQueryRunner(query=similarity_query, team=self._team)+ runner = DocumentEmbeddingsQueryRunner(query=similarity_query, team=self._team, user=self._user)response = runner.run(analytics_props={"source": EventSource.POSTHOG_AI})if not isinstance(response, CachedDocumentSimilarityQueryResponse):raise ValueError(diff --git a/ee/hogai/llm_traces_summaries/tools/get_traces.py b/ee/hogai/llm_traces_summaries/tools/get_traces.pyindex 6058b3cf0b77..f7aba4fb2a12 100644--- a/ee/hogai/llm_traces_summaries/tools/get_traces.py+++ b/ee/hogai/llm_traces_summaries/tools/get_traces.py@@ -3,17 +3,19 @@ from posthog.schema import CachedTracesQueryResponse, DateRange, HogQLPropertyFifrom posthog.event_usage import EventSourcefrom posthog.hogql_queries.ai.traces_query_runner import TracesQueryRunnerfrom posthog.models.team.team import Team+from posthog.models.user import Userclass LLMTracesSummarizerCollector:- def __init__(self, team: Team):+ def __init__(self, team: Team, user: User | None = None):self._team = team+ self._user = user# Should be large enough to go fast, and small enough to avoid any memory issuesself._traces_per_page = 100def get_db_traces_per_page(self, offset: int, date_range: DateRange) -> CachedTracesQueryResponse:query = self._get_traces_query(offset=offset, date_range=date_range, limit=self._traces_per_page)- runner = TracesQueryRunner(query=query, team=self._team)+ runner = TracesQueryRunner(query=query, team=self._team, user=self._user)response = runner.run(analytics_props={"source": EventSource.POSTHOG_AI})if not isinstance(response, CachedTracesQueryResponse):raise ValueError(f"Failed to get result for the previous day when summarizing LLM traces: {response}")@@ -22,7 +24,7 @@ class LLMTracesSummarizerCollector:def get_db_trace_ids(self, date_range: DateRange, limit: int) -> list[str]:"""Get all the trace ids (but ids only) within the date range."""query = self._get_traces_query(offset=0, date_range=date_range, limit=limit)- runner = TracesQueryRunner(query=query, team=self._team)+ runner = TracesQueryRunner(query=query, team=self._team, user=self._user)# Expecting to get all trace ids in a single query, as it should be lightweight-ishtrace_ids, _, _ = runner._get_trace_ids()return trace_idsdiff --git a/ee/hogai/tools/manage_memories.py b/ee/hogai/tools/manage_memories.pyindex ccbf7328b840..9e0194295278 100644--- a/ee/hogai/tools/manage_memories.py+++ b/ee/hogai/tools/manage_memories.py@@ -191,6 +191,7 @@ class ManageMemoriesTool(MaxTool):query_type="ManageMemoriesTool",query=query,team=self._team,+ user=self._user,placeholders={"query_text": ast.Constant(value=query_text),"model_name": ast.Constant(value=EMBEDDING_MODEL),diff --git a/ee/hogai/tools/read_data/test/test_tool.py b/ee/hogai/tools/read_data/test/test_tool.pyindex 27ce74c4b7f2..2131bf1609aa 100644--- a/ee/hogai/tools/read_data/test/test_tool.py+++ b/ee/hogai/tools/read_data/test/test_tool.py@@ -1699,14 +1699,13 @@ class TestReadDataTool(BaseTest):team=self.team, name="Allowed Survey", questions=[{"type": "open", "question": "Test?"}])- user = MagicMock()state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))context_manager = MagicMock()context_manager.check_user_has_billing_access = AsyncMock(return_value=False)context_manager.check_has_audit_logs_access = AsyncMock(return_value=False)tool = await ReadDataTool.create_tool_class(- team=self.team, user=user, state=state, context_manager=context_manager+ team=self.team, user=self.user, state=state, context_manager=context_manager)with patch.object(tool, "user_access_control") as mock_uac:diff --git a/ee/hogai/tools/read_data/tool.py b/ee/hogai/tools/read_data/tool.pyindex 23c9f4665514..6e8bb44357e6 100644--- a/ee/hogai/tools/read_data/tool.py+++ b/ee/hogai/tools/read_data/tool.py@@ -755,6 +755,7 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):dashboard_ctx = DashboardContext(team=self._team,insights_data=insights_data,+ user=self._user,name=dashboard_name,description=dashboard.description,dashboard_id=dashboard_id,@@ -770,6 +771,7 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):async def _read_error_tracking_issue(self, issue_id: str) -> str:context = ErrorTrackingIssueContext(team=self._team,+ user=self._user,issue_id=issue_id,)return await context.execute_and_format()@@ -777,6 +779,7 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):async def _read_survey(self, survey_id: str) -> str:context = SurveyContext(team=self._team,+ user=self._user,survey_id=survey_id,)survey = await context.aget_survey()@@ -795,6 +798,7 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):case VisualizationArtifactContent():context = InsightContext(team=self._team,+ user=self._user,query=content.query,name=content.name,description=content.description,@@ -921,7 +925,7 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):trace_query = TraceQuery(traceId=trace_id)utc_now = timezone.now().astimezone(UTC)- executor = AssistantQueryExecutor(self._team, utc_now)+ executor = AssistantQueryExecutor(self._team, utc_now, user=self._user)query_results = await executor.aexecute_query(trace_query)results = query_results.get("results", [])diff --git a/ee/hogai/tools/read_taxonomy/core.py b/ee/hogai/tools/read_taxonomy/core.pyindex e9605ccd7320..f20a039277ef 100644--- a/ee/hogai/tools/read_taxonomy/core.py+++ b/ee/hogai/tools/read_taxonomy/core.py@@ -2,7 +2,7 @@ from typing import Literal, Unionfrom pydantic import BaseModel, Field-from posthog.models import Team+from posthog.models import Team, Userfrom ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkitfrom ee.hogai.utils.helpers import format_events_yaml@@ -94,7 +94,7 @@ If the user's question involves feature flags, construct the property name using""".strip()-def execute_taxonomy_query(query: ReadTaxonomyQuery, toolkit: TaxonomyAgentToolkit, team: Team) -> str:+def execute_taxonomy_query(query: ReadTaxonomyQuery, toolkit: TaxonomyAgentToolkit, team: Team, user: User) -> str:"""Execute a taxonomy query and return the result.@@ -102,7 +102,7 @@ def execute_taxonomy_query(query: ReadTaxonomyQuery, toolkit: TaxonomyAgentToolk"""match query:case ReadEvents():- return format_events_yaml([], team, limit=query.limit, offset=query.offset)+ return format_events_yaml([], team, user, limit=query.limit, offset=query.offset)case ReadEventProperties():result = toolkit.retrieve_event_or_action_properties(query.event_name)return f"{result}\n\n{DYNAMIC_EVENT_PROPERTIES_HINT}"diff --git a/ee/hogai/tools/read_taxonomy/mcp_tool.py b/ee/hogai/tools/read_taxonomy/mcp_tool.pyindex 30f28b37d23a..51fe3fde4776 100644--- a/ee/hogai/tools/read_taxonomy/mcp_tool.py+++ b/ee/hogai/tools/read_taxonomy/mcp_tool.py@@ -25,7 +25,7 @@ class ReadTaxonomyMCPTool(MCPTool[ReadTaxonomyToolArgs]):@database_sync_to_async(thread_sensitive=False)def _execute_query():- return execute_taxonomy_query(args.query, toolkit, self._team)+ return execute_taxonomy_query(args.query, toolkit, self._team, self._user)return await _execute_query()except ValueError as e:diff --git a/ee/hogai/tools/read_taxonomy/test/test_tool.py b/ee/hogai/tools/read_taxonomy/test/test_tool.pyindex 36e371b1c7d9..4dd39cea29fc 100644--- a/ee/hogai/tools/read_taxonomy/test/test_tool.py+++ b/ee/hogai/tools/read_taxonomy/test/test_tool.py@@ -106,17 +106,17 @@ class TestReadTaxonomyTool(NonAtomicBaseTest):def test_execute_taxonomy_query_read_events(self, mock_format_events, mock_toolkit_class):mock_format_events.return_value = "events:\n - $pageview\n - $autocapture"- result = execute_taxonomy_query(ReadEvents(), mock_toolkit_class.return_value, self.team)+ result = execute_taxonomy_query(ReadEvents(), mock_toolkit_class.return_value, self.team, self.user)self.assertIn("events:", result)- mock_format_events.assert_called_once_with([], self.team, limit=500, offset=0)+ mock_format_events.assert_called_once_with([], self.team, self.user, limit=500, offset=0)@patch("ee.hogai.tools.read_taxonomy.core.TaxonomyAgentToolkit")def test_person_entity_properties_include_dynamic_hint(self, mock_toolkit_class):mock_toolkit = mock_toolkit_class.return_valuemock_toolkit.retrieve_entity_properties.return_value = "- email\n- name"- result = execute_taxonomy_query(ReadEntityProperties(entity="person"), mock_toolkit, self.team)+ result = execute_taxonomy_query(ReadEntityProperties(entity="person"), mock_toolkit, self.team, self.user)self.assertIn(DYNAMIC_PERSON_PROPERTIES_HINT, result)self.assertIn("$survey_dismissed", result)@@ -128,7 +128,7 @@ class TestReadTaxonomyTool(NonAtomicBaseTest):mock_toolkit = mock_toolkit_class.return_valuemock_toolkit.retrieve_entity_properties.return_value = "- $start_timestamp"- result = execute_taxonomy_query(ReadEntityProperties(entity="session"), mock_toolkit, self.team)+ result = execute_taxonomy_query(ReadEntityProperties(entity="session"), mock_toolkit, self.team, self.user)self.assertNotIn(DYNAMIC_PERSON_PROPERTIES_HINT, result)@@ -137,7 +137,7 @@ class TestReadTaxonomyTool(NonAtomicBaseTest):mock_toolkit = mock_toolkit_class.return_valuemock_toolkit.retrieve_event_or_action_properties.return_value = "- $browser\n- $os"- result = execute_taxonomy_query(ReadEventProperties(event_name="$pageview"), mock_toolkit, self.team)+ result = execute_taxonomy_query(ReadEventProperties(event_name="$pageview"), mock_toolkit, self.team, self.user)self.assertIn(DYNAMIC_EVENT_PROPERTIES_HINT, result)self.assertIn("$feature/{flag_key}", result)diff --git a/ee/hogai/tools/read_taxonomy/tool.py b/ee/hogai/tools/read_taxonomy/tool.pyindex e0bce40750a3..89a11b01d082 100644--- a/ee/hogai/tools/read_taxonomy/tool.py+++ b/ee/hogai/tools/read_taxonomy/tool.py@@ -92,7 +92,7 @@ class ReadTaxonomyTool(MaxTool):toolkit = TaxonomyAgentToolkit(self._team, self._user)try:- res = execute_taxonomy_query(validated_query, toolkit, self._team)+ res = execute_taxonomy_query(validated_query, toolkit, self._team, self._user)except ValueError as e:raise MaxToolRetryableError(str(e))diff --git a/ee/hogai/tools/replay/filter_session_recordings.py b/ee/hogai/tools/replay/filter_session_recordings.pyindex df22e8d02da5..071c10e0d9b1 100644--- a/ee/hogai/tools/replay/filter_session_recordings.py+++ b/ee/hogai/tools/replay/filter_session_recordings.py@@ -197,7 +197,7 @@ class FilterSessionRecordingsTool(MaxTool):org_id=self._team.organization_id,):query_runner = SessionRecordingListFromQuery(- team=self._team, query=recordings_query, hogql_query_modifiers=None+ team=self._team, query=recordings_query, hogql_query_modifiers=None, user=self._user)return query_runner.run()diff --git a/ee/hogai/tools/replay/summarize_sessions.py b/ee/hogai/tools/replay/summarize_sessions.pyindex d71540a49446..52351c7ca919 100644--- a/ee/hogai/tools/replay/summarize_sessions.py+++ b/ee/hogai/tools/replay/summarize_sessions.py@@ -263,7 +263,7 @@ class SummarizeSessionsTool(MaxTool):org_id=self._team.organization_id,):query_runner = SessionRecordingListFromQuery(- team=self._team, query=replay_filters, hogql_query_modifiers=None+ team=self._team, query=replay_filters, hogql_query_modifiers=None, user=self._user)results = query_runner.run()except Exception as e:diff --git a/ee/hogai/tools/search_traces.py b/ee/hogai/tools/search_traces.pyindex 910184177f86..3aff71e33c9c 100644--- a/ee/hogai/tools/search_traces.py+++ b/ee/hogai/tools/search_traces.py@@ -108,7 +108,7 @@ class SearchLLMTracesTool(MaxTool):query.offset = current_offsetutc_now = timezone.now().astimezone(UTC)- executor = AssistantQueryExecutor(self._team, utc_now)+ executor = AssistantQueryExecutor(self._team, utc_now, user=self._user)query_results = await executor.aexecute_query(query)raw_results = cast(list[dict], query_results.get("results", []))diff --git a/ee/hogai/tools/upsert_dashboard/tool.py b/ee/hogai/tools/upsert_dashboard/tool.pyindex 24b4a3de96f5..189549f63252 100644--- a/ee/hogai/tools/upsert_dashboard/tool.py+++ b/ee/hogai/tools/upsert_dashboard/tool.py@@ -567,6 +567,7 @@ class UpsertDashboardTool(MaxTool):context = DashboardContext(team=self._team,insights_data=insights_data,+ user=self._user,name=dashboard.name,description=dashboard.description,dashboard_id=str(dashboard.id),diff --git a/ee/hogai/utils/helpers.py b/ee/hogai/utils/helpers.pyindex f62cb76e013a..1368f68f05be 100644--- a/ee/hogai/utils/helpers.py+++ b/ee/hogai/utils/helpers.py@@ -40,7 +40,7 @@ from posthog.schema import (from posthog.event_usage import EventSourcefrom posthog.hogql_queries.ai.team_taxonomy_query_runner import TeamTaxonomyQueryRunnerfrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUPfrom ee.hogai.utils.anthropic import SUPPORTED_ANTHROPIC_BLOCKS@@ -173,12 +173,13 @@ def convert_tool_messages_to_dict(messages: Sequence[AssistantMessageUnion]) ->def _process_events_data(events_in_context: list[MaxEventContext],team: Team,+ user: User,limit: int | None = None,offset: int | None = None,) -> tuple[list[dict], dict[str, str], bool]:"""Common logic for processing events and building event data."""query = TeamTaxonomyQuery(limit=limit, offset=offset)- response = TeamTaxonomyQueryRunner(query, team).run(+ response = TeamTaxonomyQueryRunner(query, team, user=user).run(ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,analytics_props={"source": EventSource.POSTHOG_AI},)@@ -232,8 +233,8 @@ def _process_events_data(return processed_events, event_to_description, has_more-def format_events_xml(events_in_context: list[MaxEventContext], team: Team) -> str:- processed_events, _, _ = _process_events_data(events_in_context, team)+def format_events_xml(events_in_context: list[MaxEventContext], team: Team, user: User) -> str:+ processed_events, _, _ = _process_events_data(events_in_context, team, user)root = ET.Element("defined_events")for event_data in processed_events:@@ -250,10 +251,11 @@ def format_events_xml(events_in_context: list[MaxEventContext], team: Team) -> sdef format_events_yaml(events_in_context: list[MaxEventContext],team: Team,+ user: User,limit: int | None = None,offset: int | None = None,) -> str:- processed_events, _, has_more = _process_events_data(events_in_context, team, limit=limit, offset=offset)+ processed_events, _, has_more = _process_events_data(events_in_context, team, user, limit=limit, offset=offset)formatted_events = ["events:"]for event_data in processed_events:diff --git a/ee/hogai/utils/test/test_format_events_prompt.py b/ee/hogai/utils/test/test_format_events_prompt.pyindex 9bcd4ee86f40..55e610720625 100644--- a/ee/hogai/utils/test/test_format_events_prompt.py+++ b/ee/hogai/utils/test/test_format_events_prompt.py@@ -123,7 +123,7 @@ class TestFormatEventsPrompt(BaseTest):])- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)# Verify the XML structureroot = ET.fromstring(result)@@ -151,7 +151,7 @@ class TestFormatEventsPrompt(BaseTest):self._setup_mock_runner(mock_runner_class, taxonomy_items)events_in_context: list[MaxEventContext] = []- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)event_names = self._get_event_names_from_xml(result)@@ -169,7 +169,7 @@ class TestFormatEventsPrompt(BaseTest):self._setup_mock_runner(mock_runner_class, taxonomy_items)events_in_context: list[MaxEventContext] = []- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)event_names = self._get_event_names_from_xml(result)@@ -193,7 +193,7 @@ class TestFormatEventsPrompt(BaseTest):])- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)event_names = self._get_event_names_from_xml(result)@@ -216,7 +216,7 @@ class TestFormatEventsPrompt(BaseTest):])- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)description = self._get_event_description(result, "custom_event")self.assertEqual(description, "Custom event description")@@ -232,7 +232,7 @@ class TestFormatEventsPrompt(BaseTest):])- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)description = self._get_event_description(result, "test_event")self.assertEqual(description, "Line 1 Line 2 Line 3")@@ -248,7 +248,7 @@ class TestFormatEventsPrompt(BaseTest):self._setup_mock_runner(mock_runner_class, taxonomy_items)events_in_context: list[MaxEventContext] = []- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)event_names = self._get_event_names_from_xml(result)self.assertEqual(set(event_names), {"All events", "$pageview"})@@ -264,7 +264,7 @@ class TestFormatEventsPrompt(BaseTest):])- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)root = ET.fromstring(result)test_event = root.find(".//event[name='test_event']")@@ -285,7 +285,7 @@ class TestFormatEventsPrompt(BaseTest):])- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)root = ET.fromstring(result)test_event = root.find(".//event[name='test_event']")@@ -310,7 +310,7 @@ class TestFormatEventsPrompt(BaseTest):])- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)event_names = self._get_event_names_from_xml(result)@@ -327,7 +327,7 @@ class TestFormatEventsPrompt(BaseTest):events_in_context: list[MaxEventContext] = []with self.assertRaises(ValueError, msg="Failed to generate events prompt."):- format_events_xml(events_in_context, self.team)+ format_events_xml(events_in_context, self.team, self.user)@patch("ee.hogai.utils.helpers.TeamTaxonomyQueryRunner")def test_format_events_xml_uses_label_llm_when_available(self, mock_runner_class):@@ -340,7 +340,7 @@ class TestFormatEventsPrompt(BaseTest):self._setup_mock_runner(mock_runner_class, taxonomy_items)events_in_context: list[MaxEventContext] = []- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)description = self._get_event_description(result, "$pageview")@@ -360,7 +360,7 @@ class TestFormatEventsPrompt(BaseTest):MaxEventContext(id="2", name="", description="Empty name event", type="event"),]- result = format_events_xml(events_in_context, self.team)+ result = format_events_xml(events_in_context, self.team, self.user)event_names = self._get_event_names_from_xml(result)@@ -373,10 +373,10 @@ class TestFormatEventsPrompt(BaseTest):self._setup_mock_runner(mock_runner_class, [])events_in_context: list[MaxEventContext] = []- format_events_xml(events_in_context, self.team)+ format_events_xml(events_in_context, self.team, self.user)# Verify TeamTaxonomyQueryRunner was called correctly- mock_runner_class.assert_called_once_with(TeamTaxonomyQuery(), self.team)+ mock_runner_class.assert_called_once_with(TeamTaxonomyQuery(), self.team, user=self.user)mock_runner_class.return_value.run.assert_called_once_with(ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,analytics_props=ANY,diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.pyindex 8b953082c3d2..2b08f8aeed57 100644--- a/posthog/session_recordings/queries/session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py@@ -21,7 +21,7 @@ from posthog.hogql.property import property_to_exprfrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.insights.paginators import HogQLCursorPaginator, HogQLHasMorePaginator-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.session_recordings.queries.sub_queries.base_query import SessionRecordingsListingBaseQueryfrom posthog.session_recordings.queries.sub_queries.cohort_subquery import CohortPropertyGroupsSubQueryfrom posthog.session_recordings.queries.sub_queries.events_subquery import ReplayFiltersEventsSubQuery@@ -127,8 +127,10 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):extra_having_predicates: list[ast.Expr] | None = None,session_ids_to_exclude: list[str] | None = None,bypass_date_window_for_session_ids: bool = False,+ user: User | None = None,**_,):+ self._user = userself._bypass_date_window_for_session_ids = bypass_date_window_for_session_ids# TRICKY: we need to make sure we init test account filters only once,# otherwise we'll end up with a lot of duplicated test account filters in the query@@ -203,6 +205,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):# TODO I guess the paginator needs to know how to handle union queries or all callers are supposed to collapse them or .... 🤷query=cast(ast.SelectQuery, query),team=self._team,+ user=self._user,query_type="SessionRecordingListQuery",modifiers=self._hogql_query_modifiers,settings=HogQLGlobalSettings(diff --git a/products/error_tracking/backend/logic/tools/search_issues.py b/products/error_tracking/backend/logic/tools/search_issues.pyindex dfc77e034320..136d529a83c5 100644--- a/products/error_tracking/backend/logic/tools/search_issues.py+++ b/products/error_tracking/backend/logic/tools/search_issues.py@@ -215,7 +215,7 @@ class SearchErrorTrackingIssuesTool(MaxTool):try:utc_now = timezone.now().astimezone(UTC)- executor = AssistantQueryExecutor(self._team, utc_now)+ executor = AssistantQueryExecutor(self._team, utc_now, user=self._user)query_results = await executor.aexecute_query(query)except MaxToolRetryableError:raisediff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex ed04cee19c7b..43c24c38916d 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -601,7 +601,7 @@ class SearchReplayVisionObservationsTool(MaxTool):LIMIT {{limit}}"""tag_queries(product=Product.REPLAY_VISION, feature=Feature.SEMANTIC_SEARCH)- result = execute_hogql_query(query=hogql_query, team=self._team, placeholders=placeholders)+ result = execute_hogql_query(query=hogql_query, team=self._team, user=self._user, placeholders=placeholders)return [row[0] for row in (result.results or [])]def _read_output(self, obs: ReplayObservation) -> dict[str, Any] | None:diff --git a/products/web_analytics/backend/max_tools.py b/products/web_analytics/backend/max_tools.pyindex ad2d73c86791..50dd8d93ea89 100644--- a/products/web_analytics/backend/max_tools.py+++ b/products/web_analytics/backend/max_tools.py@@ -132,6 +132,7 @@ class WebAnalyticsFilterOptionsToolkit(TaxonomyAgentToolkit):runner = PropertyValuesQueryRunner(team=self._team,query=PropertyValuesQuery(property_type=PropertyType.EVENT, property_key=property_name),+ user=self._user,)response = runner.run(ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)return [item.name for item in getattr(response, "results", []) or []]@@ -451,6 +452,7 @@ class AssessHeatmapTool(MaxTool):) -> tuple[str, dict[str, Any]]:data = await database_sync_to_async(_gather_heatmap_data)(self._team,+ self._user,page_url=page_url,date_from=date_from,date_to=date_to,@@ -489,6 +491,7 @@ _TOP_ELEMENTS = 15def _gather_heatmap_data(team: Team,+ user: User,*,page_url: str,date_from: str,@@ -529,12 +532,12 @@ def _gather_heatmap_data("date_to": resolved_to.isoformat(),"viewport_width_min": viewport_width_min,"viewport_width_max": viewport_width_max,- "clicks": _coordinate_points(team, click_exprs),- "fold": _fold_summary(team, click_exprs),- "rageclicks": _coordinate_points(team, rage_exprs),- "scrolldepth": _scroll_buckets(team, scroll_exprs),+ "clicks": _coordinate_points(team, user, click_exprs),+ "fold": _fold_summary(team, user, click_exprs),+ "rageclicks": _coordinate_points(team, user, rage_exprs),+ "scrolldepth": _scroll_buckets(team, user, scroll_exprs),"elements": _autocapture_elements(- team, page_url, resolved_from, resolved_to, viewport_width_min, viewport_width_max+ team, user, page_url, resolved_from, resolved_to, viewport_width_min, viewport_width_max),}@@ -576,13 +579,15 @@ def _heatmap_predicates(return validated, exprs-def _execute(team: Team, stmt: ast.SelectQuery | ast.SelectSetQuery) -> Any:+def _execute(team: Team, user: User, stmt: ast.SelectQuery | ast.SelectSetQuery) -> Any:context = HogQLContext(team_id=team.pk, limit_top_select=False)with tags_context(product=Product.MAX_AI, team_id=team.pk, org_id=team.organization_id):- return execute_hogql_query(query=stmt, team=team, limit_context=LimitContext.HEATMAPS, context=context)+ return execute_hogql_query(+ query=stmt, team=team, user=user, limit_context=LimitContext.HEATMAPS, context=context+ )-def _coordinate_points(team: Team, exprs: list[ast.Expr]) -> list[dict[str, Any]]:+def _coordinate_points(team: Team, user: User, exprs: list[ast.Expr]) -> list[dict[str, Any]]:stmt = parse_select(DEFAULT_QUERY,{@@ -592,7 +597,7 @@ def _coordinate_points(team: Team, exprs: list[ast.Expr]) -> list[dict[str, Any]"offset": ast.Constant(value=0),},)- result = _execute(team, stmt)+ result = _execute(team, user, stmt)return [{"pointer_target_fixed": bool(item[0]),@@ -604,19 +609,19 @@ def _coordinate_points(team: Team, exprs: list[ast.Expr]) -> list[dict[str, Any]]-def _fold_summary(team: Team, exprs: list[ast.Expr]) -> dict[str, Any]:+def _fold_summary(team: Team, user: User, exprs: list[ast.Expr]) -> dict[str, Any]:stmt = parse_select(FOLD_SUMMARY_QUERY, {"predicates": ast.And(exprs=exprs)})- result = _execute(team, stmt)+ result = _execute(team, user, stmt)row = result.results[0] if result.results else Nonereturn parse_fold_summary_row(row)-def _scroll_buckets(team: Team, exprs: list[ast.Expr]) -> list[dict[str, Any]]:+def _scroll_buckets(team: Team, user: User, exprs: list[ast.Expr]) -> list[dict[str, Any]]:stmt = parse_select(SCROLL_DEPTH_QUERY,{"aggregation_count": parse_expr("count(*)"), "predicates": ast.And(exprs=exprs)},)- result = _execute(team, stmt)+ result = _execute(team, user, stmt)return [{"scroll_depth_bucket": int(item[0]), "bucket_count": int(item[1]), "cumulative_count": int(item[2])}for item in result.results or []@@ -625,6 +630,7 @@ def _scroll_buckets(team: Team, exprs: list[ast.Expr]) -> list[dict[str, Any]]:def _autocapture_elements(team: Team,+ user: User,page_url: str,date_from: date,date_to: date,@@ -653,7 +659,7 @@ def _autocapture_elements("viewport_filter": viewport_filter,},)- result = _execute(team, stmt)+ result = _execute(team, user, stmt)return [{"text": item[0], "elements_chain": item[1], "clicks": int(item[2])} for item in result.results or []]