Skip to content

: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.

feat(insights): add an internal users check to the insight data checks (#118700)

Sam Penningtonf76cb382f7e7
diff --git a/products/product_analytics/backend/chart_events.py b/products/product_analytics/backend/chart_events.py
index 1d4b9467137a..122cd2e2b7ac 100644
--- a/products/product_analytics/backend/chart_events.py
+++ b/products/product_analytics/backend/chart_events.py
@@ -61,14 +61,12 @@ class ChartEvents:
query: str,
*,
where: ast.Expr,
- prewhere: ast.Expr | None = None,
sample: ast.SampleExpr | None = None,
**placeholders: ast.Expr,
) -> ast.SelectQuery:
"""`query`, a select from the events table, set to read these events with `where`."""
select = cast(ast.SelectQuery, parse_select(query, placeholders=placeholders))
select.select_from = ast.JoinExpr(table=ast.Field(chain=["events"]), alias=self.alias, sample=sample)
- select.prewhere = prewhere
select.where = where
return select
diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.py
index fdcdec9e5260..06eb92558b55 100644
--- a/products/product_analytics/backend/facade/contracts.py
+++ b/products/product_analytics/backend/facade/contracts.py
@@ -108,6 +108,13 @@ class InsightDataChecks:
coverage: InsightDataChecksCoverage | None
+@dataclass(frozen=True)
+class TeamEmailAccess:
+ # A match reveals that an email belongs to the team, so each source needs the caller to be allowed to read it.
+ member_emails: bool
+ verified_domains: bool
+
+
@dataclass(frozen=True)
class InsightSeries:
short_id: str
diff --git a/products/product_analytics/backend/facade/data_checks.py b/products/product_analytics/backend/facade/data_checks.py
index 746fa1e4f812..1166081c5978 100644
--- a/products/product_analytics/backend/facade/data_checks.py
+++ b/products/product_analytics/backend/facade/data_checks.py
@@ -12,12 +12,15 @@ from posthog.models.team import Team
from posthog.models.user import User
from products.product_analytics.backend import insight_data_checks
-from products.product_analytics.backend.facade.contracts import InsightDataChecks
+from products.product_analytics.backend.facade.contracts import InsightDataChecks, TeamEmailAccess
-def run_insight_data_checks(query: Mapping[str, Any], *, team: Team, user: User) -> InsightDataChecks:
- """Check the events an insight query reads for local traffic, bots and events sent twice.
+def run_insight_data_checks(
+ query: Mapping[str, Any], *, team: Team, user: User, email_access: TeamEmailAccess
+) -> InsightDataChecks:
+ """Check the events an insight query reads for internal users, local traffic, bots and events sent twice.
The checks read the events as `user`. They do not run when a property they read is hidden from that person.
+ The internal users check matches only the member emails and verified domains that `email_access` allows.
"""
- return insight_data_checks.run_insight_data_checks(query, team, user)
+ return insight_data_checks.run_insight_data_checks(query, team, user, email_access=email_access)
diff --git a/products/product_analytics/backend/facade/enums.py b/products/product_analytics/backend/facade/enums.py
index d9c4e9665203..b5f195b37d35 100644
--- a/products/product_analytics/backend/facade/enums.py
+++ b/products/product_analytics/backend/facade/enums.py
@@ -18,6 +18,7 @@ class InsightVariableType(LabeledStrEnum):
class InsightDataCheckKey(LabeledStrEnum):
+ INTERNAL_USERS = "internal_users", "Internal and test users"
LOCAL_DEVELOPMENT = "local_development", "Local development events"
BOT_TRAFFIC = "bot_traffic", "Bot and crawler traffic"
DUPLICATE_EVENTS = "duplicate_events", "Events sent twice"
@@ -42,9 +43,12 @@ class InsightDataCheckSkipReason(LabeledStrEnum):
MEMORY_LIMIT = "memory_limit", "The check needed more memory than it is allowed"
TOO_FEW_SAMPLED_EVENTS = "too_few_sampled_events", "The sample has too few events to give a share"
FILTERED_BY_TRAFFIC_TYPE = "filtered_by_traffic_type", "The insight already filters on traffic type"
+ HIDDEN_PROPERTY = "hidden_property", "A property the check reads is hidden from you"
+ INVALID_FILTER = "invalid_filter", "The project's internal and test users filter cannot run"
class InsightDataCheckAction(LabeledStrEnum):
+ FILTER_INTERNAL_USERS = "filter_internal_users", "Turn on the internal and test users filter for the insight"
OPEN_FILTER_SETTINGS = "open_filter_settings", "Change the project's internal and test users filter"
diff --git a/products/product_analytics/backend/insight_data_check_results.py b/products/product_analytics/backend/insight_data_check_results.py
index 2cbc428d900a..c9fbbde6fde9 100644
--- a/products/product_analytics/backend/insight_data_check_results.py
+++ b/products/product_analytics/backend/insight_data_check_results.py
@@ -33,6 +33,27 @@ class LocalEvents:
top_events: list[str]
+@frozen
+class InternalEvents:
+ # Events the project's internal and test users filter removes, when the insight does not apply that filter.
+ removed_by_filter: int
+ # Events from the team's own emails or test accounts that the filter keeps.
+ missed_by_filter: int
+ top_events: list[str]
+
+ @property
+ def count(self) -> int:
+ return self.removed_by_filter + self.missed_by_filter
+
+
+@frozen
+class CountedEvents:
+ # Every event the insight reads on the days checked, so a counted check needs no sample for its share.
+ events: int
+ local: LocalEvents
+ internal: InternalEvents | Skipped
+
+
@frozen
class SampledEvents:
rate: float
@@ -51,7 +72,7 @@ class SampledEvents:
@frozen
class CheckedEvents:
- local: LocalEvents | Skipped
+ counted: CountedEvents | Skipped
sample: SampledEvents | Skipped
insight_filters_traffic_type: bool = False
@@ -74,23 +95,48 @@ def _usable_sample(sample: SampledEvents | Skipped) -> SampledEvents | Skipped:
return sample
-def _local_share(local_events: int, sample: SampledEvents | Skipped) -> float | None:
- """The share of local events, or None when the sample is too small to estimate the events checked."""
- usable = _usable_sample(sample)
- if isinstance(usable, Skipped):
- return None
- # The local count is exact and the sample is an estimate, so the share is capped at all of the events.
- events_checked = max(usable.events / usable.rate, local_events)
- return local_events / events_checked
+def _share(count: int, events: int) -> float | None:
+ return count / events if events else None
+
+
+def _is_finding(count: int, events: int) -> bool:
+ return count >= MIN_FINDING_EVENTS and count >= MIN_FINDING_SHARE * events
+
+
+def _internal_users_check(checked: CheckedEvents) -> InsightDataCheck:
+ key = InsightDataCheckKey.INTERNAL_USERS
+ counted = checked.counted
+ if isinstance(counted, Skipped):
+ return not_checked(key, counted.reason)
+ internal = counted.internal
+ if isinstance(internal, Skipped):
+ return not_checked(key, internal.reason)
+
+ share = _share(internal.count, counted.events)
+ is_finding = _is_finding(internal.count, counted.events)
+ # Turning the filter on for the insight is enough, unless the filter keeps the team's own emails.
+ action = InsightDataCheckAction.FILTER_INTERNAL_USERS
+ if _is_finding(internal.missed_by_filter, counted.events):
+ action = InsightDataCheckAction.OPEN_FILTER_SETTINGS
+ return InsightDataCheck(
+ key=key,
+ level=_finding_level(share) if is_finding else InsightDataCheckLevel.PASSED,
+ method=InsightDataCheckMethod.COUNTED,
+ events=internal.count,
+ share=share,
+ action=action if is_finding else None,
+ top_events=internal.top_events,
+ )
def _local_development_check(checked: CheckedEvents) -> InsightDataCheck:
key = InsightDataCheckKey.LOCAL_DEVELOPMENT
- local = checked.local
- if isinstance(local, Skipped):
- return not_checked(key, local.reason)
+ counted = checked.counted
+ if isinstance(counted, Skipped):
+ return not_checked(key, counted.reason)
- share = _local_share(local.count, checked.sample)
+ local = counted.local
+ share = _share(local.count, counted.events)
# No minimum share: a local session also creates test persons and flag exposures, whatever its share.
is_finding = local.count >= MIN_FINDING_EVENTS
return InsightDataCheck(
@@ -152,6 +198,8 @@ def _duplicate_events_check(checked: CheckedEvents) -> InsightDataCheck:
def found_no_events(checked: CheckedEvents) -> bool:
+ if isinstance(checked.counted, CountedEvents):
+ return checked.counted.events == 0
sample = checked.sample
return isinstance(sample, SampledEvents) and sample.read_every_event and sample.events == 0
@@ -159,6 +207,7 @@ def found_no_events(checked: CheckedEvents) -> bool:
def evaluate_data_checks(checked: CheckedEvents) -> list[InsightDataCheck]:
"""Every check, in a fixed order, so the list shows what was checked whatever the result."""
return [
+ _internal_users_check(checked),
_local_development_check(checked),
_bot_traffic_check(checked),
_duplicate_events_check(checked),
diff --git a/products/product_analytics/backend/insight_data_check_team_emails.py b/products/product_analytics/backend/insight_data_check_team_emails.py
new file mode 100644
index 000000000000..3e12ffaebd28
--- /dev/null
+++ b/products/product_analytics/backend/insight_data_check_team_emails.py
@@ -0,0 +1,86 @@
+"""Finds the emails of a project's own team, so the internal users check can match them in events."""
+
+import re
+from collections import Counter
+from functools import cache
+
+from posthog.dataclasses import frozen
+from posthog.models.organization import OrganizationMembership
+from posthog.models.organization_domain import OrganizationDomain
+from posthog.models.team import Team
+from posthog.models.user import User
+from posthog.utils import GenericEmails
+
+from products.access_control.backend.facade.subject_access_control import restricted_visible_membership_ids
+from products.product_analytics.backend.facade.contracts import TeamEmailAccess
+
+# A real person's email can contain one of these words, so only a word that stands alone marks a test account.
+TEST_ACCOUNT_WORDS = "test|testing|qa|demo|dummy|fake"
+# A member on a company domain is found by the domain, so these limits only bound the size of the pattern.
+MAX_TEAM_DOMAINS = 20
+MAX_TEAM_ADDRESSES = 200
+
+
+@frozen
+class TeamEmails:
+ # Company domains, the one with the most members first.
+ domains: tuple[str, ...]
+ # Members on a public email provider, where the domain says nothing about the team.
+ addresses: tuple[str, ...]
+
+
+@cache
+def _generic_emails() -> GenericEmails:
+ return GenericEmails()
+
+
+def _visible_member_emails(team: Team, user: User) -> list[str]:
+ memberships = OrganizationMembership.objects.filter(organization_id=team.organization_id)
+ # A match on a member `user` may not see would tell them that the address belongs to a member.
+ visible_membership_ids = restricted_visible_membership_ids(team.organization, user)
+ if visible_membership_ids is not None:
+ memberships = memberships.filter(id__in=visible_membership_ids)
+ return list(memberships.values_list("user__email", flat=True))
+
+
+def _verified_domains(team: Team) -> list[str]:
+ verified_domains = OrganizationDomain.objects.verified_domains().filter(organization_id=team.organization_id)
+ return list(verified_domains.values_list("domain", flat=True))
+
+
+def team_emails_of(team: Team, user: User, access: TeamEmailAccess) -> TeamEmails:
+ """The emails of the organization's members that `user` may see, and the organization's verified domains."""
+ domains: Counter[str] = Counter()
+ addresses: set[str] = set()
+ for member_email in _visible_member_emails(team, user) if access.member_emails else []:
+ email = member_email.strip().lower()
+ if "@" not in email:
+ continue
+ if _generic_emails().is_generic(email):
+ addresses.add(email)
+ else:
+ domains[email.rpartition("@")[2]] += 1
+ for domain in _verified_domains(team) if access.verified_domains else []:
+ domains.setdefault(domain.strip().lower(), 0)
+
+ most_members_first = sorted(
+ domains.items(), key=lambda domain_and_members: (-domain_and_members[1], domain_and_members[0])
+ )
+ return TeamEmails(
+ domains=tuple(domain for domain, _ in most_members_first[:MAX_TEAM_DOMAINS]),
+ addresses=tuple(sorted(addresses)[:MAX_TEAM_ADDRESSES]),
+ )
+
+
+def team_email_pattern(emails: TeamEmails) -> str:
+ """A pattern for a lowercase email that belongs to the team or to a test account."""
+ alternatives = [
+ rf"^(?:{TEST_ACCOUNT_WORDS})(?:[._+0-9-][^@]*)?@",
+ rf"\+(?:{TEST_ACCOUNT_WORDS})(?:[._0-9-][^@]*)?@",
+ ]
+ if emails.domains:
+ # A subdomain of a company domain is the same company. The end anchor keeps acme.com.br out.
+ alternatives.append(rf"@(?:[a-z0-9-]+\.)*(?:{'|'.join(map(re.escape, emails.domains))})$")
+ if emails.addresses:
+ alternatives.append(rf"^(?:{'|'.join(map(re.escape, emails.addresses))})$")
+ return "|".join(f"(?:{alternative})" for alternative in alternatives)
diff --git a/products/product_analytics/backend/insight_data_checks.py b/products/product_analytics/backend/insight_data_checks.py
index 65763e49922c..6364e44c15f7 100644
--- a/products/product_analytics/backend/insight_data_checks.py
+++ b/products/product_analytics/backend/insight_data_checks.py
@@ -1,37 +1,45 @@
-"""Checks the events an insight reads for local development, bots and events sent twice."""
+"""Checks the events an insight reads for internal users, local development, bots and events sent twice."""
from collections.abc import Mapping
from datetime import date, datetime, time, timedelta
from typing import Any, cast
from zoneinfo import ZoneInfo
-from posthog.schema import HogQLQueryModifiers
+from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
+from posthog.hogql.errors import ExposedHogQLError, ResolutionError
from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query
-from posthog.hogql.visitor import TraversingVisitor
+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.dataclasses import frozen
-from posthog.errors import CHQueryErrorTooManyBytes
+from posthog.errors import CHQueryErrorTooManyBytes, ExposedCHQueryError
from posthog.exceptions import (
ClickHouseEstimatedQueryExecutionTimeTooLong,
ClickHouseQueryMemoryLimitExceeded,
ClickHouseQueryTimeOut,
)
+from posthog.exceptions_capture import capture_exception
from posthog.models.team import Team
from posthog.models.user import User
-from products.access_control.backend.facade.api import get_restricted_properties_with_group_type_index_for_team
+from products.access_control.backend.facade.api import (
+ get_restricted_properties_with_group_type_index_for_team,
+ split_restricted_property_names,
+)
+from products.access_control.backend.facade.contracts import RestrictedPropertyNames
from products.product_analytics.backend.chart_events import ChartEvents, chart_events
from products.product_analytics.backend.facade.contracts import (
InsightDataChecks,
InsightDataChecksCoverage,
InsightDataChecksSample,
+ TeamEmailAccess,
)
from products.product_analytics.backend.facade.enums import (
InsightDataCheckKey,
@@ -41,6 +49,8 @@ from products.product_analytics.backend.facade.enums import (
from products.product_analytics.backend.insight_data_check_days import CheckWindow, days_between, newest_days_within
from products.product_analytics.backend.insight_data_check_results import (
CheckedEvents,
+ CountedEvents,
+ InternalEvents,
LocalEvents,
SampledEvents,
Skipped,
@@ -49,6 +59,7 @@ from products.product_analytics.backend.insight_data_check_results import (
not_checked,
status_of,
)
+from products.product_analytics.backend.insight_data_check_team_emails import team_email_pattern, team_emails_of
# The checks read only the newest days of a range, so they stay cheap enough to run on every load.
MAX_CHECKED_DAYS = 7
@@ -76,6 +87,7 @@ REPEAT_WINDOW_MILLISECONDS = 100
CHECKED_PROPERTIES = frozenset(
{"$host", "$raw_user_agent", "$ip", "$current_url", "$screen_name", "$feature_flag", "$event_type"}
)
+EMAIL_PROPERTY = "email"
# The fields and functions that classify traffic, which apply a project's own bot rules.
TRAFFIC_TYPE_FIELDS = frozenset(
{"$virt_is_bot", "$virt_traffic_type", "$virt_traffic_category", "$virt_bot_name", "$virt_bot_operator"}
@@ -90,16 +102,25 @@ _EVENTS_PER_DAY_QUERY = """
GROUP BY day
"""
-_LOCAL_EVENTS_QUERY = """
+# One scan counts both checks, so the internal users check costs little more than the local check alone.
+# HogQL has no topKIf, and topK skips NULL, so each list ranks only the events its check found.
+_COUNTED_EVENTS_QUERY = """
SELECT
count() AS events,
- topK(3)(toString(properties.$host)) AS top_hosts,
- topK(3)(event) AS top_events
+ countIf({is_local_host}) AS local_events,
+ topK(3)(if({is_local_host}, toString(properties.$host), NULL)) AS top_local_hosts,
+ topK(3)(if({is_local_host}, event, NULL)) AS top_local_events,
+ countIf(NOT {passes_filter}) AS removed_by_filter,
+ countIf({passes_filter} AND {is_team_email}) AS missed_by_filter,
+ topK(3)(if(NOT {passes_filter} OR {is_team_email}, event, NULL)) AS top_internal_events
FROM events
"""
_IS_LOCAL_HOST = "match(toString(properties.$host), {local_host_pattern})"
+# Without persons on events, `person` is an inner join that drops events with no person, so read the event's copy.
+_IS_TEAM_EMAIL = "match(lower(toString(poe.properties.email)), {team_email_pattern})"
+
_SAMPLED_EVENTS_QUERY = """
SELECT
distinct_id,
@@ -230,9 +251,10 @@ def _check_modifiers(chart_modifiers: HogQLQueryModifiers, *, keep_project_bot_r
return chart_modifiers.model_copy(update=update)
-def _hidden_property_names(team: Team, user: User) -> set[str]:
- restricted = get_restricted_properties_with_group_type_index_for_team(user=user, team_id=team.pk)
- return {restricted_property.name for restricted_property in restricted}
+def _hidden_properties(team: Team, user: User) -> RestrictedPropertyNames:
+ return split_restricted_property_names(
+ get_restricted_properties_with_group_type_index_for_team(user=user, team_id=team.pk)
+ )
def _start_of(day: date, timezone: ZoneInfo) -> ast.Constant:
@@ -304,27 +326,197 @@ def _choose_window(events: ChartEvents, reader: _EventReader, timezone: ZoneInfo
)
-def _count_local_events(
- events: ChartEvents, reader: _EventReader, where: ast.Expr, *, use_prewhere: bool
-) -> LocalEvents | Skipped:
- is_local_host = parse_expr(
- _IS_LOCAL_HOST, placeholders={"local_host_pattern": ast.Constant(value=LOCAL_HOST_PATTERN)}
+@frozen
+class _InternalUsersMatch:
+ passes_filter: ast.Expr
+ is_team_email: ast.Expr
+ # The person fields `passes_filter` reads from the current person join, or None when it needs no join.
+ person_fields: frozenset[str] | None = None
+
+
+_NO_INTERNAL_USERS = _InternalUsersMatch(
+ passes_filter=ast.Constant(value=True), is_team_email=ast.Constant(value=False)
+)
+
+
+# The lookup's columns sit next to the event's columns, so they take names the events table does not use.
+_CURRENT_PERSON = "current_person"
+
+# The latest person of each distinct ID, as the persons join finds it. Each table reads only the rows of the
+# checked events' distinct IDs, so the lookup does not read the whole project.
+_CURRENT_PERSON_QUERY = """
+ SELECT person_ids.distinct_id AS current_person_distinct_id, person_ids.person_id AS current_person_id
+ FROM (
+ SELECT distinct_id, argMax(person_id, version) AS person_id
+ FROM raw_person_distinct_ids
+ WHERE distinct_id IN {checked_distinct_ids}
+ GROUP BY distinct_id
+ HAVING argMax(is_deleted, version) = 0
+ ) AS person_ids
+ LEFT JOIN (
+ SELECT id
+ FROM raw_persons
+ WHERE id IN (SELECT person_id FROM raw_person_distinct_ids WHERE distinct_id IN {checked_distinct_ids_again})
+ GROUP BY id
+ HAVING argMax(is_deleted, version) = 0
+ ) AS current_persons ON current_persons.id = person_ids.person_id
+"""
+
+
+class _PersonFromLeftJoin(CloningVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ # None while the filter reads no person.
+ self.person_fields: set[str] | None = None
+
+ # A field in a subquery belongs to that subquery's own tables.
+ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:
+ return clone_expr(node)
+
+ def visit_field(self, node: ast.Field) -> ast.Field:
+ if node.chain[:1] == ["person"] and len(node.chain) > 1:
+ self.person_fields = {*(self.person_fields or ()), str(node.chain[1])}
+ return ast.Field(chain=[_CURRENT_PERSON, f"{_CURRENT_PERSON}_{node.chain[1]}", *node.chain[2:]])
+ if node.chain == ["person_id"]:
+ self.person_fields = self.person_fields or set()
+ return ast.Field(chain=[_CURRENT_PERSON, "current_person_id"])
+ return super().visit_field(node)
+
+
+def _passes_internal_users_filter(events: ChartEvents, team: Team) -> tuple[ast.Expr, frozenset[str] | None]:
+ # An insight that applies the filter has already dropped the events it removes.
+ if events.filters_test_accounts or not team.test_account_filters:
+ return ast.Constant(value=True), None
+ project_filter = property_to_expr(team.test_account_filters, team)
+ person_fields: frozenset[str] | None = None
+ # Without persons on events, the person comes from an inner join that drops the events with no person, which
+ # the insight counts. A left join on the same table reads the same person and keeps those events.
+ if events.modifiers.personsOnEventsMode == PersonsOnEventsMode.DISABLED:
+ person_from_left_join = _PersonFromLeftJoin()
+ project_filter = person_from_left_join.visit(project_filter)
+ if person_from_left_join.person_fields is not None:
+ person_fields = frozenset(person_from_left_join.person_fields)
+ # The insight's own WHERE drops an event whose filter is NULL, so NULL counts as removed.
+ return ast.Call(name="ifNull", args=[project_filter, ast.Constant(value=False)]), person_fields
+
+
+def _current_person_join(events: ChartEvents, where: ast.Expr, person_fields: frozenset[str]) -> ast.JoinExpr:
+ def checked_distinct_ids() -> ast.SelectQuery:
+ return events.select("SELECT distinct_id FROM events", where=clone_expr(where))
+
+ lookup = cast(
+ ast.SelectQuery,
+ parse_select(
+ _CURRENT_PERSON_QUERY,
+ placeholders={
+ "checked_distinct_ids": checked_distinct_ids(),
+ "checked_distinct_ids_again": checked_distinct_ids(),
+ },
+ ),
)
- if use_prewhere:
- # In PREWHERE, ClickHouse reads only `$host` for every event, and the chart's filters only for the few that match.
- query = events.select(_LOCAL_EVENTS_QUERY, where=where, prewhere=is_local_host)
- else:
- # ClickHouse cannot run the function that hides a restricted property inside PREWHERE.
- query = events.select(_LOCAL_EVENTS_QUERY, where=ast.And(exprs=[where, is_local_host]))
+ person_ids = cast(ast.JoinExpr, lookup.select_from)
+ persons = cast(ast.JoinExpr, person_ids.next_join)
+ if not person_fields:
+ person_ids.next_join = None
+ for field in sorted(person_fields):
+ latest_value = parse_expr("argMax({field}, version)", placeholders={"field": ast.Field(chain=[field])})
+ cast(ast.SelectQuery, persons.table).select.append(ast.Alias(alias=field, expr=latest_value))
+ lookup.select.append(
+ ast.Alias(alias=f"{_CURRENT_PERSON}_{field}", expr=ast.Field(chain=["current_persons", field]))
+ )
+ return ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=lookup,
+ alias=_CURRENT_PERSON,
+ constraint=ast.JoinConstraint(
+ expr=ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=[_CURRENT_PERSON, "current_person_distinct_id"]),
+ right=ast.Field(chain=[events.alias or "events", "distinct_id"]),
+ ),
+ constraint_type="ON",
+ ),
+ )
+
+
+def _internal_users_match(
+ events: ChartEvents,
+ reader: _EventReader,
+ *,
+ email_access: TeamEmailAccess,
+ hidden_properties: RestrictedPropertyNames,
+) -> _InternalUsersMatch | Skipped:
+ # A hidden email reads as empty, so the check would miss every member found by email.
+ if EMAIL_PROPERTY in hidden_properties.person:
+ return Skipped(reason=InsightDataCheckSkipReason.HIDDEN_PROPERTY)
+
+ team_emails = team_emails_of(reader.team, reader.user, email_access)
+ passes_filter, person_fields = _passes_internal_users_filter(events, reader.team)
+ return _InternalUsersMatch(
+ passes_filter=passes_filter,
+ person_fields=person_fields,
+ is_team_email=parse_expr(
+ _IS_TEAM_EMAIL, placeholders={"team_email_pattern": ast.Constant(value=team_email_pattern(team_emails))}
+ ),
+ )
+
+
+def _count_every_event(
+ events: ChartEvents, reader: _EventReader, where: ast.Expr, internal_users: _InternalUsersMatch | Skipped
+) -> CountedEvents | Skipped:
+ match = _NO_INTERNAL_USERS if isinstance(internal_users, Skipped) else internal_users
+ query = events.select(
+ _COUNTED_EVENTS_QUERY,
+ where=where,
+ is_local_host=parse_expr(
+ _IS_LOCAL_HOST, placeholders={"local_host_pattern": ast.Constant(value=LOCAL_HOST_PATTERN)}
+ ),
+ passes_filter=match.passes_filter,
+ is_team_email=match.is_team_email,
+ )
+ if match.person_fields is not None:
+ cast(ast.JoinExpr, query.select_from).next_join = _current_person_join(events, where, match.person_fields)
rows = reader.rows_within_limits(
- query, query_type="insight_data_checks_local", max_bytes_read_per_shard=MAX_BYTES_READ_PER_SHARD
+ query, query_type="insight_data_checks_counted", max_bytes_read_per_shard=MAX_BYTES_READ_PER_SHARD
)
if isinstance(rows, Skipped):
return rows
- row: list[Any] = rows[0] if rows else [0, [], []]
- count, top_hosts, top_events = row
- return LocalEvents(count=int(count or 0), top_hosts=list(top_hosts), top_events=list(top_events))
+ row: list[Any] = rows[0] if rows else [0, 0, [], [], 0, 0, []]
+ count, local_count, top_local_hosts, top_local_events, removed, missed, top_internal_events = row
+ internal: InternalEvents | Skipped
+ if isinstance(internal_users, Skipped):
+ internal = internal_users
+ else:
+ internal = InternalEvents(
+ removed_by_filter=int(removed or 0), missed_by_filter=int(missed or 0), top_events=list(top_internal_events)
+ )
+ return CountedEvents(
+ events=int(count or 0),
+ local=LocalEvents(
+ count=int(local_count or 0), top_hosts=list(top_local_hosts), top_events=list(top_local_events)
+ ),
+ internal=internal,
+ )
+
+
+def _count_events_on_checked_days(
+ events: ChartEvents,
+ reader: _EventReader,
+ where: ast.Expr,
+ *,
+ email_access: TeamEmailAccess,
+ hidden_properties: RestrictedPropertyNames,
+) -> CountedEvents | Skipped:
+ try:
+ internal_users = _internal_users_match(
+ events, reader, email_access=email_access, hidden_properties=hidden_properties
+ )
+ return _count_every_event(events, reader, where, internal_users)
+ except (ExposedHogQLError, ResolutionError, ExposedCHQueryError) as error:
+ # The project's filter, such as one on a deleted cohort, is the likely cause, so count again without it.
+ capture_exception(error)
+ return _count_every_event(events, reader, where, Skipped(reason=InsightDataCheckSkipReason.INVALID_FILTER))
def _sample_events(
@@ -372,18 +564,21 @@ def _read_checked_days(
window: CheckWindow,
timezone: ZoneInfo,
*,
- hides_properties: bool,
+ hidden_properties: RestrictedPropertyNames,
filters_traffic_type: bool,
+ email_access: TeamEmailAccess,
) -> CheckedEvents:
# The bounds apply to a whole range too, because a lifecycle chart also reads the interval before its range.
first, last = window.days_to_check[0], window.days_to_check[-1]
where = ast.And(exprs=[events.where, _between_days(events, first, last, timezone)])
- local: LocalEvents | Skipped = Skipped(reason=InsightDataCheckSkipReason.TOO_MANY_EVENTS)
+ counted: CountedEvents | Skipped = Skipped(reason=InsightDataCheckSkipReason.TOO_MANY_EVENTS)
if window.events_on_days_to_check <= MAX_COUNTED_EVENTS:
- local = _count_local_events(events, reader, where, use_prewhere=not hides_properties)
+ counted = _count_events_on_checked_days(
+ events, reader, where, email_access=email_access, hidden_properties=hidden_properties
+ )
sample = _sample_events(events, reader, where, events_before_filters=window.events_on_days_to_check)
- return CheckedEvents(local=local, sample=sample, insight_filters_traffic_type=filters_traffic_type)
+ return CheckedEvents(counted=counted, sample=sample, insight_filters_traffic_type=filters_traffic_type)
def _sample_summary(sample: SampledEvents | Skipped) -> InsightDataChecksSample | None:
@@ -392,7 +587,15 @@ def _sample_summary(sample: SampledEvents | Skipped) -> InsightDataChecksSample
return InsightDataChecksSample(rate=sample.rate, events=sample.events, distinct_ids=sample.distinct_ids)
-def _coverage(events: ChartEvents, window: CheckWindow, sample: SampledEvents | Skipped) -> InsightDataChecksCoverage:
+def _events_checked(checked: CheckedEvents) -> int | None:
+ if isinstance(checked.counted, CountedEvents):
+ return checked.counted.events
+ if isinstance(checked.sample, SampledEvents):
+ return round(checked.sample.events / checked.sample.rate)
+ return None
+
+
+def _coverage(events: ChartEvents, window: CheckWindow, checked: CheckedEvents) -> InsightDataChecksCoverage:
return InsightDataChecksCoverage(
date_from=window.days_in_range[0],
date_to=window.days_in_range[-1],
@@ -401,8 +604,8 @@ def _coverage(events: ChartEvents, window: CheckWindow, sample: SampledEvents |
checked_date_to=window.days_to_check[-1],
days_checked=len(window.days_to_check),
filters_test_accounts=events.filters_test_accounts,
- events_checked=None if isinstance(sample, Skipped) else round(sample.events / sample.rate),
- sample=_sample_summary(sample),
+ events_checked=_events_checked(checked),
+ sample=_sample_summary(checked.sample),
)
@@ -415,13 +618,15 @@ def _nothing_checked(
return InsightDataChecks(status=status, checks=checks, coverage=coverage)
-def run_insight_data_checks(query: Mapping[str, Any], team: Team, user: User) -> InsightDataChecks:
+def run_insight_data_checks(
+ query: Mapping[str, Any], team: Team, user: User, *, email_access: TeamEmailAccess
+) -> InsightDataChecks:
with tags_context(product=Product.PRODUCT_ANALYTICS, feature=Feature.INSIGHT, name="insight_data_checks"):
events = chart_events(query, team, user)
if events is None:
return _nothing_checked(InsightDataChecksStatus.UNSUPPORTED)
- hidden_properties = _hidden_property_names(team, user)
- if hidden_properties & CHECKED_PROPERTIES:
+ hidden_properties = _hidden_properties(team, user)
+ if hidden_properties.event & CHECKED_PROPERTIES:
return _nothing_checked(InsightDataChecksStatus.UNSUPPORTED)
# A chart that filters on traffic type reads the project's bot rules, so the checks keep them to read its events.
@@ -441,11 +646,12 @@ def run_insight_data_checks(query: Mapping[str, Any], team: Team, user: User) ->
reader,
window,
timezone,
- hides_properties=bool(hidden_properties),
+ hidden_properties=hidden_properties,
filters_traffic_type=filters_traffic_type,
+ email_access=email_access,
)
- coverage = _coverage(events, window, checked.sample)
+ coverage = _coverage(events, window, checked)
if found_no_events(checked):
return _nothing_checked(InsightDataChecksStatus.NO_EVENTS, coverage)
checks = evaluate_data_checks(checked)
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 13db01fc0c91..e74dd203b1af 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -102,7 +102,11 @@ from posthog.models.organization import Organization
from posthog.models.tagged_item import TaggedItem
from posthog.models.team.team import Team
from posthog.models.utils import UUIDT
-from posthog.permissions import TeamMemberStrictManagementPermission
+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 (
@@ -116,6 +120,7 @@ from posthog.renderers import SafeJSONRenderer
from posthog.resource_limits import LimitKey, check_count_limit
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
@@ -174,6 +179,7 @@ from products.product_analytics.backend.facade.api import (
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,
@@ -1760,8 +1766,9 @@ class InsightDataCheckSerializer(serializers.Serializer):
choices=InsightDataCheckAction.choices,
allow_null=True,
help_text=(
- "The change that fixes it. `open_filter_settings`: change the project's internal and test users filter. "
- "Null when there is no single change."
+ "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. Null when there is "
+ "no single change."
),
)
top_events = serializers.ListField(
@@ -1800,8 +1807,8 @@ class InsightDataChecksCoverageSerializer(serializers.Serializer):
events_checked = serializers.IntegerField(
allow_null=True,
help_text=(
- "How many events the insight reads on the days checked, scaled up from the sample when the sample did "
- "not read every event. Null when the sample did not run."
+ "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(
@@ -2562,12 +2569,14 @@ When set, the specified dashboard's filters and date range override will be appl
200: OpenApiResponse(response=InsightDataChecksSerializer, description="The result of every check.")
},
description=(
- "Check the events behind an insight for the common ways they mislead: 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. 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/`."
+ "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`. 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"])
@@ -2601,11 +2610,32 @@ When set, the specified dashboard's filters and date range override will be appl
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))
+ checks = run_insight_data_checks(
+ query,
+ team=self.team,
+ user=cast(User, self.request.user),
+ email_access=self._team_email_access(),
+ )
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:
+ if project_scoped:
+ return False
+ return scopes is None or "*" in scopes or not scopes_not_covered(scopes, [scope])
+
+ return TeamEmailAccess(
+ member_emails=holds("organization_member:read"), verified_domains=holds("organization:read")
+ )
+
# `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(
diff --git a/products/product_analytics/backend/tests/test_insight_data_checks.py b/products/product_analytics/backend/tests/test_insight_data_checks.py
index 5dc4cd40e1d3..d2564daa7e21 100644
--- a/products/product_analytics/backend/tests/test_insight_data_checks.py
+++ b/products/product_analytics/backend/tests/test_insight_data_checks.py
@@ -1,3 +1,4 @@
+import re
from collections.abc import Mapping
from dataclasses import replace
from datetime import UTC, date, datetime, timedelta
@@ -16,15 +17,21 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.errors import ExposedCHQueryError
from posthog.exceptions import APIQueriesBudgetExceeded
-from posthog.models import PropertyDefinition
+from posthog.models import PersonalAPIKey, PropertyDefinition
from posthog.models.organization import OrganizationMembership
+from posthog.models.organization_domain import OrganizationDomain
from posthog.models.team import Team
from products.access_control.backend.facade.api import upsert_property_access_control
from products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInput
from products.access_control.backend.models.access_control import AccessControl
from products.cohorts.backend.models.cohort import Cohort
-from products.product_analytics.backend.facade.contracts import InsightDataChecks, InsightDataChecksCoverage
+from products.product_analytics.backend.facade.contracts import (
+ InsightDataCheck,
+ InsightDataChecks,
+ InsightDataChecksCoverage,
+ TeamEmailAccess,
+)
from products.product_analytics.backend.facade.data_checks import run_insight_data_checks
from products.product_analytics.backend.facade.enums import (
InsightDataCheckKey,
@@ -35,17 +42,21 @@ from products.product_analytics.backend.facade.models import Insight
from products.product_analytics.backend.insight_data_check_days import newest_days_within
from products.product_analytics.backend.insight_data_check_results import (
CheckedEvents,
+ CountedEvents,
+ InternalEvents,
LocalEvents,
SampledEvents,
Skipped,
evaluate_data_checks,
status_of,
)
+from products.product_analytics.backend.insight_data_check_team_emails import TeamEmails, team_email_pattern
PASSED = InsightDataCheckLevel.PASSED
WARNING = InsightDataCheckLevel.WARNING
PROBLEM = InsightDataCheckLevel.PROBLEM
SKIPPED = InsightDataCheckLevel.SKIPPED
+INTERNAL = InsightDataCheckKey.INTERNAL_USERS
LOCAL = InsightDataCheckKey.LOCAL_DEVELOPMENT
BOTS = InsightDataCheckKey.BOT_TRAFFIC
DUPLICATES = InsightDataCheckKey.DUPLICATE_EVENTS
@@ -69,19 +80,32 @@ HAS_NO_PLAN_TODAY = {"key": "plan", "value": "is_not_set", "operator": "is_not_s
ONE_STEP = [{"kind": "EventsNode", "event": EVENT}]
TWO_STEPS = [{"kind": "EventsNode", "event": EVENT}, {"kind": "EventsNode", "event": EVENT}]
SEVEN_DAYS = [date(2026, 3, 1) + timedelta(days=offset) for offset in range(7)]
+CHECK_SCOPES = ["insight:read", "query:read"]
+MEMBER_EMAIL = "[email protected]"
+VERIFIED_DOMAIN_EMAIL = "[email protected]"
def checked(
sampled_events: int,
*,
+ removed_by_filter: int = 0,
+ missed_by_filter: int = 0,
local: int | None = 0,
bots: int = 0,
repeats: int = 0,
sample_rate: float = 1.0,
) -> CheckedEvents:
- too_many_to_count = Skipped(reason=InsightDataCheckSkipReason.TOO_MANY_EVENTS)
+ counted: CountedEvents | Skipped = Skipped(reason=InsightDataCheckSkipReason.TOO_MANY_EVENTS)
+ if local is not None:
+ counted = CountedEvents(
+ events=round(sampled_events / sample_rate),
+ local=LocalEvents(count=local, top_hosts=[], top_events=[]),
+ internal=InternalEvents(
+ removed_by_filter=removed_by_filter, missed_by_filter=missed_by_filter, top_events=[]
+ ),
+ )
return CheckedEvents(
- local=too_many_to_count if local is None else LocalEvents(count=local, top_hosts=[], top_events=[]),
+ counted=counted,
sample=SampledEvents(
rate=sample_rate,
events=sampled_events,
@@ -98,10 +122,13 @@ def checked(
class TestEvaluateDataChecks(SimpleTestCase):
@parameterized.expand(
[
+ ("internal_small_share_is_a_warning", checked(10_000, removed_by_filter=200), {INTERNAL: WARNING}),
+ ("internal_under_one_percent", checked(100_000, removed_by_filter=900), {}),
+ ("internal_fifth_is_a_problem", checked(1000, missed_by_filter=200), {INTERNAL: PROBLEM}),
("local_tiny_share_still_counts", checked(1_000_000, local=60), {LOCAL: WARNING}),
("local_under_50_events", checked(100, local=49), {}),
("local_fifth_is_a_problem", checked(1000, local=200), {LOCAL: PROBLEM}),
- ("local_too_many_events_to_count", checked(1000, local=None), {LOCAL: SKIPPED}),
+ ("too_many_events_to_count", checked(1000, local=None), {INTERNAL: SKIPPED, LOCAL: SKIPPED}),
("bots_small_share_is_a_warning", checked(10_000, bots=200), {BOTS: WARNING}),
(
"bots_under_50_sampled_events_but_over_50_in_the_range",
@@ -120,9 +147,9 @@ class TestEvaluateDataChecks(SimpleTestCase):
("duplicates_fifth_is_a_problem", checked(1000, repeats=250), {DUPLICATES: PROBLEM}),
("sample_too_small_to_check", checked(500, sample_rate=0.1), {BOTS: SKIPPED, DUPLICATES: SKIPPED}),
(
- "local_with_an_empty_partial_sample_is_at_most_a_warning",
- checked(0, local=60, sample_rate=0.1),
- {LOCAL: WARNING, BOTS: SKIPPED, DUPLICATES: SKIPPED},
+ "local_share_of_every_event_not_of_the_sample",
+ checked(1000, local=300, sample_rate=0.1),
+ {LOCAL: WARNING},
),
]
)
@@ -151,10 +178,7 @@ class TestEvaluateDataChecks(SimpleTestCase):
(
"duplicates_whose_sample_hit_the_read_limit",
DUPLICATES,
- CheckedEvents(
- local=LocalEvents(count=0, top_hosts=[], top_events=[]),
- sample=Skipped(reason=InsightDataCheckSkipReason.READ_LIMIT),
- ),
+ replace(checked(1000), sample=Skipped(reason=InsightDataCheckSkipReason.READ_LIMIT)),
"read_limit",
),
]
@@ -165,10 +189,28 @@ class TestEvaluateDataChecks(SimpleTestCase):
skip_reasons = {check.key: check.skip_reason for check in evaluate_data_checks(checked_events)}
assert skip_reasons[key] == reason
+ @parameterized.expand(
+ [
+ ("filter_removes_them", 300, 0, "filter_internal_users"),
+ ("filter_misses_too_few_to_change_it", 300, 10, "filter_internal_users"),
+ ("filter_misses_the_team", 0, 300, "open_filter_settings"),
+ ("filter_misses_some_of_the_team", 300, 100, "open_filter_settings"),
+ ]
+ )
+ def test_internal_users_fix_turns_the_filter_on_unless_the_filter_misses_the_team(
+ self, _name: str, removed_by_filter: int, missed_by_filter: int, action: str
+ ) -> None:
+ checks = evaluate_data_checks(
+ checked(1000, removed_by_filter=removed_by_filter, missed_by_filter=missed_by_filter)
+ )
+
+ internal_users = next(check for check in checks if check.key == INTERNAL)
+ assert (internal_users.events, internal_users.action) == (removed_by_filter + missed_by_filter, action)
+
def test_status_is_inconclusive_when_every_check_is_skipped(self) -> None:
checks = evaluate_data_checks(
CheckedEvents(
- local=Skipped(reason=InsightDataCheckSkipReason.TOO_MANY_EVENTS),
+ counted=Skipped(reason=InsightDataCheckSkipReason.TOO_MANY_EVENTS),
sample=Skipped(reason=InsightDataCheckSkipReason.READ_LIMIT),
)
)
@@ -188,6 +230,30 @@ class TestNewestDaysWithin(SimpleTestCase):
assert newest_days_within(dict.fromkeys(SEVEN_DAYS, 10), budget) == expected
+class TestTeamEmailPattern(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("company_domain", "[email protected]", True),
+ ("subdomain_of_the_company_domain", "[email protected]", True),
+ ("member_on_a_public_provider", "[email protected]", True),
+ ("test_account", "[email protected]", True),
+ ("numbered_test_account", "[email protected]", True),
+ ("test_alias", "[email protected]", True),
+ ("longer_domain_that_starts_the_same", "[email protected]", False),
+ ("domain_that_ends_the_same", "[email protected]", False),
+ ("another_person_on_the_public_provider", "[email protected]", False),
+ ("word_that_starts_with_test", "[email protected]", False),
+ ("word_that_contains_test", "[email protected]", False),
+ ("word_that_starts_with_demo", "[email protected]", False),
+ ("alias_that_is_not_a_test_word", "[email protected]", False),
+ ]
+ )
+ def test_matches_the_team_and_test_accounts_only(self, _name: str, email: str, matches: bool) -> None:
+ pattern = team_email_pattern(TeamEmails(domains=("acme.example",), addresses=("[email protected]",)))
+
+ assert bool(re.search(pattern, email)) == matches
+
+
@time_machine.travel(NOW, tick=False)
@patch(f"{CHECKS_MODULE}.SIZING_SAMPLE_ONE_IN", 1)
@patch(f"{CHECKS_MODULE}.MAX_CHECKED_DAYS", 10_000)
@@ -202,7 +268,7 @@ class TestInsightDataChecks(ClickhouseTestMixin, APIBaseTest):
_create_person(team=self.team, distinct_ids=["internal"], properties={"email": "[email protected]"})
self._second = 0
self._events(200)
- self._events(60, distinct_id="internal")
+ self._events(60, distinct_id="internal", person_properties={"email": "[email protected]"})
self._events(60, properties={"$host": LOCAL_HOST})
self._events(30, properties={"$raw_user_agent": BOT_USER_AGENT, "$group_0": "acme"})
self._events(30, properties={"$raw_user_agent": BROWSER_USER_AGENT, "$ip": CRAWLER_IP, "$group_0": "acme"})
@@ -250,7 +316,15 @@ class TestInsightDataChecks(ClickhouseTestMixin, APIBaseTest):
}
def _check(self, query: dict[str, Any]) -> InsightDataChecks:
- return run_insight_data_checks(query, team=self.team, user=self.user)
+ return run_insight_data_checks(
+ query,
+ team=self.team,
+ user=self.user,
+ email_access=TeamEmailAccess(member_emails=True, verified_domains=True),
+ )
+
+ def _internal_users(self, result: InsightDataChecks) -> InsightDataCheck:
+ return next(check for check in result.checks if check.key == INTERNAL)
def _coverage(self, result: InsightDataChecks) -> InsightDataChecksCoverage:
assert result.coverage is not None
@@ -267,11 +341,13 @@ class TestInsightDataChecks(ClickhouseTestMixin, APIBaseTest):
assert coverage.events_checked == 600
assert coverage.days_checked == coverage.days_in_range
assert {check.key: (check.level, check.events) for check in result.checks} == {
+ "internal_users": ("warning", 60),
"local_development": ("warning", 60),
"bot_traffic": ("warning", 60),
"duplicate_events": ("warning", 110),
}
assert {check.key: (check.top_events, check.top_hosts, check.top_bots) for check in result.checks} == {
+ "internal_users": ([EVENT], [], []),
"local_development": ([EVENT], [LOCAL_HOST], []),
"bot_traffic": ([EVENT], [], ["Google fetcher", "Googlebot"]),
"duplicate_events": ([EVENT], [], []),
@@ -515,6 +591,93 @@ class TestInsightDataChecks(ClickhouseTestMixin, APIBaseTest):
duplicates = next(check for check in result.checks if check.key == DUPLICATES)
assert (duplicates.events, duplicates.top_events) == (10, [WIDELY_SENT_EVENT])
+ @parameterized.expand(
+ [
+ ("insight_without_the_filter", True, {}, (60, "filter_internal_users")),
+ ("insight_with_the_filter", True, {"filterTestAccounts": True}, (0, None)),
+ ("project_without_a_filter", False, {}, (60, "open_filter_settings")),
+ ]
+ )
+ def test_internal_users_check_follows_the_filter_in_place(
+ self, _name: str, project_has_a_filter: bool, source: dict[str, Any], expected: tuple[int, str | None]
+ ) -> None:
+ if not project_has_a_filter:
+ self.team.test_account_filters = []
+ self.team.save()
+
+ internal_users = self._internal_users(self._check(self._query(**source)))
+
+ assert (internal_users.events, internal_users.action) == expected
+
+ @parameterized.expand(
+ [("without_a_project_filter", None), ("with_a_person_filter", "person"), ("with_a_cohort_filter", "cohort")]
+ )
+ def test_keeps_events_without_a_person_when_persons_are_not_on_events(
+ self, _name: str, filter_type: str | None
+ ) -> None:
+ if filter_type is None:
+ self.team.test_account_filters = []
+ elif filter_type == "cohort":
+ staff = Cohort.objects.create(team=self.team, name="staff", is_static=True)
+ self.team.test_account_filters = [{"key": "id", "type": "cohort", "value": staff.id, "operator": "not_in"}]
+ self.team.save()
+ self._events(20, distinct_id="no person", event=WIDELY_SENT_EVENT)
+ flush_persons_and_events()
+ query = self._query(
+ [{"kind": "EventsNode", "event": WIDELY_SENT_EVENT}],
+ kind="TrendsQuery",
+ modifiers={"personsOnEventsMode": "disabled"},
+ )
+
+ result = self._check(query)
+
+ assert (self._coverage(result).events_checked, self._internal_users(result).events) == (20, 0)
+
+ @parameterized.expand(
+ [
+ ("persons_are_not_on_events", "disabled", 80),
+ ("persons_are_joined", "person_id_override_properties_joined", 80),
+ ("persons_are_on_events", "person_id_override_properties_on_events", 60),
+ (
+ "filter_with_a_subquery",
+ "disabled",
+ 80,
+ "person.properties.email NOT ILIKE '%@posthog.com' "
+ "AND person_id NOT IN (SELECT person_id FROM person_distinct_ids WHERE distinct_id = 'nobody')",
+ ),
+ ]
+ )
+ def test_reads_person_properties_from_where_the_insight_reads_them(
+ self, _name: str, persons_on_events_mode: str, internal_user_events: int, hogql_filter: str | None = None
+ ) -> None:
+ if hogql_filter is not None:
+ self.team.test_account_filters = [{"type": "hogql", "key": hogql_filter}]
+ self.team.save()
+ _create_person(team=self.team, distinct_ids=["joined later"], properties={"email": "[email protected]"})
+ self._events(20, distinct_id="joined later", person_properties={"email": "[email protected]"})
+ flush_persons_and_events()
+
+ result = self._check(self._query(modifiers={"personsOnEventsMode": persons_on_events_mode}))
+
+ assert self._internal_users(result).events == internal_user_events
+
+ @parameterized.expand([("on_a_deleted_cohort", "cohort"), ("on_a_field_that_does_not_exist", "hogql")])
+ def test_reports_the_other_checks_when_the_projects_filter_cannot_run(self, _name: str, filter_type: str) -> None:
+ if filter_type == "cohort":
+ deleted = Cohort.objects.create(team=self.team, name="deleted", deleted=True)
+ self.team.test_account_filters = [
+ {"key": "id", "type": "cohort", "value": deleted.id, "operator": "not_in"}
+ ]
+ else:
+ self.team.test_account_filters = [{"type": "hogql", "key": "timestamp.day"}]
+ self.team.save()
+
+ result = self._check(self._query())
+
+ local = next(check for check in result.checks if check.key == LOCAL)
+ assert (local.level, local.events) == ("warning", 60)
+ assert self._internal_users(result).skip_reason == "invalid_filter"
+
@parameterized.expand(
[
("unknown_event", [{"kind": "EventsNode", "event": "never sent"}], 1_000_000_000, "no_events"),
@@ -539,20 +702,25 @@ class TestInsightDataChecks(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
- ("a_property_the_checks_read", "$host", "unsupported"),
- ("a_property_the_checks_do_not_read", "plan", "warning"),
+ ("a_property_the_checks_read", "$host", PropertyDefinition.Type.EVENT, "unsupported", None),
+ ("a_property_the_checks_do_not_read", "plan", PropertyDefinition.Type.EVENT, "warning", None),
+ ("the_email_of_a_person", "email", PropertyDefinition.Type.PERSON, "warning", "hidden_property"),
+ ("an_event_property_named_email", "email", PropertyDefinition.Type.EVENT, "warning", None),
]
)
def test_a_hidden_property_stops_the_checks_only_when_they_read_it(
- self, _name: str, hidden_property: str, status: str
+ self,
+ _name: str,
+ hidden_property: str,
+ property_type: PropertyDefinition.Type,
+ status: str,
+ internal_users_skip_reason: str | None,
) -> None:
self.organization.available_product_features = [
{"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
]
self.organization.save()
- definition = PropertyDefinition.objects.create(
- team=self.team, name=hidden_property, type=PropertyDefinition.Type.EVENT
- )
+ definition = PropertyDefinition.objects.create(team=self.team, name=hidden_property, type=property_type)
upsert_property_access_control(
team_id=self.team.id,
created_by_id=self.user.id,
@@ -563,7 +731,10 @@ class TestInsightDataChecks(ClickhouseTestMixin, APIBaseTest):
),
)
- assert self._check(self._query()).status == status
+ result = self._check(self._query())
+
+ assert result.status == status
+ assert self._internal_users(result).skip_reason == internal_users_skip_reason
@parameterized.expand(
[
@@ -617,6 +788,95 @@ class TestInsightDataChecks(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == expected, response.content
+ @parameterized.expand(
+ [
+ ("member_for_a_session_that_may_see_them", MEMBER_EMAIL, None, True, 80),
+ (
+ "member_for_a_token_with_the_member_scope",
+ MEMBER_EMAIL,
+ [*CHECK_SCOPES, "organization_member:read"],
+ True,
+ 80,
+ ),
+ ("member_for_a_token_without_the_member_scope", MEMBER_EMAIL, CHECK_SCOPES, True, 0),
+ ("member_for_a_session_that_may_not_see_them", MEMBER_EMAIL, None, False, 0),
+ (
+ "verified_domain_for_a_token_with_the_organization_scope",
+ VERIFIED_DOMAIN_EMAIL,
+ [*CHECK_SCOPES, "organization:read"],
+ True,
+ 80,
+ ),
+ (
+ "verified_domain_for_a_token_without_the_organization_scope",
+ VERIFIED_DOMAIN_EMAIL,
+ [*CHECK_SCOPES, "organization_member:read"],
+ True,
+ 0,
+ ),
+ (
+ "member_for_a_token_confined_to_the_project",
+ MEMBER_EMAIL,
+ [*CHECK_SCOPES, "organization_member:read", "organization:read"],
+ True,
+ 0,
+ True,
+ ),
+ ]
+ )
+ def test_matches_a_team_email_only_for_a_caller_who_may_read_it(
+ self,
+ _name: str,
+ email: str,
+ scopes: list[str] | None,
+ member_is_visible: bool,
+ internal_user_events: int,
+ confined_to_the_project: bool = False,
+ ) -> None:
+ self._create_user(MEMBER_EMAIL)
+ OrganizationDomain.objects.create(organization=self.organization, domain="acme.example", verified_at=NOW)
+ _create_person(team=self.team, distinct_ids=["teammate"], properties={"email": email})
+ self._events(80, distinct_id="teammate", person_properties={"email": email})
+ flush_persons_and_events()
+ if not member_is_visible:
+ self._limit_the_member_list_to_project_members()
+ headers = {}
+ if scopes is not None:
+ headers = {"authorization": f"Bearer {self.create_personal_api_key_with_scopes(scopes)}"}
+ if confined_to_the_project:
+ PersonalAPIKey.objects.filter(user=self.user).update(scoped_teams=[self.team.id])
+ self.client.logout()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/insights/data_checks/",
+ {"query": self._query(filterTestAccounts=True)},
+ format="json",
+ headers=headers,
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ internal_users = next(check for check in response.json()["checks"] if check["key"] == INTERNAL)
+ assert internal_users["events"] == internal_user_events
+
+ def _limit_the_member_list_to_project_members(self) -> None:
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.ACCESS_CONTROL, "key": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.members_can_see_org_members = False
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="project",
+ resource_id=str(self.team.id),
+ organization_member=self.organization_membership,
+ access_level="member",
+ )
+
@parameterized.expand(
[("api_key", True, status.HTTP_429_TOO_MANY_REQUESTS), ("session", False, status.HTTP_200_OK)]
)
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 5906262b4903..98e605cd8c8a 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -9163,6 +9163,7 @@ export const InsightDataChecksStatusEnumApi = {
} as const
/**
+ * * `internal_users` - Internal and test users
* * `local_development` - Local development events
* * `bot_traffic` - Bot and crawler traffic
* * `duplicate_events` - Events sent twice
@@ -9170,6 +9171,7 @@ export const InsightDataChecksStatusEnumApi = {
export type InsightDataCheckKeyEnumApi = (typeof InsightDataCheckKeyEnumApi)[keyof typeof InsightDataCheckKeyEnumApi]
export const InsightDataCheckKeyEnumApi = {
+ InternalUsers: 'internal_users',
LocalDevelopment: 'local_development',
BotTraffic: 'bot_traffic',
DuplicateEvents: 'duplicate_events',
@@ -9198,6 +9200,8 @@ export const InsightDataCheckLevelEnumApi = {
* * `memory_limit` - The check needed more memory than it is allowed
* * `too_few_sampled_events` - The sample has too few events to give a share
* * `filtered_by_traffic_type` - The insight already filters on traffic type
+ * * `hidden_property` - A property the check reads is hidden from you
+ * * `invalid_filter` - The project's internal and test users filter cannot run
*/
export type InsightDataCheckSkipReasonEnumApi =
(typeof InsightDataCheckSkipReasonEnumApi)[keyof typeof InsightDataCheckSkipReasonEnumApi]
@@ -9209,6 +9213,8 @@ export const InsightDataCheckSkipReasonEnumApi = {
MemoryLimit: 'memory_limit',
TooFewSampledEvents: 'too_few_sampled_events',
FilteredByTrafficType: 'filtered_by_traffic_type',
+ HiddenProperty: 'hidden_property',
+ InvalidFilter: 'invalid_filter',
} as const
/**
@@ -9224,18 +9230,21 @@ export const InsightDataCheckMethodEnumApi = {
} as const
/**
+ * * `filter_internal_users` - Turn on the internal and test users filter for the insight
* * `open_filter_settings` - Change the project's internal and test users filter
*/
export type InsightDataCheckActionEnumApi =
(typeof InsightDataCheckActionEnumApi)[keyof typeof InsightDataCheckActionEnumApi]
export const InsightDataCheckActionEnumApi = {
+ FilterInternalUsers: 'filter_internal_users',
OpenFilterSettings: 'open_filter_settings',
} as const
export interface InsightDataCheckApi {
/** Which check this is.
*
+ * * `internal_users` - Internal and test users
* * `local_development` - Local development events
* * `bot_traffic` - Bot and crawler traffic
* * `duplicate_events` - Events sent twice */
@@ -9254,7 +9263,9 @@ export interface InsightDataCheckApi {
* * `time_limit` - The check took longer than it is allowed
* * `memory_limit` - The check needed more memory than it is allowed
* * `too_few_sampled_events` - The sample has too few events to give a share
- * * `filtered_by_traffic_type` - The insight already filters on traffic type */
+ * * `filtered_by_traffic_type` - The insight already filters on traffic type
+ * * `hidden_property` - A property the check reads is hidden from you
+ * * `invalid_filter` - The project's internal and test users filter cannot run */
skip_reason: InsightDataCheckSkipReasonEnumApi | null
/** `counted` when the check counted every event on the days checked, `sampled` when it read a sample. Null when the check did not run.
*
@@ -9273,8 +9284,9 @@ export interface InsightDataCheckApi {
share: number | null
/** True when `events` is an estimate scaled up from a sample, rather than a count of every event. */
scaled: boolean
- /** The change that fixes it. `open_filter_settings`: change the project's internal and test users filter. Null when there is no single change.
+ /** 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. Null when there is no single change.
*
+ * * `filter_internal_users` - Turn on the internal and test users filter for the insight
* * `open_filter_settings` - Change the project's internal and test users filter */
action: InsightDataCheckActionEnumApi | null
/** The event names the check found most often, most affected first. */
@@ -9310,7 +9322,7 @@ export interface InsightDataChecksCoverageApi {
/** True when the insight filters out the project's internal and test users. */
filters_test_accounts: boolean
/**
- * How many events the insight reads on the days checked, scaled up from the sample when the sample did not read every event. Null when the sample did not run.
+ * 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.
* @nullable
*/
events_checked: number | null
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index b281a6cc6db6..159c0bb59847 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -849,7 +849,7 @@ export const getInsightsDataChecksCreateUrl = (projectId: string, params?: Insig
}
/**
- * Check the events behind an insight for the common ways they mislead: 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. 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/`.
+ * 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`. 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/`.
*/
export const insightsDataChecksCreate = async (
projectId: string,
diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.ts
index ce11674670b4..9d7444b36951 100644
--- a/products/product_analytics/frontend/generated/api.zod.ts
+++ b/products/product_analytics/frontend/generated/api.zod.ts
@@ -287,7 +287,7 @@ export const InsightsCancelCreateBody = /* @__PURE__ */ zod
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
/**
- * Check the events behind an insight for the common ways they mislead: 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. 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/`.
+ * 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`. 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/`.
*/
export const InsightsDataChecksCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a437d8995114..88b78779b6df 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -60467,6 +60467,7 @@ export namespace Schemas {
}
/**
+ * * `internal_users` - Internal and test users
* * `local_development` - Local development events
* * `bot_traffic` - Bot and crawler traffic
* * `duplicate_events` - Events sent twice
@@ -60475,6 +60476,7 @@ export namespace Schemas {
export const InsightDataCheckKeyEnum = {
+ InternalUsers: 'internal_users',
LocalDevelopment: 'local_development',
BotTraffic: 'bot_traffic',
DuplicateEvents: 'duplicate_events',
@@ -60503,6 +60505,8 @@ export namespace Schemas {
* * `memory_limit` - The check needed more memory than it is allowed
* * `too_few_sampled_events` - The sample has too few events to give a share
* * `filtered_by_traffic_type` - The insight already filters on traffic type
+ * * `hidden_property` - A property the check reads is hidden from you
+ * * `invalid_filter` - The project's internal and test users filter cannot run
*/
export type InsightDataCheckSkipReasonEnum = typeof InsightDataCheckSkipReasonEnum[keyof typeof InsightDataCheckSkipReasonEnum];
@@ -60514,6 +60518,8 @@ export namespace Schemas {
MemoryLimit: 'memory_limit',
TooFewSampledEvents: 'too_few_sampled_events',
FilteredByTrafficType: 'filtered_by_traffic_type',
+ HiddenProperty: 'hidden_property',
+ InvalidFilter: 'invalid_filter',
} as const;
/**
@@ -60529,18 +60535,21 @@ export namespace Schemas {
} as const;
/**
+ * * `filter_internal_users` - Turn on the internal and test users filter for the insight
* * `open_filter_settings` - Change the project's internal and test users filter
*/
export type InsightDataCheckActionEnum = typeof InsightDataCheckActionEnum[keyof typeof InsightDataCheckActionEnum];
export const InsightDataCheckActionEnum = {
+ FilterInternalUsers: 'filter_internal_users',
OpenFilterSettings: 'open_filter_settings',
} as const;
export interface InsightDataCheck {
/** Which check this is.
*
+ * * `internal_users` - Internal and test users
* * `local_development` - Local development events
* * `bot_traffic` - Bot and crawler traffic
* * `duplicate_events` - Events sent twice */
@@ -60559,7 +60568,9 @@ export namespace Schemas {
* * `time_limit` - The check took longer than it is allowed
* * `memory_limit` - The check needed more memory than it is allowed
* * `too_few_sampled_events` - The sample has too few events to give a share
- * * `filtered_by_traffic_type` - The insight already filters on traffic type */
+ * * `filtered_by_traffic_type` - The insight already filters on traffic type
+ * * `hidden_property` - A property the check reads is hidden from you
+ * * `invalid_filter` - The project's internal and test users filter cannot run */
skip_reason: InsightDataCheckSkipReasonEnum | null;
/** `counted` when the check counted every event on the days checked, `sampled` when it read a sample. Null when the check did not run.
*
@@ -60578,8 +60589,9 @@ export namespace Schemas {
share: number | null;
/** True when `events` is an estimate scaled up from a sample, rather than a count of every event. */
scaled: boolean;
- /** The change that fixes it. `open_filter_settings`: change the project's internal and test users filter. Null when there is no single change.
+ /** 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. Null when there is no single change.
*
+ * * `filter_internal_users` - Turn on the internal and test users filter for the insight
* * `open_filter_settings` - Change the project's internal and test users filter */
action: InsightDataCheckActionEnum | null;
/** The event names the check found most often, most affected first. */
@@ -60635,7 +60647,7 @@ export namespace Schemas {
/** True when the insight filters out the project's internal and test users. */
filters_test_accounts: boolean;
/**
- * How many events the insight reads on the days checked, scaled up from the sample when the sample did not read every event. Null when the sample did not run.
+ * 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.
* @nullable
*/
events_checked: number | null;