: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
import json
import builtins
import dataclasses
from collections import defaultdict
from collections.abc import Sequence
from copy import deepcopy
from datetime import datetime, timedelta
from functools import lru_cache
from typing import Any, Union, cast
from uuid import UUID
from django.conf import settings
from django.db import transaction
from django.db.models import Count, Exists, F, Max, QuerySet
from django.db.models.query_utils import Q
from django.utils.functional import SimpleLazyObject
from django.utils.timezone import now
import structlog
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema_view
from opentelemetry import trace
from prometheus_client import Counter
from pydantic import (
BaseModel,
Field as PydanticField,
RootModel,
ValidationError as PydanticValidationError,
)
from rest_framework import request, serializers, status, viewsets
from rest_framework.exceptions import APIException, NotFound, ParseError, PermissionDenied, ValidationError
from rest_framework.parsers import JSONParser
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework.utils.urls import replace_query_param
from rest_framework_csv import renderers as csvrenderers
from posthog.schema import (
AccessControlFilterWarning,
BreakdownNotAppliedWarning,
DataWarehouseSyncWarning,
ProductKey,
QueryStatus,
)
from posthog.hogql.errors import ExposedHogQLError, ResolutionError
from posthog import schema
from posthog.api.documentation import extend_schema, extend_schema_field, extend_schema_serializer
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.monitoring import Feature, monitor
from posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param
from posthog.api.query import add_query_response_identity_headers, get_query_request_analytics_properties
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.api.sharing_publish_gate import insight_query_access_error
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import action
from posthog.auth import (
PersonalAPIKeyAuthentication,
SessionAuthentication,
SharingAccessTokenAuthentication,
SharingPasswordProtectedAuthentication,
)
from posthog.caching.insight_result import InsightResult
from posthog.clickhouse.cancel import cancel_query_on_cluster
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import AccessMethod, get_query_tag_value, tag_queries, tags_context
from posthog.constants import INSIGHT
from posthog.errors import CHQueryErrorQueryWasCancelled, ExposedCHQueryError, QueryErrorCategory, classify_query_error
from posthog.event_usage import EventSource, get_event_source, report_user_action
from posthog.exceptions import ClickHouseAtCapacity
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.helpers.trigram_search import (
DESCRIPTION_FIELD,
MAX_SEARCH_LENGTH,
NAME_FIELD,
TrigramSearchField,
apply_trigram_search,
drop_similar_when_exact_exists,
)
from posthog.hogql_queries.apply_dashboard_filters import (
WRAPPER_NODE_KINDS,
apply_dashboard_filters_to_dict,
apply_dashboard_variables_to_dict,
resolve_effective_dashboard_filters,
resolve_filter_layers_by_priority,
)
from posthog.hogql_queries.query_runner import ExecutionMode, enforce_api_queries_budget
from posthog.hogql_queries.refresh_policy import ComputeSurface, resolve_execution_mode
from posthog.hogql_queries.utils.result_series import get_response_action_names
from posthog.kafka_client.topics import KAFKA_METRICS_TIME_TO_SEE_DATA
from posthog.models import User
from posthog.models.activity_logging.activity_log import (
Change,
Detail,
LogActivityEntry,
bulk_log_activity,
changes_between,
describe_change,
load_activity,
log_activity,
)
from posthog.models.activity_logging.activity_page import (
ActivityLogPaginatedResponseSerializer,
activity_page_response,
parse_activity_page_params,
)
from posthog.models.file_system.file_system import delete_files
from posthog.models.organization import Organization
from posthog.models.tagged_item import TaggedItem
from posthog.models.team.team import Team
from posthog.permissions import (
TeamMemberStrictManagementPermission,
get_authenticator_scoped_team_ids,
get_authenticator_scopes,
)
from posthog.query_cache import QueryCache
from posthog.query_scan.serve import hydrate_scan_summary
from posthog.rate_limit import (
AIObservabilitySummarizationBurstThrottle,
AIObservabilitySummarizationDailyThrottle,
AIObservabilitySummarizationSustainedThrottle,
ClickHouseBurstRateThrottle,
ClickHouseSustainedRateThrottle,
)
from posthog.renderers import SafeJSONRenderer
from posthog.schema_migrations.upgrade import upgrade
from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.scopes import scopes_not_covered
from posthog.settings import CAPTURE_TIME_TO_SEE_DATA
from posthog.shared_link_user import SharedLinkUser
from posthog.user_permissions import UserPermissionsSerializerMixin
from posthog.utils import (
filters_override_requested_by_client,
generate_cache_key_prefix,
refresh_requested_by_client,
relative_date_parse,
str_to_bool,
tile_filters_override_requested_by_client,
variables_override_requested_by_client,
)
from products.access_control.backend.facade.user_access_control import (
UserAccessControl,
access_level_satisfied_for_resource,
)
from products.access_control.backend.presentation.access_control import (
AccessControlViewSetMixin,
UserAccessControlSerializerMixin,
)
from products.alerts.backend.facade.api import delete_insight_alerts
from products.alerts.backend.presentation.views.insight_alerts import insight_alerts_prefetch, serialize_insight_alerts
from products.dashboards.backend.facade.access import (
DashboardAccessMethod,
dashboard_access_method,
record_dashboard_cache_outcome,
)
from products.dashboards.backend.facade.api import (
CannotAddToDashboard,
CannotRemoveFromDashboard,
DashboardNotFound,
DashboardTileBasicSerializer,
InsightTilePlacement,
check_insight_tile_limit,
dashboard_refs,
hide_tiles_for_insights,
insight_has_listed_tile,
insight_ids_on_dashboard,
insights_with_dashboard_edit_access,
plan_insight_tile_placement,
restore_tiles_for_insights,
tile_for_insight_on_dashboard,
tile_for_render,
tile_ids_prefetch,
tile_permissions_prefetch,
unknown_dashboard_ids,
update_insight_dashboard_membership,
)
from products.product_analytics.backend.facade.account_filters import plan_test_account_filter_update
from products.product_analytics.backend.facade.api import (
insight_variables_for_team,
lock_insight_for_evaluation,
map_stale_to_latest,
recent_viewers_by_insight,
recently_viewed_insights,
record_insight_view,
record_insight_views,
with_last_viewed_at,
)
from products.product_analytics.backend.facade.contracts import TeamEmailAccess
from products.product_analytics.backend.facade.data_checks import run_insight_data_checks
from products.product_analytics.backend.facade.enums import (
InsightDataCheckAction,
InsightDataCheckKey,
InsightDataCheckLevel,
InsightDataCheckMethod,
InsightDataChecksDepth,
InsightDataCheckSkipReason,
InsightDataChecksStatus,
)
from products.product_analytics.backend.facade.models import Insight, resolve_insight_by_id_or_short_id
from products.product_analytics.backend.presentation.insight_metadata import (
InsightMetadataTimeoutError,
generate_insight_metadata,
)
from products.product_analytics.backend.presentation.insight_permissions import CanEditInsightDashboards
from products.product_analytics.backend.presentation.insight_write_validation import validate_insight_write
from products.product_analytics.backend.presentation.query_concurrency import query_concurrency_slots
from products.subscriptions.backend.facade.api import delete_insight_subscriptions
from common.hogvm.python.utils import HogVMException
logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
EXPORT_QUERY_CACHE_MISS = Counter(
"export_query_cache_miss",
"Cache misses during PNG export rendering when expected cache key was not found",
)
def get_insight_type(insight: Insight) -> str:
"""Return a normalized lowercase insight type string for analytics (used by the dashboard tile event)."""
if insight.query:
source = insight.query.get("source", insight.query)
kind = source.get("kind", "") if isinstance(source, dict) else ""
return kind.replace("Query", "").lower() if kind else "json"
return str(insight.filters.get("insight", "TRENDS")).lower()
def log_and_report_insight_activity(
*,
activity: str,
insight: Insight,
insight_id: int,
insight_short_id: str,
organization_id: UUID,
team_id: int,
user: User,
was_impersonated: bool,
request: Request | None = None,
changes: list[Change] | None = None,
) -> None:
"""
Insight id and short_id are passed separately as some activities (like delete) alter the Insight instance
The experiments feature creates insights without a name, this does not log those
"""
insight_name: str | None = insight.name if insight.name else insight.derived_name
if insight_name:
log_activity(
organization_id=organization_id,
team_id=team_id,
user=user,
was_impersonated=was_impersonated,
item_id=insight_id,
scope="Insight",
activity=activity,
detail=Detail(name=insight_name, changes=changes, short_id=insight_short_id),
)
organization = Organization.objects.get(id=organization_id)
team = Team.objects.get(id=team_id)
if not was_impersonated:
report_user_action(
user,
f"insight {activity}",
{
"insight_id": insight_short_id,
**insight.get_analytics_query_kinds(),
**insight.get_analytics_query_metadata(),
},
team=team,
organization=organization,
request=request,
)
def viewable_insight_or_404(*, team_id: int, insight_id: int, user_access_control: UserAccessControl) -> Insight:
"""The live insight of this team with this ID, for an endpoint of another product that acts on it.
Raises NotFound when the team has no such insight, and PermissionDenied when access rules hide it.
"""
insight = Insight.objects.filter(team_id=team_id, pk=insight_id).first()
if insight is None:
raise NotFound()
# The request's access control answers only for the team in the URL, and the insight can belong to a
# sibling environment of the project, whose own rules decide.
insight_access = user_access_control.for_team_ids([insight.team_id])[insight.team_id]
if not insight_access.check_access_level_for_object(insight, "viewer"):
raise PermissionDenied("You don't have permission to view this insight.")
return insight
class QuerySchemaParser(JSONParser):
"""
A query schema parser that only parses the query field and validates it against the schema if it is present
If there is no query field this parser is a no-op
"""
def parse(self, stream, media_type=None, parser_context=None):
data = super().parse(stream, media_type, parser_context)
try:
query = data.get("query", None)
if query:
schema.QuerySchemaRoot.model_validate(query)
except Exception as error:
raise ParseError(detail=str(error))
else:
return data
class DashboardIdsField(serializers.ListField):
"""The dashboard ids an insight sits on.
Written as a plain id list, read back off the prefetched tiles rather than the `dashboards`
m2m, so serializing a page of insights costs no extra query per insight.
"""
child = serializers.IntegerField()
def get_attribute(self, instance: Insight) -> list[int]:
return [tile.dashboard_id for tile in instance.dashboard_tiles.all()]
def to_representation(self, data: Sequence[Any]) -> list[Any]:
return list(data)
INCLUDE_DASHBOARDS_PARAM = "include_dashboards"
DEPRECATED_DASHBOARDS_FIELD_USED_COUNTER = Counter(
"posthog_api_insight_deprecated_dashboards_field_used_total",
"Times the deprecated insight `dashboards` field was served in an insight payload (usage=read) "
"or accepted as write input on a permitted create/update (usage=write, including no-op writes), "
"by authentication method. Rejected requests are not counted.",
labelnames=["usage", "access_method"],
)
# Access methods that still need the deprecated field without opting in. Shared/exporter views
# have their own frontend lifecycle, and unresolved auth is not a caller we can migrate safely.
_DEPRECATED_DASHBOARDS_FIELD_EXEMPT_ACCESS_METHODS = frozenset({"no_authenticator", "sharing_token"})
def _dashboards_field_access_method(request: Request | None) -> str:
authenticator = getattr(request, "successful_authenticator", None)
# An unresolved authenticator (no DRF auth ran) is treated as session below: it's not a
# token caller we're trying to migrate off the field, so keep serving it.
if authenticator is None:
return "no_authenticator"
if isinstance(authenticator, SessionAuthentication):
return "session"
if isinstance(authenticator, SharingAccessTokenAuthentication | SharingPasswordProtectedAuthentication):
return "sharing_token"
if isinstance(authenticator, PersonalAPIKeyAuthentication):
return "personal_api_key"
return type(authenticator).__name__
def _is_internal_serialization_context(context: dict) -> bool:
# Internal serialization (exports, subscriptions, my_last_viewed) has no requesting client to
# migrate, so it's exempt from both the opt-in gate and the deprecation-usage counter.
return context.get("request") is None
def should_serve_deprecated_dashboards_field(context: dict) -> bool:
"""
The insight `dashboards` field is deprecated in favor of `dashboard_tiles`. Removal is
two-phase: while INSIGHT_DASHBOARDS_OPT_IN_ENFORCED is off, every caller still receives the
field and reads are metered by access method so remaining usage can drain; once enforced,
token callers must opt in with `?include_dashboards=true`. Session-authenticated requests
already require the opt-in because the web app has migrated to `dashboard_tiles`.
"""
if _is_internal_serialization_context(context):
return True
request = context["request"]
query_params = getattr(request, "query_params", None)
if query_params is not None and str_to_bool(query_params.get(INCLUDE_DASHBOARDS_PARAM, "0")):
return True
access_method = _dashboards_field_access_method(request)
if access_method == "session":
return False
if access_method in _DEPRECATED_DASHBOARDS_FIELD_EXEMPT_ACCESS_METHODS:
return True
return not settings.INSIGHT_DASHBOARDS_OPT_IN_ENFORCED
def _record_deprecated_dashboards_field_used(context: dict, usage: str) -> None:
if _is_internal_serialization_context(context):
return
DEPRECATED_DASHBOARDS_FIELD_USED_COUNTER.labels(
usage=usage, access_method=_dashboards_field_access_method(context["request"])
).inc()
@extend_schema_serializer(exclude_fields=["saved"], deprecate_fields=["dashboards"])
class InsightBasicSerializer(
SearchMatchTypeSerializerMixin,
TaggedItemSerializerMixin,
UserPermissionsSerializerMixin,
serializers.ModelSerializer,
UserAccessControlSerializerMixin,
):
"""
Simplified serializer to speed response times when loading large amounts of objects.
"""
dashboard_tiles = DashboardTileBasicSerializer(many=True, read_only=True)
dashboards = serializers.SerializerMethodField(read_only=True)
created_by = UserBasicSerializer(read_only=True)
last_viewed_at = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Insight
fields = [
"id",
"short_id",
"name",
"derived_name",
"query",
"dashboards",
"dashboard_tiles",
"description",
"last_refresh",
"refreshing",
"saved",
"tags",
"updated_at",
"created_by",
"created_at",
"last_modified_at",
"favorited",
"user_access_level",
"last_viewed_at",
"search_match_type",
]
read_only_fields = ("short_id", "updated_at", "last_refresh", "refreshing")
def create(self, validated_data: dict, *args: Any, **kwargs: Any) -> Any:
raise NotImplementedError()
@extend_schema_field(serializers.ListField(child=serializers.IntegerField()))
def get_dashboards(self, instance: Insight) -> list[int]:
# `to_representation` below always recomputes this field when serving it, so this only
# backs schema generation and any other caller of the method field directly. Excludes
# soft-deleted tiles to match that recomputation — filtered in Python, not with
# .exclude(), since a chained queryset bypasses the dashboard_tiles prefetch cache and
# reintroduces a per-insight query.
return [tile.dashboard_id for tile in instance.dashboard_tiles.all() if not tile.deleted]
@extend_schema_field(serializers.DateTimeField(allow_null=True))
def get_last_viewed_at(self, instance: Insight):
"""Get the last viewed timestamp for this insight by any user in the team."""
return getattr(instance, "last_viewed_at", None)
def to_representation(self, instance):
representation = super().to_representation(instance)
if should_serve_deprecated_dashboards_field(self.context):
_record_deprecated_dashboards_field_used(self.context, usage="read")
# Exclude soft-deleted tiles, matching the write-echo correction and the frontend's
# dashboard_tiles-based derivation.
representation["dashboards"] = [
tile["dashboard_id"] for tile in representation["dashboard_tiles"] if not tile.get("deleted")
]
else:
representation.pop("dashboards", None)
# upgrade the query to the latest version
representation["query"] = upgrade(instance.query)
return representation
@lru_cache(maxsize=1) # noqa: B019 - short-lived serializer
def _dashboard_tiles(self, instance):
return [tile.dashboard_id for tile in instance.dashboard_tiles.all()]
class TrendingInsightSerializer(InsightBasicSerializer):
"""Insight enriched with view-count and recent-viewer fields, used by the trending action."""
view_count = serializers.IntegerField(
read_only=True,
help_text=(
"Number of distinct viewers in the time window. Higher values indicate insights that more people "
"in the project actively look at, which is a strong proxy for which insights matter."
),
)
viewers = UserBasicSerializer(
many=True,
read_only=True,
help_text="Up to 3 of the most recent users who viewed this insight in the time window.",
)
# Surfaced here (not on InsightBasicSerializer) so agents ranking trending insights can see
# who is currently iterating on each — useful context alongside the view-count signal.
last_modified_by = UserBasicSerializer(
read_only=True,
help_text="User who last modified this insight, or null if never modified after creation.",
)
class Meta(InsightBasicSerializer.Meta):
fields = [*InsightBasicSerializer.Meta.fields, "view_count", "viewers", "last_modified_by"]
class _InsightQuerySchema(RootModel):
"""The query definition for this insight. The `kind` field determines the query type:
- `InsightVizNode` — product analytics (trends, funnels, retention, paths, stickiness, lifecycle)
- `DataVisualizationNode` — SQL insights using HogQL
- `BIVisualizationNode` — business intelligence worksheets with a HogQL source
- `DataTableNode` — raw data tables
- `HogQuery` — Hog language queries
"""
root: (
schema.InsightVizNode
| schema.DataTableNode
| schema.DataVisualizationNode
| schema.BIVisualizationNode
| schema.HogQuery
) = PydanticField(discriminator="kind")
_METRICS_QUERY_KINDS = frozenset({"MetricsQuery", "MetricsHistogramQuery"})
METRICS_VARIABLE_VALUES_MESSAGE = (
"A saved metrics insight can't store variable values. Keep the $name references in the query, "
"and set the values with a dashboard variable or on the alert."
)
def _reject_metrics_variable_values(query: Any) -> None:
if isinstance(query, dict) and query.get("kind") in _METRICS_QUERY_KINDS and query.get("variables"):
raise ValidationError({"query": [METRICS_VARIABLE_VALUES_MESSAGE]})
@extend_schema_field(_InsightQuerySchema) # type: ignore[arg-type]
class QueryFieldSerializer(serializers.Serializer):
def to_representation(self, value):
return self.parent._query_variables_mapping(value) # type: ignore
def to_internal_value(self, data):
if data is not None and not isinstance(data, dict):
raise serializers.ValidationError("Query must be a valid JSON object")
return data
# Bare query sources that only render inside an InsightVizNode. The UI (Query.tsx) routes
# wrapper nodes and a few standalone kinds (e.g. WebOverviewQuery) to real renderers; the
# kinds below have no bare renderer and fall through to a JSON-dump fallback that paints
# ~0px inside a dashboard tile, so they are safe (and necessary) to auto-wrap on save.
#
# Keep this exhaustive over the InsightVizNode source union; BARE_RENDERED_INSIGHT_VIZ_SOURCE_KINDS
# holds the exceptions. A test pins both sets against that union, so a new source kind fails
# loudly — but it can't see Query.tsx, so a renderer added or dropped there still needs a human.
AUTO_WRAPPED_INSIGHT_QUERY_KINDS = frozenset(
{
"TrendsQuery",
"FunnelsQuery",
"RetentionQuery",
"PathsQuery",
"PathsV2Query",
"StickinessQuery",
"LifecycleQuery",
"WebStatsTableQuery",
}
)
# InsightVizNode sources the UI also renders unwrapped, so saving them bare is legitimate.
BARE_RENDERED_INSIGHT_VIZ_SOURCE_KINDS = frozenset({"WebOverviewQuery"})
class InsightFilterOverrideContext(BaseModel):
dashboard: schema.DashboardFilter | None = PydanticField(
default=None, description="Dashboard filters that remain active after applying tile precedence."
)
tile: schema.TileFilters | None = PydanticField(
default=None, description="Tile filters applied above the dashboard filters."
)
overridden_dashboard: schema.DashboardFilter | None = PydanticField(
default=None, description="Dashboard filters replaced by the tile filters."
)
class _InsightResultWarnings(RootModel):
"""Warnings attached to the query response that produced an insight's results."""
root: list[DataWarehouseSyncWarning | AccessControlFilterWarning | BreakdownNotAppliedWarning]
RESOLVED_DATE_RANGE_SCHEMA = {
"type": "object",
"nullable": True,
"properties": {
"date_from": {"type": "string", "format": "date-time"},
"date_to": {"type": "string", "format": "date-time"},
},
}
@extend_schema_serializer(deprecate_fields=["dashboards"])
class InsightSerializer(InsightBasicSerializer):
result = serializers.SerializerMethodField()
hasMore = serializers.SerializerMethodField()
columns = serializers.SerializerMethodField()
last_refresh = serializers.SerializerMethodField(
read_only=True,
help_text="""
The datetime this insight's results were generated.
If added to one or more dashboards the insight can be refreshed separately on each.
Returns the appropriate last_refresh datetime for the context the insight is viewed in
(see from_dashboard query parameter).
""",
)
cache_target_age = serializers.SerializerMethodField(
read_only=True,
help_text="The target age of the cached results for this insight.",
)
next_allowed_client_refresh = serializers.SerializerMethodField(
read_only=True,
help_text="""
The earliest possible datetime at which we'll allow the cached results for this insight to be refreshed
by querying the database.
""",
)
is_cached = serializers.SerializerMethodField(read_only=True)
created_by = UserBasicSerializer(read_only=True)
last_modified_by = UserBasicSerializer(read_only=True)
timezone = serializers.SerializerMethodField(help_text="The timezone this chart is displayed in.")
last_viewed_at = serializers.SerializerMethodField(read_only=True)
dashboards = DashboardIdsField( # type: ignore[assignment]
help_text="""
DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.
A dashboard ID for each of the dashboards that this insight is displayed on.
This field is omitted from session-authenticated responses unless `include_dashboards=true`
is passed. Once opt-in enforcement is enabled, API-token callers (personal API keys, OAuth)
must opt in the same way. Do not rely on it being present.
""",
required=False,
)
dashboard_tiles = DashboardTileBasicSerializer(
many=True,
read_only=True,
help_text="""
A dashboard tile ID and dashboard_id for each of the dashboards that this insight is displayed on.
""",
)
query = QueryFieldSerializer(required=False, allow_null=True)
query_status = serializers.SerializerMethodField()
hogql = serializers.SerializerMethodField()
types = serializers.SerializerMethodField()
action_names = serializers.SerializerMethodField(
read_only=True,
help_text="The name of each action the insight's series reference, keyed by action id. A series saved without "
"a name displays this name.",
)
query_scan = serializers.SerializerMethodField(
read_only=True,
help_text="What ClickHouse read for this insight's last slow run, with the findings of its query scan.",
)
warnings = serializers.SerializerMethodField(
read_only=True,
allow_null=True,
help_text=(
"Warnings from the run that produced these results. A `warehouse_sync` warning means the query"
" read a data warehouse table whose sync failed, is paused, or is overdue, so the results can be"
" out of date. Reflects the sync state when the results were computed. Null for shared insights."
),
)
_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)
alerts = serializers.SerializerMethodField(read_only=True)
filter_override_context = serializers.SerializerMethodField(
read_only=True,
allow_null=True,
help_text="Resolved dashboard and tile filter layers used to explain filter precedence in the UI.",
)
class Meta:
model = Insight
fields = [
"id",
"short_id",
"name",
"derived_name",
"query",
"order",
"deleted",
"dashboards",
"dashboard_tiles",
"last_refresh",
"cache_target_age",
"next_allowed_client_refresh",
"result",
"hasMore",
"columns",
"created_at",
"created_by",
"description",
"updated_at",
"tags",
"favorited",
"saved",
"last_modified_at",
"last_modified_by",
"is_sample",
"user_access_level",
"timezone",
"is_cached",
"query_status",
"hogql",
"types",
"resolved_date_range",
"resolved_compare_date_range",
"action_names",
"query_scan",
"warnings",
"_create_in_folder",
"alerts",
"filter_override_context",
"last_viewed_at",
"search_match_type",
]
read_only_fields = (
"created_at",
"created_by",
"last_modified_at",
"last_modified_by",
"short_id",
"updated_at",
"is_sample",
"user_access_level",
"timezone",
"refreshing",
"is_cached",
)
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
query = attrs.get("query") if "query" in attrs else None
_reject_metrics_variable_values(query)
# `filters` is read-only, so DRF drops it before validation. The raw payload is the only
# place a legacy write still shows up, and it has to be answered rather than ignored.
sent_filters = self.initial_data.get("filters")
using_legacy_filters = sent_filters is not None and query in (None, {})
if using_legacy_filters:
# Opens with the sentence the deprecation notice told these callers to expect.
raise PermissionDenied(
"Creating or updating insights with legacy filters is not available for this user. "
"Send a query object instead. See https://posthog.com/docs/api/insights"
)
if query in (None, {}):
if self.instance is None:
raise ValidationError(
{
"query": "Creating an insight needs a query. See https://posthog.com/docs/api/insights",
}
)
if "query" in attrs:
# Writing the empty query would erase the stored definition, and nothing renders
# an insight without one, so the write is refused instead.
raise ValidationError(
{
"query": "An insight needs a query. To keep the stored one, leave query out of the "
"request. See https://posthog.com/docs/api/insights",
}
)
validate_insight_write(
query=query,
team=self.context["get_team"](),
user=self.context["request"].user,
request=self.context["request"],
)
new_dashboard_ids = attrs.get("dashboards")
if new_dashboard_ids is not None:
team = self.context["get_team"]()
dashboard_names = {dashboard.id: dashboard.name for dashboard in dashboard_refs(new_dashboard_ids)}
existing_dashboard_ids: set[int] = set()
if self.instance is not None:
existing_dashboard_ids = set(
self.instance.dashboard_tiles.exclude(deleted=True).values_list("dashboard_id", flat=True)
)
for dashboard_id in new_dashboard_ids:
if dashboard_id in existing_dashboard_ids:
continue
check_insight_tile_limit(
team=team,
dashboard_id=dashboard_id,
dashboard_name=dashboard_names.get(dashboard_id),
user=self.context["request"].user,
)
return super().validate(attrs)
def validate_dashboards(self, value: list[int]) -> list[int]:
# Fails safe like the team-scoped related field this replaced: without a team in context,
# no id resolves.
team_id = self.context.get("team_id")
unknown = list(value) if not team_id else unknown_dashboard_ids(value, team_id=team_id)
if unknown:
raise serializers.ValidationError(
f"Dashboard not found: {', '.join(str(dashboard_id) for dashboard_id in unknown)}"
)
return value
def validate_query(self, value: dict[str, Any] | None) -> dict[str, Any] | None:
"""Auto-wrap bare query sources in the wrapper node the UI renders.
Bare sources save and execute fine, but the UI only routes wrapper nodes to chart
renderers, so unwrapped queries show up as blank tiles. Everything else passes
through untouched: already-wrapped nodes must round-trip verbatim, and payloads we
don't positively recognize keep today's accept-as-is behavior — hard rejection
stays MCP-only (see MCPInsightSerializer).
"""
if not value:
return value
try:
if value.get("kind") == "HogQLQuery":
return schema.DataVisualizationNode(source=schema.HogQLQuery.model_validate(value)).model_dump(
exclude_none=True, mode="json"
)
if value.get("kind") in AUTO_WRAPPED_INSIGHT_QUERY_KINDS:
return schema.InsightVizNode.model_validate({"kind": "InsightVizNode", "source": value}).model_dump(
exclude_none=True, mode="json"
)
except PydanticValidationError:
pass
return value
@monitor(feature=Feature.INSIGHT, endpoint="insight", method="POST")
def create(self, validated_data: dict, *args: Any, **kwargs: Any) -> Insight:
request = self.context["request"]
tags = validated_data.pop("tags", None) # tags are created separately as global tag relationships
team_id = self.context["team_id"]
created_by = validated_data.pop("created_by", request.user)
dashboard_ids = validated_data.pop("dashboards", None)
# Validate dashboard access before creating anything: create() runs in autocommit,
# so raising mid-way would otherwise leave an orphaned insight (and emit user actions
# for tiles that never persist on multi-dashboard requests).
placement: InsightTilePlacement | None = None
if dashboard_ids is not None:
# Per-dashboard limit (analytics.max_insights_per_dashboard) is enforced
# in validate(); see InsightSerializer.validate above.
try:
placement = plan_insight_tile_placement(
dashboard_ids=dashboard_ids,
team_id=team_id,
query=validated_data.get("query"),
user=request.user,
user_access_control=self.user_access_control,
)
except CannotAddToDashboard as error:
raise PermissionDenied(f"You don't have permission to add insights to dashboard: {error.dashboard_id}")
except DashboardNotFound:
raise serializers.ValidationError("Dashboard not found")
# Counts the field being accepted as write input (even an empty list), after
# permission checks so rejected requests don't inflate the metric.
_record_deprecated_dashboards_field_used(self.context, usage="write")
insight = Insight.objects.create(
team_id=team_id,
created_by=created_by,
last_modified_by=request.user,
**validated_data,
)
record_insight_view(insight_id=insight.pk, team_id=team_id, user_id=request.user.pk)
if placement is not None:
for dashboard in placement.create_tiles(insight):
report_user_action(
self.context["request"].user,
"dashboard tile added",
{
"tile_type": "insight",
"insight_type": get_insight_type(insight),
"dashboard_id": dashboard.id,
},
team=insight.team,
request=self.context["request"],
)
# Manual tag creation since this create method doesn't call super()
self._attempt_set_tags(tags, insight)
log_and_report_insight_activity(
activity="created",
insight=insight,
insight_id=insight.id,
insight_short_id=insight.short_id,
organization_id=self.context["request"].user.current_organization_id,
team_id=team_id,
user=self.context["request"].user,
was_impersonated=is_impersonated(self.context["request"]),
request=self.context["request"],
)
return insight
@transaction.atomic()
@monitor(feature=Feature.INSIGHT, endpoint="insight", method="PATCH")
def update(self, instance: Insight, validated_data: dict, **kwargs) -> Insight:
dashboards_before_change: list[Union[str, dict]] = []
try:
# since it is possible to be restoring a soft deleted insight
# the state captured before the update has to include soft deleted insights
# or we can't capture undeletes to the activity log
before_update = Insight.objects_including_soft_deleted.prefetch_related(
"tagged_items__tag", "dashboards"
).get(pk=instance.id)
dashboards_before_change = [describe_change(dt.dashboard) for dt in instance.dashboard_tiles.all()]
dashboards_before_change = sorted(
dashboards_before_change,
key=lambda x: -1 if isinstance(x, str) else x["id"],
)
except Insight.DoesNotExist:
before_update = None
# Remove is_sample if it's set as user has altered the sample configuration
validated_data["is_sample"] = False
# Legacy insights, some API callers (e.g. MCP),
# and insights created from a template may have saved=False.
# The saved field is a vestige of a removed "insight history" feature (2020).
# Some functionalities (like search) depend on saved=True, so ensure any
# update corrects this for older records.
validated_data.setdefault("saved", True)
if validated_data.keys() & Insight.MATERIAL_INSIGHT_FIELDS:
instance.last_modified_at = now()
instance.last_modified_by = self.context["request"].user
# Shared links and subscription deliveries run without access checks, so an edit that adds
# a table the editor can't run must not reach them. Other insights save without any access query.
new_query = validated_data.get("query")
if new_query != instance.query and (
error := insight_query_access_error(
self.context["request"].user, instance, new_query, self.user_access_control
)
):
raise serializers.ValidationError(error)
with transaction.atomic():
if validated_data.get("deleted", False):
# Alert creation locks the insight, then checks `deleted`. Taking the same lock before
# the sweep keeps a concurrent create from adding an alert the sweep never sees.
lock_insight_for_evaluation(team_id=instance.team_id, insight_id=instance.id)
delete_insight_subscriptions(project_id=instance.team.project_id, insight_ids=[instance.id])
hide_tiles_for_insights([instance.id])
for alert in instance.alertconfiguration_set.all():
alert.delete()
else:
dashboard_ids = validated_data.pop("dashboards", None)
if dashboard_ids is not None:
# The membership write runs before the query is saved, so gate on the incoming one.
self._update_insight_dashboards(
dashboard_ids, instance, validated_data.get("query", instance.query)
)
updated_insight = super().update(instance, validated_data)
# Delete linked alerts only when the insight can no longer carry any alert. A switch between
# alertable kinds (e.g. trends -> SQL) is left alone: the config type no longer matches, but
# the alert check cycle re-validates against the current query and auto-disables + notifies on
# mismatch (see validate_alert_config + disable_invalid_alert in the alerts temporal activity),
# so the alert and its history are preserved and the user can reconfigure rather than lose it.
if updated_insight.alertable_query_kind is None:
for alert in instance.alertconfiguration_set.all():
alert.delete()
self._log_insight_update(before_update, dashboards_before_change, updated_insight)
return updated_insight
def _log_insight_update(
self,
before_update,
dashboards_before_change,
updated_insight,
):
"""
KLUDGE: Automatic detection of insight dashboard updates is flaky
This removes any detected update from the auto-detected changes
And adds in a synthetic change using data captured at the point dashboards are updated
"""
detected_changes = [
c
for c in changes_between("Insight", previous=before_update, current=updated_insight)
if c.field != "dashboards"
]
synthetic_dashboard_changes = self._synthetic_dashboard_changes(dashboards_before_change)
changes = detected_changes + synthetic_dashboard_changes
activity = "updated"
deleted_change = next((change for change in changes if change.field == "deleted"), None)
if deleted_change:
if bool(deleted_change.after):
activity = "deleted"
elif bool(deleted_change.before):
activity = "restored"
log_and_report_insight_activity(
activity=activity,
insight=updated_insight,
insight_id=updated_insight.id,
insight_short_id=updated_insight.short_id,
organization_id=self.context["request"].user.current_organization_id,
team_id=self.context["team_id"],
user=self.context["request"].user,
was_impersonated=is_impersonated(self.context["request"]),
request=self.context["request"],
changes=changes,
)
def _synthetic_dashboard_changes(self, dashboards_before_change: list[dict]) -> list[Change]:
artificial_dashboard_changes = self.context.get("after_dashboard_changes", [])
if artificial_dashboard_changes:
return [
Change(
type="Insight",
action="changed",
field="dashboards",
before=dashboards_before_change,
after=artificial_dashboard_changes,
)
]
return []
def _update_insight_dashboards(self, dashboard_ids: list[int], instance: Insight, query: Any) -> None:
# Counts the field being accepted as write input — before the no-op early return, so
# integrations that round-trip an unchanged dashboards list still register as writers.
_record_deprecated_dashboards_field_used(self.context, usage="write")
try:
change = update_insight_dashboard_membership(
insight=instance,
dashboard_ids=dashboard_ids,
query=query,
user=self.context["request"].user,
user_access_control=self.user_access_control,
)
except CannotAddToDashboard as error:
raise PermissionDenied(f"You don't have permission to add insights to dashboard: {error.dashboard_id}")
except CannotRemoveFromDashboard as error:
raise PermissionDenied(f"You don't have permission to remove insights from dashboard: {error.dashboard_id}")
except DashboardNotFound:
raise serializers.ValidationError("Dashboard not found")
if change is None:
return
for dashboard_id in change.added_dashboard_ids:
report_user_action(
self.context["request"].user,
"dashboard tile added",
{
"tile_type": "insight",
"insight_type": get_insight_type(instance),
"dashboard_id": dashboard_id,
},
team=instance.team,
request=self.context["request"],
)
for dashboard_id in change.removed_dashboard_ids:
report_user_action(
self.context["request"].user,
"dashboard tile removed",
{
"tile_type": "insight",
"insight_type": get_insight_type(instance),
"dashboard_id": dashboard_id,
},
team=instance.team,
request=self.context["request"],
)
# Dashboard membership is mutated through separate querysets above, so the instance's
# prefetched relation no longer reflects what was persisted. The response serializer must
# reload it because session callers now derive membership exclusively from dashboard_tiles.
getattr(instance, "_prefetched_objects_cache", {}).pop("dashboard_tiles", None)
# Same shape describe_change() renders a dashboard as, so this lines up with the "before"
# side of the synthetic dashboards change further up.
self.context["after_dashboard_changes"] = [
{"id": dashboard.id, "name": dashboard.name} for dashboard in change.dashboards
]
@extend_schema_field(OpenApiTypes.ANY)
def get_result(self, insight: Insight):
return self.insight_result(insight).result
@extend_schema_field(serializers.BooleanField(allow_null=True))
def get_hasMore(self, insight: Insight):
return self.insight_result(insight).has_more
@extend_schema_field(serializers.ListField(child=serializers.CharField(), allow_null=True))
def get_columns(self, insight: Insight):
return self.insight_result(insight).columns
@extend_schema_field(serializers.CharField(allow_null=True))
def get_timezone(self, insight: Insight):
# :TODO: This doesn't work properly as background cache updates don't set timezone in the response.
# This should get refactored.
if refresh_requested_by_client(self.context["request"]):
return insight.team.timezone
return self.insight_result(insight).timezone
@extend_schema_field(serializers.DateTimeField(allow_null=True))
def get_last_refresh(self, insight: Insight):
return self.insight_result(insight).last_refresh
@extend_schema_field(serializers.DateTimeField(allow_null=True))
def get_cache_target_age(self, insight: Insight):
return self.insight_result(insight).cache_target_age
@extend_schema_field(serializers.DateTimeField(allow_null=True))
def get_next_allowed_client_refresh(self, insight: Insight):
return self.insight_result(insight).next_allowed_client_refresh
@extend_schema_field(serializers.BooleanField())
def get_is_cached(self, insight: Insight):
return self.insight_result(insight).is_cached
@extend_schema_field(OpenApiTypes.ANY)
def get_query_status(self, insight: Insight):
query_status = self.insight_result(insight).query_status
if not self.context.get("is_shared") or not isinstance(query_status, dict):
return query_status
# A shared insight is read from outside the project, and both fields address the stored
# analysis of its data.
return {key: value for key, value in query_status.items() if key not in ("cache_key", "query_scan")}
def _query_variables_mapping(self, query: dict):
if (
query
and isinstance(query, dict)
and query.get("kind") in ("DataVisualizationNode", "BIVisualizationNode")
and query.get("source", {}).get("variables")
):
query["source"]["variables"] = map_stale_to_latest(
query["source"]["variables"], list(self.context["insight_variables"])
)
return query
@extend_schema_field(serializers.CharField(allow_null=True))
def get_hogql(self, insight: Insight):
return self.insight_result(insight).hogql
@extend_schema_field(serializers.ListField(allow_null=True))
def get_types(self, insight: Insight):
return self.insight_result(insight).types
@extend_schema_field(RESOLVED_DATE_RANGE_SCHEMA)
def get_resolved_date_range(self, insight: Insight):
return self.insight_result(insight).resolved_date_range
@extend_schema_field(serializers.DictField(child=serializers.CharField(), allow_null=True))
def get_action_names(self, insight: Insight):
return self.insight_result(insight).action_names
resolved_date_range = serializers.SerializerMethodField(
read_only=True,
help_text=(
"The period that this insight's query covered, with both ends resolved to timestamps."
" Null when the insight has no result yet or its query type does not report the range."
),
)
resolved_compare_date_range = serializers.SerializerMethodField(
read_only=True,
help_text=(
"The earlier period that this insight's query compared against, with both ends resolved to timestamps."
" Null when comparison is off, when the insight has no result yet, or when its query type does not report the range."
),
)
@extend_schema_field(RESOLVED_DATE_RANGE_SCHEMA)
def get_resolved_compare_date_range(self, insight: Insight):
return self.insight_result(insight).resolved_compare_date_range
@extend_schema_field(OpenApiTypes.ANY)
def get_query_scan(self, insight: Insight):
# A shared insight is read from outside the project, and the scan describes the
# project's data volume.
if self.context.get("is_shared"):
return None
result = self.insight_result(insight)
summary = result.query_scan
cache_key = result.cache_key
query_status = result.query_status or {}
if query_status.get("error"):
# A killed run has no response to carry the summary, so it rides on the status.
summary = query_status.get("query_scan") or summary
cache_key = query_status.get("cache_key") or cache_key
if not isinstance(summary, dict):
return None
return hydrate_scan_summary(self.context["get_team"](), summary, cache_key)
@extend_schema_field(_InsightResultWarnings) # type: ignore[arg-type]
def get_warnings(self, insight: Insight) -> list[dict] | None:
# Sync warnings name warehouse tables and sources, which a shared viewer outside the
# project must not see.
if self.context.get("is_shared"):
return None
return self.insight_result(insight).warnings
@extend_schema_field(serializers.ListField())
def get_alerts(self, insight: Insight):
if insight.alertable_query_kind is None:
return []
# Alert configs carry their creator's and subscribers' names and emails, which anonymous
# viewers of a shared dashboard must never receive, so omit them when hiding authorship.
if self.context.get("hide_extra_details", False):
return []
# Use prefetched alerts data
alerts = getattr(insight, "_prefetched_alerts", [])
return serialize_insight_alerts(alerts, self.context)
@extend_schema_field(InsightFilterOverrideContext) # type: ignore[arg-type]
def get_filter_override_context(self, insight: Insight) -> dict[str, object] | None:
dashboard: Any = self.context.get("dashboard")
request: Request | None = self.context.get("request")
if request is None:
return None
is_shared = self.context.get("is_shared", False)
dashboard_filters_override = filters_override_requested_by_client(request, dashboard, is_shared=is_shared)
dashboard_tile = self.dashboard_tile_from_context(insight, dashboard)
tile_filters_override = tile_filters_override_requested_by_client(request, dashboard_tile, is_shared=is_shared)
dashboard_filters = (
dashboard_filters_override
if dashboard_filters_override is not None
else dashboard.filters
if dashboard
else {}
)
if not dashboard_filters and not tile_filters_override:
return None
resolved_layers = resolve_filter_layers_by_priority(dashboard_filters, tile_filters_override)
return {key: value or None for key, value in resolved_layers.items()}
def to_representation(self, instance: Insight):
representation = super().to_representation(instance)
# Check if user has access to this insight when viewed in dashboard context
if self.context.get("dashboard"):
user_access_level = representation.get("user_access_level")
if user_access_level and not access_level_satisfied_for_resource("insight", user_access_level, "viewer"):
# User doesn't have sufficient access - return minimal insight data
return {
"id": instance.id,
"short_id": instance.short_id,
"user_access_level": user_access_level,
}
# the ORM doesn't know about deleted dashboard tiles
# when they have just been updated
# we store them and can use that list to correct the response
# and avoid refreshing from the DB
#
# `after_dashboard_changes` is only set (even to an empty list) when this request itself
# wrote `dashboards` (see _update_insight_dashboards). Correct the value only for callers
# that opted into receiving the deprecated field.
if "after_dashboard_changes" in self.context and should_serve_deprecated_dashboards_field(self.context):
representation["dashboards"] = [
described_dashboard["id"] for described_dashboard in self.context["after_dashboard_changes"]
]
dashboard: Any = self.context.get("dashboard")
request: Request | None = self.context.get("request")
is_shared = self.context.get("is_shared", False)
dashboard_filters_override = (
filters_override_requested_by_client(request, dashboard, is_shared=is_shared) if request else None
)
dashboard_variables_override = variables_override_requested_by_client(
request, dashboard, list(self.context["insight_variables"]), is_shared=is_shared
)
# Tile filters merge on top of dashboard filters (same semantics as the compute path in
# calculate_results.py). Keeping this in sync ensures the returned `query` field matches the
# filter set the cached result was computed with — otherwise the persons modal would use a
# different filter set than the chart.
dashboard_tile = self.dashboard_tile_from_context(instance, dashboard)
tile_filters_override = (
tile_filters_override_requested_by_client(request, dashboard_tile, is_shared=is_shared) if request else {}
)
if instance.query is not None:
# Upgrade before applying dashboard filters: the stored query may predate the current
# schema, and apply_dashboard_filters_to_dict validates against the latest one
query = upgrade(instance.query)
if (
dashboard is not None
or dashboard_filters_override is not None
or dashboard_variables_override is not None
or tile_filters_override
):
base_filters = (
dashboard_filters_override
if dashboard_filters_override is not None
else dashboard.filters
if dashboard
else {}
)
# Same dashboard+tile+insight precedence the compute path applies in calculate_results.py,
# so the returned query matches what the cached result was actually computed with.
effective = resolve_effective_dashboard_filters(query, base_filters, tile_filters_override)
query = apply_dashboard_filters_to_dict(
effective.query,
effective.filters,
instance.team,
)
query = apply_dashboard_variables_to_dict(
query,
dashboard_variables_override or {},
instance.team,
)
representation["query"] = query
else:
representation["query"] = instance.get_effective_query(
dashboard=dashboard,
dashboard_filters_override=dashboard_filters_override,
dashboard_variables_override=dashboard_variables_override,
)
representation["filters_hash"] = self.insight_result(instance).cache_key
# Hide PII fields when hideExtraDetails from SharingConfiguration is enabled
if self.context.get("hide_extra_details", False):
representation.pop("created_by", None)
representation.pop("last_modified_by", None)
representation.pop("created_at", None)
representation.pop("last_modified_at", None)
return representation
@lru_cache(maxsize=1) # noqa: B019 - short-lived serializer
def insight_result(self, insight: Insight) -> InsightResult:
from posthog.caching.calculate_results import calculate_for_query_based_insight
dashboard: Any = self.context.get("dashboard")
# Check if we have an expected cache key from the image exporter
export_cache_keys: dict[int, str] | None = self.context.get("export_cache_keys")
expected_cache_key = (export_cache_keys or {}).get(insight.id)
# The cache key is unauthenticated input carried on the render URL, and the store it indexes is
# shared across teams. `generate_cache_key` prefixes every key with the team it was computed for,
# so a key that doesn't carry this insight's team can't be one the runner would produce for it.
if expected_cache_key and not expected_cache_key.startswith(generate_cache_key_prefix(insight.team_id)):
logger.error(
"export_cache_key_team_mismatch",
insight_id=insight.id,
expected_cache_key=expected_cache_key,
message="Cache key does not belong to the insight's team - falling back to normal calculation",
)
expected_cache_key = None
if expected_cache_key:
entry = QueryCache(team_id=insight.team_id, cache_key=expected_cache_key).lookup().entry
cached_response = entry.as_full_response() if entry else None
if cached_response:
action_names = cached_response.get("action_names")
if action_names is None and isinstance(insight.query, dict):
# An entry cached before responses carried `action_names` lacks the field, and this shortcut
# skips the runner that fills it on a cache hit.
action_names = get_response_action_names(insight.team, upgrade(deepcopy(insight.query)))
return dataclasses.replace(
InsightResult.from_response_dict(cached_response),
cache_key=expected_cache_key,
is_cached=True,
action_names=action_names,
)
else:
EXPORT_QUERY_CACHE_MISS.inc()
logger.error(
"export_cache_key_miss",
insight_id=insight.id,
expected_cache_key=expected_cache_key,
message="Expected cache key not found during export - falling back to normal calculation",
)
with upgrade_insight(insight):
try:
is_shared = self.context.get("is_shared", False)
execution_mode, shared_cache_age_seconds = resolve_execution_mode(
self.context["request"],
surface=self.context.get("compute_surface", ComputeSurface.LEGACY_UNKNOWN),
is_shared=is_shared,
)
filters_override = filters_override_requested_by_client(
self.context["request"], dashboard, is_shared=is_shared
)
variables_override = variables_override_requested_by_client(
self.context["request"], dashboard, list(self.context["insight_variables"]), is_shared=is_shared
)
dashboard_tile = self.dashboard_tile_from_context(insight, dashboard)
tile_filters_override = tile_filters_override_requested_by_client(
self.context["request"], dashboard_tile, is_shared=is_shared
)
# Shared rendering bypasses the FE scene-tag flow, so set product/feature
# tags here. No-op overwrite for authenticated paths (same values).
shared_tags = {"access_method": AccessMethod.SHARING_TOKEN} if is_shared else {}
request_user = None if self.context["request"].user.is_anonymous else self.context["request"].user
if request_user is None and is_shared:
# Anonymous shared views execute as the shared-link user, so
# warehouse-backed tiles resolve instead of failing with "no access"
request_user = self.context.get("shared_link_user")
# Reuse the request's single UserAccessControl across all of a dashboard's insight
# runners, so the cache fingerprint resolves access once per request, not per tile.
# Real users only - a shared-link viewer has no access-control snapshot.
view = self.context.get("view")
request_user_access_control = (
getattr(view, "user_access_control", None) if isinstance(request_user, User) else None
)
# Raw cached results (orjson.Fragment) are only valid when the response is
# rendered by orjson: SafeJSONRenderer directly, or a caller that declares it
# renders tiles with SafeJSONRenderer itself (the SSE tile stream sets
# raw_results_supported — SSE content negotiation alone doesn't guarantee an
# orjson boundary). Pretty-printed output (?indent=) would not indent inside a
# fragment, so keep the parsed path there.
accepted_renderer = getattr(self.context["request"], "accepted_renderer", None)
allow_raw_results = (
(isinstance(accepted_renderer, SafeJSONRenderer) or bool(self.context.get("raw_results_supported")))
and not self.context["request"].query_params.get("indent")
and not self.context.get("require_parsed_results")
)
with tags_context(product=ProductKey.PRODUCT_ANALYTICS, feature=Feature.INSIGHT, **shared_tags):
insight_result = calculate_for_query_based_insight(
insight,
team=self.context["get_team"](),
dashboard=dashboard,
execution_mode=execution_mode,
user=request_user,
user_access_control=request_user_access_control,
filters_override=filters_override,
variables_override=variables_override,
tile_filters_override=tile_filters_override,
cache_age_seconds=shared_cache_age_seconds,
analytics_props=get_query_request_analytics_properties(self.context["request"]),
allow_raw_results=allow_raw_results,
)
access_method: DashboardAccessMethod | None = self.context.get("dashboard_access_method")
if (
dashboard is not None
and access_method is not None
and execution_mode
not in {
ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
ExecutionMode.CALCULATE_ASYNC_ALWAYS,
}
):
record_dashboard_cache_outcome(
access_method,
is_cached=insight_result.is_cached,
)
return insight_result
except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:
return self._degraded_insight_result(
insight,
dashboard,
error=e,
error_message=str(e),
error_code=getattr(e, "code_name", None),
last_refresh=None,
)
except Exception as e:
is_rate_limited = classify_query_error(e) == QueryErrorCategory.RATE_LIMITED
error_message = str(e)
if is_rate_limited:
# Older dashboard clients retry on this marker. Other capacity messages can
# contain internal Redis keys, task IDs or raw ClickHouse details.
error_message = (
"concurrency_limit_exceeded"
if isinstance(e, ConcurrencyLimitExceeded)
else ClickHouseAtCapacity.default_detail
)
logger.warn(
"insight_calculation_rate_limited",
exception=e,
insight_id=insight.id,
team_id=insight.team_id,
)
else:
# Capture unexpected crashes so the API list doesn't fail
logger.exception("insight_calculation_error", insight_id=insight.id, team_id=insight.team_id)
return self._degraded_insight_result(
insight,
dashboard,
error=e,
error_message=error_message,
error_code=QueryErrorCategory.RATE_LIMITED if is_rate_limited else None,
last_refresh=now() if is_rate_limited else None,
)
def _degraded_insight_result(
self,
insight: Insight,
dashboard: Any,
*,
error: Exception,
error_message: str,
error_code: str | None,
last_refresh: datetime | None,
) -> InsightResult:
"""A 200 response carrying the failure on query_status, so a failing insight degrades in
place rather than failing the whole request. `error_code` lets the client tell a
deterministic query failure from a transient one.
A run ClickHouse stopped carries its scan on the exception, and the analysis is stored
under the cache key, so both ride along instead of dropping with the results."""
query_scan = getattr(error, "query_scan", None)
return InsightResult(
result=None,
last_refresh=last_refresh,
is_cached=False,
query_status=dict(
QueryStatus(
# QueryStatus.id is a required str; without a client_query_id this
# fallback used to crash pydantic validation and turn the degraded
# error state into a 500.
id=self.context["request"].query_params.get("client_query_id") or "",
team_id=insight.team_id,
insight_id=str(insight.id),
dashboard_id=str(dashboard.id) if dashboard else None,
error_message=error_message,
error_code=error_code,
error=True,
)
),
cache_key=getattr(error, "cache_key", None),
query_scan=query_scan if isinstance(query_scan, dict) else None,
hogql=None,
columns=None,
has_more=None,
timezone=self.context["get_team"]().timezone,
)
@lru_cache(maxsize=1) # noqa: B019 - short-lived serializer, one insight/tile combo
def dashboard_tile_from_context(self, insight: Insight, dashboard: Any) -> Any:
dashboard_tile: Any = self.context.get("dashboard_tile", None)
if dashboard_tile and dashboard_tile.deleted:
self.context.update({"dashboard_tile": None})
dashboard_tile = None
if not dashboard_tile and dashboard:
dashboard_tile = tile_for_render(insight=insight, dashboard=dashboard)
return dashboard_tile
def _pydantic_error_details(exc: PydanticValidationError) -> str:
return "; ".join(f"{'.'.join(str(part) for part in e['loc'])}: {e['msg']}" for e in exc.errors())
class MCPInsightSerializer(InsightSerializer):
"""Serializer for MCP insight create/update requests.
Accepts raw product analytics queries and normalizes them into the correct saved-insight
wrapper before persisting: HogQLQuery → DataVisualizationNode, insight queries
(TrendsQuery, FunnelsQuery, PathsQuery) → InsightVizNode, EventsQuery → DataTableNode. MetricsQuery and
MetricsHistogramQuery stay bare.
"""
query = QueryFieldSerializer(required=False, allow_null=True)
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
if self.context["view"].action == "create" and "query" not in attrs:
raise serializers.ValidationError({"query": "This field is required."})
return super().validate(attrs)
def validate_query(self, value: dict[str, Any] | None) -> dict[str, Any]:
# Raw HogQL → DataVisualizationNode
try:
return schema.DataVisualizationNode(source=schema.HogQLQuery.model_validate(value)).model_dump(
exclude_none=True, mode="json", by_alias=True
)
except PydanticValidationError:
pass
try:
return schema.DataTableNode(source=schema.EventsQuery.model_validate(value)).model_dump(
exclude_none=True, mode="json"
)
except PydanticValidationError:
pass
# Already-wrapped node → use as-is
for wrapped_cls in (
schema.DataVisualizationNode,
schema.BIVisualizationNode,
schema.InsightVizNode,
schema.DataTableNode,
):
try:
wrapped_node = wrapped_cls.model_validate(value)
if isinstance(wrapped_node, schema.DataTableNode) and not isinstance(
wrapped_node.source, schema.EventsQuery
):
raise serializers.ValidationError("MCP data table insights must have an EventsQuery source.")
normalized_query = wrapped_node.model_dump(exclude_none=True, mode="json", by_alias=True)
if isinstance(wrapped_node, (schema.DataVisualizationNode, schema.BIVisualizationNode)):
box_plot = wrapped_node.chartSettings.boxPlot if wrapped_node.chartSettings else None
if box_plot is not None:
normalized_box_plot = normalized_query.setdefault("chartSettings", {}).setdefault("boxPlot", {})
for field in ("xAxisColumn", "seriesColumn"):
if field in box_plot.model_fields_set and getattr(box_plot, field) is None:
normalized_box_plot[field] = None
if isinstance(wrapped_node, schema.BIVisualizationNode):
for entry in normalized_query["config"].get("memberAliases", []):
for alias in entry["aliases"]:
alias.setdefault("value", None)
if "colorBy" in wrapped_node.config.model_fields_set and wrapped_node.config.colorBy is None:
normalized_query["config"]["colorBy"] = None
return normalized_query
except PydanticValidationError:
pass
# A metrics insight saves its query bare, as the metrics editor and the metrics dashboard builders do
metrics_classes: dict[str, type[schema.MetricsQuery] | type[schema.MetricsHistogramQuery]] = {
"MetricsQuery": schema.MetricsQuery,
"MetricsHistogramQuery": schema.MetricsHistogramQuery,
}
kind = value.get("kind") if value is not None else None
metrics_cls = metrics_classes.get(kind) if isinstance(kind, str) else None
if value is not None and metrics_cls is not None:
if value.get("language") in ("promql", "sql"):
# A PromQL or SQL metrics query has no builder clauses, but the schema still requires the field.
value = {**value, "clauses": value.get("clauses") or []}
try:
return metrics_cls.model_validate(value).model_dump(exclude_none=True, mode="json", by_alias=True)
except PydanticValidationError as exc:
raise serializers.ValidationError(f"This query can't be saved: {_pydantic_error_details(exc)}")
# Raw product analytics query → InsightVizNode
try:
return schema.InsightVizNode.model_validate({"kind": "InsightVizNode", "source": value}).model_dump(
exclude_none=True, mode="json", by_alias=True
)
except PydanticValidationError as exc:
raise serializers.ValidationError(f"This query can't be saved: {_pydantic_error_details(exc)}")
# Insights can be looked up by either the numeric primary key or the 8-character `short_id`
# (the alphanumeric code visible in URLs like `/insights/AaVQ8Ijw`). The resolution happens in
# `InsightViewSet.safely_get_object`: a purely-numeric string is treated as the PK, otherwise it
# falls back to `short_id`. Advertise both forms in the OpenAPI schema so generated clients
# (frontend, MCP tools) do not constrain callers to integers.
INSIGHT_ID_PATH_PARAMETER = OpenApiParameter(
name="id",
location=OpenApiParameter.PATH,
type={"oneOf": [{"type": "integer"}, {"type": "string"}]},
description="Numeric primary key or 8-character `short_id` (for example `AaVQ8Ijw`) identifying the insight.",
)
INCLUDE_DASHBOARDS_PARAMETER = OpenApiParameter(
name=INCLUDE_DASHBOARDS_PARAM,
type=OpenApiTypes.BOOL,
description=(
"Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in "
"enforcement is enabled, API-token callers stop receiving it by default; use "
"`dashboard_tiles` instead."
),
)
INSIGHT_VIEWED_MAX_IDS = 2500
class InsightViewedRequestSerializer(serializers.Serializer):
insight_ids = serializers.ListField(
child=serializers.IntegerField(),
allow_empty=False,
max_length=INSIGHT_VIEWED_MAX_IDS,
help_text=(
f"Insight IDs that were just viewed by the current user. At most {INSIGHT_VIEWED_MAX_IDS} ids per request."
),
)
INSIGHT_BULK_DELETE_MAX_IDS = 1000
class InsightBulkDeleteRequestSerializer(serializers.Serializer):
ids = serializers.ListField(
child=serializers.IntegerField(min_value=1),
allow_empty=False,
max_length=INSIGHT_BULK_DELETE_MAX_IDS,
help_text=(
f"Insight IDs to soft-delete (or restore). At most {INSIGHT_BULK_DELETE_MAX_IDS} ids per request. "
"Soft-deleted insights can be brought back via the bulk_restore endpoint."
),
)
class InsightBulkOperationResultSerializer(serializers.Serializer):
id = serializers.IntegerField(help_text="ID of the insight that was soft-deleted or restored.")
name = serializers.CharField(
allow_null=True,
help_text="The insight's name (or derived name) at the time of the operation; null when it has neither.",
)
class InsightBulkOperationSkippedSerializer(serializers.Serializer):
id = serializers.IntegerField(help_text="ID of the insight that was skipped.")
reason = serializers.CharField(
help_text="Human-readable reason the insight was skipped (for example, not found or no edit permission)."
)
class InsightBulkDeleteResponseSerializer(serializers.Serializer):
deleted = InsightBulkOperationResultSerializer(many=True, help_text="Insights that were successfully soft-deleted.")
skipped = InsightBulkOperationSkippedSerializer(
many=True, help_text="Insights that were not deleted, with the reason for each."
)
class InsightBulkRestoreResponseSerializer(serializers.Serializer):
restored = InsightBulkOperationResultSerializer(many=True, help_text="Insights that were successfully restored.")
skipped = InsightBulkOperationSkippedSerializer(
many=True, help_text="Insights that were not restored, with the reason for each."
)
INSIGHT_BULK_TEST_ACCOUNT_FILTER_BATCH_SIZE = 500
class InsightBulkSetTestAccountFilterRequestSerializer(serializers.Serializer):
enabled = serializers.BooleanField(
help_text="Whether every existing insight should filter out internal and test users."
)
class InsightBulkSetTestAccountFilterResponseSerializer(serializers.Serializer):
updated = serializers.IntegerField(help_text="Number of insights whose test account filter was changed.")
unchanged = serializers.IntegerField(help_text="Number of insights that already had the requested value.")
unsupported = serializers.IntegerField(
help_text="Number of insights with no test account filter to set, such as SQL insights."
)
skipped = serializers.IntegerField(help_text="Number of insights the requester cannot edit.")
legacy = serializers.IntegerField(
help_text=(
"Number of insights left as they are because they still store legacy `filters` rather than a query. "
"They keep whatever value they already had. Opening and saving one converts it, after which this "
"endpoint covers it."
)
)
DEPTH_HELP_TEXT = (
"`quick`, the default, reads within a small budget so the checks can run on every load. On an insight they would "
"read a lot of data for, a quick check does not run and `status` is `on_request`. `full` runs the checks with the "
"same limits as the insight's own query."
)
class InsightDataChecksRequestSerializer(serializers.Serializer):
query = QueryFieldSerializer(
help_text=(
"The insight query to check, in the shape an insight stores it: an `InsightVizNode` with its `source`. "
"Pass the query of a saved insight, or one that is not saved yet."
)
)
client_query_id = serializers.CharField(
required=False,
max_length=128,
help_text=(
"An id for this run, chosen by the client. To stop the queries of the run, send a DELETE request to "
"`query/{client_query_id}/`."
),
)
depth = serializers.ChoiceField(
choices=InsightDataChecksDepth.choices,
required=False,
default=InsightDataChecksDepth.QUICK,
help_text=DEPTH_HELP_TEXT,
)
class InsightDataChecksQueryParamsSerializer(serializers.Serializer):
depth = serializers.ChoiceField(
choices=InsightDataChecksDepth.choices,
required=False,
default=InsightDataChecksDepth.QUICK,
help_text=DEPTH_HELP_TEXT,
)
class InsightDataCheckFilterSerializer(serializers.Serializer):
key = serializers.CharField(help_text="The property the rule reads, such as `$host`.")
type = serializers.CharField(help_text="The kind of property, such as `event` or `person`.")
operator = serializers.CharField(help_text="How the rule compares the property, such as `not_regex`.")
value = serializers.ListField(
child=serializers.CharField(), help_text="The values the rule compares the property to."
)
class InsightDataCheckSerializer(serializers.Serializer):
key = serializers.ChoiceField(choices=InsightDataCheckKey.choices, help_text="Which check this is.")
level = serializers.ChoiceField(
choices=InsightDataCheckLevel.choices,
help_text=(
"`passed` when the check found nothing worth acting on, `warning` for a small share of the events, "
"`problem` for a fifth of the events or more, and `skipped` when the check could not run. The local "
"development check is never a `problem`, because some apps serve real users from a local host."
),
)
skip_reason = serializers.ChoiceField(
choices=InsightDataCheckSkipReason.choices,
allow_null=True,
help_text="Why the check did not run. Null unless `level` is `skipped`.",
)
method = serializers.ChoiceField(
choices=InsightDataCheckMethod.choices,
allow_null=True,
help_text=(
"`counted` when the check counted every event on the days checked, `sampled` when it read a sample. "
"Null when the check did not run."
),
)
events = serializers.IntegerField(
allow_null=True,
help_text="How many events on the days checked the check found. Null when the check did not run.",
)
share = serializers.FloatField(
allow_null=True,
help_text=(
"`events` as a share of the events checked, from 0 to 1. Null when the check did not run, or when the "
"sample is too small to give a share."
),
)
scaled = serializers.BooleanField(
help_text="True when `events` is an estimate scaled up from a sample, rather than a count of every event."
)
action = serializers.ChoiceField(
choices=InsightDataCheckAction.choices,
allow_null=True,
help_text=(
"The change that fixes it. `filter_internal_users`: set `filterTestAccounts` to true on the insight's "
"query. `open_filter_settings`: change the project's internal and test users filter, for example by "
"adding `filter_to_add`. Null when there is no single change."
),
)
top_events = serializers.ListField(
child=serializers.CharField(), help_text="The event names the check found most often, most affected first."
)
top_hosts = serializers.ListField(
child=serializers.CharField(),
help_text=(
"For the local development check, the local hosts whose events the project's internal and test users "
"filter keeps, most affected first."
),
)
distinct_hosts = serializers.IntegerField(
allow_null=True,
help_text=(
"For the local development check, how many local hosts sent the events in `events`. Null for the other "
"checks and when the check did not run."
),
)
top_bots = serializers.ListField(
child=serializers.CharField(),
help_text="For the bot traffic check, the bots and crawlers found most often, most affected first.",
)
distinct_bots = serializers.IntegerField(
allow_null=True,
help_text=(
"For the bot traffic check, how many named bots and crawlers sent the sampled events. Null for the other "
"checks and when the check did not run."
),
)
removed_by_filter = serializers.IntegerField(
allow_null=True,
help_text=(
"For the internal users check, the part of `events` that the project's internal and test users filter "
"removes. It is 0 when the insight already applies the filter. Null for the other checks and when the "
"check did not run."
),
)
missed_by_filter = serializers.IntegerField(
allow_null=True,
help_text=(
"For the internal users check, the part of `events` from team emails that the project's internal and "
"test users filter keeps. Null for the other checks and when the check did not run."
),
)
top_emails = serializers.ListField(
child=serializers.CharField(),
help_text=(
"For the internal users check, the team emails whose events the project's internal and test users filter "
"keeps, most affected first. Only emails the caller may see as the team's are matched. Empty for a token "
"without the `person:read` scope."
),
)
distinct_emails = serializers.IntegerField(
allow_null=True,
help_text=(
"For the internal users check, how many team emails sent events that the project's internal and test "
"users filter keeps. Null for the other checks and when the check did not run."
),
)
filter_to_add = InsightDataCheckFilterSerializer(
allow_null=True,
help_text=(
"A rule for the project's internal and test users filter that removes what the check found: the local "
"hosts or team emails it found, up to 50 values, or bot and AI agent traffic. Null when the check found "
"none, and for the internal users check for a token without the `person:read` scope."
),
)
class InsightDataChecksSampleSerializer(serializers.Serializer):
rate = serializers.FloatField(
help_text="The share of the events on the days checked that the sample read, from 0 to 1."
)
events = serializers.IntegerField(help_text="How many events the sample read.")
distinct_ids = serializers.IntegerField(help_text="How many distinct IDs sent the events the sample read.")
class InsightDataChecksCoverageSerializer(serializers.Serializer):
date_from = serializers.DateField(help_text="The first day of the insight's date range.")
date_to = serializers.DateField(help_text="The last day of the insight's date range.")
days_in_range = serializers.IntegerField(help_text="How many days the insight's date range holds.")
checked_date_from = serializers.DateField(help_text="The first day the checks read.")
checked_date_to = serializers.DateField(help_text="The last day the checks read.")
days_checked = serializers.IntegerField(
help_text="How many days the checks read. The checks read the newest days of the range, up to 7."
)
filters_test_accounts = serializers.BooleanField(
help_text="True when the insight filters out the project's internal and test users."
)
events_checked = serializers.IntegerField(
allow_null=True,
help_text=(
"How many events the insight reads on the days checked. Counted exactly, or scaled up from the sample "
"when the days hold too many events to count. Null when neither ran."
),
)
sample = InsightDataChecksSampleSerializer(
allow_null=True, help_text="The sample the bot and duplicate checks read. Null when the sample did not run."
)
class InsightDataChecksSerializer(serializers.Serializer):
status = serializers.ChoiceField(
choices=InsightDataChecksStatus.choices,
help_text=(
"The worst result across the checks. `no_events` when no event matches the insight's events, filters "
"and date range. `unsupported` when the insight has no event series to check, such as a SQL insight, "
"and when a property the checks read is hidden from the caller. `inconclusive` when no check could run. "
"`partial` when some checks could not run and the others found nothing. `on_request` when the checks "
"would read a lot of data for a quick check, so they did not run: send `depth` `full` to run them."
),
)
checks = InsightDataCheckSerializer(many=True, help_text="Every check, in a fixed order, whatever its result.")
coverage = InsightDataChecksCoverageSerializer(
allow_null=True,
help_text=(
"Which days and how many events the checks read. Null when the checks could not choose the days to "
"read, such as for an `unsupported` insight."
),
)
def chart_display_filter(value: str) -> Q:
displays = [display for display in value.split(",") if display]
unknown = set(displays) - {display.value for display in schema.ChartDisplayType}
if not displays or unknown:
raise ValidationError({"display": f"Unknown chart types: {', '.join(sorted(unknown)) or value!r}."})
trends_display = Q(query__source__trendsFilter__display__in=displays)
if schema.ChartDisplayType.ACTIONS_LINE_GRAPH in displays:
trends_display |= Q(query__source__trendsFilter__display__isnull=True)
return (
Q(query__kind=schema.NodeKind.INSIGHT_VIZ_NODE, query__source__kind=schema.NodeKind.TRENDS_QUERY)
& trends_display
) | Q(query__kind=schema.NodeKind.DATA_VISUALIZATION_NODE, query__display__in=displays)
@extend_schema(extensions={"x-product": ProductKey.PRODUCT_ANALYTICS})
@extend_schema_view(
list=extend_schema(
parameters=[
OpenApiParameter(
name="refresh",
enum=list(ExecutionMode),
default=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
# Sync the `refresh` description here with the other one in this file, and with frontend/src/queries/schema.ts
description="""
Whether to refresh the retrieved insights, how aggressively, and if sync or async:
- `'force_cache'` - return cached data or a cache miss; always completes immediately as it never calculates
- `'blocking'` - calculate synchronously (returning only when the query is done), UNLESS there are very fresh results in the cache
- `'async'` - kick off background calculation (returning immediately with a query status), UNLESS there are very fresh results in the cache
- `'lazy_async'` - kick off background calculation, UNLESS there are somewhat fresh results in the cache
- `'force_blocking'` - calculate synchronously, even if fresh results are already cached
- `'force_async'` - kick off background calculation, even if fresh results are already cached
Background calculation can be tracked using the `query_status` response field.""",
),
OpenApiParameter(
name="basic",
type=OpenApiTypes.BOOL,
description="Return basic insight metadata only (no results, faster).",
),
INCLUDE_DASHBOARDS_PARAMETER,
OpenApiParameter(
name="search",
type=OpenApiTypes.STR,
description=(
"Search term matched across name, derived_name, description, and tag names. Returns exact "
"(case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy "
"trigram) matches instead. Each result's `search_match_type` is `exact` or `similar`."
),
),
OpenApiParameter(
name="created_by",
type=OpenApiTypes.STR,
description="JSON-encoded array of user IDs. Only returns insights whose `created_by` is in the list, e.g. `[1,42]`.",
),
OpenApiParameter(
name="user",
type=OpenApiTypes.BOOL,
description="Include this parameter (any value) to restrict results to insights created by the authenticated user.",
),
OpenApiParameter(
name="favorited",
type=OpenApiTypes.BOOL,
description="Include this parameter (any value) to restrict results to insights marked as favorited.",
),
OpenApiParameter(
name="saved",
type=OpenApiTypes.BOOL,
description="When truthy, restricts results to insights that are saved (or attached to a visible dashboard). When falsy, only unsaved insights.",
),
OpenApiParameter(
name="insight",
enum=[
"TRENDS",
"FUNNELS",
"RETENTION",
"PATHS",
"JOURNEYS",
"STICKINESS",
"LIFECYCLE",
"JSON",
"SQL",
"BI",
],
description="Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries; `BI` matches editable worksheets.",
),
OpenApiParameter(
name="exclude_bi",
type=OpenApiTypes.BOOL,
description="Exclude Business intelligence worksheets from the insight list.",
),
OpenApiParameter(
name="display",
type=OpenApiTypes.STR,
description=(
"Comma-separated chart types, e.g. `ActionsLineGraph,ActionsBar`. Only returns trends and SQL "
"insights shown as one of them. A trends insight with no chart type set counts as "
"`ActionsLineGraph`."
),
),
OpenApiParameter(
name="order",
type=OpenApiTypes.STR,
description="Sort by an insight field, with a leading minus for descending order. Supports last_modified_at and last_viewed_at.",
),
OpenApiParameter(
name="date_from",
type=OpenApiTypes.STR,
description="Filter by `last_modified_at > date_from`. Accepts absolute dates (`2025-04-23`) or relative strings (`-7d`, `-1m`).",
),
OpenApiParameter(
name="date_to",
type=OpenApiTypes.STR,
description="Filter by `last_modified_at < date_to`. Accepts absolute dates or relative strings.",
),
OpenApiParameter(
name="created_date_from",
type=OpenApiTypes.STR,
description="Filter by `created_at > created_date_from`. Accepts absolute or relative dates.",
),
OpenApiParameter(
name="created_date_to",
type=OpenApiTypes.STR,
description="Filter by `created_at < created_date_to`. Accepts absolute or relative dates.",
),
OpenApiParameter(
name="last_viewed_date_from",
type=OpenApiTypes.STR,
description="Filter by `last_viewed_at > last_viewed_date_from`. Accepts absolute or relative dates.",
),
OpenApiParameter(
name="last_viewed_date_to",
type=OpenApiTypes.STR,
description="Filter by `last_viewed_at < last_viewed_date_to`. Accepts absolute or relative dates.",
),
OpenApiParameter(
name="dashboards",
type=OpenApiTypes.STR,
description="JSON-encoded array of dashboard IDs. Returns insights attached to every listed dashboard (AND).",
),
OpenApiParameter(
name="tags",
type=OpenApiTypes.STR,
description="JSON-encoded array of tag names. Returns insights with any of the listed tags.",
),
]
),
create=extend_schema(parameters=[INCLUDE_DASHBOARDS_PARAMETER]),
retrieve=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER, INCLUDE_DASHBOARDS_PARAMETER]),
update=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER, INCLUDE_DASHBOARDS_PARAMETER]),
partial_update=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER, INCLUDE_DASHBOARDS_PARAMETER]),
destroy=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER]),
)
class InsightViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
TaggedItemViewSetMixin,
ForbidDestroyModel,
viewsets.ModelViewSet,
):
scope_object = "insight"
permission_classes = [CanEditInsightDashboards]
# Record a tags change per insight when bulk_update_tags mutates it, matching the single-object path.
bulk_tag_activity_scope = "Insight"
serializer_class = InsightSerializer
throttle_classes = [
ClickHouseBurstRateThrottle,
ClickHouseSustainedRateThrottle,
]
renderer_classes = cast(
tuple[type[BaseRenderer], ...],
(*tuple(api_settings.DEFAULT_RENDERER_CLASSES), csvrenderers.CSVRenderer),
)
filter_backends = [DjangoFilterBackend]
filterset_fields = ["short_id"]
sharing_enabled_actions = ["retrieve", "list"]
queryset = Insight.objects_including_soft_deleted.all()
parser_classes = (QuerySchemaParser,)
def finalize_response(self, request: Request, response: Response, *args: Any, **kwargs: Any) -> Response:
return add_query_response_identity_headers(super().finalize_response(request, response, *args, **kwargs))
def get_throttles(self):
"""Apply LLM-specific throttles to the AI metadata endpoint."""
if self.action == "generate_metadata":
return [
AIObservabilitySummarizationBurstThrottle(),
AIObservabilitySummarizationSustainedThrottle(),
AIObservabilitySummarizationDailyThrottle(),
]
return super().get_throttles()
def _validate_ai_feature_access(self) -> None:
"""Validate that AI data processing is approved by the organization."""
if not self.organization.is_ai_data_processing_approved:
raise PermissionDenied("AI data processing must be approved by your organization")
@staticmethod
def _is_mcp_request(request: Request) -> bool:
return request.headers.get("x-posthog-client") == "mcp"
def _is_basic_request(self) -> bool:
return self.action in ("list", "retrieve") and str_to_bool(self.request.query_params.get("basic", "0"))
@tracer.start_as_current_span("insight_api_list")
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
span = trace.get_current_span()
span.set_attribute("posthog.team_id", self.team_id)
span.set_attribute("posthog.basic", self._is_basic_request())
span.set_attribute("posthog.saved", str_to_bool(request.query_params.get("saved", "0")))
span.set_attribute("posthog.order", request.query_params.get("order", ""))
response = super().list(request, *args, **kwargs)
if request.query_params.get("search"):
data = response.data if isinstance(response.data, dict) else {}
results_len = data.get("count", len(data.get("results", [])))
span.set_attribute("insight.search.result_count", results_len)
span.set_attribute("insight.search.empty", results_len == 0)
return response
def get_serializer_class(self) -> type[serializers.BaseSerializer]:
if self._is_basic_request():
return InsightBasicSerializer
if self.action in ("create", "partial_update") and self._is_mcp_request(self.request):
return MCPInsightSerializer
return super().get_serializer_class()
def get_serializer_context(self) -> dict[str, Any]:
context = super().get_serializer_context()
context["is_shared"] = isinstance(
self.request.successful_authenticator,
SharingAccessTokenAuthentication | SharingPasswordProtectedAuthentication,
)
if isinstance(self.request.user, SharedLinkUser):
# Sharing-token API refreshes authenticate as the shared-link viewer; expose it under
# the same context key the /shared/ page render uses (SharingViewerPageViewSet).
context["shared_link_user"] = self.request.user
# Deferred: every insight and dashboard response carries this, but only payloads that
# hold variables read it, so resolving it eagerly costs a query on every list request.
context["insight_variables"] = SimpleLazyObject(lambda: insight_variables_for_team(self.team.pk))
context["compute_surface"] = (
ComputeSurface.INSIGHT_LIST if self.action == "list" else ComputeSurface.INSIGHT_DETAIL
)
return context
def dangerously_get_queryset(self):
# Insights are retrieved under /environments/ because they include team-specific query results,
# but they are in fact project-level, rather than environment-level
assert self.team.project_id is not None
queryset = self.queryset.filter(team__project_id=self.team.project_id)
include_deleted = False
if isinstance(
self.request.successful_authenticator,
SharingAccessTokenAuthentication | SharingPasswordProtectedAuthentication,
):
queryset = queryset.filter(
id__in=self.request.successful_authenticator.sharing_configuration.get_connected_insight_ids()
)
elif self.action == "partial_update" and self.request.data.get("deleted") is False:
# an insight can be restored by patching {"deleted": False}
include_deleted = True
if not include_deleted:
queryset = queryset.exclude(deleted=True)
# InsightBasicSerializer skips alerts and only needs PKs from dashboards plus
# (id, dashboard_id, deleted) from tiles, so the heavy team→organization joins
# the full serializer relies on are pure waste on the basic path.
is_basic = self._is_basic_request()
if is_basic:
queryset = queryset.prefetch_related(tile_ids_prefetch())
else:
queryset = queryset.prefetch_related(
tile_permissions_prefetch(),
insight_alerts_prefetch(to_attr="_prefetched_alerts"),
)
# Add access level filtering for list actions if not sharing access token
if not isinstance(self.request.successful_authenticator, SharingAccessTokenAuthentication):
queryset = self._filter_queryset_by_access_level(queryset)
if is_basic:
queryset = queryset.select_related("created_by", "team")
else:
queryset = queryset.select_related("created_by", "last_modified_by", "team")
if self.action == "list":
queryset = queryset.prefetch_related("tagged_items__tag")
queryset = with_last_viewed_at(queryset)
queryset = self._filter_request(self.request, queryset)
return self.order_queryset(queryset)
def safely_get_object(self, queryset: QuerySet) -> Insight | None:
return resolve_insight_by_id_or_short_id(queryset, self.kwargs[self.lookup_field])
def filter_queryset(self, queryset: QuerySet) -> QuerySet:
return drop_similar_when_exact_exists(super().filter_queryset(queryset))
def order_queryset(self, queryset: QuerySet) -> QuerySet:
order = self.request.GET.get("order", None)
if not order:
if self.request.GET.get("search"):
return queryset
# `order` is a vestigial nullable column with no index, so sorting on it forces a full
# scan and sort of the project. `-last_modified_at` is covered by dashboarditem_team_lmod_idx.
# `-pk` breaks ties so paginated pages stay stable when timestamps collide.
return queryset.order_by("-last_modified_at", "-pk")
if order == "-last_viewed_at":
return queryset.order_by(F("last_viewed_at").desc(nulls_last=True))
if order == "last_viewed_at":
return queryset.order_by(F("last_viewed_at").asc(nulls_first=True))
return queryset.order_by(order)
@action(methods=["GET"], detail=False)
def my_last_viewed(self, request: request.Request, *args, **kwargs) -> Response:
"""
Returns basic details about the last 5 insights viewed by this user. Most recently viewed first.
"""
recently_viewed = recently_viewed_insights(team_id=self.team.pk, user_id=cast(User, request.user).pk, limit=5)
response = InsightBasicSerializer(recently_viewed, many=True)
return Response(data=response.data, status=status.HTTP_200_OK)
@extend_schema(
operation_id="insights_trending_retrieve",
filters=False,
parameters=[
OpenApiParameter(
name="days",
type=OpenApiTypes.INT,
location=OpenApiParameter.QUERY,
description=(
"Time window in days to compute view counts over. Defaults to 7. Larger windows surface "
"consistently popular insights; smaller windows surface what's hot right now."
),
required=False,
),
OpenApiParameter(
name="limit",
type=OpenApiTypes.INT,
location=OpenApiParameter.QUERY,
description="Maximum number of insights to return. Defaults to 10. Capped at 100.",
required=False,
),
INCLUDE_DASHBOARDS_PARAMETER,
],
responses={200: TrendingInsightSerializer(many=True)},
description=(
"Returns insights ranked by view count over the last N days (default 7), highest first. Each "
"result includes the same metadata as the standard insights list, plus a `view_count` and up to "
"3 recent `viewers`. Useful for surfacing the most-used insights in a project."
),
)
@action(methods=["GET"], detail=False, required_scopes=["insight:read"])
def trending(self, request: request.Request, *args, **kwargs) -> Response:
try:
days = int(request.GET.get("days", "7"))
limit = min(int(request.GET.get("limit", "10")), 100)
offset = int(request.GET.get("offset", "0"))
except (ValueError, TypeError):
raise ValidationError("days, limit and offset must be valid integers")
if limit <= 0 or offset < 0:
raise ValidationError("limit must be positive and offset must not be negative")
cutoff_date = now() - timedelta(days=days)
queryset = (
Insight.objects.filter(team__project_id=self.team.project_id)
.select_related("created_by", "last_modified_by", "team")
.annotate(
view_count=Count(
"insightviewed",
filter=Q(insightviewed__last_viewed_at__gte=cutoff_date),
)
)
.filter(view_count__gt=0)
.order_by("-view_count", "-last_modified_at", "-id")
)
queryset = self._filter_queryset_by_access_level(queryset)
# Fetch one extra row to know if a next page exists without a separate count query.
queryset = queryset[offset : offset + limit + 1]
queryset = queryset.annotate(last_viewed_at=Max("insightviewed__last_viewed_at"))
insights = list(queryset)
has_next = len(insights) > limit
insights = insights[:limit]
# Batch fetch viewers once to avoid N+1 queries
viewers_by_insight = recent_viewers_by_insight(
team_id=self.team.pk,
insight_ids=[insight.pk for insight in insights],
since=cutoff_date,
max_per_insight=3,
)
for insight in insights:
insight.viewers = viewers_by_insight.get(insight.pk, [])
data = TrendingInsightSerializer(insights, many=True, context=self.get_serializer_context()).data
# Wrap in the standard paginated envelope so the response shape matches the auto-generated
# OpenAPI schema (drf-spectacular wraps `many=True` responses as `Paginated*List` when the
# viewset has a paginator). This keeps the MCP-generated client and any other typed consumer
# happy. `count` is the size of this page, not the total.
page_url = request.build_absolute_uri()
next_url = (
replace_query_param(replace_query_param(page_url, "offset", offset + limit), "limit", limit)
if has_next
else None
)
previous_url = (
replace_query_param(replace_query_param(page_url, "offset", max(offset - limit, 0)), "limit", limit)
if offset > 0
else None
)
return Response({"count": len(data), "next": next_url, "previous": previous_url, "results": data})
@staticmethod
@tracer.start_as_current_span("InsightViewSet._apply_search")
def _apply_search(queryset: QuerySet, search: str) -> QuerySet:
return apply_trigram_search(
queryset,
search,
span_prefix="insight.search",
fields=(NAME_FIELD, TrigramSearchField("derived_name"), DESCRIPTION_FIELD),
include_tag_search=True,
tiebreakers=("name",),
)
def _filter_request(self, request: request.Request, queryset: QuerySet) -> QuerySet:
filters = request.GET.dict()
search_term: str | None = None
for key in filters:
if key == "saved":
if str_to_bool(request.GET["saved"]):
queryset = queryset.filter(Q(saved=True) | insight_has_listed_tile())
else:
queryset = queryset.filter(Q(saved=False))
elif key == "feature_flag":
feature_flag = request.GET["feature_flag"]
feature_flag_breakdown = f"$feature/{feature_flag}"
# Legacy insights store breakdown in `filters.breakdown` and reference
# the flag name in `filters.properties`. Query-based insights store
# breakdown config in the `query` JSON field (e.g. inside
# `breakdownFilter.breakdown`). The properties search uses the raw flag
# name because legacy filters reference it without the `$feature/` prefix.
queryset = queryset.filter(
Q(filters__breakdown__icontains=feature_flag_breakdown)
| Q(filters__properties__icontains=feature_flag)
| Q(query__icontains=feature_flag_breakdown)
)
elif key == "events":
events_filter = request.GET["events"]
events = json.loads(events_filter) if events_filter else []
for event in events:
queryset = queryset.filter(Q(query_metadata__events__contains=[event]))
elif key == "user":
queryset = queryset.filter(created_by=request.user)
elif key == "favorited":
queryset = queryset.filter(Q(favorited=True))
elif key == "exclude_bi":
if str_to_bool(request.GET["exclude_bi"]):
queryset = queryset.exclude(query__kind="BIVisualizationNode")
elif key == "hide_feature_flag_insights":
if str_to_bool(request.GET["hide_feature_flag_insights"]):
from posthog.helpers.dashboard_templates import feature_flag_generated_insight_q
queryset = queryset.exclude(feature_flag_generated_insight_q())
elif key == "date_from":
queryset = queryset.filter(
last_modified_at__gt=relative_date_parse(request.GET["date_from"], self.team.timezone_info)
)
elif key == "date_to":
queryset = queryset.filter(
last_modified_at__lt=relative_date_parse(request.GET["date_to"], self.team.timezone_info)
)
elif key == INSIGHT:
insight = request.GET[INSIGHT]
legacy_filter = Q(query__isnull=True) & Q(filters__insight=insight)
legacy_to_hogql_mapping = {
"TRENDS": schema.NodeKind.TRENDS_QUERY,
"FUNNELS": schema.NodeKind.FUNNELS_QUERY,
"RETENTION": schema.NodeKind.RETENTION_QUERY,
"PATHS": schema.NodeKind.PATHS_QUERY,
"JOURNEYS": schema.NodeKind.PATHS_V2_QUERY,
"STICKINESS": schema.NodeKind.STICKINESS_QUERY,
"LIFECYCLE": schema.NodeKind.LIFECYCLE_QUERY,
}
if insight == "BI":
queryset = queryset.filter(query__kind="BIVisualizationNode")
elif insight == "JSON":
queryset = queryset.filter(query__isnull=False)
queryset = queryset.exclude(query__kind__in=WRAPPER_NODE_KINDS, query__source__kind="HogQLQuery")
queryset = queryset.exclude(
query__kind__in=WRAPPER_NODE_KINDS, query__source__kind__in=legacy_to_hogql_mapping.values()
)
elif insight == "SQL":
queryset = queryset.filter(query__isnull=False)
queryset = queryset.filter(query__kind__in=WRAPPER_NODE_KINDS, query__source__kind="HogQLQuery")
elif insight in legacy_to_hogql_mapping:
queryset = queryset.filter(
legacy_filter
| Q(query__isnull=False)
& Q(query__kind=schema.NodeKind.INSIGHT_VIZ_NODE)
& Q(query__source__kind=legacy_to_hogql_mapping[insight])
)
else:
queryset = queryset.filter(legacy_filter)
elif key == "display":
queryset = queryset.filter(chart_display_filter(request.GET["display"]))
elif key == "search":
term = request.GET["search"]
if len(term) > MAX_SEARCH_LENGTH:
raise ValidationError({"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."})
search_term = term
elif key == "dashboards":
dashboards_filter = request.GET["dashboards"]
if dashboards_filter:
dashboards_ids = json.loads(dashboards_filter)
for dashboard_id in dashboards_ids:
# filter by dashboards one at a time so the filter is AND not OR
queryset = queryset.filter(id__in=insight_ids_on_dashboard(dashboard_id))
elif key == "tags":
tags_filter = request.GET["tags"]
if tags_filter:
tags_list = json.loads(tags_filter)
if tags_list:
# A semi-join returns one row per insight, so the list needs no
# `.distinct()` sort over the wide insight JSON columns.
matching_tags = TaggedItem.objects.matching_outer(Insight).filter(tag__name__in=tags_list)
queryset = queryset.filter(Exists(matching_tags))
elif key == "created_by":
created_by_filter = request.GET["created_by"]
if created_by_filter:
created_by_ids = json.loads(created_by_filter)
if created_by_ids:
queryset = queryset.filter(created_by__id__in=created_by_ids)
elif key == "created_date_from":
queryset = queryset.filter(
created_at__gt=relative_date_parse(request.GET["created_date_from"], self.team.timezone_info)
)
elif key == "created_date_to":
queryset = queryset.filter(
created_at__lt=relative_date_parse(request.GET["created_date_to"], self.team.timezone_info)
)
elif key == "last_viewed_date_from":
queryset = queryset.filter(
last_viewed_at__gt=relative_date_parse(
request.GET["last_viewed_date_from"], self.team.timezone_info
)
)
elif key == "last_viewed_date_to":
queryset = queryset.filter(
last_viewed_at__lt=relative_date_parse(request.GET["last_viewed_date_to"], self.team.timezone_info)
)
if search_term is not None:
queryset = self._apply_search(queryset, search_term)
return queryset
@extend_schema(
parameters=[
INSIGHT_ID_PATH_PARAMETER,
OpenApiParameter(
name="refresh",
enum=[*ExecutionMode],
default=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
# Sync the `refresh` description here with the other one in this file, and with frontend/src/queries/schema.ts
description="""
Whether to refresh the insight, how aggresively, and if sync or async:
- `'force_cache'` - return cached data or a cache miss; always completes immediately as it never calculates
- `'blocking'` - calculate synchronously (returning only when the query is done), UNLESS there are very fresh results in the cache
- `'async'` - kick off background calculation (returning immediately with a query status), UNLESS there are very fresh results in the cache
- `'lazy_async'` - kick off background calculation, UNLESS there are somewhat fresh results in the cache
- `'force_blocking'` - calculate synchronously, even if fresh results are already cached
- `'force_async'` - kick off background calculation, even if fresh results are already cached
Background calculation can be tracked using the `query_status` response field.""",
),
OpenApiParameter(
name="from_dashboard",
type=OpenApiTypes.INT,
description="""
Only if loading an insight in the context of a dashboard: The relevant dashboard's ID.
When set, the specified dashboard's filters and date range override will be applied.""",
),
make_variables_override_param(subject_label="the insight's HogQL", tool_name="insight-get"),
make_filters_override_param(subject_label="the insight's"),
],
)
@monitor(feature=Feature.INSIGHT, endpoint="insight", method="GET")
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer_context = self.get_serializer_context()
dashboard_tile: Any = None
dashboard_id = request.query_params.get("from_dashboard", None)
if dashboard_id is not None:
dashboard_tile = tile_for_insight_on_dashboard(insight_id=instance.id, dashboard_id=dashboard_id)
if dashboard_tile is not None:
authenticator = request.successful_authenticator
if isinstance(
authenticator,
SharingAccessTokenAuthentication | SharingPasswordProtectedAuthentication,
):
can_view_dashboard = authenticator.sharing_configuration.dashboard_id == dashboard_tile.dashboard_id
else:
can_view_dashboard = self.user_access_control.check_access_level_for_object(
dashboard_tile.dashboard, "viewer"
)
if not can_view_dashboard:
dashboard_tile = None
if dashboard_tile is not None:
# context is used in the to_representation method to report filters used
serializer_context.update(
{
"dashboard": dashboard_tile.dashboard,
"dashboard_access_method": dashboard_access_method(
request, is_shared=serializer_context["is_shared"]
),
"compute_surface": ComputeSurface.DASHBOARD_TILE,
}
)
try:
serialized_data = self.get_serializer(instance, context=serializer_context).data
except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:
raise ValidationError(str(e), getattr(e, "code_name", None))
if dashboard_tile is not None:
serialized_data["color"] = dashboard_tile.color
layouts = dashboard_tile.layouts
# workaround because DashboardTiles layouts were migrated as stringified JSON :/
if isinstance(layouts, str):
layouts = json.loads(layouts)
serialized_data["layouts"] = layouts
response = Response(serialized_data)
# Track non-web reads (API/MCP/wizard/…) as a distinct event so programmatic
# reads are measurable without inflating the web-only `insight viewed` metric.
if get_event_source(request) != EventSource.WEB:
report_user_action(
request.user,
"insight read",
# Sibling `insight created/updated/deleted` events store the short_id under `insight_id`;
# match that (plus query/source kind) so reads correlate with the rest of the lifecycle.
{"insight_id": instance.short_id, **instance.get_analytics_query_kinds()},
team=self.team,
request=request,
)
return response
@action(methods=["POST"], detail=False, required_scopes=["insight:write"])
def generate_metadata(self, request: Request, **kwargs) -> Response:
"""Generate an AI-suggested name and description for an insight based on its query configuration."""
self._validate_ai_feature_access()
query_data = request.data.get("query")
if not query_data:
raise ValidationError("Missing 'query' field in request body")
kind = query_data.get("kind")
try:
if kind == "ActorsQuery":
validated_query: (
schema.InsightVizNode | schema.ActorsQuery | schema.EventsQuery | schema.GroupsQuery
) = schema.ActorsQuery.model_validate(query_data)
elif kind == "EventsQuery":
validated_query = schema.EventsQuery.model_validate(query_data)
elif kind == "GroupsQuery":
validated_query = schema.GroupsQuery.model_validate(query_data)
else:
validated_query = schema.InsightVizNode.model_validate(query_data)
except Exception:
raise ValidationError("Invalid query format")
try:
metadata = generate_insight_metadata(validated_query, self.team)
except InsightMetadataTimeoutError as e:
capture_exception(e)
raise APIException("Generating a name took too long. Please try again.")
except Exception as e:
capture_exception(e)
raise APIException("Failed to generate insight metadata. Please try again.")
return Response({"name": metadata.name, "description": metadata.description})
# ******************************************
# /projects/:id/insights/viewed
# Creates or updates InsightViewed objects for the user/insight combo(s)
# Accepts an array of insight_ids
# ******************************************
@validated_request(
request_serializer=InsightViewedRequestSerializer,
responses={201: OpenApiResponse(description="Views recorded.")},
description=(
"Record that the current user has just viewed one or more insights. "
"Submitted ids that do not belong to the current project or that point at deleted insights "
"are silently dropped, as are views from impersonated staff-support sessions. "
"Returns 201 on success regardless of how many ids were retained."
),
)
@action(methods=["POST"], detail=False, required_scopes=["insight:read"])
def viewed(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
"""
Update insight view timestamps in bulk.
Expects: {"insight_ids": [1, 2, 3, ...]}
"""
# Views during staff impersonation aren't the team's own activity - skip the write
# so support sessions don't bump the team-facing "Last viewed" column.
if is_impersonated(request):
return Response(status=status.HTTP_201_CREATED)
insight_ids: list[int] = request.validated_data["insight_ids"]
visible_insight_ids = list(
Insight.objects.filter(
id__in=insight_ids,
team__project_id=self.team.project_id,
deleted=False,
).values_list("id", flat=True)
)
record_insight_views(
team_id=self.team.pk,
user_id=cast(User, request.user).pk,
last_viewed_at_by_insight_id=dict.fromkeys(visible_insight_ids, now()),
)
return Response(status=status.HTTP_201_CREATED)
@validated_request(
request_serializer=InsightDataChecksRequestSerializer,
responses={
200: OpenApiResponse(response=InsightDataChecksSerializer, description="The result of every check.")
},
description=(
"Check the events behind an insight for the common ways they mislead: internal and test users, local "
"development traffic, bots and crawlers, and events sent twice. Works for trends, funnels, stickiness "
"and lifecycle insights whose series are events. The checks apply the insight's own filters, and read "
"the newest days of its date range, up to 7. The bot and duplicate checks read a sample of those days. "
"For a token, the internal users check matches the emails of the organization's members only with the "
"`organization_member:read` scope, and its verified domains only with `organization:read`. It names the "
"emails it finds only with `person:read`. Nothing is stored. This route runs the query it is sent, so it needs query access as well as insight access. To "
"check a saved insight by its id, send a GET request to `insights/{id}/data_checks/`."
),
)
@action(methods=["POST"], detail=False, required_scopes=["insight:read", "query:read"])
def data_checks(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
# The scope covers a token. A session has no scopes, and a token's scope does not prove its owner has access.
if not self.user_access_control.check_access_level_for_resource("query", "viewer"):
raise PermissionDenied("You need query access to check a query that is not saved as an insight.")
if client_query_id := request.validated_data.get("client_query_id"):
tag_queries(client_query_id=client_query_id)
return self._data_checks_response(request.validated_data["query"], depth=request.validated_data["depth"])
@validated_request(
query_serializer=InsightDataChecksQueryParamsSerializer,
parameters=[INSIGHT_ID_PATH_PARAMETER],
responses={
200: OpenApiResponse(response=InsightDataChecksSerializer, description="The result of every check.")
},
description=(
"Run the data checks on a saved insight, found by its numeric id or its `short_id`. The checks read the "
"query the insight stores, and work the same way as the checks on a query that is not saved. The "
"`status` is `unsupported` for an insight that still stores legacy `filters` and no query. Nothing is "
"stored."
),
)
@action(methods=["GET"], detail=True, url_path="data_checks", required_scopes=["insight:read"])
def saved_insight_data_checks(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
insight = self.get_object()
return self._data_checks_response(
upgrade(insight.query) if insight.query else {},
depth=request.validated_query_data["depth"],
)
def _data_checks_response(self, query: dict[str, Any], *, depth: InsightDataChecksDepth) -> Response:
# A personal API key reads within the same hourly budget as the query API, and each check query debits it.
if get_query_tag_value("access_method") == AccessMethod.PERSONAL_API_KEY:
tag_queries(api_queries_budgeted=True)
enforce_api_queries_budget(self.team)
try:
with query_concurrency_slots(self.team):
checks = run_insight_data_checks(
query,
team=self.team,
user=cast(User, self.request.user),
email_access=self._team_email_access(),
depth=InsightDataChecksDepth(depth),
)
except CHQueryErrorQueryWasCancelled:
# The client cancelled the run, so nothing reads a body. 499 is Nginx's "Client Closed Request".
return Response(status=499)
except (ExposedHogQLError, ExposedCHQueryError, ResolutionError) as error:
raise ValidationError(str(error), getattr(error, "code_name", None))
return Response(InsightDataChecksSerializer(checks).data)
def _team_email_access(self) -> TeamEmailAccess:
# A session has no scopes. A token may only match the emails it could read through the organization's API,
# which rejects a token confined to some projects.
authenticator = self.request.successful_authenticator
scopes = get_authenticator_scopes(authenticator)
project_scoped = bool(get_authenticator_scoped_team_ids(authenticator))
def holds(scope: str) -> bool:
return scopes is None or "*" in scopes or not scopes_not_covered(scopes, [scope])
return TeamEmailAccess(
member_emails=not project_scoped and holds("organization_member:read"),
verified_domains=not project_scoped and holds("organization:read"),
person_emails=holds("person:read"),
)
def validate_bulk_tag_changes(self, objects: Sequence[Insight], tag_action: str, tags: builtins.list[str]) -> None:
editable_ids = insights_with_dashboard_edit_access(
[insight.id for insight in objects],
user_access_control=self.user_access_control,
project_id=self.team.project_id,
)
if any(insight.id not in editable_ids for insight in objects):
raise PermissionDenied(CanEditInsightDashboards.message)
super().validate_bulk_tag_changes(objects, tag_action, tags)
# `Sequence` rather than `list` here: this viewset defines a `list` method that shadows the builtin `list`
# in the class namespace, so `list[...]` in this signature breaks both at class-definition time and for mypy.
def _bulk_filter_editable_insights(
self, ids: Sequence[int], *, deleted: bool
) -> tuple[Sequence[Insight], Sequence[dict[str, Any]]]:
"""Resolve `ids` to insights in this project with the given `deleted` state, split into the ones
the requester may edit and `skipped` entries (not found, or missing edit permission)."""
# objects_including_soft_deleted so the restore path (deleted=True) can find soft-deleted insights;
# the default manager excludes them.
insights = list(
Insight.objects_including_soft_deleted.filter(
id__in=ids, team__project_id=self.team.project_id, deleted=deleted
).select_related("team")
)
found_ids = {insight.id for insight in insights}
skipped: list[dict[str, Any]] = [
{"id": missing_id, "reason": "Insight not found"} for missing_id in ids if missing_id not in found_ids
]
if not insights or not self.user_access_control:
return insights, skipped
self.user_access_control.preload_object_access_controls(cast(list, insights))
# Deletion hides the tiles used by normal edit checks. Tile restoration checks each dashboard separately.
dashboard_editable_ids = (
{insight.id for insight in insights}
if deleted
else insights_with_dashboard_edit_access(
[insight.id for insight in insights],
user_access_control=self.user_access_control,
project_id=self.team.project_id,
)
)
editable: list[Insight] = []
for insight in insights:
user_access_level = self.user_access_control.get_user_access_level(insight)
if (
insight.id in dashboard_editable_ids
and user_access_level
and access_level_satisfied_for_resource("insight", user_access_level, "editor")
):
editable.append(insight)
else:
skipped.append({"id": insight.id, "reason": "You don't have permission to edit this insight"})
return editable, skipped
@validated_request(
request_serializer=InsightBulkDeleteRequestSerializer,
responses={200: OpenApiResponse(response=InsightBulkDeleteResponseSerializer)},
description=(
"Soft-delete insights in bulk by ID. Mirrors the single-insight delete: sets deleted=True, "
"soft-deletes the insights' dashboard tiles, and removes their linked alerts. Insights the "
"requester cannot edit are skipped and reported in `skipped`. Reversible via the bulk_restore endpoint."
),
)
@action(methods=["POST"], detail=False, required_scopes=["insight:write"])
def bulk_delete(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
ids: list[int] = request.validated_data["ids"]
insights, skipped = self._bulk_filter_editable_insights(ids, deleted=False)
deleted: list[dict[str, Any]] = []
if insights:
current_user = cast(User, request.user)
was_impersonated = is_impersonated(request)
organization_id = current_user.current_organization_id
insight_ids = [insight.id for insight in insights]
with transaction.atomic():
Insight.objects_including_soft_deleted.filter(
id__in=insight_ids, team__project_id=self.team.project_id
).update(deleted=True, last_modified_at=now(), last_modified_by=current_user)
refs_by_team: dict[int, list[str]] = defaultdict(list)
teams = {}
for insight in insights:
teams[insight.team_id] = insight.team
refs_by_team[insight.team_id].append(insight.short_id)
for team_id, refs in refs_by_team.items():
delete_files(team=teams[team_id], file_type="insight", refs=refs)
# Match InsightSerializer.update: hide the insights' tiles and remove linked alerts.
hide_tiles_for_insights(insight_ids)
delete_insight_alerts(insight_ids)
delete_insight_subscriptions(project_id=self.team.project_id, insight_ids=insight_ids)
activity_log_entries: list[LogActivityEntry] = []
for insight in insights:
insight_name = insight.name or insight.derived_name
deleted.append({"id": insight.id, "name": insight_name})
# The experiments feature creates unnamed insights; the single-delete path skips logging those.
if insight_name:
activity_log_entries.append(
LogActivityEntry(
organization_id=organization_id,
team_id=self.team_id,
user=current_user,
was_impersonated=was_impersonated,
item_id=insight.id,
scope="Insight",
activity="deleted",
detail=Detail(name=insight_name, short_id=insight.short_id),
)
)
bulk_log_activity(activity_log_entries)
return Response({"deleted": deleted, "skipped": skipped})
@validated_request(
request_serializer=InsightBulkDeleteRequestSerializer,
responses={200: OpenApiResponse(response=InsightBulkRestoreResponseSerializer)},
description=(
"Restore soft-deleted insights in bulk by ID — the inverse of bulk_delete. Sets deleted=False and "
"re-activates the insights' dashboard tiles on dashboards that still exist. Linked alerts are not "
"restored (they are removed on delete). Insights the requester cannot edit are reported in `skipped`."
),
)
@action(methods=["POST"], detail=False, required_scopes=["insight:write"])
def bulk_restore(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
ids: list[int] = request.validated_data["ids"]
insights, skipped = self._bulk_filter_editable_insights(ids, deleted=True)
restored: list[dict[str, Any]] = []
if insights:
current_user = cast(User, request.user)
was_impersonated = is_impersonated(request)
organization_id = current_user.current_organization_id
insight_ids = [insight.id for insight in insights]
with transaction.atomic():
Insight.objects_including_soft_deleted.filter(
id__in=insight_ids, team__project_id=self.team.project_id
).update(deleted=False, last_modified_at=now(), last_modified_by=current_user)
restored_insights = Insight.objects.filter(
id__in=insight_ids, team__project_id=self.team.project_id
).select_related("team")
for insight in restored_insights:
insight.sync_file_system()
restore_tiles_for_insights(insight_ids, user_access_control=self.user_access_control)
activity_log_entries: list[LogActivityEntry] = []
for insight in insights:
insight_name = insight.name or insight.derived_name
restored.append({"id": insight.id, "name": insight_name})
if insight_name:
activity_log_entries.append(
LogActivityEntry(
organization_id=organization_id,
team_id=self.team_id,
user=current_user,
was_impersonated=was_impersonated,
item_id=insight.id,
scope="Insight",
activity="restored",
detail=Detail(name=insight_name, short_id=insight.short_id),
)
)
bulk_log_activity(activity_log_entries)
return Response({"restored": restored, "skipped": skipped})
@validated_request(
request_serializer=InsightBulkSetTestAccountFilterRequestSerializer,
responses={200: OpenApiResponse(response=InsightBulkSetTestAccountFilterResponseSerializer)},
description=(
"Turn 'filter out internal and test users' on or off for every existing insight in the project. "
"Requires project admin, matching the settings UI that fronts it. The setting of the same name only "
"decides the default for new insights; this applies it to the insights that already exist. Only "
"insights that store a query are changed; insights still holding legacy `filters` are counted in "
"`legacy` and left as they are. Insights with nowhere to put the toggle, such as SQL insights, are "
"left alone, as are insights the requester cannot edit. Dashboards follow their insights unless the "
"dashboard sets its own override. Insights are updated in batches, so a failure part way through "
"leaves the finished batches applied. Retrying is safe and picks up the rest."
),
)
@action(
methods=["POST"],
detail=False,
required_scopes=["insight:write"],
# Layered onto the viewset's chain rather than replacing it: `TeamAndOrgViewSetMixin.get_permissions`
# builds its own list and extends it with `self.permission_classes`, which is what this sets.
permission_classes=[TeamMemberStrictManagementPermission],
)
def bulk_set_test_account_filter(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
enabled: bool = request.validated_data["enabled"]
# Project-scoped to match `dangerously_get_queryset`, since insights are project-level even though they
# are served under /environments/. The per-insight access check below resolves rows team-scoped, which is
# equivalent today because team_id == project_id, and asymmetric only under the deprecated
# multi-team-per-project path being removed. Same trade-off as the feature flag bulk endpoint.
saved_insights = Insight.objects.filter(team__project_id=self.team.project_id, saved=True)
# Counted rather than silently dropped: the toggle lives in the query, so a run that leaves these
# behind has to say so instead of reporting that nothing needed changing.
legacy_count = saved_insights.filter(query__isnull=True).count()
totals = {"updated": 0, "unchanged": 0, "unsupported": 0, "skipped": 0, "legacy": legacy_count}
considered = legacy_count
# Keyset pagination, so each batch scans forward from the previous batch's last id rather than re-walking
# the index from the start, and no project's whole insight list has to sit in memory. The writes below
# never touch `id`, so the cursor can't skip or repeat a row.
cursor = 0
while True:
batch = list(
saved_insights.filter(query__isnull=False, id__gt=cursor).order_by("id")[
:INSIGHT_BULK_TEST_ACCOUNT_FILTER_BATCH_SIZE
]
)
if not batch:
break
cursor = batch[-1].id
considered += len(batch)
for key, count in self._set_test_account_filter_on_batch(batch, enabled=enabled).items():
totals[key] += count
# Reported even when nothing changed: a run that finds no insights to flip still tells us
# someone reached for this, and the no-op rate is the signal for whether it's discoverable.
report_user_action(
request.user,
"insights bulk test account filter set",
{
"enabled": enabled,
# Includes the legacy rows so the outcome counts still add up to what was considered.
"insights_considered": considered,
**{f"insights_{outcome}": count for outcome, count in totals.items()},
},
team=self.team,
request=request,
)
return Response(totals)
# Annotated as Sequence rather than list because this viewset defines a `list` action, which shadows the
# builtin inside the class body: `list[Insight]` here raises TypeError at import.
def _editable_insights(self, insights: Sequence[Insight]) -> tuple[Sequence[Insight], int]:
"""The insights from this batch the caller may edit, and how many were held back.
Access has to be resolved one insight at a time. `filter_queryset_by_access_level` answers whether an
insight is visible rather than whether it can be edited, so filtering in the query would let insights
the caller only has `viewer` on through to the write.
"""
if not self.user_access_control:
return insights, 0
self.user_access_control.preload_object_access_controls(cast(list, list(insights)))
editable = [
insight
for insight in insights
if (level := self.user_access_control.get_user_access_level(insight))
and access_level_satisfied_for_resource("insight", level, "editor")
]
return editable, len(insights) - len(editable)
def _set_test_account_filter_on_batch(self, insights: Sequence[Insight], *, enabled: bool) -> dict[str, int]:
editable, skipped = self._editable_insights(insights)
counts = {"updated": 0, "unchanged": 0, "unsupported": 0, "skipped": skipped}
current_user = cast(User, self.request.user)
was_impersonated = is_impersonated(self.request)
organization_id = current_user.current_organization_id
modified_at = now()
to_update: list[Insight] = []
activity_log_entries: list[LogActivityEntry] = []
for insight in editable:
update = plan_test_account_filter_update(insight.query, enabled=enabled)
if not update.supported:
counts["unsupported"] += 1
continue
if not update.changed:
counts["unchanged"] += 1
continue
change = Change(type="Insight", field="query", action="changed", before=insight.query, after=update.query)
insight.query = update.query
insight.last_modified_at = modified_at
insight.last_modified_by = current_user
to_update.append(insight)
counts["updated"] += 1
insight_name = insight.name or insight.derived_name
# The experiments feature creates unnamed insights; the single-update path skips logging those.
if insight_name:
activity_log_entries.append(
LogActivityEntry(
organization_id=organization_id,
team_id=self.team_id,
user=current_user,
was_impersonated=was_impersonated,
item_id=insight.id,
scope="Insight",
activity="updated",
detail=Detail(name=insight_name, short_id=insight.short_id, changes=[change]),
)
)
if to_update:
with transaction.atomic():
# `query_metadata` is derived from the query's entities, which this toggle doesn't touch, so it
# stays valid even though bulk_update skips the regeneration in `Insight.save`.
Insight.objects.bulk_update(to_update, ["query", "last_modified_at", "last_modified_by"])
bulk_log_activity(activity_log_entries)
return counts
@extend_schema(
operation_id="insights_all_activity_retrieve",
parameters=[
OpenApiParameter(
name="limit",
type=OpenApiTypes.INT,
location=OpenApiParameter.QUERY,
description="Page size. Defaults to 10.",
required=False,
),
OpenApiParameter(
name="page",
type=OpenApiTypes.INT,
location=OpenApiParameter.QUERY,
description="1-indexed page number. Defaults to 1.",
required=False,
),
],
responses={200: ActivityLogPaginatedResponseSerializer},
description=(
"Project-wide audit trail across all insights — who created, edited, deleted, or restored insights, "
"what changed (with before/after diffs), and when. Useful for surfacing what people (or agents) have "
"been working on recently."
),
)
@action(methods=["GET"], url_path="activity", detail=False, required_scopes=["activity_log:read"])
def all_activity(self, request: request.Request, **kwargs):
page_params = parse_activity_page_params(request)
activity_page = load_activity(
scope="Insight", team_id=self.team_id, limit=page_params.limit, page=page_params.page
)
return activity_page_response(activity_page, page_params.limit, page_params.page, request)
@extend_schema(
parameters=[
OpenApiParameter(
name="limit",
type=OpenApiTypes.INT,
location=OpenApiParameter.QUERY,
description="Page size. Defaults to 10.",
required=False,
),
OpenApiParameter(
name="page",
type=OpenApiTypes.INT,
location=OpenApiParameter.QUERY,
description="1-indexed page number. Defaults to 1.",
required=False,
),
],
responses={200: ActivityLogPaginatedResponseSerializer},
description=(
"Audit trail for a single insight — every change made to it, by whom, and when. Use this when you "
"want the change history of a specific insight; use the project-wide activity endpoint for a broader view."
),
)
@action(methods=["GET"], detail=True, required_scopes=["activity_log:read"])
def activity(self, request: request.Request, **kwargs):
page_params = parse_activity_page_params(request)
item = self.get_object()
activity_page = load_activity(
scope="Insight",
team_id=self.team_id,
item_ids=[str(item.id)],
limit=page_params.limit,
page=page_params.page,
)
return activity_page_response(activity_page, page_params.limit, page_params.page, request)
@action(methods=["POST"], detail=False)
@monitor(feature=Feature.INSIGHT, endpoint="insight", method="CANCEL")
def cancel(self, request: request.Request, **kwargs):
if "client_query_id" not in request.data:
raise serializers.ValidationError({"client_query_id": "Field is required."})
cancel_query_on_cluster(team_id=self.team.pk, client_query_id=request.data["client_query_id"])
return Response(status=status.HTTP_201_CREATED)
@extend_schema(exclude=True) # internal endpoint, not for public use
@action(methods=["POST"], detail=False)
def timing(self, request: request.Request, **kwargs):
from posthog.kafka_client.routing import get_producer
from posthog.models.event.util import format_clickhouse_timestamp
from posthog.utils import cast_timestamp_or_now
if CAPTURE_TIME_TO_SEE_DATA:
payload = {
**request.data,
"team_id": self.team_id,
"user_id": self.request.user.pk,
"timestamp": format_clickhouse_timestamp(cast_timestamp_or_now(None)),
}
if "min_last_refresh" in payload:
payload["min_last_refresh"] = format_clickhouse_timestamp(payload["min_last_refresh"])
if "max_last_refresh" in payload:
payload["max_last_refresh"] = format_clickhouse_timestamp(payload["max_last_refresh"])
get_producer(topic=KAFKA_METRICS_TIME_TO_SEE_DATA).produce(
topic=KAFKA_METRICS_TIME_TO_SEE_DATA, data=payload
)
return Response(status=status.HTTP_201_CREATED)