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): flag local, bot and duplicate traffic in insight events (#116813)

Sam Penningtoned1a5101d5fc
diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txt
index 5069a1eed4c3..621549bb7e53 100644
--- a/.github/new-events-schema-targets.txt
+++ b/.github/new-events-schema-targets.txt
@@ -40,6 +40,7 @@ products/mcp_analytics/backend/tests/test_protocol_version_breakdown.py
products/mcp_analytics/backend/tests/test_tool_quality_tables.py
products/mcp_analytics/backend/tests/test_tool_tables.py
products/product_analytics/backend/hogql_queries
+products/product_analytics/backend/tests/test_insight_data_checks.py
products/replay_vision/backend/tests/test_session_identity.py
products/web_analytics/backend/hogql_queries
diff --git a/products/product_analytics/backend/chart_events.py b/products/product_analytics/backend/chart_events.py
index f8e97d7d81bb..1d4b9467137a 100644
--- a/products/product_analytics/backend/chart_events.py
+++ b/products/product_analytics/backend/chart_events.py
@@ -1,5 +1,6 @@
from collections.abc import Mapping
from dataclasses import field
+from datetime import datetime
from typing import Any, cast
from pydantic import ValidationError
@@ -47,19 +48,33 @@ class ChartEvents:
where: ast.Expr
# The part of `where` on event names and dates only, so a count with it reads no event property.
sort_key_where: ast.Expr
+ # The first and last moment any of the chart's queries reads, in the project's timezone.
+ date_from: datetime
+ date_to: datetime
+ filters_test_accounts: bool
modifiers: HogQLQueryModifiers
# The database the filter was read with, for the queries that run it.
database: Database = field(repr=False, compare=False)
def select(
- self, query: str, *, where: ast.Expr, sample: ast.SampleExpr | None = None, **placeholders: ast.Expr
+ self,
+ 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
+ def timestamp(self) -> ast.Field:
+ return ast.Field(chain=[self.alias, "timestamp"] if self.alias else ["timestamp"])
+
def chart_events(query: Mapping[str, Any], team: Team, user: User) -> ChartEvents | None:
"""The events an insight's chart reads, taken from the query the chart runs.
@@ -89,6 +104,7 @@ def chart_events(query: Mapping[str, Any], team: Team, user: User) -> ChartEvent
return None
alias = aliases.pop()
wheres = [_from_date(where, date_range, alias) for _, where, date_range in filters]
+ date_ranges = [date_range for _, _, date_range in filters]
return ChartEvents(
alias=alias,
where=_any_of(wheres),
@@ -98,6 +114,9 @@ def chart_events(query: Mapping[str, Any], team: Team, user: User) -> ChartEvent
for where in wheres
]
),
+ date_from=min(date_range.date_from() for date_range in date_ranges),
+ date_to=max(date_range.date_to() for date_range in date_ranges),
+ filters_test_accounts=bool(runner.query.filterTestAccounts),
modifiers=runner.modifiers,
database=database,
)
diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.py
index c1a5c0051766..aae9d58260bc 100644
--- a/products/product_analytics/backend/facade/contracts.py
+++ b/products/product_analytics/backend/facade/contracts.py
@@ -12,12 +12,22 @@ loses a field surfaces at the facade boundary instead of further down the caller
(``facade.models``, ``facade.queries``); as they convert, their contracts land here too.
"""
-from datetime import datetime
+from dataclasses import field
+from datetime import date, datetime
from typing import Any
from uuid import UUID
from pydantic.dataclasses import dataclass
+from products.product_analytics.backend.facade.enums import (
+ InsightDataCheckAction,
+ InsightDataCheckKey,
+ InsightDataCheckLevel,
+ InsightDataCheckMethod,
+ InsightDataCheckSkipReason,
+ InsightDataChecksStatus,
+)
+
@dataclass(frozen=True)
class InsightVariableDefinition:
@@ -49,3 +59,50 @@ class SavedInsightDefinition:
short_id: str
name: str | None
query: dict[str, Any]
+
+
+@dataclass(frozen=True)
+class InsightDataCheck:
+ key: InsightDataCheckKey
+ level: InsightDataCheckLevel
+ skip_reason: InsightDataCheckSkipReason | None = None
+ method: InsightDataCheckMethod | None = None
+ # The affected events on the checked days, scaled up from the sample when `scaled` is true.
+ events: int | None = None
+ share: float | None = None
+ scaled: bool = False
+ action: InsightDataCheckAction | None = None
+ # The most affected values first, so a finding says what is affected as well as how much.
+ top_events: list[str] = field(default_factory=list)
+ top_hosts: list[str] = field(default_factory=list)
+ top_bots: list[str] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class InsightDataChecksSample:
+ # The share of the events on the checked days that the sample reads.
+ rate: float
+ events: int
+ distinct_ids: int
+
+
+@dataclass(frozen=True)
+class InsightDataChecksCoverage:
+ date_from: date
+ date_to: date
+ days_in_range: int
+ # The newest days of the range, which are all of it when the range is short.
+ checked_date_from: date
+ checked_date_to: date
+ days_checked: int
+ filters_test_accounts: bool
+ # The events on the checked days, scaled up from the sample when the sample did not read every event.
+ events_checked: int | None
+ sample: InsightDataChecksSample | None
+
+
+@dataclass(frozen=True)
+class InsightDataChecks:
+ status: InsightDataChecksStatus
+ checks: list[InsightDataCheck]
+ coverage: InsightDataChecksCoverage | None
diff --git a/products/product_analytics/backend/facade/data_checks.py b/products/product_analytics/backend/facade/data_checks.py
new file mode 100644
index 000000000000..746fa1e4f812
--- /dev/null
+++ b/products/product_analytics/backend/facade/data_checks.py
@@ -0,0 +1,23 @@
+"""
+Data checks on the events an insight reads.
+
+Split out of ``facade.api`` for the same reason as ``facade.account_filters``: the implementation
+runs a HogQL query, and that import chain is too heavy for the light facade module.
+"""
+
+from collections.abc import Mapping
+from typing import Any
+
+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
+
+
+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.
+
+ The checks read the events as `user`. They do not run when a property they read is hidden from that person.
+ """
+ return insight_data_checks.run_insight_data_checks(query, team, user)
diff --git a/products/product_analytics/backend/facade/enums.py b/products/product_analytics/backend/facade/enums.py
index 1a7bc03251b1..d9c4e9665203 100644
--- a/products/product_analytics/backend/facade/enums.py
+++ b/products/product_analytics/backend/facade/enums.py
@@ -1,4 +1,4 @@
-"""Enumerations the product_analytics models use.
+"""Enumerations the product_analytics models and facade contracts use.
Consumers that only need a variable type read it from here and do not need the model class. The
model keeps it as a class attribute (``InsightVariable.Type``) so existing call sites are
@@ -15,3 +15,43 @@ class InsightVariableType(LabeledStrEnum):
BOOLEAN = "Boolean", "Boolean"
LIST = "List", "List"
DATE = "Date", "Date"
+
+
+class InsightDataCheckKey(LabeledStrEnum):
+ LOCAL_DEVELOPMENT = "local_development", "Local development events"
+ BOT_TRAFFIC = "bot_traffic", "Bot and crawler traffic"
+ DUPLICATE_EVENTS = "duplicate_events", "Events sent twice"
+
+
+class InsightDataCheckLevel(LabeledStrEnum):
+ PASSED = "passed", "Passed"
+ WARNING = "warning", "Warning"
+ PROBLEM = "problem", "Problem"
+ SKIPPED = "skipped", "Not checked"
+
+
+class InsightDataCheckMethod(LabeledStrEnum):
+ COUNTED = "counted", "Counted every event on the days checked"
+ SAMPLED = "sampled", "Checked a sample of the events on the days checked"
+
+
+class InsightDataCheckSkipReason(LabeledStrEnum):
+ TOO_MANY_EVENTS = "too_many_events", "The days checked hold too many events to count"
+ READ_LIMIT = "read_limit", "The check would read more data than it is allowed"
+ TIME_LIMIT = "time_limit", "The check took longer than it is allowed"
+ 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"
+
+
+class InsightDataCheckAction(LabeledStrEnum):
+ OPEN_FILTER_SETTINGS = "open_filter_settings", "Change the project's internal and test users filter"
+
+
+class InsightDataChecksStatus(LabeledStrEnum):
+ PASSED = "passed", "No data issues found"
+ WARNING = "warning", "A check found a small issue"
+ PROBLEM = "problem", "A check found a large issue"
+ NO_EVENTS = "no_events", "No events to check"
+ UNSUPPORTED = "unsupported", "This kind of insight cannot be checked"
+ INCONCLUSIVE = "inconclusive", "No check could run"
diff --git a/products/product_analytics/backend/insight_data_check_days.py b/products/product_analytics/backend/insight_data_check_days.py
new file mode 100644
index 000000000000..3b70fdb9ebe8
--- /dev/null
+++ b/products/product_analytics/backend/insight_data_check_days.py
@@ -0,0 +1,39 @@
+"""Which days of an insight's range the data checks read."""
+
+from collections.abc import Mapping
+from datetime import date, timedelta
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class CheckWindow:
+ days_in_range: list[date]
+ # The newest days of the range, oldest first.
+ days_to_check: list[date]
+ # Estimated before the chart's filters, from the sizing sample.
+ events_per_day: dict[date, int]
+
+ @property
+ def checks_whole_range(self) -> bool:
+ return self.days_to_check == self.days_in_range
+
+ @property
+ def events_on_days_to_check(self) -> int:
+ return sum(self.events_per_day[day] for day in self.days_to_check)
+
+
+def days_between(first: date, last: date) -> list[date]:
+ return [first + timedelta(days=offset) for offset in range((last - first).days + 1)]
+
+
+def newest_days_within(events_per_day: Mapping[date, int], budget: int) -> list[date]:
+ chosen: list[date] = []
+ total = 0
+ for day in sorted(events_per_day, reverse=True):
+ total += events_per_day[day]
+ # The newest day is always checked, even when it alone is over the budget.
+ if chosen and total > budget:
+ break
+ chosen.append(day)
+ return sorted(chosen)
diff --git a/products/product_analytics/backend/insight_data_check_results.py b/products/product_analytics/backend/insight_data_check_results.py
new file mode 100644
index 000000000000..2cbc428d900a
--- /dev/null
+++ b/products/product_analytics/backend/insight_data_check_results.py
@@ -0,0 +1,176 @@
+"""Turns the counts the data checks read into a level for each check."""
+
+from posthog.dataclasses import frozen
+
+from products.product_analytics.backend.facade.contracts import InsightDataCheck
+from products.product_analytics.backend.facade.enums import (
+ InsightDataCheckAction,
+ InsightDataCheckKey,
+ InsightDataCheckLevel,
+ InsightDataCheckMethod,
+ InsightDataCheckSkipReason,
+ InsightDataChecksStatus,
+)
+
+MIN_SAMPLED_EVENTS = 1_000
+MIN_FINDING_EVENTS = 50
+MIN_FINDING_SHARE = 0.01
+MIN_DUPLICATE_EVENTS = 100
+# Higher than the other share floors, because events that differ only in custom properties count as repeats.
+MIN_DUPLICATE_SHARE = 0.05
+PROBLEM_SHARE = 0.2
+
+
+@frozen
+class Skipped:
+ reason: InsightDataCheckSkipReason
+
+
+@frozen
+class LocalEvents:
+ count: int
+ top_hosts: list[str]
+ top_events: list[str]
+
+
+@frozen
+class SampledEvents:
+ rate: float
+ events: int
+ distinct_ids: int
+ bot_events: int
+ top_bots: list[str]
+ top_bot_events: list[str]
+ repeated_events: int
+ top_repeated_events: list[str]
+
+ @property
+ def read_every_event(self) -> bool:
+ return self.rate >= 1
+
+
+@frozen
+class CheckedEvents:
+ local: LocalEvents | Skipped
+ sample: SampledEvents | Skipped
+ insight_filters_traffic_type: bool = False
+
+
+def not_checked(key: InsightDataCheckKey, reason: InsightDataCheckSkipReason | None = None) -> InsightDataCheck:
+ return InsightDataCheck(key=key, level=InsightDataCheckLevel.SKIPPED, skip_reason=reason)
+
+
+def _finding_level(share: float | None) -> InsightDataCheckLevel:
+ if share is not None and share >= PROBLEM_SHARE:
+ return InsightDataCheckLevel.PROBLEM
+ return InsightDataCheckLevel.WARNING
+
+
+def _usable_sample(sample: SampledEvents | Skipped) -> SampledEvents | Skipped:
+ if isinstance(sample, Skipped):
+ return sample
+ if not sample.events or (not sample.read_every_event and sample.events < MIN_SAMPLED_EVENTS):
+ return Skipped(reason=InsightDataCheckSkipReason.TOO_FEW_SAMPLED_EVENTS)
+ 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 _local_development_check(checked: CheckedEvents) -> InsightDataCheck:
+ key = InsightDataCheckKey.LOCAL_DEVELOPMENT
+ local = checked.local
+ if isinstance(local, Skipped):
+ return not_checked(key, local.reason)
+
+ share = _local_share(local.count, checked.sample)
+ # 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(
+ key=key,
+ level=_finding_level(share) if is_finding else InsightDataCheckLevel.PASSED,
+ method=InsightDataCheckMethod.COUNTED,
+ events=local.count,
+ share=share,
+ action=InsightDataCheckAction.OPEN_FILTER_SETTINGS if is_finding else None,
+ top_events=local.top_events,
+ top_hosts=local.top_hosts,
+ )
+
+
+def _bot_traffic_check(checked: CheckedEvents) -> InsightDataCheck:
+ key = InsightDataCheckKey.BOT_TRAFFIC
+ # The insight's own traffic type filter already decides which bots it keeps, so a bot check adds nothing.
+ if checked.insight_filters_traffic_type:
+ return not_checked(key, InsightDataCheckSkipReason.FILTERED_BY_TRAFFIC_TYPE)
+
+ sample = _usable_sample(checked.sample)
+ if isinstance(sample, Skipped):
+ return not_checked(key, sample.reason)
+
+ share = sample.bot_events / sample.events
+ estimate = sample.bot_events / sample.rate
+ is_finding = estimate >= MIN_FINDING_EVENTS and share >= MIN_FINDING_SHARE
+ return InsightDataCheck(
+ key=key,
+ level=_finding_level(share) if is_finding else InsightDataCheckLevel.PASSED,
+ method=InsightDataCheckMethod.SAMPLED,
+ events=round(estimate),
+ share=share,
+ scaled=not sample.read_every_event,
+ action=InsightDataCheckAction.OPEN_FILTER_SETTINGS if is_finding else None,
+ top_events=sample.top_bot_events,
+ top_bots=sample.top_bots,
+ )
+
+
+def _duplicate_events_check(checked: CheckedEvents) -> InsightDataCheck:
+ key = InsightDataCheckKey.DUPLICATE_EVENTS
+ sample = _usable_sample(checked.sample)
+ if isinstance(sample, Skipped):
+ return not_checked(key, sample.reason)
+
+ share = sample.repeated_events / sample.events
+ estimate = sample.repeated_events / sample.rate
+ is_finding = estimate >= MIN_DUPLICATE_EVENTS and share >= MIN_DUPLICATE_SHARE
+ return InsightDataCheck(
+ key=key,
+ level=_finding_level(share) if is_finding else InsightDataCheckLevel.PASSED,
+ method=InsightDataCheckMethod.SAMPLED,
+ events=round(estimate),
+ share=share,
+ scaled=not sample.read_every_event,
+ top_events=sample.top_repeated_events,
+ )
+
+
+def found_no_events(checked: CheckedEvents) -> bool:
+ sample = checked.sample
+ return isinstance(sample, SampledEvents) and sample.read_every_event and sample.events == 0
+
+
+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 [
+ _local_development_check(checked),
+ _bot_traffic_check(checked),
+ _duplicate_events_check(checked),
+ ]
+
+
+def status_of(checks: list[InsightDataCheck]) -> InsightDataChecksStatus:
+ levels = {check.level for check in checks}
+ if levels == {InsightDataCheckLevel.SKIPPED}:
+ return InsightDataChecksStatus.INCONCLUSIVE
+ if InsightDataCheckLevel.PROBLEM in levels:
+ return InsightDataChecksStatus.PROBLEM
+ if InsightDataCheckLevel.WARNING in levels:
+ return InsightDataChecksStatus.WARNING
+ return InsightDataChecksStatus.PASSED
diff --git a/products/product_analytics/backend/insight_data_checks.py b/products/product_analytics/backend/insight_data_checks.py
new file mode 100644
index 000000000000..65763e49922c
--- /dev/null
+++ b/products/product_analytics/backend/insight_data_checks.py
@@ -0,0 +1,452 @@
+"""Checks the events an insight reads for 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.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.parser import parse_expr, parse_select
+from posthog.hogql.query import execute_hogql_query
+from posthog.hogql.visitor import TraversingVisitor
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.dataclasses import frozen
+from posthog.errors import CHQueryErrorTooManyBytes
+from posthog.exceptions import (
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQueryTimeOut,
+)
+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.product_analytics.backend.chart_events import ChartEvents, chart_events
+from products.product_analytics.backend.facade.contracts import (
+ InsightDataChecks,
+ InsightDataChecksCoverage,
+ InsightDataChecksSample,
+)
+from products.product_analytics.backend.facade.enums import (
+ InsightDataCheckKey,
+ InsightDataCheckSkipReason,
+ InsightDataChecksStatus,
+)
+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,
+ LocalEvents,
+ SampledEvents,
+ Skipped,
+ evaluate_data_checks,
+ found_no_events,
+ not_checked,
+ status_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
+# The most events the local development check counts, so a busy event checks fewer days.
+EVENT_BUDGET = 20_000_000
+# A day cannot be split, so the newest day alone is counted up to this size.
+MAX_COUNTED_EVENTS = 2 * EVENT_BUDGET
+SAMPLE_SIZE = 100_000
+SIZING_SAMPLE_ONE_IN = 1_000
+
+# A check that takes longer than this is skipped, so it never holds up the insight it sits next to.
+MAX_EXECUTION_SECONDS = 5
+# Backstops for a size estimate that is far too low, such as for an event sent under a few distinct IDs.
+# ClickHouse applies them to each shard separately.
+MAX_BYTES_READ_PER_SHARD = 1_000_000_000
+# The sample reads wide columns and sorts them for the repeat window, so it gets a tighter limit.
+MAX_SAMPLE_BYTES_READ_PER_SHARD = 250_000_000
+
+LOCAL_HOST_PATTERN = r"(?i)^(localhost|[a-z0-9.-]+\.localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:[0-9]+)?$"
+# An event with no user agent has the type "Automation", and server-side SDKs send those, so it is not a crawler.
+CRAWLER_TRAFFIC_TYPES = ("Bot", "AI Agent")
+# A person cannot repeat an action this fast, but an app that sends an event twice does.
+REPEAT_WINDOW_MILLISECONDS = 100
+# A hidden property reads as empty, so the checks cannot run when one of these is hidden.
+CHECKED_PROPERTIES = frozenset(
+ {"$host", "$raw_user_agent", "$ip", "$current_url", "$screen_name", "$feature_flag", "$event_type"}
+)
+# 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"}
+)
+TRAFFIC_TYPE_FUNCTIONS = frozenset(
+ {"isLikelyBot", "getTrafficType", "getTrafficCategory", "getBotName", "getBotOperator"}
+)
+
+_EVENTS_PER_DAY_QUERY = """
+ SELECT toDate(timestamp) AS day, count() AS events
+ FROM events
+ GROUP BY day
+"""
+
+_LOCAL_EVENTS_QUERY = """
+ SELECT
+ count() AS events,
+ topK(3)(toString(properties.$host)) AS top_hosts,
+ topK(3)(event) AS top_events
+ FROM events
+"""
+
+_IS_LOCAL_HOST = "match(toString(properties.$host), {local_host_pattern})"
+
+_SAMPLED_EVENTS_QUERY = """
+ SELECT
+ distinct_id,
+ event,
+ toString(properties.$raw_user_agent) AS user_agent,
+ toString(properties.$ip) AS ip,
+ dateDiff(
+ 'millisecond',
+ lagInFrame(timestamp) OVER (
+ PARTITION BY
+ distinct_id,
+ event,
+ toString(properties.$raw_user_agent),
+ toString(properties.$current_url),
+ toString(properties.$screen_name),
+ toString(properties.$feature_flag),
+ toString(properties.$event_type),
+ elements_chain_texts,
+ elements_chain_href,
+ elements_chain_ids,
+ elements_chain_elements
+ ORDER BY timestamp
+ ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
+ ),
+ timestamp
+ ) AS milliseconds_since_identical_event
+ FROM events
+"""
+
+# Each event, user agent and IP is classified once, which costs far less than classifying every event.
+_SAMPLE_COUNTS_QUERY = """
+ SELECT
+ sum(source_events) AS events,
+ uniqExactMerge(source_distinct_ids) AS distinct_ids,
+ sumIf(source_events, is_bot) AS bot_events,
+ sumMapIf([bot_name], [source_events], is_bot) AS bot_events_by_bot,
+ sumMapIf([event], [source_events], is_bot) AS bot_events_by_event,
+ sum(source_repeated_events) AS repeated_events,
+ sumMap([event], [source_repeated_events]) AS repeated_events_by_event
+ FROM (
+ SELECT
+ event,
+ getTrafficType(user_agent, ip) IN {crawler_traffic_types} AS is_bot,
+ getBotName(user_agent, ip) AS bot_name,
+ source_events,
+ source_repeated_events,
+ source_distinct_ids
+ FROM (
+ SELECT
+ event,
+ user_agent,
+ ip,
+ count() AS source_events,
+ countIf(milliseconds_since_identical_event < {repeat_window_milliseconds}) AS source_repeated_events,
+ uniqExactState(distinct_id) AS source_distinct_ids
+ FROM {sampled_events}
+ GROUP BY event, user_agent, ip
+ )
+ )
+"""
+
+
+@frozen
+class _EventReader:
+ team: Team
+ user: User
+ modifiers: HogQLQueryModifiers
+ # The database the chart's events were read with, so the checks do not build another.
+ database: Database
+
+ def rows_within_limits(
+ self, query: ast.SelectQuery, *, query_type: str, max_bytes_read_per_shard: int
+ ) -> list[list[Any]] | Skipped:
+ try:
+ response = execute_hogql_query(
+ query=query,
+ team=self.team,
+ user=self.user,
+ query_type=query_type,
+ modifiers=self.modifiers,
+ context=HogQLContext(team_id=self.team.pk, user=self.user, database=self.database),
+ settings=_query_settings(max_bytes_read_per_shard),
+ )
+ except CHQueryErrorTooManyBytes:
+ return Skipped(reason=InsightDataCheckSkipReason.READ_LIMIT)
+ except (ClickHouseQueryTimeOut, ClickHouseEstimatedQueryExecutionTimeTooLong):
+ return Skipped(reason=InsightDataCheckSkipReason.TIME_LIMIT)
+ except ClickHouseQueryMemoryLimitExceeded:
+ return Skipped(reason=InsightDataCheckSkipReason.MEMORY_LIMIT)
+ return [list(row) for row in response.results or []]
+
+
+def _query_settings(max_bytes_read_per_shard: int) -> HogQLGlobalSettings:
+ # Without "throw", a query that reaches a limit can return the events it counted so far as the answer.
+ return HogQLGlobalSettings(
+ max_execution_time=MAX_EXECUTION_SECONDS,
+ timeout_overflow_mode="throw",
+ max_bytes_to_read=max_bytes_read_per_shard,
+ read_overflow_mode="throw",
+ )
+
+
+class _TrafficTypeFinder(TraversingVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ self.found = False
+
+ def visit_field(self, node: ast.Field) -> None:
+ self.found = self.found or any(part in TRAFFIC_TYPE_FIELDS for part in node.chain)
+
+ def visit_call(self, node: ast.Call) -> None:
+ self.found = self.found or node.name in TRAFFIC_TYPE_FUNCTIONS
+ super().visit_call(node)
+
+
+def _filters_on_traffic_type(where: ast.Expr) -> bool:
+ finder = _TrafficTypeFinder()
+ finder.visit(where)
+ return finder.found
+
+
+def _check_modifiers(chart_modifiers: HogQLQueryModifiers, *, keep_project_bot_rules: bool) -> HogQLQueryModifiers:
+ # With `debug` on, a failed query returns an error and no rows, which would read as no events.
+ update: dict[str, Any] = {"debug": False}
+ if not keep_project_bot_rules:
+ # The bot check uses PostHog's definition of a bot, so a project's own bot rules do not apply.
+ update["customBotDefinitions"] = []
+ 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 _start_of(day: date, timezone: ZoneInfo) -> ast.Constant:
+ return ast.Constant(value=datetime.combine(day, time.min, tzinfo=timezone))
+
+
+def _between_days(events: ChartEvents, first: date, last: date, timezone: ZoneInfo) -> ast.Expr:
+ """The events from the start of `first` to the end of `last`, as a timestamp range ClickHouse can skip by."""
+ return ast.And(
+ exprs=[
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq, left=events.timestamp(), right=_start_of(first, timezone)
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Lt,
+ left=events.timestamp(),
+ right=_start_of(last + timedelta(days=1), timezone),
+ ),
+ ]
+ )
+
+
+def _sample_of(count: int, total: int) -> ast.SampleExpr:
+ if total <= count:
+ return ast.SampleExpr(sample_value=ast.RatioExpr(left=ast.Constant(value=1)))
+ return ast.SampleExpr(sample_value=ast.RatioExpr(left=ast.Constant(value=count), right=ast.Constant(value=total)))
+
+
+def _top_three(values_by_key: tuple[list[str], list[int]] | None) -> list[str]:
+ """The three keys with the highest values, highest first, from the key and value arrays that sumMap returns."""
+ if not values_by_key:
+ return []
+ keys, values = values_by_key
+ ranked = sorted(zip(keys, values), key=lambda key_and_value: key_and_value[1], reverse=True)
+ return [key for key, value in ranked if key and value > 0][:3]
+
+
+def _count_events_per_day(
+ events: ChartEvents, reader: _EventReader, days: list[date], timezone: ZoneInfo
+) -> dict[date, int] | Skipped:
+ """Each day's events before the chart's filters, estimated from a sample of distinct IDs."""
+ query = events.select(
+ _EVENTS_PER_DAY_QUERY,
+ where=ast.And(exprs=[events.sort_key_where, _between_days(events, days[0], days[-1], timezone)]),
+ sample=_sample_of(1, SIZING_SAMPLE_ONE_IN),
+ )
+ rows = reader.rows_within_limits(
+ query, query_type="insight_data_checks_sizing", max_bytes_read_per_shard=MAX_BYTES_READ_PER_SHARD
+ )
+ if isinstance(rows, Skipped):
+ return rows
+
+ sampled = {day: int(count) for day, count in rows}
+ return {day: sampled.get(day, 0) * SIZING_SAMPLE_ONE_IN for day in days}
+
+
+def _choose_window(events: ChartEvents, reader: _EventReader, timezone: ZoneInfo) -> CheckWindow | Skipped:
+ days_in_range = days_between(
+ events.date_from.astimezone(timezone).date(), events.date_to.astimezone(timezone).date()
+ )
+ events_per_day = _count_events_per_day(events, reader, days_in_range[-MAX_CHECKED_DAYS:], timezone)
+ if isinstance(events_per_day, Skipped):
+ return events_per_day
+
+ return CheckWindow(
+ days_in_range=days_in_range,
+ days_to_check=newest_days_within(events_per_day, EVENT_BUDGET),
+ events_per_day=events_per_day,
+ )
+
+
+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)}
+ )
+ 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]))
+ rows = reader.rows_within_limits(
+ query, query_type="insight_data_checks_local", 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))
+
+
+def _sample_events(
+ events: ChartEvents, reader: _EventReader, where: ast.Expr, *, events_before_filters: int
+) -> SampledEvents | Skipped:
+ sampled_events = events.select(
+ _SAMPLED_EVENTS_QUERY,
+ where=where,
+ # The events table samples by distinct ID, so a sampled ID keeps all its events and no repeat is split.
+ sample=_sample_of(SAMPLE_SIZE, events_before_filters),
+ )
+ query = parse_select(
+ _SAMPLE_COUNTS_QUERY,
+ placeholders={
+ "sampled_events": sampled_events,
+ "crawler_traffic_types": ast.Tuple(exprs=[ast.Constant(value=name) for name in CRAWLER_TRAFFIC_TYPES]),
+ "repeat_window_milliseconds": ast.Constant(value=REPEAT_WINDOW_MILLISECONDS),
+ },
+ )
+ rows = reader.rows_within_limits(
+ cast(ast.SelectQuery, query),
+ query_type="insight_data_checks_sample",
+ max_bytes_read_per_shard=MAX_SAMPLE_BYTES_READ_PER_SHARD,
+ )
+ if isinstance(rows, Skipped):
+ return rows
+
+ row: list[Any] = rows[0] if rows else [0] * 7
+ sampled, distinct_ids, bot_events, by_bot, bots_by_event, repeated_events, repeats_by_event = row
+ return SampledEvents(
+ rate=min(1.0, SAMPLE_SIZE / events_before_filters) if events_before_filters else 1.0,
+ events=int(sampled or 0),
+ distinct_ids=int(distinct_ids or 0),
+ bot_events=int(bot_events or 0),
+ top_bots=_top_three(by_bot),
+ top_bot_events=_top_three(bots_by_event),
+ repeated_events=int(repeated_events or 0),
+ top_repeated_events=_top_three(repeats_by_event),
+ )
+
+
+def _read_checked_days(
+ events: ChartEvents,
+ reader: _EventReader,
+ window: CheckWindow,
+ timezone: ZoneInfo,
+ *,
+ hides_properties: bool,
+ filters_traffic_type: bool,
+) -> 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)
+ if window.events_on_days_to_check <= MAX_COUNTED_EVENTS:
+ local = _count_local_events(events, reader, where, use_prewhere=not hides_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)
+
+
+def _sample_summary(sample: SampledEvents | Skipped) -> InsightDataChecksSample | None:
+ if isinstance(sample, Skipped):
+ return None
+ return InsightDataChecksSample(rate=sample.rate, events=sample.events, distinct_ids=sample.distinct_ids)
+
+
+def _coverage(events: ChartEvents, window: CheckWindow, sample: SampledEvents | Skipped) -> InsightDataChecksCoverage:
+ return InsightDataChecksCoverage(
+ date_from=window.days_in_range[0],
+ date_to=window.days_in_range[-1],
+ days_in_range=len(window.days_in_range),
+ checked_date_from=window.days_to_check[0],
+ 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),
+ )
+
+
+def _nothing_checked(
+ status: InsightDataChecksStatus,
+ coverage: InsightDataChecksCoverage | None = None,
+ reason: InsightDataCheckSkipReason | None = None,
+) -> InsightDataChecks:
+ checks = [not_checked(key, reason) for key in InsightDataCheckKey]
+ return InsightDataChecks(status=status, checks=checks, coverage=coverage)
+
+
+def run_insight_data_checks(query: Mapping[str, Any], team: Team, user: User) -> 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:
+ 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.
+ filters_traffic_type = _filters_on_traffic_type(events.where)
+ reader = _EventReader(
+ team=team,
+ user=user,
+ modifiers=_check_modifiers(events.modifiers, keep_project_bot_rules=filters_traffic_type),
+ database=events.database,
+ )
+ timezone = ZoneInfo(team.timezone)
+ window = _choose_window(events, reader, timezone)
+ if isinstance(window, Skipped):
+ return _nothing_checked(InsightDataChecksStatus.INCONCLUSIVE, reason=window.reason)
+ checked = _read_checked_days(
+ events,
+ reader,
+ window,
+ timezone,
+ hides_properties=bool(hidden_properties),
+ filters_traffic_type=filters_traffic_type,
+ )
+
+ coverage = _coverage(events, window, checked.sample)
+ if found_no_events(checked):
+ return _nothing_checked(InsightDataChecksStatus.NO_EVENTS, coverage)
+ checks = evaluate_data_checks(checked)
+ return InsightDataChecks(status=status_of(checks), checks=checks, coverage=coverage)
diff --git a/products/product_analytics/backend/tests/test_insight_data_checks.py b/products/product_analytics/backend/tests/test_insight_data_checks.py
new file mode 100644
index 000000000000..504697321d72
--- /dev/null
+++ b/products/product_analytics/backend/tests/test_insight_data_checks.py
@@ -0,0 +1,559 @@
+from collections.abc import Mapping
+from dataclasses import replace
+from datetime import UTC, date, datetime, timedelta
+from types import MappingProxyType
+from typing import Any
+
+import time_machine
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.errors import ExposedCHQueryError
+from posthog.models import PropertyDefinition
+
+from products.access_control.backend.facade.api import upsert_property_access_control
+from products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInput
+from products.cohorts.backend.models.cohort import Cohort
+from products.product_analytics.backend.facade.contracts import InsightDataChecks, InsightDataChecksCoverage
+from products.product_analytics.backend.facade.data_checks import run_insight_data_checks
+from products.product_analytics.backend.facade.enums import (
+ InsightDataCheckKey,
+ InsightDataCheckLevel,
+ InsightDataCheckSkipReason,
+)
+from products.product_analytics.backend.insight_data_check_days import newest_days_within
+from products.product_analytics.backend.insight_data_check_results import (
+ CheckedEvents,
+ LocalEvents,
+ SampledEvents,
+ Skipped,
+ evaluate_data_checks,
+ status_of,
+)
+
+PASSED = InsightDataCheckLevel.PASSED
+WARNING = InsightDataCheckLevel.WARNING
+PROBLEM = InsightDataCheckLevel.PROBLEM
+SKIPPED = InsightDataCheckLevel.SKIPPED
+LOCAL = InsightDataCheckKey.LOCAL_DEVELOPMENT
+BOTS = InsightDataCheckKey.BOT_TRAFFIC
+DUPLICATES = InsightDataCheckKey.DUPLICATE_EVENTS
+NOW = datetime(2026, 3, 10, 12, tzinfo=UTC)
+EVENT = "signed up"
+WIDELY_SENT_EVENT = "opened app"
+SENT_ON_THE_FREE_PLAN = "invited teammate"
+BOT_USER_AGENT = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
+BROWSER_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0"
+CRAWLER_IP = "66.249.84.5"
+ORDINARY_BROWSER_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AcmeBrowser/1.0"
+LOCAL_HOST = "localhost:8010"
+CHECKS_MODULE = "products.product_analytics.backend.insight_data_checks"
+RESULTS_MODULE = "products.product_analytics.backend.insight_data_check_results"
+ON_LOCAL_HOST = {"key": "$host", "value": [LOCAL_HOST], "operator": "exact", "type": "event"}
+FROM_A_BOT = {"key": "$raw_user_agent", "value": [BOT_USER_AGENT], "operator": "exact", "type": "event"}
+NOT_A_BOT = {"key": "$virt_traffic_type", "value": ["Bot"], "operator": "is_not", "type": "event"}
+IS_PAID = {"key": "plan", "value": ["paid"], "operator": "exact", "type": "event"}
+HAS_NO_PLAN_TODAY = {"key": "plan", "value": "is_not_set", "operator": "is_not_set", "type": "person"}
+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)]
+
+
+def checked(
+ sampled_events: int,
+ *,
+ 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)
+ return CheckedEvents(
+ local=too_many_to_count if local is None else LocalEvents(count=local, top_hosts=[], top_events=[]),
+ sample=SampledEvents(
+ rate=sample_rate,
+ events=sampled_events,
+ distinct_ids=sampled_events,
+ bot_events=bots,
+ top_bots=[],
+ top_bot_events=[],
+ repeated_events=repeats,
+ top_repeated_events=[],
+ ),
+ )
+
+
+class TestEvaluateDataChecks(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("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}),
+ ("bots_small_share_is_a_warning", checked(10_000, bots=200), {BOTS: WARNING}),
+ (
+ "bots_under_50_sampled_events_but_over_50_in_the_range",
+ checked(1000, bots=40, sample_rate=0.1),
+ {BOTS: WARNING},
+ ),
+ ("bots_under_one_percent", checked(100_000, bots=500), {}),
+ ("duplicates_under_100_events", checked(1000, repeats=99), {}),
+ ("duplicates_under_five_percent", checked(10_000, repeats=400), {}),
+ ("duplicates_over_both_floors", checked(10_000, repeats=600), {DUPLICATES: WARNING}),
+ (
+ "duplicates_under_100_sampled_events_but_over_100_in_the_range",
+ checked(1000, repeats=80, sample_rate=0.01),
+ {DUPLICATES: WARNING},
+ ),
+ ("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},
+ ),
+ ]
+ )
+ def test_level_follows_count_and_share(
+ self,
+ _name: str,
+ checked_events: CheckedEvents,
+ expected: dict[InsightDataCheckKey, InsightDataCheckLevel],
+ ) -> None:
+ checks = evaluate_data_checks(checked_events)
+ assert {check.key: check.level for check in checks} == {
+ **dict.fromkeys(InsightDataCheckKey, PASSED),
+ **expected,
+ }
+
+ @parameterized.expand(
+ [
+ ("local_with_too_many_events_to_count", LOCAL, checked(1000, local=None), "too_many_events"),
+ ("bots_with_too_few_sampled_events", BOTS, checked(500, sample_rate=0.1), "too_few_sampled_events"),
+ (
+ "bots_when_the_insight_filters_on_traffic_type",
+ BOTS,
+ replace(checked(1000), insight_filters_traffic_type=True),
+ "filtered_by_traffic_type",
+ ),
+ (
+ "duplicates_whose_sample_hit_the_read_limit",
+ DUPLICATES,
+ CheckedEvents(
+ local=LocalEvents(count=0, top_hosts=[], top_events=[]),
+ sample=Skipped(reason=InsightDataCheckSkipReason.READ_LIMIT),
+ ),
+ "read_limit",
+ ),
+ ]
+ )
+ def test_a_skipped_check_says_why(
+ self, _name: str, key: InsightDataCheckKey, checked_events: CheckedEvents, reason: str
+ ) -> None:
+ skip_reasons = {check.key: check.skip_reason for check in evaluate_data_checks(checked_events)}
+ assert skip_reasons[key] == reason
+
+ def test_status_is_inconclusive_when_every_check_is_skipped(self) -> None:
+ checks = evaluate_data_checks(
+ CheckedEvents(
+ local=Skipped(reason=InsightDataCheckSkipReason.TOO_MANY_EVENTS),
+ sample=Skipped(reason=InsightDataCheckSkipReason.READ_LIMIT),
+ )
+ )
+
+ assert status_of(checks) == "inconclusive"
+
+
+class TestNewestDaysWithin(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("days_within_the_budget", 1000, SEVEN_DAYS),
+ ("budget_reached", 30, SEVEN_DAYS[-3:]),
+ ("newest_day_alone_over_the_budget", 5, SEVEN_DAYS[-1:]),
+ ]
+ )
+ def test_keeps_the_newest_days_within_the_budget(self, _name: str, budget: int, expected: list[date]) -> None:
+ assert newest_days_within(dict.fromkeys(SEVEN_DAYS, 10), budget) == expected
+
+
+@time_machine.travel(NOW, tick=False)
+@patch(f"{CHECKS_MODULE}.SIZING_SAMPLE_ONE_IN", 1)
+@patch(f"{CHECKS_MODULE}.MAX_CHECKED_DAYS", 10_000)
+class TestInsightDataChecks(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.test_account_filters = [
+ {"key": "email", "value": "@posthog.com", "operator": "not_icontains", "type": "person"}
+ ]
+ self.team.save()
+ _create_person(team=self.team, distinct_ids=["real"], properties={"email": "[email protected]"})
+ _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, 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"})
+ self._events(30, properties={"$host": LOCAL_HOST, "$process_person_profile": False})
+ for _ in range(110):
+ self._events(2, seconds_apart=0, properties={"$current_url": "https://example.com/pricing"})
+ self._events(50, event="another event", properties={"$host": LOCAL_HOST})
+ self._events(50, days_ago=70, properties={"$host": LOCAL_HOST})
+ self._events(40, event=SENT_ON_THE_FREE_PLAN, person_properties={"plan": "free"})
+ flush_persons_and_events()
+
+ def _events(
+ self,
+ count: int,
+ *,
+ distinct_id: str = "real",
+ event: str = EVENT,
+ days_ago: int = 1,
+ seconds_apart: int = 1,
+ properties: Mapping[str, Any] = MappingProxyType({}),
+ person_properties: Mapping[str, Any] = MappingProxyType({}),
+ ) -> None:
+ for _ in range(count):
+ _create_event(
+ team=self.team,
+ event=event,
+ distinct_id=distinct_id,
+ timestamp=NOW - timedelta(days=days_ago, seconds=self._second),
+ properties=dict(properties),
+ person_properties=dict(person_properties),
+ )
+ self._second += seconds_apart
+ self._second += 1
+
+ def _query(self, series: list[dict[str, Any]] = ONE_STEP, **source: Any) -> dict[str, Any]:
+ return {
+ "kind": "InsightVizNode",
+ "source": {
+ # Not a trends query: the repo's crossing scan reads one in a test as a run of web analytics code.
+ "kind": "LifecycleQuery",
+ "series": series,
+ "dateRange": {"date_from": "-60d"},
+ **source,
+ },
+ }
+
+ def _check(self, query: dict[str, Any]) -> InsightDataChecks:
+ return run_insight_data_checks(query, team=self.team, user=self.user)
+
+ def _coverage(self, result: InsightDataChecks) -> InsightDataChecksCoverage:
+ assert result.coverage is not None
+ return result.coverage
+
+ def _events_checked(self, query: dict[str, Any]) -> int | None:
+ return self._coverage(self._check(query)).events_checked
+
+ def test_counts_each_problem_in_the_events_the_insight_reads(self) -> None:
+ result = self._check(self._query())
+
+ coverage = self._coverage(result)
+ assert result.status == "warning"
+ 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} == {
+ "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} == {
+ "local_development": ([EVENT], [LOCAL_HOST], []),
+ "bot_traffic": ([EVENT], [], ["Google fetcher", "Googlebot"]),
+ "duplicate_events": ([EVENT], [], []),
+ }
+
+ @parameterized.expand(
+ [
+ ("internal_users_filter", {"filterTestAccounts": True}, 540),
+ ("property_filter", {"properties": [ON_LOCAL_HOST]}, 60),
+ (
+ "filter_on_the_series",
+ {"series": [{"kind": "EventsNode", "event": EVENT, "properties": [ON_LOCAL_HOST]}]},
+ 60,
+ ),
+ (
+ "a_filter_on_each_series",
+ {
+ "kind": "StickinessQuery",
+ "series": [
+ {"kind": "EventsNode", "event": EVENT, "properties": [ON_LOCAL_HOST]},
+ {"kind": "EventsNode", "properties": [FROM_A_BOT]},
+ ],
+ },
+ 120,
+ ),
+ (
+ "series_that_counts_groups",
+ {
+ "kind": "StickinessQuery",
+ "series": [
+ {
+ "kind": "EventsNode",
+ "event": EVENT,
+ "math": "unique_group",
+ "math_group_type_index": 0,
+ }
+ ],
+ },
+ 60,
+ ),
+ ("insight_that_counts_groups", {"aggregation_group_type_index": 0}, 60),
+ (
+ "funnel_that_counts_a_property",
+ {
+ "kind": "FunnelsQuery",
+ "series": TWO_STEPS,
+ "funnelsFilter": {"funnelAggregateByHogQL": "properties.$current_url"},
+ },
+ 220,
+ ),
+ ("shorter_date_range", {"kind": "StickinessQuery", "dateRange": {"date_from": "-12h"}}, 0),
+ ("date_range_without_a_start", {"dateRange": {}}, 600),
+ ("weekdays", {"kind": "StickinessQuery", "dateRange": {"date_from": "-80d", "daysOfWeek": [2]}}, 50),
+ (
+ "query_modifiers",
+ {
+ "series": [{"kind": "EventsNode", "event": SENT_ON_THE_FREE_PLAN}],
+ "properties": [HAS_NO_PLAN_TODAY],
+ "modifiers": {"personsOnEventsMode": "person_id_override_properties_joined"},
+ },
+ 40,
+ ),
+ ]
+ )
+ def test_checks_only_what_the_insights_own_filters_keep(
+ self, _name: str, source: dict[str, Any], events_checked: int
+ ) -> None:
+ assert self._events_checked(self._query(**source)) == events_checked
+
+ @parameterized.expand(
+ [
+ ("trends_reads_the_cohort", "TrendsQuery", ONE_STEP, ["@posthog.com"], [], 60),
+ (
+ "trends_reads_everyone_when_all_users_is_a_value",
+ "TrendsQuery",
+ ONE_STEP,
+ ["@posthog.com"],
+ ["all"],
+ 630,
+ ),
+ (
+ "funnel_with_two_cohorts_reads_them",
+ "FunnelsQuery",
+ TWO_STEPS,
+ ["@posthog.com", "@nobody.example"],
+ [],
+ 60,
+ ),
+ ("funnel_with_one_cohort_reads_everyone", "FunnelsQuery", TWO_STEPS, ["@posthog.com"], [], 630),
+ ]
+ )
+ def test_checks_the_people_a_cohort_breakdown_reads(
+ self,
+ _name: str,
+ kind: str,
+ series: list[dict[str, Any]],
+ cohort_domains: list[str],
+ other_values: list[str],
+ events_checked: int,
+ ) -> None:
+ cohorts = [
+ Cohort.objects.create(
+ team=self.team,
+ name=domain,
+ groups=[{"properties": [{"key": "email", "value": domain, "operator": "icontains", "type": "person"}]}],
+ )
+ for domain in cohort_domains
+ ]
+ for cohort in cohorts:
+ cohort.calculate_people_ch(pending_version=0)
+ query = self._query(
+ series,
+ kind=kind,
+ breakdownFilter={
+ "breakdown_type": "cohort",
+ "breakdown": [*(cohort.id for cohort in cohorts), *other_values],
+ },
+ )
+
+ assert self._events_checked(query) == events_checked
+
+ def test_a_first_time_series_checks_only_the_events_in_its_date_range(self) -> None:
+ query = self._query([{"kind": "EventsNode", "event": EVENT, "math": "first_time_for_user"}], kind="TrendsQuery")
+
+ assert self._events_checked(query) == 630
+
+ @parameterized.expand(
+ [
+ ("that_has_no_filter", [], 98, PASSED),
+ ("whose_filter_keeps_too_few_sampled_events", [IS_PAID], 6, SKIPPED),
+ ]
+ )
+ def test_samples_an_insight_with_more_events_than_the_sample_size(
+ self,
+ _name: str,
+ properties: list[dict[str, Any]],
+ sampled_events: int,
+ bot_check_level: InsightDataCheckLevel,
+ ) -> None:
+ for person in range(10):
+ self._events(2, distinct_id=f"person-{person}", event=WIDELY_SENT_EVENT, properties={"plan": "paid"})
+ for person in range(10, 200):
+ self._events(2, distinct_id=f"person-{person}", event=WIDELY_SENT_EVENT)
+ flush_persons_and_events()
+
+ with (
+ patch(f"{CHECKS_MODULE}.SAMPLE_SIZE", 100),
+ patch(f"{RESULTS_MODULE}.MIN_SAMPLED_EVENTS", 50),
+ ):
+ result = self._check(
+ self._query([{"kind": "EventsNode", "event": WIDELY_SENT_EVENT}], properties=properties)
+ )
+
+ sample = self._coverage(result).sample
+ assert sample is not None
+ assert (sample.rate, sample.events) == (0.25, sampled_events)
+ assert {check.key: check.level for check in result.checks}[BOTS] == bot_check_level
+
+ @parameterized.expand(
+ [
+ ("events_on_every_day", range(20), "problem", 70),
+ ("no_events_on_the_newest_days", range(10, 20), "no_events", 0),
+ ]
+ )
+ def test_checks_only_the_newest_days_of_a_longer_range(
+ self, _name: str, days_with_events: range, status: str, events_checked: int
+ ) -> None:
+ for days_ago in days_with_events:
+ self._events(10, event=WIDELY_SENT_EVENT, days_ago=days_ago, properties={"$host": LOCAL_HOST})
+ flush_persons_and_events()
+ query = self._query(
+ [{"kind": "EventsNode", "event": WIDELY_SENT_EVENT}],
+ kind="StickinessQuery",
+ dateRange={"date_from": "-19d"},
+ )
+
+ with patch(f"{CHECKS_MODULE}.MAX_CHECKED_DAYS", 7):
+ result = self._check(query)
+
+ coverage = self._coverage(result)
+ assert (result.status, coverage.days_in_range, coverage.days_checked) == (status, 20, 7)
+ assert coverage.events_checked == events_checked
+
+ @parameterized.expand(
+ [
+ ("insight_without_a_traffic_type_filter", [], 620, 60, None),
+ ("insight_that_filters_on_traffic_type", [NOT_A_BOT], 540, None, "filtered_by_traffic_type"),
+ ]
+ )
+ def test_applies_a_projects_own_bot_rules_only_to_the_insights_filters(
+ self,
+ _name: str,
+ properties: list[dict[str, Any]],
+ events_checked: int,
+ bot_events: int | None,
+ bot_skip_reason: str | None,
+ ) -> None:
+ self._events(20, properties={"$raw_user_agent": ORDINARY_BROWSER_USER_AGENT})
+ flush_persons_and_events()
+ self.team.modifiers = {
+ "customBotDefinitions": [
+ {
+ "id": "acme",
+ "name": "Acme",
+ "combiner": "OR",
+ "items": [{"id": "1", "key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBrowser"}],
+ }
+ ]
+ }
+ self.team.save()
+
+ result = self._check(self._query(properties=properties))
+
+ bots = next(check for check in result.checks if check.key == BOTS)
+ assert self._coverage(result).events_checked == events_checked
+ assert (bots.events, bots.skip_reason) == (bot_events, bot_skip_reason)
+
+ def test_ignores_the_interval_a_lifecycle_chart_reads_before_its_range(self) -> None:
+ self._events(10, event=WIDELY_SENT_EVENT, days_ago=8, properties={"$host": LOCAL_HOST})
+ flush_persons_and_events()
+ query = self._query([{"kind": "EventsNode", "event": WIDELY_SENT_EVENT}], dateRange={"date_from": "-7d"})
+
+ assert self._check(query).status == "no_events"
+
+ def test_counts_an_event_as_sent_twice_only_when_an_identical_one_came_under_100_ms_before(self) -> None:
+ sent_twice_by_the_app = (timedelta(0), timedelta(milliseconds=20))
+ clicked_twice_by_a_person = (timedelta(seconds=30), timedelta(seconds=30.3))
+ for pair in range(10):
+ sent_at = NOW - timedelta(days=2, minutes=pair)
+ for gap in (*sent_twice_by_the_app, *clicked_twice_by_a_person):
+ _create_event(team=self.team, event=WIDELY_SENT_EVENT, distinct_id="real", timestamp=sent_at + gap)
+ flush_persons_and_events()
+
+ never_sent_twice = {"kind": "EventsNode", "event": SENT_ON_THE_FREE_PLAN}
+ query = self._query(
+ [{"kind": "EventsNode", "event": WIDELY_SENT_EVENT}, never_sent_twice], kind="StickinessQuery"
+ )
+
+ result = self._check(query)
+
+ duplicates = next(check for check in result.checks if check.key == DUPLICATES)
+ assert (duplicates.events, duplicates.top_events) == (10, [WIDELY_SENT_EVENT])
+
+ @parameterized.expand(
+ [
+ ("unknown_event", [{"kind": "EventsNode", "event": "never sent"}], 1_000_000_000, "no_events"),
+ ("action_series", [{"kind": "ActionsNode", "id": 1}], 1_000_000_000, "unsupported"),
+ ("read_limit_reached_while_sizing", ONE_STEP, 1, "inconclusive"),
+ ]
+ )
+ def test_reports_why_nothing_was_checked(
+ self, _name: str, series: list[dict[str, Any]], max_bytes_read_per_shard: int, expected: str
+ ) -> None:
+ with patch(f"{CHECKS_MODULE}.MAX_BYTES_READ_PER_SHARD", max_bytes_read_per_shard):
+ result = self._check(self._query(series))
+
+ assert result.status == expected
+ assert {check.level for check in result.checks} == {"skipped"}
+
+ def test_a_filter_that_cannot_run_raises_with_the_debug_modifier_on(self) -> None:
+ query = self._query(properties=[{"type": "hogql", "key": "throwIf(1, 'stop') = 0"}], modifiers={"debug": True})
+
+ with self.assertRaises(ExposedCHQueryError):
+ self._check(query)
+
+ @parameterized.expand(
+ [
+ ("a_property_the_checks_read", "$host", "unsupported"),
+ ("a_property_the_checks_do_not_read", "plan", "warning"),
+ ]
+ )
+ def test_a_hidden_property_stops_the_checks_only_when_they_read_it(
+ self, _name: str, hidden_property: str, status: str
+ ) -> 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
+ )
+ upsert_property_access_control(
+ team_id=self.team.id,
+ created_by_id=self.user.id,
+ input=UpsertPropertyAccessControlInput(
+ access_level=PropertyAccessLevel.NONE,
+ property_definition_id=str(definition.id),
+ organization_member_id=self.organization_membership.id,
+ ),
+ )
+
+ assert self._check(self._query()).status == status