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(hogql): add a statistics provider for the cost planner (#99037)

George Munyorob81e4206c07e
diff --git a/posthog/hogql/cost/statistics.py b/posthog/hogql/cost/statistics.py
new file mode 100644
index 000000000000..700b2eb1ce57
--- /dev/null
+++ b/posthog/hogql/cost/statistics.py
@@ -0,0 +1,124 @@
+"""Per-team statistics for the HogQL cost planner.
+
+The estimator asks one question of many sources: how big is this thing for this team? The sources differ
+(a ClickHouse rollup, a warehouse Delta log, a Postgres definition table) and most of them can be missing.
+This module gives them one shape. A provider returns ``None`` for any fact it cannot supply, and the
+estimator decides what to do without it, so a missing statistic never fails a query.
+
+``ClickHouseStatisticsProvider`` reads the rollups the ingestion pipeline already maintains.
+``FixedStatisticsProvider`` returns whatever a test hands it.
+"""
+
+from collections.abc import Mapping
+from datetime import date, timedelta
+from typing import Protocol
+
+from django.conf import settings
+
+import structlog
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.clickhouse.workload import Workload
+from posthog.dataclasses import frozen
+from posthog.models.usage_report_events_preagg.sql import (
+ USAGE_REPORT_EVENTS_PREAGG_TABLE,
+ USAGE_REPORT_EVENTS_PREAGG_TTL_DAYS,
+)
+
+logger = structlog.get_logger(__name__)
+
+# The rollup drops parts past its TTL, so a window this long is the most it can answer. Today is excluded
+# because it is still filling, and a team that stopped sending has fewer days than the window, so callers
+# scale by ``EventVolume.days`` rather than dividing by the window they asked for.
+EVENT_VOLUME_WINDOW_DAYS = USAGE_REPORT_EVENTS_PREAGG_TTL_DAYS - 1
+
+
+@frozen
+class EventVolume:
+ """How many events a team ingested over a recent window, in total and per event name."""
+
+ total: int
+ by_event: Mapping[str, int]
+ # Distinct days that had data. Divides ``total`` into a daily rate the estimator can scale to any range.
+ days: int
+
+ def __post_init__(self) -> None:
+ if self.total < 0 or self.days < 0:
+ raise ValueError("EventVolume counts cannot be negative")
+
+ @property
+ def per_day(self) -> float:
+ return self.total / self.days if self.days else 0.0
+
+ def event_fraction(self, event: str) -> float | None:
+ """Share of the team's volume carried by one event name, or None when the name was never seen."""
+ if not self.total:
+ return None
+ count = self.by_event.get(event)
+ return None if count is None else count / self.total
+
+
+class StatisticsProvider(Protocol):
+ """Contract the estimator consumes. Every method returns ``None`` when the fact is unavailable."""
+
+ def event_volume(self, team_id: int) -> EventVolume | None: ...
+
+
+class ClickHouseStatisticsProvider:
+ """Reads statistics from the rollups ClickHouse already maintains.
+
+ Instances are meant to live for one query: results are memoized per instance so several
+ consumers in one planning pass share one lookup.
+ """
+
+ def __init__(self, *, today: date | None = None) -> None:
+ self._today = today
+ self._event_volume: dict[int, EventVolume | None] = {}
+
+ def event_volume(self, team_id: int) -> EventVolume | None:
+ if team_id not in self._event_volume:
+ self._event_volume[team_id] = self._load_event_volume(team_id)
+ return self._event_volume[team_id]
+
+ def _load_event_volume(self, team_id: int) -> EventVolume | None:
+ today = self._today or date.today()
+ since = today - timedelta(days=EVENT_VOLUME_WINDOW_DAYS)
+ try:
+ with tags_context(product=Product.INTERNAL, feature=Feature.SCHEMA_INTROSPECTION, team_id=team_id):
+ # nosemgrep: clickhouse-fstring-param-audit - the f-string only interpolates a module constant table name; team_id is bound as a parameter
+ rows = sync_execute(
+ f"""
+ SELECT date, event, sumMerge(event_count) AS event_count
+ FROM {settings.CLICKHOUSE_DATABASE}.{USAGE_REPORT_EVENTS_PREAGG_TABLE}
+ WHERE team_id = %(team_id)s AND date >= %(since)s AND date < %(today)s
+ GROUP BY date, event
+ """,
+ {"team_id": team_id, "since": since, "today": today},
+ workload=Workload.OFFLINE,
+ team_id=team_id,
+ readonly=True,
+ )
+ except Exception:
+ # Statistics are advisory. Log and let the estimator run without them.
+ logger.warning("hogql_cost_event_volume_unavailable", team_id=team_id, exc_info=True)
+ return None
+
+ if not rows:
+ return None
+ by_event: dict[str, int] = {}
+ days: set[date] = set()
+ for row_date, event, count in rows:
+ by_event[str(event)] = by_event.get(str(event), 0) + int(count)
+ days.add(row_date)
+ return EventVolume(total=sum(by_event.values()), by_event=by_event, days=len(days))
+
+
+class FixedStatisticsProvider:
+ """Returns the statistics it was constructed with. For tests and for callers that already hold them."""
+
+ def __init__(self, *, event_volume: Mapping[int, EventVolume] | None = None) -> None:
+ self._event_volume = dict(event_volume or {})
+
+ def event_volume(self, team_id: int) -> EventVolume | None:
+ return self._event_volume.get(team_id)
diff --git a/posthog/hogql/cost/test/test_statistics.py b/posthog/hogql/cost/test/test_statistics.py
new file mode 100644
index 000000000000..ec492e5d1a25
--- /dev/null
+++ b/posthog/hogql/cost/test/test_statistics.py
@@ -0,0 +1,127 @@
+from datetime import date, timedelta
+from uuid import uuid4
+
+from posthog.test.base import ClickhouseTestMixin
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.hogql.cost.statistics import (
+ EVENT_VOLUME_WINDOW_DAYS,
+ ClickHouseStatisticsProvider,
+ EventVolume,
+ FixedStatisticsProvider,
+)
+
+from posthog.clickhouse.client import sync_execute
+from posthog.models.usage_report_events_preagg.sql import (
+ DISTRIBUTED_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL,
+ SHARDED_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL,
+ WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE,
+ WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL,
+)
+
+# Seeded rows must sit inside the rollup's 14-day TTL or ClickHouse drops the part on its next merge, so the
+# fixtures are relative to the real clock and the provider is handed the same day.
+TODAY = date.today()
+
+
+class TestEventVolume(SimpleTestCase):
+ def test_per_day_and_event_fraction_scale_from_the_recorded_window(self):
+ volume = EventVolume(total=1_000, by_event={"$pageview": 600, "signup": 400}, days=10)
+
+ assert volume.per_day == 100.0
+ assert volume.event_fraction("$pageview") == 0.6
+ assert volume.event_fraction("never_seen") is None
+
+ def test_empty_volume_does_not_divide_by_zero(self):
+ volume = EventVolume(total=0, by_event={}, days=0)
+
+ assert volume.per_day == 0.0
+ assert volume.event_fraction("$pageview") is None
+
+ def test_fixed_provider_returns_none_for_unknown_teams(self):
+ provider = FixedStatisticsProvider(event_volume={1: EventVolume(total=5, by_event={"a": 5}, days=1)})
+
+ assert provider.event_volume(1) is not None
+ assert provider.event_volume(2) is None
+
+
+class TestClickHouseStatisticsProvider(ClickhouseTestMixin, SimpleTestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ super().setUpClass()
+ sync_execute(SHARDED_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL())
+ sync_execute(DISTRIBUTED_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL())
+ sync_execute(WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL())
+
+ def setUp(self) -> None:
+ super().setUp()
+ # A fresh team per test instead of a DELETE: a lightweight delete is a mutation on `team_id`, and it
+ # can still apply to a part inserted right after it, which eats the rows the test just seeded.
+ self.team_id = 4_000_000 + int(uuid4().int % 1_000_000)
+
+ def _seed(self, rows: list[tuple[date, str, str, int]]) -> None:
+ # (date, lib, event, count). Two libs on one day is how a real team splits, and it is what
+ # the provider has to re-sum: the rollup is keyed by lib, the planner is not.
+ values = ", ".join(
+ f"('{d.isoformat()}', {self.team_id}, 'full', '{lib}', '{event}', "
+ f"initializeAggregation('uniqExactState', (toUInt64(0), toUInt64(0), toUInt64(0))), "
+ f"initializeAggregation('sumState', toUInt64({count})))"
+ for d, lib, event, count in rows
+ )
+ sync_execute(
+ f"INSERT INTO {WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE} "
+ "(date, team_id, person_mode, lib, event, distinct_events_unique, event_count) "
+ f"VALUES {values}"
+ )
+
+ def test_sums_across_libs_and_days_and_counts_distinct_days(self):
+ self._seed(
+ [
+ (TODAY - timedelta(days=1), "web", "$pageview", 100),
+ (TODAY - timedelta(days=1), "posthog-python", "$pageview", 20),
+ (TODAY - timedelta(days=1), "web", "signup", 5),
+ (TODAY - timedelta(days=3), "web", "$pageview", 80),
+ ]
+ )
+
+ volume = ClickHouseStatisticsProvider(today=TODAY).event_volume(self.team_id)
+
+ assert volume == EventVolume(total=205, by_event={"$pageview": 200, "signup": 5}, days=2)
+
+ # The day past the window coincides with the table TTL, so it cannot be seeded reliably and is not a case here.
+ @parameterized.expand(
+ [
+ ("today_is_partial_and_excluded", 0, 1),
+ ("oldest_day_in_the_window_is_included", EVENT_VOLUME_WINDOW_DAYS, 1000),
+ ]
+ )
+ def test_window_edges(self, _name, days_ago, expected_total):
+ self._seed([(TODAY - timedelta(days=days_ago), "web", "$pageview", 999)])
+ self._seed([(TODAY - timedelta(days=1), "web", "$pageview", 1)])
+
+ volume = ClickHouseStatisticsProvider(today=TODAY).event_volume(self.team_id)
+
+ assert volume is not None
+ assert volume.total == expected_total
+
+ def test_team_without_data_yields_none(self):
+ assert ClickHouseStatisticsProvider(today=TODAY).event_volume(self.team_id) is None
+
+ def test_memoizes_per_team_within_one_provider(self):
+ self._seed([(TODAY - timedelta(days=1), "web", "$pageview", 7)])
+ provider = ClickHouseStatisticsProvider(today=TODAY)
+
+ with patch("posthog.hogql.cost.statistics.sync_execute", wraps=sync_execute) as execute:
+ first = provider.event_volume(self.team_id)
+ second = provider.event_volume(self.team_id)
+
+ assert first == second
+ assert execute.call_count == 1
+
+ def test_clickhouse_failure_degrades_to_none(self):
+ with patch("posthog.hogql.cost.statistics.sync_execute", side_effect=RuntimeError("boom")):
+ assert ClickHouseStatisticsProvider(today=TODAY).event_volume(self.team_id) is None