: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(signals): bound scored buckets query per interval and skip slow teams (#123235)
posthog[bot]03c7dc4480e0
diff --git a/products/signals/backend/anomaly_scores/queue.py b/products/signals/backend/anomaly_scores/queue.pyindex 5b6fafae5983..af9c5d9e4f90 100644--- a/products/signals/backend/anomaly_scores/queue.py+++ b/products/signals/backend/anomaly_scores/queue.py@@ -13,6 +13,8 @@ from typing import Any, castfrom django.core.cache import cache+import structlog+from posthog.schema import ChartDisplayType, IntervalTypefrom posthog.hogql import ast@@ -22,6 +24,11 @@ from posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.clickhouse.workload import Workloadfrom posthog.dataclasses import frozen+from posthog.exceptions import (+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQueryTimeOut,+)from posthog.interval_specs import interval_specfrom posthog.models import Teamfrom posthog.tasks.alerts.utils import NON_TIME_SERIES_DISPLAY_TYPES@@ -44,6 +51,8 @@ from products.signals.backend.anomaly_scores.state import RunPlan, load_states,from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, list_limited_team_attributes+logger = structlog.get_logger(__name__)+SCORE_EVENT = "$anomaly_score"SOURCE_INSIGHT = "insight"# An insight counts as watched when it is on a dashboard or someone viewed it in this window.@@ -65,6 +74,13 @@ _CALENDAR_INTERVALS = {IntervalType.WEEK: CalendarInterval.WEEKLY,IntervalType.MONTH: CalendarInterval.MONTHLY,}+# A scored-buckets query that hits a ClickHouse limit skips its team for the tick, so the other teams still get picks.+# The cluster memory limit is a subclass of the query memory limit.+_SCORED_BUCKETS_LIMIT_ERRORS = (+ ClickHouseQueryTimeOut,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseEstimatedQueryExecutionTimeTooLong,+)# The scorer rejects these, so selection leaves them out instead of picking them on every tick._UNSCORED_DISPLAYS = sorted(display.value for display in {*NON_TIME_SERIES_DISPLAY_TYPES, ChartDisplayType.ACTIONS_LINE_GRAPH_CUMULATIVE}@@ -150,11 +166,11 @@ def watched_insights(]-def scored_state_since(config: AnomalyScoringConfig, now: datetime.datetime) -> datetime.datetime:- """How far back the scored state reaches: one bucket more than the backfill cap of the longest interval."""- return min(- now - interval_spec(interval).period * (config.limits.max_backfill_buckets + 1) for interval in config.intervals- )+def scored_state_since(+ config: AnomalyScoringConfig, interval: IntervalType, now: datetime.datetime+) -> datetime.datetime:+ """How far back the scored state of an insight with this interval reaches: one bucket more than the backfill cap."""+ return now - interval_spec(interval).period * (config.limits.max_backfill_buckets + 1)def _utc(value: datetime.datetime) -> datetime.datetime:@@ -363,11 +379,27 @@ def select_insights() -> Selection:teams = {team.id: team for team in eligible_teams(config)}insights = watched_insights(list(teams), config.intervals, now)- since = scored_state_since(config, now)state: dict[int, dict[str, datetime.datetime]] = {}- for team_id in sorted({insight.team_id for insight in insights}):- team_insight_ids = {insight.insight_id for insight in insights if insight.team_id == team_id}- state.update(scored_buckets(teams[team_id], team_insight_ids, since, now))+ failed_teams: set[int] = set()+ # One query per team and interval, so a day or week insight does not read the months a month insight needs.+ for team_id, interval in sorted({(insight.team_id, insight.interval) for insight in insights}):+ if team_id in failed_teams:+ continue+ insight_ids = {+ insight.insight_id for insight in insights if insight.team_id == team_id and insight.interval == interval+ }+ try:+ state.update(scored_buckets(teams[team_id], insight_ids, scored_state_since(config, interval, now), now))+ except _SCORED_BUCKETS_LIMIT_ERRORS as error:+ logger.warning(+ "anomaly_scoring_scored_buckets_failed",+ team_id=team_id,+ interval=interval.value,+ error_class=type(error).__name__,+ )+ failed_teams.add(team_id)+ # Without its scored state, every insight of the team looks never scored, so the team waits for a later tick.+ insights = [insight for insight in insights if insight.team_id not in failed_teams]newest_buckets = {insight.insight_id: max(state[insight.insight_id].values()) if insight.insight_id in state else Nonediff --git a/products/signals/backend/test/test_anomaly_scoring_tick.py b/products/signals/backend/test/test_anomaly_scoring_tick.pyindex 7dc48843538e..fee7064f359d 100644--- a/products/signals/backend/test/test_anomaly_scoring_tick.py+++ b/products/signals/backend/test/test_anomaly_scoring_tick.py@@ -703,14 +703,19 @@ class TestScoredBuckets(ClickhouseTestMixin, BaseTest):dashboard = Dashboard.objects.create(team=self.team, name="Main")insights = {name: Insight.objects.create(team=self.team, name=name, query=_trends(interval="day"))- for name in ("never_scored", "stale", "fresh")+ for name in ("never_scored", "stale", "fresh", "past_day_window")}for insight in insights.values():DashboardTile.objects.create(dashboard=dashboard, insight=insight)cache.delete(_cooldown_key(insight.id))cache.delete_many([_fleet_budget_key(NOW), _project_budget_key(self.team.id, NOW)])today = NOW.replace(hour=0)- for name, bucket in (("stale", today - timedelta(days=3)), ("fresh", today - timedelta(days=1))):+ for name, bucket in (+ ("stale", today - timedelta(days=3)),+ ("fresh", today - timedelta(days=1)),+ # Inside the window of a month insight, but older than the window of a day insight.+ ("past_day_window", today - timedelta(days=40)),+ ):_create_event(team=self.team,event="$anomaly_score",@@ -729,8 +734,10 @@ class TestScoredBuckets(ClickhouseTestMixin, BaseTest):with patch("products.signals.backend.anomaly_scores.queue.list_limited_team_attributes", return_value=[]):selection = select_insights(config, SelectionConfig(weighting=Weighting.UNIFORM), NOW, limit=10)- assert [pick.insight_id for pick in selection.picks] == [insights["never_scored"].id, insights["stale"].id]- assert selection.picks[1].scored_through == {"stale": today - timedelta(days=3)}+ picks = {pick.insight_id: pick for pick in selection.picks}+ assert set(picks) == {insights[name].id for name in ("never_scored", "stale", "past_day_window")}+ assert picks[insights["stale"].id].scored_through == {"stale": today - timedelta(days=3)}+ assert picks[insights["past_day_window"].id].scored_through == {}@time_machine.travel(NOW, tick=False)def test_select_insights_lets_each_project_pick_before_any_project_picks_twice(self) -> None:@@ -764,6 +771,38 @@ class TestScoredBuckets(ClickhouseTestMixin, BaseTest):assert selection.picks[1].insight_id == small_insight.idassert selection.candidates == 4+ @time_machine.travel(NOW, tick=False)+ def test_select_insights_skips_a_project_whose_scored_buckets_query_times_out(self) -> None:+ slow_team = Team.objects.create(organization=self.organization, name="Slow")+ dashboards = {team.id: Dashboard.objects.create(team=team, name="Main") for team in (self.team, slow_team)}+ insights = {}+ for team in (self.team, slow_team):+ insight = Insight.objects.create(team=team, name=team.name, query=_trends(interval="day"))+ DashboardTile.objects.create(dashboard=dashboards[team.id], insight=insight)+ cache.delete(_cooldown_key(insight.id))+ insights[team.id] = insight+ cache.delete_many(+ [_fleet_budget_key(NOW), *(_project_budget_key(team_id, NOW) for team_id in (self.team.id, slow_team.id))]+ )+ config = AnomalyScoringConfig(+ enabled=True,+ organization_ids=(str(self.organization.id),),+ allow_team_ids=(self.team.id, slow_team.id),+ )++ def buckets(team: Team, *args: Any) -> dict[int, dict[str, datetime]]:+ if team.id == slow_team.id:+ raise ClickHouseQueryTimeOut()+ return scored_buckets(team, *args)++ with (+ patch("products.signals.backend.anomaly_scores.queue.list_limited_team_attributes", return_value=[]),+ patch("products.signals.backend.anomaly_scores.queue.scored_buckets", side_effect=buckets),+ ):+ selection = select_insights(config, SelectionConfig(weighting=Weighting.UNIFORM), NOW, limit=10)++ assert [pick.insight_id for pick in selection.picks] == [insights[self.team.id].id]+async def _run_tick(plan: AnomalyScoringTickPlan, statuses: dict[int, str]