:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(heatmaps): rewrite element stats in HogQL to fix person filters (#68418)
Paul D'Ambra682044c77671
diff --git a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx b/frontend/src/scenes/heatmaps/components/FilterPanel.tsxindex cf815612d0c0..cfb56a16f2df 100644--- a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx+++ b/frontend/src/scenes/heatmaps/components/FilterPanel.tsx@@ -1,7 +1,14 @@import { useActions, useValues } from 'kea'import { useEffect, useState } from 'react'-import { IconGear, IconLaptop, IconPhone, IconTabletLandscape, IconTabletPortrait } from '@posthog/icons'+import {+ IconCursorClick,+ IconGear,+ IconLaptop,+ IconPhone,+ IconTabletLandscape,+ IconTabletPortrait,+} from '@posthog/icons'import { LemonBanner, LemonButton, LemonSegmentedButton, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'@@ -130,6 +137,7 @@ export function FilterPanel({onClickmapEnabledChange?: (enabled: boolean) => void}): JSX.Element {const [isSettingsOpen, setIsSettingsOpen] = useState(false)+ const [isClickmapSettingsOpen, setIsClickmapSettingsOpen] = useState(false)const {heatmapFilters,heatmapColorPalette,@@ -191,7 +199,7 @@ export function FilterPanel({<div className="mt-2 md:mt-0"><Popoveroverlay={- <div className="p-2">+ <div className="p-2 w-80"><HeatmapsSettingsheatmapFilters={heatmapFilters}patchHeatmapFilters={patchHeatmapFilters}@@ -223,34 +231,6 @@ export function FilterPanel({/></SectionSetting>)}- {clickmapEnabled !== undefined && onClickmapEnabledChange && (- <SectionSetting- title="Clickmap"- info="Overlay click counts on the elements users actually clicked"- >- <LemonSwitch- checked={clickmapEnabled}- onChange={onClickmapEnabledChange}- label="Show clickmap"- size="small"- />- </SectionSetting>- )}- <SectionSetting- title="Internal and test users filter"- info="Filter out internal and test users"- >- <TestAccountFilter- size="small"- filters={{ filter_test_accounts: commonFilters?.filter_test_accounts }}- onChange={(value) => {- setCommonFilters?.({- ...commonFilters,- filter_test_accounts: value.filter_test_accounts,- })- }}- />- </SectionSetting></div>}visible={isSettingsOpen}@@ -271,6 +251,53 @@ export function FilterPanel({</LemonButton></Popover></div>+ {clickmapEnabled !== undefined && onClickmapEnabledChange && (+ <div className="mt-2 md:mt-0">+ <Popover+ overlay={+ <div className="p-2 w-80 flex flex-col gap-2">+ <LemonSwitch+ checked={clickmapEnabled}+ onChange={onClickmapEnabledChange}+ label="Show clickmap"+ size="small"+ />+ <div className="text-xs text-muted">+ Overlay click counts on the elements users actually clicked.+ </div>+ </div>+ }+ visible={isClickmapSettingsOpen}+ onClickOutside={() => {+ setIsClickmapSettingsOpen(false)+ }}+ placement="bottom"+ >+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setIsClickmapSettingsOpen(!isClickmapSettingsOpen)}+ icon={<IconCursorClick />}+ tooltip="Clickmap settings"+ data-attr="clickmap-settings"+ >+ Clickmap settings+ </LemonButton>+ </Popover>+ </div>+ )}+ <div className="mt-2 md:mt-0">+ <TestAccountFilter+ size="small"+ filters={{ filter_test_accounts: commonFilters?.filter_test_accounts }}+ onChange={(value) => {+ setCommonFilters?.({+ ...commonFilters,+ filter_test_accounts: value.filter_test_accounts,+ })+ }}+ />+ </div></div><ViewportChooser /></div>diff --git a/posthog/api/element.py b/posthog/api/element.pyindex 137f8938f84e..ee2e2bf2f7d8 100644--- a/posthog/api/element.py+++ b/posthog/api/element.py@@ -1,3 +1,4 @@+from datetime import datetimefrom typing import Literalfrom django.conf import settings@@ -8,17 +9,22 @@ from prometheus_client import Histogramfrom rest_framework import request, response, serializers, viewsetsfrom rest_framework.exceptions import ValidationError-from posthog.schema import ProductKey+from posthog.schema import DateRange, ProductKey++from posthog.hogql import ast+from posthog.hogql.constants import MAX_SELECT_HEATMAPS_LIMIT, LimitContext+from posthog.hogql.parser import parse_select+from posthog.hogql.property import property_to_expr+from posthog.hogql.query import execute_hogql_queryfrom posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import ServerTimingsGathered, actionfrom posthog.clickhouse.client import sync_execute+from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models import Element, Filterfrom posthog.models.element.element import build_attributes_filter, chain_to_element_dicts-from posthog.models.element.sql import GET_ELEMENTS, GET_VALUES-from posthog.models.property.util import parse_prop_grouped_clauses-from posthog.queries.query_date_range import QueryDateRange+from posthog.models.element.sql import GET_VALUESfrom posthog.utils import format_query_params_absolute_urltracer = trace.get_tracer(__name__)@@ -125,40 +131,85 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):timer = ServerTimingsGathered()with timer("prepare_for_query"), tracer.start_as_current_span("elements_api_stats.prepare_for_query"):+ # Filter parses the properties param (including property groups) and folds the+ # team's test-account filters in when filter_test_accounts is setfilter = Filter(request=request, team=self.team)- date_params = {}- query_date_range = QueryDateRange(filter=filter, team=self.team, should_round=True)- date_from, date_from_params = query_date_range.date_from- date_to, date_to_params = query_date_range.date_to- date_params.update(date_from_params)- date_params.update(date_to_params)+ date_range = QueryDateRange(+ date_range=DateRange(+ date_from=request.query_params.get("date_from", "-7d"),+ date_to=request.query_params.get("date_to"),+ ),+ team=self.team,+ interval=None,+ now=datetime.now(),+ )+ # the stats UI only picks a day, never a time, so always query from+ # the start of the chosen day (QueryDateRange leaves an absolute+ # date_from untruncated, unlike the relative "-7d" default)+ query_date_from = date_range.date_from().replace(hour=0, minute=0, second=0, microsecond=0)try:limit = int(request.query_params.get("limit", settings.ELEMENT_STATS_DEFAULT_LIMIT))except ValueError:- raise ValidationError("Limit must be an integer")+ raise ValidationError("limit must be an integer")+ # keep the limit + 1 pagination probe below the printer's hard cap, so+ # has_next can still see the extra row instead of it being clamped away+ if not 0 < limit < MAX_SELECT_HEATMAPS_LIMIT:+ raise ValidationError(f"limit must be between 1 and {MAX_SELECT_HEATMAPS_LIMIT - 1}")try:offset = int(request.query_params.get("offset", 0))except ValueError:raise ValidationError("offset must be an integer")+ if offset < 0:+ raise ValidationError("offset must be zero or greater")try:sampling_factor = float(request.query_params.get("sampling_factor", 1))except ValueError:raise ValidationError("sampling_factor must be a float")+ # 0 would silently return no rows (SAMPLE 0); out-of-range values 500 in ClickHouse+ if not 0 < sampling_factor <= 1:+ raise ValidationError("sampling_factor must be greater than 0 and at most 1")events_filter = self._events_filter(request)attributes_filter = build_attributes_filter(request.query_params.get("data_attributes", "").split(","))- # unless someone is using this as an API client, this is only for the toolbar,- # which only ever queries date range, event type, and URL- prop_filters, prop_filter_params = parse_prop_grouped_clauses(- team_id=self.team.pk,- property_group=filter.property_groups,- hogql_context=filter.hogql_context,+ # HogQL resolves property access per the team's modifiers (materialized+ # columns, person-on-events mode), so no per-mode handling is needed here+ select = parse_select(+ """+ SELECT+ elements_chain,+ count() / {sampling_factor} AS occurrences,+ event AS event_type,+ cityHash64(elements_chain) AS chain_hash+ FROM events+ WHERE event IN {event_types}+ AND elements_chain != ''+ AND timestamp >= {date_from}+ AND timestamp <= {date_to}+ AND {property_filters}+ GROUP BY elements_chain, event+ ORDER BY occurrences DESC+ LIMIT {limit} OFFSET {offset}+ """,+ placeholders={+ "sampling_factor": ast.Constant(value=sampling_factor),+ "event_types": ast.Constant(value=list(events_filter)),+ "date_from": ast.Constant(value=query_date_from),+ "date_to": ast.Constant(value=date_range.date_to()),+ "property_filters": property_to_expr(filter.property_groups, team=self.team),+ "limit": ast.Constant(value=limit + 1),+ "offset": ast.Constant(value=offset),+ },)+ assert isinstance(select, ast.SelectQuery) and select.select_from is not None+ if sampling_factor != 1:+ select.select_from.sample = ast.SampleExpr(+ sample_value=ast.RatioExpr(left=ast.Constant(value=sampling_factor))+ )span.set_attribute("team_id", self.team.pk)span.set_attribute("limit", limit)@@ -167,25 +218,14 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):span.set_attribute("include_event_types", ",".join(sorted(events_filter)))with timer("execute_query"), tracer.start_as_current_span("elements_api_stats.execute_query"):- result = sync_execute(- GET_ELEMENTS.format(- date_from=date_from,- date_to=date_to,- query=prop_filters,- sampling_factor=sampling_factor,- limit=limit + 1,- offset=offset,- ),- {- "team_id": self.team.pk,- "timezone": self.team.timezone,- "sampling_factor": sampling_factor,- **prop_filter_params,- **date_params,- "filter_event_types": events_filter,- **filter.hogql_context.values,- },- )+ result = execute_hogql_query(+ query=select,+ team=self.team,+ query_type="elements_stats",+ # the toolbar paginates in pages of up to 50k, so limit + 1 must+ # survive above the default 50k query cap+ limit_context=LimitContext.HEATMAPS,+ ).resultswith timer("serialize_elements"), tracer.start_as_current_span("elements_api_stats.serialize_elements"):# parses chains straight to response dicts (shaped exactly likediff --git a/posthog/api/test/__snapshots__/test_element.ambr b/posthog/api/test/__snapshots__/test_element.ambrindex af14d876096c..3ec14179fbd9 100644--- a/posthog/api/test/__snapshots__/test_element.ambr+++ b/posthog/api/test/__snapshots__/test_element.ambr@@ -86,6 +86,271 @@LIMIT 21'''# ---+# name: TestElement.test_element_stats_postgres_queries_are_as_expected.10+ '''+ SELECT "posthog_externaldatasource"."created_by_id",+ "posthog_externaldatasource"."created_at",+ "posthog_externaldatasource"."updated_at",+ "posthog_externaldatasource"."deleted",+ "posthog_externaldatasource"."deleted_at",+ "posthog_externaldatasource"."id",+ "posthog_externaldatasource"."source_id",+ "posthog_externaldatasource"."connection_id",+ "posthog_externaldatasource"."destination_id",+ "posthog_externaldatasource"."team_id",+ "posthog_externaldatasource"."sync_frequency",+ "posthog_externaldatasource"."status",+ "posthog_externaldatasource"."source_type",+ "posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."connection_metadata",+ "posthog_externaldatasource"."are_tables_created",+ "posthog_externaldatasource"."prefix",+ "posthog_externaldatasource"."description",+ "posthog_externaldatasource"."created_via",+ "posthog_externaldatasource"."access_method",+ "posthog_externaldatasource"."direct_query_enabled",+ "posthog_externaldatasource"."revenue_analytics_enabled",+ "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id",+ "posthog_externaldatasourcerevenueanalyticsconfig"."enabled",+ "posthog_externaldatasourcerevenueanalyticsconfig"."include_invoiceless_charges"+ FROM "posthog_externaldatasource"+ LEFT OUTER JOIN "posthog_externaldatasourcerevenueanalyticsconfig" ON ("posthog_externaldatasource"."id" = "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id")+ WHERE ("posthog_externaldatasource"."source_type" IN ('Stripe')+ AND "posthog_externaldatasource"."team_id" = 99999+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL))+ '''+# ---+# name: TestElement.test_element_stats_postgres_queries_are_as_expected.11+ '''+ SELECT "posthog_datawarehousetable"."created_by_id",+ "posthog_datawarehousetable"."created_at",+ "posthog_datawarehousetable"."updated_at",+ "posthog_datawarehousetable"."deleted",+ "posthog_datawarehousetable"."deleted_at",+ "posthog_datawarehousetable"."id",+ "posthog_datawarehousetable"."name",+ "posthog_datawarehousetable"."format",+ "posthog_datawarehousetable"."team_id",+ "posthog_datawarehousetable"."url_pattern",+ "posthog_datawarehousetable"."queryable_folder",+ "posthog_datawarehousetable"."credential_id",+ "posthog_datawarehousetable"."external_data_source_id",+ "posthog_datawarehousetable"."columns",+ "posthog_datawarehousetable"."options",+ "posthog_datawarehousetable"."row_count",+ "posthog_datawarehousetable"."size_in_s3_mib",+ "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_password_reset_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in"+ FROM "posthog_datawarehousetable"+ LEFT OUTER JOIN "posthog_externaldatasource" ON ("posthog_datawarehousetable"."external_data_source_id" = "posthog_externaldatasource"."id")+ LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousetable"."created_by_id" = "posthog_user"."id")+ WHERE ("posthog_datawarehousetable"."team_id" = 99999+ AND NOT ("posthog_datawarehousetable"."deleted"+ AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."access_method" = 'direct'+ AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC+ '''+# ---+# name: TestElement.test_element_stats_postgres_queries_are_as_expected.12+ '''+ SELECT "posthog_datawarehousejoin"."created_by_id",+ "posthog_datawarehousejoin"."created_at",+ "posthog_datawarehousejoin"."deleted",+ "posthog_datawarehousejoin"."deleted_at",+ "posthog_datawarehousejoin"."id",+ "posthog_datawarehousejoin"."team_id",+ "posthog_datawarehousejoin"."source_table_name",+ "posthog_datawarehousejoin"."source_table_key",+ "posthog_datawarehousejoin"."joining_table_name",+ "posthog_datawarehousejoin"."joining_table_key",+ "posthog_datawarehousejoin"."field_name",+ "posthog_datawarehousejoin"."configuration"+ FROM "posthog_datawarehousejoin"+ WHERE ("posthog_datawarehousejoin"."team_id" = 99999+ AND NOT ("posthog_datawarehousejoin"."deleted"+ AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))+ '''+# ---+# name: TestElement.test_element_stats_postgres_queries_are_as_expected.13+ '''+ SELECT "posthog_team"."id",+ "posthog_team"."uuid",+ "posthog_team"."organization_id",+ "posthog_team"."parent_team_id",+ "posthog_team"."project_id",+ "posthog_team"."api_token",+ "posthog_team"."app_urls",+ "posthog_team"."name",+ "posthog_team"."slack_incoming_webhook",+ "posthog_team"."created_at",+ "posthog_team"."updated_at",+ "posthog_team"."anonymize_ips",+ "posthog_team"."completed_snippet_onboarding",+ "posthog_team"."has_completed_onboarding_for",+ "posthog_team"."onboarding_tasks",+ "posthog_team"."ingested_event",+ "posthog_team"."ingested_production_event",+ "posthog_team"."ingested_production_event_last_checked_at",+ "posthog_team"."person_processing_opt_out",+ "posthog_team"."secret_api_token",+ "posthog_team"."secret_api_token_backup",+ "posthog_team"."session_recording_opt_in",+ "posthog_team"."session_recording_sample_rate",+ "posthog_team"."session_recording_minimum_duration_milliseconds",+ "posthog_team"."session_recording_linked_flag",+ "posthog_team"."session_recording_network_payload_capture_config",+ "posthog_team"."session_recording_masking_config",+ "posthog_team"."session_recording_url_trigger_config",+ "posthog_team"."session_recording_url_blocklist_config",+ "posthog_team"."session_recording_event_trigger_config",+ "posthog_team"."session_recording_trigger_match_type_config",+ "posthog_team"."session_recording_trigger_groups",+ "posthog_team"."session_replay_config",+ "posthog_team"."session_recording_retention_period",+ "posthog_team"."event_retention_months",+ "posthog_team"."conversations_enabled",+ "posthog_team"."conversations_settings",+ "posthog_team"."proactive_tasks_enabled",+ "posthog_team"."survey_config",+ "posthog_team"."surveys_opt_in",+ "posthog_team"."product_tours_opt_in",+ "posthog_team"."capture_console_log_opt_in",+ "posthog_team"."capture_performance_opt_in",+ "posthog_team"."capture_dead_clicks",+ "posthog_team"."autocapture_opt_out",+ "posthog_team"."autocapture_web_vitals_opt_in",+ "posthog_team"."autocapture_web_vitals_allowed_metrics",+ "posthog_team"."autocapture_exceptions_opt_in",+ "posthog_team"."autocapture_exceptions_errors_to_ignore",+ "posthog_team"."logs_settings",+ "posthog_team"."llm_gateway_enabled_at",+ "posthog_team"."llm_gateway_revoked_at",+ "posthog_team"."llm_gateway_overspend_allowance_usd",+ "posthog_team"."heatmaps_opt_in",+ "posthog_team"."receive_org_level_activity_logs",+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",+ "posthog_team"."web_analytics_pre_aggregated_tables_version",+ "posthog_team"."flags_persistence_default",+ "posthog_team"."feature_flag_confirmation_enabled",+ "posthog_team"."feature_flag_confirmation_message",+ "posthog_team"."default_evaluation_environments_enabled",+ "posthog_team"."require_evaluation_environment_tags",+ "posthog_team"."default_evaluation_contexts_enabled",+ "posthog_team"."require_evaluation_contexts",+ "posthog_team"."session_recording_version",+ "posthog_team"."signup_token",+ "posthog_team"."is_demo",+ "posthog_team"."access_control",+ "posthog_team"."week_start_day",+ "posthog_team"."inject_web_apps",+ "posthog_team"."test_account_filters",+ "posthog_team"."test_account_filters_default_checked",+ "posthog_team"."path_cleaning_filters",+ "posthog_team"."timezone",+ "posthog_team"."data_attributes",+ "posthog_team"."person_display_name_properties",+ "posthog_team"."live_events_columns",+ "posthog_team"."recording_domains",+ "posthog_team"."human_friendly_comparison_periods",+ "posthog_team"."cookieless_server_hash_mode",+ "posthog_team"."primary_dashboard_id",+ "posthog_team"."default_data_theme",+ "posthog_team"."extra_settings",+ "posthog_team"."modifiers",+ "posthog_team"."correlation_config",+ "posthog_team"."session_recording_retention_period_days",+ "posthog_team"."external_data_workspace_id",+ "posthog_team"."external_data_workspace_last_synced_at",+ "posthog_team"."api_query_rate_limit",+ "posthog_team"."drop_events_older_than",+ "posthog_team"."base_currency",+ "posthog_team"."experiment_recalculation_time",+ "posthog_team"."default_experiment_confidence_level",+ "posthog_team"."default_experiment_stats_method",+ "posthog_team"."business_model",+ "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_team"+ INNER JOIN "posthog_organization" ON ("posthog_team"."organization_id" = "posthog_organization"."id")+ WHERE "posthog_team"."id" = 99999+ ORDER BY "posthog_team"."id" ASC+ LIMIT 1+ '''+# ---# name: TestElement.test_element_stats_postgres_queries_are_as_expected.2'''SELECT "posthog_team"."id",@@ -354,3 +619,204 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ---+# name: TestElement.test_element_stats_postgres_queries_are_as_expected.7+ '''+ SELECT "posthog_datawarehousesavedquery"."created_by_id",+ "posthog_datawarehousesavedquery"."created_at",+ "posthog_datawarehousesavedquery"."updated_at",+ "posthog_datawarehousesavedquery"."deleted",+ "posthog_datawarehousesavedquery"."deleted_at",+ "posthog_datawarehousesavedquery"."id",+ "posthog_datawarehousesavedquery"."name",+ "posthog_datawarehousesavedquery"."team_id",+ "posthog_datawarehousesavedquery"."latest_error",+ "posthog_datawarehousesavedquery"."columns",+ "posthog_datawarehousesavedquery"."external_tables",+ "posthog_datawarehousesavedquery"."query",+ "posthog_datawarehousesavedquery"."status",+ "posthog_datawarehousesavedquery"."last_run_at",+ "posthog_datawarehousesavedquery"."sync_frequency_interval",+ "posthog_datawarehousesavedquery"."table_id",+ "posthog_datawarehousesavedquery"."is_materialized",+ "posthog_datawarehousesavedquery"."deleted_name",+ "posthog_datawarehousesavedquery"."managed_viewset_id",+ "posthog_datawarehousesavedquery"."folder_id",+ "posthog_datawarehousesavedquery"."origin",+ "posthog_datawarehousesavedquery"."is_test",+ "posthog_datawarehousesavedquery"."expires_at",+ "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_password_reset_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in",+ "posthog_datawarehousetable"."created_by_id",+ "posthog_datawarehousetable"."created_at",+ "posthog_datawarehousetable"."updated_at",+ "posthog_datawarehousetable"."deleted",+ "posthog_datawarehousetable"."deleted_at",+ "posthog_datawarehousetable"."id",+ "posthog_datawarehousetable"."name",+ "posthog_datawarehousetable"."format",+ "posthog_datawarehousetable"."team_id",+ "posthog_datawarehousetable"."url_pattern",+ "posthog_datawarehousetable"."queryable_folder",+ "posthog_datawarehousetable"."credential_id",+ "posthog_datawarehousetable"."external_data_source_id",+ "posthog_datawarehousetable"."columns",+ "posthog_datawarehousetable"."options",+ "posthog_datawarehousetable"."row_count",+ "posthog_datawarehousetable"."size_in_s3_mib",+ "posthog_datawarehousemanagedviewset"."created_by_id",+ "posthog_datawarehousemanagedviewset"."created_at",+ "posthog_datawarehousemanagedviewset"."updated_at",+ "posthog_datawarehousemanagedviewset"."id",+ "posthog_datawarehousemanagedviewset"."team_id",+ "posthog_datawarehousemanagedviewset"."kind"+ FROM "posthog_datawarehousesavedquery"+ LEFT OUTER JOIN "posthog_datawarehousemanagedviewset" ON ("posthog_datawarehousesavedquery"."managed_viewset_id" = "posthog_datawarehousemanagedviewset"."id")+ LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousesavedquery"."created_by_id" = "posthog_user"."id")+ LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")+ WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999+ AND NOT ("posthog_datawarehousesavedquery"."deleted"+ AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL)+ AND "posthog_datawarehousesavedquery"."managed_viewset_id" IS NULL)+ ORDER BY "posthog_datawarehousesavedquery"."name" ASC+ '''+# ---+# name: TestElement.test_element_stats_postgres_queries_are_as_expected.8+ '''+ SELECT "posthog_datawarehousesavedquery"."created_by_id",+ "posthog_datawarehousesavedquery"."created_at",+ "posthog_datawarehousesavedquery"."updated_at",+ "posthog_datawarehousesavedquery"."deleted",+ "posthog_datawarehousesavedquery"."deleted_at",+ "posthog_datawarehousesavedquery"."id",+ "posthog_datawarehousesavedquery"."name",+ "posthog_datawarehousesavedquery"."team_id",+ "posthog_datawarehousesavedquery"."latest_error",+ "posthog_datawarehousesavedquery"."columns",+ "posthog_datawarehousesavedquery"."external_tables",+ "posthog_datawarehousesavedquery"."query",+ "posthog_datawarehousesavedquery"."status",+ "posthog_datawarehousesavedquery"."last_run_at",+ "posthog_datawarehousesavedquery"."sync_frequency_interval",+ "posthog_datawarehousesavedquery"."table_id",+ "posthog_datawarehousesavedquery"."is_materialized",+ "posthog_datawarehousesavedquery"."deleted_name",+ "posthog_datawarehousesavedquery"."managed_viewset_id",+ "posthog_datawarehousesavedquery"."folder_id",+ "posthog_datawarehousesavedquery"."origin",+ "posthog_datawarehousesavedquery"."is_test",+ "posthog_datawarehousesavedquery"."expires_at",+ "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_password_reset_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in",+ "posthog_datawarehousetable"."created_by_id",+ "posthog_datawarehousetable"."created_at",+ "posthog_datawarehousetable"."updated_at",+ "posthog_datawarehousetable"."deleted",+ "posthog_datawarehousetable"."deleted_at",+ "posthog_datawarehousetable"."id",+ "posthog_datawarehousetable"."name",+ "posthog_datawarehousetable"."format",+ "posthog_datawarehousetable"."team_id",+ "posthog_datawarehousetable"."url_pattern",+ "posthog_datawarehousetable"."queryable_folder",+ "posthog_datawarehousetable"."credential_id",+ "posthog_datawarehousetable"."external_data_source_id",+ "posthog_datawarehousetable"."columns",+ "posthog_datawarehousetable"."options",+ "posthog_datawarehousetable"."row_count",+ "posthog_datawarehousetable"."size_in_s3_mib"+ FROM "posthog_datawarehousesavedquery"+ LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousesavedquery"."created_by_id" = "posthog_user"."id")+ LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")+ WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999+ AND "posthog_datawarehousesavedquery"."origin" = 'endpoint'+ AND NOT ("posthog_datawarehousesavedquery"."deleted"+ AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))+ '''+# ---+# name: TestElement.test_element_stats_postgres_queries_are_as_expected.9+ '''+ SELECT "posthog_teamrevenueanalyticsconfig"."team_id",+ "posthog_teamrevenueanalyticsconfig"."filter_test_accounts",+ "posthog_teamrevenueanalyticsconfig"."notified_first_sync",+ "posthog_teamrevenueanalyticsconfig"."events",+ "posthog_teamrevenueanalyticsconfig"."goals",+ "posthog_teamrevenueanalyticsconfig"."base_currency"+ FROM "posthog_teamrevenueanalyticsconfig"+ WHERE "posthog_teamrevenueanalyticsconfig"."team_id" = 99999+ LIMIT 21+ '''+# ---diff --git a/posthog/api/test/test_element.py b/posthog/api/test/test_element.pyindex b12809c02470..cc4b4a4602f8 100644--- a/posthog/api/test/test_element.py+++ b/posthog/api/test/test_element.py@@ -167,6 +167,22 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):response = self.client.get(f"/api/element/stats/?paginate_response=true&properties={properties_filter}").json()self.assertEqual(len(response["results"]), 1)+ @parameterized.expand([(False, False), (True, False), (True, True)])+ def test_element_stats_can_filter_by_person_properties(self, person_on_events: bool, poe_v2: bool) -> None:+ with override_settings(PERSON_ON_EVENTS_OVERRIDE=person_on_events, PERSON_ON_EVENTS_V2_OVERRIDE=poe_v2):+ self._setup_events()++ properties_filter = json.dumps(+ [{"key": "email", "value": "[email protected]", "operator": "exact", "type": "person"}]+ )+ response = self.client.get(+ f"/api/element/stats/?paginate_response=true&properties={properties_filter}"+ ).json()++ assert len(response["results"]) == 1+ assert response["results"][0]["elements"][0]["href"] == "https://posthog.com/event-2"+ assert response["results"][0]["count"] == 1+def test_element_stats_can_filter_by_hogql(self) -> None:self._setup_events()properties_filter = json.dumps(@@ -344,16 +360,22 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):rageclick_event_1 = next(row for row in first if row["type"] == "$rageclick")assert autocapture_event_1["hash"] == rageclick_event_1["hash"]- def test_element_stats_does_not_allow_non_numeric_limit(self) -> None:- response = self.client.get(f"/api/element/stats/?limit=not-a-number")- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-- def test_element_stats_does_not_allow_non_numeric_offset(self) -> None:- response = self.client.get(f"/api/element/stats/?limit=not-a-number")- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-- def test_element_stats_does_not_allow_unexepcted_include(self) -> None:- response = self.client.get(f"/api/element/stats/?include=$autocapture&include=$rageclick&include=$pageview")+ @parameterized.expand(+ [+ ("non_numeric_limit", "limit=not-a-number"),+ ("non_numeric_offset", "offset=not-a-number"),+ ("unexpected_include", "include=$autocapture&include=$rageclick&include=$pageview"),+ ("zero_limit", "limit=0"),+ ("negative_limit", "limit=-1"),+ ("limit_at_printer_cap", "limit=1000000"),+ ("negative_offset", "offset=-1"),+ ("zero_sampling_factor", "sampling_factor=0"),+ ("sampling_factor_above_one", "sampling_factor=1.5"),+ ("negative_sampling_factor", "sampling_factor=-0.5"),+ ]+ )+ def test_element_stats_rejects_invalid_query_params(self, _name: str, query: str) -> None:+ response = self.client.get(f"/api/element/stats/?{query}")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)def _setup_events(self):diff --git a/posthog/models/element/sql.py b/posthog/models/element/sql.pyindex 518c96a95dd7..70c43fa74bfe 100644--- a/posthog/models/element/sql.py+++ b/posthog/models/element/sql.py@@ -1,20 +1,3 @@-GET_ELEMENTS = """-SELECT- elements_chain, count() / %(sampling_factor)s as count, event as event_type, cityHash64(elements_chain) as chain_hash-FROM events-SAMPLE %(sampling_factor)s-WHERE- team_id = %(team_id)s AND- event in %(filter_event_types)s AND- elements_chain != ''- {date_from}- {date_to}- {query}-GROUP BY elements_chain, event-ORDER BY count DESC-LIMIT {limit} OFFSET {offset};-"""-GET_VALUES = """SELECTextract(elements_chain, %(regex)s) as value, count(1) as count