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.

fix(insights): cap the size of the retention matrix (#102262)

Sam Penningtone2504bb9cb5e
diff --git a/posthog/hogql_queries/utils/query_date_range.py b/posthog/hogql_queries/utils/query_date_range.py
index 4d99ec368ac7..4ad3e0d9d6bb 100644
--- a/posthog/hogql_queries/utils/query_date_range.py
+++ b/posthog/hogql_queries/utils/query_date_range.py
@@ -514,22 +514,41 @@ class QueryDateRangeWithIntervals(QueryDateRange):
return cast(timedelta, PERIOD_MAP[period.lower()]) * interval
@cached_property
- def intervals_between(self):
+ def intervals_between(self) -> int:
"""
Number of intervals between date_from and date_to
"""
assert self._interval
date_from = self.date_from()
+ date_to = self.date_to()
delta = PERIOD_MAP[self._interval.lower()]
- intervals = 0
- while date_from < self.date_to():
- date_from = date_from + delta
+ # Counted from the span instead of by stepping, because `dateRange` comes from the request: an hourly
+ # grain over a century would walk a million datetimes to arrive at a number. The estimate can miss by
+ # one interval around a daylight saving change, so it is corrected against the comparison it replaces.
+ intervals = self._estimated_intervals_between(date_from, date_to)
+ while date_from + delta * intervals < date_to:
intervals += 1
+ while intervals > 0 and date_from + delta * (intervals - 1) >= date_to:
+ intervals -= 1
return intervals
+ def _estimated_intervals_between(self, date_from: datetime, date_to: datetime) -> int:
+ assert self._interval
+
+ period = PERIOD_MAP[self._interval.lower()]
+ if isinstance(period, relativedelta):
+ months_per_interval = period.years * 12 + period.months
+ months_apart = (date_to.year - date_from.year) * 12 + date_to.month - date_from.month
+ return max(months_apart // months_per_interval, 0)
+
+ # Local time, not elapsed time, because adding a timedelta to an aware datetime moves the local clock
+ # by that amount whether or not a daylight saving change falls inside the step.
+ span = date_to.replace(tzinfo=None) - date_from.replace(tzinfo=None)
+ return max(span // period, 0)
+
def date_from(self) -> datetime:
assert self._interval
diff --git a/posthog/hogql_queries/utils/test/test_query_date_range.py b/posthog/hogql_queries/utils/test/test_query_date_range.py
index afc103faa5ec..5e14a80038d8 100644
--- a/posthog/hogql_queries/utils/test/test_query_date_range.py
+++ b/posthog/hogql_queries/utils/test/test_query_date_range.py
@@ -13,6 +13,7 @@ from posthog.schema import DateRange, IntervalType
from posthog.hogql import ast
from posthog.hogql_queries.utils.query_date_range import QueryDateRange, QueryDateRangeWithIntervals
+from posthog.interval_specs import PERIOD_MAP
from posthog.models.team import WeekStartDay
@@ -718,6 +719,19 @@ class TestDaysOfWeek(APIBaseTest):
self.assertIsNone(qdr.days_of_week())
+def _count_intervals_by_stepping(query: QueryDateRangeWithIntervals) -> int:
+ date_from = query.date_from()
+ date_to = query.date_to()
+ delta = PERIOD_MAP[query.interval_name]
+
+ intervals = 0
+ while date_from < date_to:
+ date_from = date_from + delta
+ intervals += 1
+
+ return intervals
+
+
class TestQueryDateRangeWithIntervals(APIBaseTest):
def setUp(self):
self.now = parser.isoparse("2021-08-25T00:00:00.000Z")
@@ -738,6 +752,37 @@ class TestQueryDateRangeWithIntervals(APIBaseTest):
# and truncates to start of interval, so 2021-07-01 00:00:00 UTC becomes 2021-07-02 00:00:00 UTC)
self.assertEqual(query.date_to(), parser.isoparse("2021-07-02T00:00:00Z"))
+ def test_intervals_between_counts_the_intervals_the_range_spans(self):
+ query = QueryDateRangeWithIntervals(DateRange(date_from="-7d"), 8, self.team, IntervalType.DAY, self.now)
+ self.assertEqual(query.intervals_between, 8)
+
+ @parameterized.expand(
+ [
+ ("hourly_over_a_decade", "-10y", "2021-08-25T00:00:00Z", IntervalType.HOUR, "UTC"),
+ ("daily_over_a_year", "-365d", "2021-08-25T00:00:00Z", IntervalType.DAY, "UTC"),
+ (
+ "hourly_across_spring_forward",
+ "2024-03-09",
+ "2024-03-11T00:00:00Z",
+ IntervalType.HOUR,
+ "America/New_York",
+ ),
+ ("hourly_across_fall_back", "2024-11-02", "2024-11-04T00:00:00Z", IntervalType.HOUR, "America/New_York"),
+ ("daily_across_spring_forward", "2024-03-01", "2024-04-01T00:00:00Z", IntervalType.DAY, "America/New_York"),
+ ("weekly_across_fall_back", "2024-10-01", "2024-12-01T00:00:00Z", IntervalType.WEEK, "America/New_York"),
+ ("monthly_over_two_years", "-24m", "2024-06-15T00:00:00Z", IntervalType.MONTH, "America/New_York"),
+ ]
+ )
+ def test_intervals_between_matches_stepping_through_the_range(
+ self, _name: str, date_from: str, now: str, interval: IntervalType, timezone: str
+ ):
+ self.team.timezone = timezone
+ query = QueryDateRangeWithIntervals(
+ DateRange(date_from=date_from), 8, self.team, interval, parser.isoparse(now)
+ )
+
+ self.assertEqual(query.intervals_between, _count_intervals_by_stepping(query))
+
def test_determine_time_delta_valid(self):
delta = QueryDateRangeWithIntervals.determine_time_delta(5, "day")
self.assertEqual(delta, timedelta(days=5))
diff --git a/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py b/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
index 3a60ef705e63..707df424a4eb 100644
--- a/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
@@ -59,6 +59,7 @@ from products.product_analytics.backend.hogql_queries.retention.retention_base_q
from products.product_analytics.backend.hogql_queries.retention.retention_validation_rules import (
DisallowBreakdownsWithDataWarehouse24HourWindows,
DisallowCumulativeWith24HourWindows,
+ DisallowExcessiveIntervals,
DisallowGroupAggregationWithDataWarehouse24HourWindows,
DisallowPropertyAggregationWith24HourWindows,
DisallowUnsupportedDataWarehouseTimestampField,
@@ -148,6 +149,7 @@ class RetentionQueryRunner(AnalyticsQueryRunner[RetentionQueryResponse]):
def validators(self) -> Sequence[QueryValidationRule[RetentionQuery]]:
return (
DisallowCumulativeWith24HourWindows(),
+ DisallowExcessiveIntervals(),
DisallowBreakdownsWithDataWarehouse24HourWindows(),
DisallowGroupAggregationWithDataWarehouse24HourWindows(),
DisallowPropertyAggregationWith24HourWindows(),
@@ -702,11 +704,13 @@ class RetentionQueryRunner(AnalyticsQueryRunner[RetentionQueryResponse]):
breakdown_totals[breakdown_value] = breakdown_totals.get(breakdown_value, 0) + count
# Step 2: Rank breakdowns and determine top N and 'Other'
- breakdown_limit = (
+ requested_breakdown_limit = (
self.query.breakdownFilter.breakdown_limit
if self.query.breakdownFilter and self.query.breakdownFilter.breakdown_limit is not None
else get_breakdown_limit_for_context(self.limit_context)
)
+ # A negative limit slices from the end of the ranked values, which keeps all but the last one.
+ breakdown_limit = max(requested_breakdown_limit, 0)
sorted_breakdowns = sorted(breakdown_totals.items(), key=lambda item: (-item[1], item[0]))
other_values = {item[0] for item in sorted_breakdowns[breakdown_limit:]}
diff --git a/products/product_analytics/backend/hogql_queries/retention/retention_validation_rules.py b/products/product_analytics/backend/hogql_queries/retention/retention_validation_rules.py
index 6cd2e30f6b8d..8d39953d1d54 100644
--- a/products/product_analytics/backend/hogql_queries/retention/retention_validation_rules.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_validation_rules.py
@@ -1,14 +1,45 @@
+from typing import Protocol, cast
+
from rest_framework.exceptions import ValidationError
from posthog.schema import AggregationType, EntityType, RetentionQuery
+from posthog.hogql.constants import LimitContext, get_breakdown_limit_for_context
from posthog.hogql.database.database import Database
from posthog.hogql.database.models import DateDatabaseField, DateTimeDatabaseField
from posthog.hogql_queries.utils.breakdowns import has_breakdown_filter
from posthog.hogql_queries.utils.data_warehouse_schema_mixin import resolve_warehouse_field
+from posthog.hogql_queries.utils.query_date_range import QueryDateRangeWithIntervals
from posthog.hogql_queries.validation.validation import QueryValidationContext
+# Well above the 32 intervals the insight editor allows, so only a hand-written query reaches it.
+MAX_RETENTION_INTERVALS = 100
+
+# One cohort row per interval the date range spans. Well above an all-time daily chart on a project that
+# has collected events for years, which is the widest shape a saved insight reaches.
+MAX_RETENTION_COHORTS = 10_000
+
+# Both axes at their own limit would still be a million cells, so the product carries the limit that decides
+# how much memory one matrix can take.
+MAX_RETENTION_CELLS = 100_000
+
+# A breakdown builds the whole matrix once per breakdown value, and `breakdown_limit` comes from the request,
+# so the response needs its own limit. Set above a CSV export of a breakdown chart, which asks for the widest
+# response the product itself produces.
+MAX_RETENTION_RESPONSE_CELLS = 1_000_000
+
+
+class SupportsRetentionMatrixSize(Protocol):
+ @property
+ def query_date_range(self) -> QueryDateRangeWithIntervals: ...
+
+ @property
+ def lookahead_period_count(self) -> int: ...
+
+ @property
+ def limit_context(self) -> LimitContext: ...
+
class DisallowCumulativeWith24HourWindows:
code = "retention_cumulative_24_hour_windows_unsupported"
@@ -143,3 +174,66 @@ class DisallowPropertyAggregationWith24HourWindows:
"Sum and average aggregation are not supported for 24 hour windows.",
code=self.code,
)
+
+
+class DisallowExcessiveIntervals:
+ """The result matrix has one cell for each pair of a start interval and a return interval, and the query
+ builds every cell in Python, so its cost is the product of the two axes. The request sets each axis on its
+ own: the columns through `totalIntervals` or the custom brackets, the rows through the number of intervals
+ the date range spans, which is why a limit on one axis alone still leaves a query that allocates for
+ millions of cells. The row count also sizes the `date_range` array that ClickHouse builds for every
+ actor."""
+
+ code = "retention_too_many_intervals"
+
+ def validate(self, context: QueryValidationContext[RetentionQuery]) -> None:
+ retention_filter = context.query.retentionFilter
+ requested: float = retention_filter.totalIntervals or 0
+ brackets = retention_filter.retentionCustomBrackets
+ if brackets:
+ requested = max(requested, len(brackets), sum(brackets))
+ if requested > MAX_RETENTION_INTERVALS:
+ raise ValidationError(
+ f"Retention supports up to {MAX_RETENTION_INTERVALS} intervals. "
+ "Ask for fewer intervals, or use a longer period.",
+ code=self.code,
+ )
+
+ runner = cast(SupportsRetentionMatrixSize, context.runner)
+ cohorts = runner.query_date_range.intervals_between
+ if cohorts > MAX_RETENTION_COHORTS:
+ raise ValidationError(
+ f"Retention supports up to {MAX_RETENTION_COHORTS:,} cohorts. "
+ "Shorten the date range, or use a longer period.",
+ code=self.code,
+ )
+
+ cells = cohorts * runner.lookahead_period_count
+ if cells > MAX_RETENTION_CELLS:
+ raise ValidationError(
+ f"Retention supports up to {MAX_RETENTION_CELLS:,} cells, and this query asks for {cells:,}. "
+ "Shorten the date range, or ask for fewer intervals.",
+ code=self.code,
+ )
+
+ response_cells = cells * self._matrix_count(context, runner)
+ if response_cells > MAX_RETENTION_RESPONSE_CELLS:
+ raise ValidationError(
+ f"Retention supports up to {MAX_RETENTION_RESPONSE_CELLS:,} cells across a breakdown, and this "
+ f"query asks for {response_cells:,}. Break down by fewer values, shorten the date range, "
+ "or ask for fewer intervals.",
+ code=self.code,
+ )
+
+ def _matrix_count(
+ self, context: QueryValidationContext[RetentionQuery], runner: SupportsRetentionMatrixSize
+ ) -> int:
+ breakdown_filter = context.query.breakdownFilter
+ if not has_breakdown_filter(breakdown_filter):
+ return 1
+ assert breakdown_filter is not None
+ requested = breakdown_filter.breakdown_limit
+ if requested is None:
+ requested = get_breakdown_limit_for_context(runner.limit_context)
+ # The values past the limit fold into one more matrix, labelled "Other".
+ return max(requested, 0) + 1
diff --git a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
index f1f4929286e4..70ecbfcb13a7 100644
--- a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
@@ -6580,6 +6580,24 @@ class TestClickhouseRetentionGroupAggregation(ClickhouseTestMixin, APIBaseTest):
),
)
+ # A negative limit slices the ranked values from the end, which would keep all but one of them.
+ negative_limit_result = self.run_query(
+ query={
+ "dateRange": {"date_to": _date(5, hour=0)},
+ "retentionFilter": {
+ "totalIntervals": 6,
+ "period": "Day",
+ },
+ "breakdownFilter": {
+ "breakdowns": [{"property": "browser", "type": "event"}],
+ "breakdown_limit": -1,
+ },
+ }
+ )
+
+ negative_limit_values = {c.get("breakdown_value") for c in negative_limit_result}
+ self.assertEqual(negative_limit_values, {BREAKDOWN_OTHER_STRING_LABEL})
+
def test_retention_with_virtual_person_property_breakdown(self):
with time_machine.travel("2020-01-12T12:00:00Z", tick=False):
# Create person with initial referring domain
diff --git a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_validation_rules.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_validation_rules.py
index 4d92e6ed97e7..e4c3c359d4d1 100644
--- a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_validation_rules.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_validation_rules.py
@@ -4,12 +4,26 @@ from unittest.mock import MagicMock
from parameterized import parameterized
from rest_framework.exceptions import ValidationError
-from posthog.schema import AggregationType, BreakdownFilter, EntityType, RetentionFilter, RetentionQuery, TimeWindowMode
+from posthog.schema import (
+ AggregationType,
+ BreakdownFilter,
+ DateRange,
+ EntityType,
+ RetentionFilter,
+ RetentionPeriod,
+ RetentionQuery,
+ TimeWindowMode,
+)
from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings
from posthog.hogql_queries.validation.validation import QueryValidationContext
+from products.product_analytics.backend.hogql_queries.retention.retention_query_runner import RetentionQueryRunner
from products.product_analytics.backend.hogql_queries.retention.retention_validation_rules import (
+ MAX_RETENTION_CELLS,
+ MAX_RETENTION_COHORTS,
+ MAX_RETENTION_INTERVALS,
+ MAX_RETENTION_RESPONSE_CELLS,
DisallowBreakdownsWithDataWarehouse24HourWindows,
DisallowCumulativeWith24HourWindows,
DisallowGroupAggregationWithDataWarehouse24HourWindows,
@@ -23,6 +37,9 @@ class TestRetentionValidationRules(BaseTest):
runner = MagicMock(query=query, team=self.team, user=None)
return QueryValidationContext(query=query, team=self.team, user=None, runner=runner)
+ def _runner(self, query: RetentionQuery) -> RetentionQueryRunner:
+ return RetentionQueryRunner(query=query, team=self.team)
+
def _data_warehouse_entity(self) -> dict[str, str]:
return {
"id": "signups",
@@ -261,3 +278,123 @@ class TestRetentionValidationRules(BaseTest):
self.assertEqual(
context.exception.get_codes(), ["retention_custom_aggregation_target_requires_data_warehouse_entities"]
)
+
+ @parameterized.expand(
+ [
+ ("default_intervals", None, None, None, None, None),
+ ("intervals_at_limit", MAX_RETENTION_INTERVALS, None, None, None, None),
+ (
+ "intervals_over_limit",
+ MAX_RETENTION_INTERVALS + 1,
+ None,
+ None,
+ None,
+ f"Retention supports up to {MAX_RETENTION_INTERVALS} intervals.",
+ ),
+ (
+ "intervals_far_over_limit",
+ 10_000_000,
+ None,
+ None,
+ None,
+ f"Retention supports up to {MAX_RETENTION_INTERVALS} intervals.",
+ ),
+ ("brackets_within_limit", 7, [1, 3, 5], None, None, None),
+ (
+ "brackets_sum_over_limit",
+ 7,
+ [1, 10_000_000],
+ None,
+ None,
+ f"Retention supports up to {MAX_RETENTION_INTERVALS} intervals.",
+ ),
+ (
+ "brackets_count_over_limit",
+ 7,
+ [0] * (MAX_RETENTION_INTERVALS + 1),
+ None,
+ None,
+ f"Retention supports up to {MAX_RETENTION_INTERVALS} intervals.",
+ ),
+ ("two_years_of_daily_cohorts", None, None, "-2y", RetentionPeriod.DAY, None),
+ (
+ "a_decade_of_hourly_cohorts",
+ None,
+ None,
+ "-10y",
+ RetentionPeriod.HOUR,
+ f"Retention supports up to {MAX_RETENTION_COHORTS:,} cohorts.",
+ ),
+ ("two_years_of_daily_cohorts_at_the_interval_limit", 100, None, "-2y", RetentionPeriod.DAY, None),
+ (
+ "five_years_of_daily_cohorts_at_the_interval_limit",
+ 100,
+ None,
+ "-5y",
+ RetentionPeriod.DAY,
+ f"Retention supports up to {MAX_RETENTION_CELLS:,} cells",
+ ),
+ ]
+ )
+ def test_disallow_excessive_intervals(
+ self,
+ _name: str,
+ total_intervals: int | None,
+ custom_brackets: list[float] | None,
+ date_from: str | None,
+ period: RetentionPeriod | None,
+ expected_message: str | None,
+ ) -> None:
+ query = RetentionQuery(
+ dateRange=DateRange(date_from=date_from) if date_from else None,
+ retentionFilter=RetentionFilter(
+ period=period,
+ totalIntervals=total_intervals,
+ retentionCustomBrackets=custom_brackets,
+ ),
+ )
+ # Through the runner, so the rule reads a real date range and its place in `validators()` is covered.
+ runner = self._runner(query)
+
+ if expected_message is None:
+ runner.validate()
+ return
+
+ with self.assertRaises(ValidationError) as error:
+ runner.validate()
+
+ self.assertIn(expected_message, str(error.exception))
+ self.assertEqual(error.exception.get_codes(), ["retention_too_many_intervals"])
+
+ @parameterized.expand(
+ [
+ ("server_chosen_breakdown_limit", None, None),
+ ("explicit_breakdown_limit", 100, None),
+ (
+ "explicit_breakdown_limit_over_limit",
+ 10_000_000,
+ f"Retention supports up to {MAX_RETENTION_RESPONSE_CELLS:,} cells across a breakdown",
+ ),
+ ]
+ )
+ def test_disallow_excessive_breakdown_matrices(
+ self, _name: str, breakdown_limit: int | None, expected_message: str | None
+ ) -> None:
+ query = RetentionQuery(
+ dateRange=DateRange(date_from="-90d"),
+ retentionFilter=RetentionFilter(period=RetentionPeriod.WEEK),
+ breakdownFilter=BreakdownFilter(
+ breakdown="$browser", breakdown_type="event", breakdown_limit=breakdown_limit
+ ),
+ )
+ runner = self._runner(query)
+
+ if expected_message is None:
+ runner.validate()
+ return
+
+ with self.assertRaises(ValidationError) as error:
+ runner.validate()
+
+ self.assertIn(expected_message, str(error.exception))
+ self.assertEqual(error.exception.get_codes(), ["retention_too_many_intervals"])