: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(warehouse): pass access context to warehouse queries (#66536)
Alex Lider49d867d980e4
diff --git a/posthog/tasks/warehouse.py b/posthog/tasks/warehouse.pyindex c103b5e00702..ecaac835f5f3 100644--- a/posthog/tasks/warehouse.py+++ b/posthog/tasks/warehouse.py@@ -18,7 +18,8 @@ def validate_data_warehouse_table_columns(team_id: int, table_id: str) -> None:table = DataWarehouseTable.objects.get(team_id=team_id, id=table_id)columns = table.columns or {}for column in columns.keys():- columns[column]["valid"] = table.validate_column_type(column)+ # Background validation is userless; validate table schema, not requester permissions.+ columns[column]["valid"] = table.validate_column_type(column, bypass_warehouse_access_control=True)table.columns = columnstable.save()diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.pyindex 2d68066f2b0a..346c97a58092 100644--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py@@ -135,7 +135,7 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):)tag_queries(product=Product.WAREHOUSE, feature=Feature.QUERY)- result = execute_hogql_query(query, team=self.team)+ result = execute_hogql_query(query, team=self.team, user=request.user)values = [row[0] for row in result.results]span.set_attribute("result_count", len(values))diff --git a/products/data_warehouse/backend/presentation/views/table.py b/products/data_warehouse/backend/presentation/views/table.pyindex b9cef012804b..c2e529e56965 100644--- a/products/data_warehouse/backend/presentation/views/table.py+++ b/products/data_warehouse/backend/presentation/views/table.py@@ -374,8 +374,9 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mtable.save()# Have to update the `valid` value separately to the `columns` value as the columns are required in the `ast.S3Table` class when querying ClickHouse+ user = cast(User, request.user)for key in updates.keys():- columns[key]["valid"] = table.validate_column_type(key)+ columns[key]["valid"] = table.validate_column_type(key, user=user)table.columns = columnstable.save()diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.pyindex c79f04d1308e..c0fa391cee9c 100644--- a/products/marketing_analytics/backend/api.py+++ b/products/marketing_analytics/backend/api.py@@ -1,4 +1,5 @@from dataclasses import asdict+from typing import castimport structlogfrom asgiref.sync import async_to_sync@@ -19,6 +20,7 @@ from posthog.api.documentation import _FallbackSerializerfrom posthog.api.mixins import validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.models.team.team import DEFAULT_CURRENCY+from posthog.models.user import Userfrom products.marketing_analytics.backend.hogql_queries.adapters.base import ExternalConfig, QueryContextfrom products.marketing_analytics.backend.hogql_queries.adapters.factory import MarketingSourceFactory@@ -489,7 +491,9 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):date_to = request.validated_query_data["date_to"]try:- audit_response = run_utm_audit(self.team, date_from=date_from, date_to=date_to)+ audit_response = run_utm_audit(+ self.team, date_from=date_from, date_to=date_to, user=cast(User, request.user)+ )response_data = UtmAuditResponseSerializer(asdict(audit_response)).datareturn Response(response_data)except Exception:@@ -512,7 +516,7 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):@action(methods=["GET"], detail=False, url_path="conversion_goals", required_scopes=["marketing_analytics:read"])def conversion_goals(self, request: Request, *args, **kwargs) -> Response:try:- response = async_to_sync(list_conversion_goals)(self.team)+ response = async_to_sync(list_conversion_goals)(self.team, user=cast(User, request.user))return Response(ConversionGoalsListResponseSerializer(response.to_dict()).data)except Exception:logger.exception("list_conversion_goals_failed", team_id=self.team.pk)@@ -654,6 +658,7 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):source_type=source_type,include_conversion_goals=include_conversion_goals,attribution_lookback_days=attribution_lookback_days,+ user=cast(User, request.user),)return Response(MarketingDiagnosticResponseSerializer(response.to_dict()).data)except Exception:@@ -710,7 +715,7 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):query.limit = ast.Constant(value=10)- result = execute_hogql_query(query, self.team)+ result = execute_hogql_query(query, self.team, user=cast(User, request.user))return Response({diff --git a/products/marketing_analytics/backend/services/conversion_goals_inspector.py b/products/marketing_analytics/backend/services/conversion_goals_inspector.pyindex bbdac6c8804d..e230994ee2ed 100644--- a/products/marketing_analytics/backend/services/conversion_goals_inspector.py+++ b/products/marketing_analytics/backend/services/conversion_goals_inspector.py@@ -26,6 +26,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.team.team import Team+from posthog.models.user import Userfrom posthog.sync import database_sync_to_asyncfrom products.actions.backend.models.action import Action@@ -129,13 +130,13 @@ class GoalExplanation:return asdict(self)-async def list_conversion_goals(team: Team) -> ConversionGoalsListResponse:+async def list_conversion_goals(team: Team, *, user: User | None = None) -> ConversionGoalsListResponse:"""Return one summary entry per configured conversion goal."""goals_raw, attribution_window, attribution_mode = await _read_team_goal_config(team)alias_map = await _build_team_alias_map(team)results = await asyncio.gather(- *(_summarize_goal(team, goal, alias_map, attribution_window) for goal in goals_raw),+ *(_summarize_goal(team, goal, alias_map, attribution_window, user=user) for goal in goals_raw),return_exceptions=True,)# Degrade a failing goal to a misconfigured entry instead of failing the whole list.@@ -305,6 +306,8 @@ async def _summarize_goal(goal: dict,alias_map: dict[str, NativeIntegration],attribution_window_days: int,+ *,+ user: User | None = None,) -> ConversionGoalSummary:goal_id = str(goal.get("conversion_goal_id") or goal.get("id") or "")name = goal.get("conversion_goal_name") or goal.get("name") or goal_id@@ -326,7 +329,7 @@ async def _summarize_goal(if kind_raw == "EventsNode":target_label = goal.get("event") or "(all events)"- total, integrated, without_utm, unmatched_with_utm = await _count_event_goal(team, goal, alias_map)+ total, integrated, without_utm, unmatched_with_utm = await _count_event_goal(team, goal, alias_map, user=user)return _summary_with_split(goal_id,name,@@ -358,7 +361,9 @@ async def _summarize_goal(misconfig_reason=action_error or f"Action {goal_id} no longer exists",)target_label = f"Action: {action.name}"- total, integrated, without_utm, unmatched_with_utm = await _count_action_goal(team, action, alias_map)+ total, integrated, without_utm, unmatched_with_utm = await _count_action_goal(+ team, action, alias_map, user=user+ )return _summary_with_split(goal_id,name,@@ -375,7 +380,7 @@ async def _summarize_goal(if kind_raw == "DataWarehouseNode":table_name = goal.get("table_name") or "(unknown table)"target_label = f"{table_name}"- last_30d_count, dw_misconfig = await _count_dw_goal(team, goal)+ last_30d_count, dw_misconfig = await _count_dw_goal(team, goal, user=user)return ConversionGoalSummary(id=goal_id,name=name,@@ -455,7 +460,7 @@ def _resolve_action(team: Team, goal_id: str) -> tuple[Action | None, str | None@database_sync_to_asyncdef _count_event_goal(- team: Team, goal: dict[str, Any], alias_map: dict[str, NativeIntegration]+ team: Team, goal: dict[str, Any], alias_map: dict[str, NativeIntegration], user: User | None = None) -> tuple[int, int, int, int]:"""For EventsNode: count last 30d events matching the goal, split by utm_source match.@@ -471,12 +476,12 @@ def _count_event_goal(if event_nameelse ast.Constant(value=True) # `goal["event"]` is None — "match any event")- return _execute_count_with_split(team, where, {"since": ast.Constant(value=since)}, alias_map)+ return _execute_count_with_split(team, where, {"since": ast.Constant(value=since)}, alias_map, user=user)@database_sync_to_asyncdef _count_action_goal(- team: Team, action: Action, alias_map: dict[str, NativeIntegration]+ team: Team, action: Action, alias_map: dict[str, NativeIntegration], user: User | None = None) -> tuple[int, int, int, int]:"""For ActionsNode: count last 30d events matching the action's full definition(`action_to_expr`, same as the dashboard), split by utm_source.@@ -487,11 +492,17 @@ def _count_action_goal(if not action.steps:return 0, 0, 0, 0since = timezone.now() - timedelta(days=DEFAULT_LOOKBACK_DAYS)- return _execute_count_with_split(team, action_to_expr(action), {"since": ast.Constant(value=since)}, alias_map)+ return _execute_count_with_split(+ team, action_to_expr(action), {"since": ast.Constant(value=since)}, alias_map, user=user+ )def _execute_count_with_split(- team: Team, where: ast.Expr, placeholders: dict[str, ast.Expr], alias_map: dict[str, NativeIntegration]+ team: Team,+ where: ast.Expr,+ placeholders: dict[str, ast.Expr],+ alias_map: dict[str, NativeIntegration],+ user: User | None = None,) -> tuple[int, int, int, int]:"""Returns (total, integrated, without_utm, unmatched_with_utm).@@ -525,7 +536,7 @@ def _execute_count_with_split("aliases": ast.Tuple(exprs=[ast.Constant(value=key) for key in alias_map]),}with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):- result = execute_hogql_query(hogql, team, placeholders=query_placeholders)+ result = execute_hogql_query(hogql, team, placeholders=query_placeholders, user=user)rows = result.results or []if not rows:return 0, 0, 0, 0@@ -534,7 +545,7 @@ def _execute_count_with_split(@database_sync_to_async-def _count_dw_goal(team: Team, goal: dict[str, Any]) -> tuple[int, str | None]:+def _count_dw_goal(team: Team, goal: dict[str, Any], user: User | None = None) -> tuple[int, str | None]:"""For DataWarehouseNode: a row count against the configured table.Returns (count, misconfig_reason). `table_name`/`timestamp_field` come from@@ -565,7 +576,7 @@ def _count_dw_goal(team: Team, goal: dict[str, Any]) -> tuple[int, str | None]:)try:with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):- result = execute_hogql_query(query, team)+ result = execute_hogql_query(query, team, user=user)except Exception as exc:logger.warning("marketing_analytics.dw_goal_query_failed",diff --git a/products/marketing_analytics/backend/services/marketing_diagnostic.py b/products/marketing_analytics/backend/services/marketing_diagnostic.pyindex 61676c2446cc..226cf5ede0f5 100644--- a/products/marketing_analytics/backend/services/marketing_diagnostic.py+++ b/products/marketing_analytics/backend/services/marketing_diagnostic.py@@ -14,6 +14,7 @@ from typing import Any, Literal, castimport structlogfrom posthog.models.team.team import Team+from posthog.models.user import Userfrom posthog.sync import database_sync_to_asyncfrom products.marketing_analytics.backend.services.attribution_health import (@@ -110,6 +111,7 @@ async def get_marketing_diagnostic(source_type: str | None = None,include_conversion_goals: bool = True,attribution_lookback_days: int = 7,+ user: User | None = None,) -> MarketingDiagnosticResponse:"""Fetch all per-domain signals in parallel and combine into a unified view.@@ -129,7 +131,7 @@ async def get_marketing_diagnostic(),]if include_conversion_goals:- coros.append(list_conversion_goals(team))+ coros.append(list_conversion_goals(team, user=user))# `return_exceptions=True` so one failing sub-service doesn't abort the whole# diagnostic. Data-source and attribution health are required to diagnose, sodiff --git a/products/marketing_analytics/backend/services/utm_audit.py b/products/marketing_analytics/backend/services/utm_audit.pyindex 7d6db6167023..245adb00faf2 100644--- a/products/marketing_analytics/backend/services/utm_audit.py+++ b/products/marketing_analytics/backend/services/utm_audit.py@@ -12,6 +12,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.team.team import DEFAULT_CURRENCY, Team+from posthog.models.user import Userfrom products.marketing_analytics.backend.hogql_queries.adapters.base import QueryContextfrom products.marketing_analytics.backend.hogql_queries.adapters.factory import MarketingSourceFactory@@ -119,7 +120,13 @@ def _build_known_sources(mappings: TeamMappings) -> set[str]:return known-def run_utm_audit(team: Team, date_from: str = "-30d", date_to: str | None = None) -> UtmAuditResponse:+def run_utm_audit(+ team: Team,+ date_from: str = "-30d",+ date_to: str | None = None,+ *,+ user: User | None = None,+) -> UtmAuditResponse:"""Run a UTM audit for all marketing integrations.@@ -137,8 +144,8 @@ def run_utm_audit(team: Team, date_from: str = "-30d", date_to: str | None = Nonmappings = _load_team_mappings(team)known_sources = _build_known_sources(mappings)- campaigns = _get_campaigns_with_spend(team, date_range)- utm_events = _get_utm_events(team, date_range)+ campaigns = _get_campaigns_with_spend(team, date_range, user=user)+ utm_events = _get_utm_events(team, date_range, user=user)results = _cross_reference(campaigns, utm_events, mappings, known_sources) if campaigns else []all_utm = _build_all_utm_events(campaigns, utm_events, mappings)@@ -155,7 +162,7 @@ def run_utm_audit(team: Team, date_from: str = "-30d", date_to: str | None = Non)-def _get_campaigns_with_spend(team: Team, date_range: QueryDateRange) -> list[Campaign]:+def _get_campaigns_with_spend(team: Team, date_range: QueryDateRange, *, user: User | None = None) -> list[Campaign]:"""Get all campaigns with spend from marketing integrations."""context = QueryContext(date_range=date_range,@@ -216,7 +223,7 @@ def _get_campaigns_with_spend(team: Team, date_range: QueryDateRange) -> list[Ca)with tags_context(product=Product.MARKETING_ANALYTICS, feature=Feature.HEALTH_CHECK, team_id=team.pk):- result = execute_hogql_query(query, team)+ result = execute_hogql_query(query, team, user=user)campaigns = []for row in result.results or []:campaigns.append(@@ -232,7 +239,7 @@ def _get_campaigns_with_spend(team: Team, date_range: QueryDateRange) -> list[Careturn campaigns-def _get_utm_events(team: Team, date_range: QueryDateRange) -> dict[tuple[str, str], int]:+def _get_utm_events(team: Team, date_range: QueryDateRange, *, user: User | None = None) -> dict[tuple[str, str], int]:"""Get distinct utm_campaign + utm_source combinations from pageview events.Returns a dict mapping (campaign, source) -> event_count.@@ -258,6 +265,7 @@ def _get_utm_events(team: Team, date_range: QueryDateRange) -> dict[tuple[str, sresult = execute_hogql_query(hogql,team,+ user=user,placeholders={"date_from": date_range.date_from_as_hogql(),"date_to": date_range.date_to_as_hogql(),diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 1d384ab18a82..630950b28a94 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -54,6 +54,8 @@ from .external_table_definitions import external_tablesif TYPE_CHECKING:from posthog.schema import HogQLQueryModifiers+ from posthog.models import User+SERIALIZED_FIELD_TO_CLICKHOUSE_MAPPING: dict[DatabaseSerializedFieldType, str] = {DatabaseSerializedFieldType.INTEGER: "Int64",DatabaseSerializedFieldType.FLOAT: "Float64",@@ -191,7 +193,13 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletprefix = ""return self.name[len(prefix) :]- def validate_column_type(self, column_key) -> bool:+ def validate_column_type(+ self,+ column_key: str,+ *,+ user: Optional["User"] = None,+ bypass_warehouse_access_control: bool = False,+ ) -> bool:from posthog.hogql.query import execute_hogql_querycolumns = self.columns or {}@@ -213,6 +221,8 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletquery,self.team,modifiers=HogQLQueryModifiers(s3TableUseInvalidColumns=True),+ user=user,+ bypass_warehouse_access_control=bypass_warehouse_access_control,)return Trueexcept: