:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix: count team event volume one month at a time (#109426)
Andy Zhaoa833d5cef83f
diff --git a/posthog/models/team/team_event_volume.py b/posthog/models/team/team_event_volume.pyindex 6aac7858ea87..edee73caa0d4 100644--- a/posthog/models/team/team_event_volume.py+++ b/posthog/models/team/team_event_volume.py@@ -7,8 +7,6 @@ from posthog.models.team import Teamclass TeamEventVolume(models.Model):- # Rows come from posthog.tasks.team_event_volume, not from team creation, so this is not- # registered as a team extension signal.team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True, db_constraint=False)events_last_year = models.BigIntegerField()computed_at = models.DateTimeField()diff --git a/posthog/tasks/team_event_volume.py b/posthog/tasks/team_event_volume.pyindex 4541935c4363..6763a0b65a6d 100644--- a/posthog/tasks/team_event_volume.py+++ b/posthog/tasks/team_event_volume.py@@ -1,4 +1,7 @@+from collections import Counter+from datetime import datetime, timedeltafrom time import perf_counter+from typing import Any, Optionalfrom django.utils import timezone@@ -20,6 +23,39 @@ logger = structlog.get_logger(__name__)EVENT_VOLUME_DAYS = 365+def _month_starts(window_start: datetime, window_end: datetime) -> list[datetime]:+ month = window_start.replace(day=1, hour=0, minute=0, second=0, microsecond=0)+ months = []+ while month <= window_end:+ months.append(month)+ month = (month + timedelta(days=31)).replace(day=1)+ return months+++def _team_counts_in_partition(+ table: str, partition_id: str, lower: Optional[datetime], upper: Optional[datetime]+) -> dict[int, int]:+ predicates = ["_partition_id = %(partition_id)s"]+ params: dict[str, Any] = {"partition_id": partition_id}+ if lower is not None:+ predicates.append("timestamp >= %(lower)s")+ params["lower"] = lower+ if upper is not None:+ predicates.append("timestamp <= %(upper)s")+ params["upper"] = upper+ rows = sync_execute( # nosemgrep: clickhouse-fstring-param-audit - table is events_read_table() output and the predicates are literals; every value is parameterized+ f"""+ SELECT team_id, count() AS events+ FROM {table}+ WHERE {" AND ".join(predicates)}+ GROUP BY team_id+ """,+ params,+ workload=Workload.OFFLINE,+ )+ return dict(rows)++@shared_task(ignore_result=True, autoretry_for=CH_TRANSIENT_ERRORS, retry_backoff=60, retry_backoff_max=600, max_retries=3)@@ -29,23 +65,25 @@ def update_team_event_volumes() -> None:returnstarted = perf_counter()computed_at = timezone.now()+ window_start = computed_at - timedelta(days=EVENT_VOLUME_DAYS)tag_queries(product=Product.INTERNAL, feature=Feature.API_QUERIES_BUDGET)- # Timestamps are client-supplied, so a future-dated event would raise the budget until its- # timestamp passed. now64() rather than now(), which truncates the sub-second timestamp.- rows = sync_execute(- f"""- SELECT team_id, count() AS events- FROM {events_read_table(use_new_events_schema())}- WHERE timestamp >= now() - INTERVAL %(days)s DAY AND timestamp <= now64()- GROUP BY team_id- """,- {"days": EVENT_VOLUME_DAYS},- workload=Workload.OFFLINE,- )+ table = events_read_table(use_new_events_schema())+ months = _month_starts(window_start, computed_at)+ counts: Counter[int] = Counter()+ for index, month in enumerate(months):+ counts.update(+ _team_counts_in_partition(+ table,+ month.strftime("%Y%m"),+ window_start if index == 0 else None,+ computed_at if index == len(months) - 1 else None,+ )+ )+team_ids = set(Team.objects.values_list("id", flat=True))volumes = [TeamEventVolume(team_id=team_id, events_last_year=events, computed_at=computed_at)- for team_id, events in rows+ for team_id, events in counts.items()if team_id in team_ids]TeamEventVolume.objects.unscoped().bulk_create(@@ -55,13 +93,15 @@ def update_team_event_volumes() -> None:unique_fields=["team"],batch_size=1000,)- # A team with no events in the window is absent from the result, so its row is the only one- # this run did not stamp.reset = (TeamEventVolume.objects.unscoped().filter(computed_at__lt=computed_at).update(events_last_year=0, computed_at=computed_at))logger.info(- "team_event_volumes_updated", teams=len(volumes), reset=reset, seconds=round(perf_counter() - started, 1)+ "team_event_volumes_updated",+ teams=len(volumes),+ reset=reset,+ partitions=len(months),+ seconds=round(perf_counter() - started, 1),)diff --git a/posthog/tasks/test/test_team_event_volume.py b/posthog/tasks/test/test_team_event_volume.pyindex f7a3f10679b7..a16a43d14c15 100644--- a/posthog/tasks/test/test_team_event_volume.py+++ b/posthog/tasks/test/test_team_event_volume.py@@ -1,12 +1,34 @@-from datetime import timedelta+from datetime import datetime, timedeltafrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from django.test import SimpleTestCasefrom django.utils import timezone+from parameterized import parameterized+from posthog.models import Teamfrom posthog.models.team.team_event_volume import TeamEventVolume-from posthog.tasks.team_event_volume import update_team_event_volumes+from posthog.tasks.team_event_volume import _month_starts, update_team_event_volumes+++class TestMonthStarts(SimpleTestCase):+ @parameterized.expand(+ [+ ("full_year", datetime(2025, 9, 30), datetime(2026, 9, 30), 13, "202509", "202609"),+ ("leap_february", datetime(2024, 1, 31), datetime(2024, 3, 1), 3, "202401", "202403"),+ ("single_month", datetime(2026, 9, 2), datetime(2026, 9, 20), 1, "202609", "202609"),+ ("ends_on_month_boundary", datetime(2026, 8, 15), datetime(2026, 9, 1), 2, "202608", "202609"),+ ]+ )+ def test_covers_every_month_the_window_touches(+ self, _name: str, start: datetime, end: datetime, count: int, first: str, last: str+ ) -> None:+ ids = [month.strftime("%Y%m") for month in _month_starts(start, end)]++ assert len(ids) == count+ assert ids == sorted(set(ids))+ assert (ids[0], ids[-1]) == (first, last)class TestUpdateTeamEventVolumes(ClickhouseTestMixin, BaseTest):