: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 the anomaly scoring plan by a deadline (#126620)
posthog[bot]349b7fafb0df
diff --git a/products/signals/backend/anomaly_scores/queue.py b/products/signals/backend/anomaly_scores/queue.pyindex 5e11dec55ed0..ebcd7ca654d2 100644--- a/products/signals/backend/anomaly_scores/queue.py+++ b/products/signals/backend/anomaly_scores/queue.py@@ -12,11 +12,12 @@ whose model is due for a soft retrain goes to the train pass first. When the trathe score pass scores it with the old model, so the train budget does not decide the score coverage."""+import timeimport datetimeimport itertoolsimport dataclassesfrom collections import Counter-from collections.abc import Callable, Collection+from collections.abc import Callable, Collection, Mappingfrom enum import StrEnumfrom typing import Any, cast@@ -27,6 +28,7 @@ import structlogfrom posthog.schema import ChartDisplayType, IntervalTypefrom posthog.hogql import ast+from posthog.hogql.parser import parse_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import ClickHouseUser@@ -34,6 +36,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.clickhouse.workload import Workloadfrom posthog.dataclasses import frozenfrom posthog.exceptions import (+ ClickHouseAtCapacity,ClickHouseEstimatedQueryExecutionTimeTooLong,ClickHouseQueryMemoryLimitExceeded,ClickHouseQueryTimeOut,@@ -92,10 +95,16 @@ _CALENDAR_INTERVALS = {# 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 = (+ ClickHouseAtCapacity,ClickHouseQueryTimeOut,ClickHouseQueryMemoryLimitExceeded,ClickHouseEstimatedQueryExecutionTimeTooLong,)+# After this many teams get a full cluster in one plan, no more teams load. The plan uses the teams it has.+_MAX_AT_CAPACITY_TEAMS = 2+# The last scored state load of a team. The team that waited longest loads first, so a plan that stops early+# does not drop the same teams on every tick.+_TEAM_LOADED_TTL = datetime.timedelta(days=1)# 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}@@ -111,7 +120,7 @@ WHERE event = {event}AND timestamp >= {since}AND timestamp <= {now}AND properties.$anomaly_source = {source}- AND toInt(properties.$anomaly_insight_id) IN {insight_ids}+ AND {windows}GROUP BY insight_id, series_keyLIMIT {limit}"""@@ -179,6 +188,9 @@ class Selection:active_reasons: dict[str, int] = dataclasses.field(default_factory=dict)# One entry for each eligible team, also a team with no active insight.census: list[TeamCensus] = dataclasses.field(default_factory=list)+ # Teams with active insights whose scored state loaded, and the teams that wait for a later tick.+ teams_planned: int = 0+ teams_skipped: int = 0# Eligible teams, and their organizations.enrolled_teams: int = 0enrolled_organizations: int = 0@@ -305,16 +317,31 @@ def _utc(value: datetime.datetime) -> datetime.datetime:return value.replace(tzinfo=datetime.UTC) if value.tzinfo is None else value.astimezone(datetime.UTC)+def _scored_window(insight_ids: Collection[int], since: datetime.datetime) -> ast.Expr:+ return parse_expr(+ "toInt(properties.$anomaly_insight_id) IN {insight_ids} AND timestamp >= {since}",+ placeholders={+ "insight_ids": ast.Tuple(exprs=[ast.Constant(value=insight_id) for insight_id in sorted(insight_ids)]),+ "since": ast.Constant(value=since),+ },+ )++def scored_buckets(- team: Team, insight_ids: Collection[int], since: datetime.datetime, now: datetime.datetime+ team: Team, insight_ids_by_since: Mapping[datetime.datetime, Collection[int]], now: datetime.datetime) -> dict[int, dict[str, datetime.datetime]]:"""Insight id to the newest scored bucket start of each of its series, for this team's own insights.+ One query reads every window. Each insight reads back only to the ``since`` of its group, so a day or+ week insight does not read the months a month insight needs.+Any member can capture an event with any properties into the project. Rows for another team'sinsight, or with a future bucket, are ignored, so they cannot stop the scoring of an insight."""- if not insight_ids:+ groups = {since: ids for since, ids in sorted(insight_ids_by_since.items()) if ids}+ if not groups:return {}+ windows = [_scored_window(ids, since) for since, ids in groups.items()]tag_queries(product=Product.SIGNALS, feature=Feature.ALERTING)response = execute_hogql_query(_SCORED_BUCKETS_QUERY,@@ -323,9 +350,9 @@ def scored_buckets(placeholders={"event": ast.Constant(value=SCORE_EVENT),"source": ast.Constant(value=SOURCE_INSIGHT),- "since": ast.Constant(value=since),+ "since": ast.Constant(value=min(groups)),"now": ast.Constant(value=now),- "insight_ids": ast.Tuple(exprs=[ast.Constant(value=insight_id) for insight_id in sorted(insight_ids)]),+ "windows": windows[0] if len(windows) == 1 else ast.Or(exprs=windows),"limit": ast.Constant(value=_MAX_SCORED_SERIES),},workload=Workload.OFFLINE,@@ -367,6 +394,23 @@ def _cooling_down(insight_ids: list[int]) -> set[int]:return {insight_id for insight_id in insight_ids if _cooldown_key(insight_id) in found}+def _team_loaded_key(team_id: int) -> str:+ return f"signals:anomaly_scores:team_loaded:{team_id}"+++def _team_load_order(team_ids: Collection[int]) -> list[int]:+ """The teams that waited longest since their last scored state load first. A team never loaded goes first."""+ loaded = cache.get_many([_team_loaded_key(team_id) for team_id in team_ids])+ return sorted(team_ids, key=lambda team_id: (loaded.get(_team_loaded_key(team_id), 0.0), team_id))+++def _mark_teams_loaded(team_ids: Collection[int], now: datetime.datetime) -> None:+ stamp = _utc(now).timestamp()+ cache.set_many(+ {_team_loaded_key(team_id): stamp for team_id in team_ids}, timeout=int(_TEAM_LOADED_TTL.total_seconds())+ )++def _hour(now: datetime.datetime) -> str:return _utc(now).strftime("%Y%m%d%H")@@ -509,36 +553,73 @@ def _take_turns(team_orders: list[list[int]]) -> list[int]:return [insight_id for turn in itertools.zip_longest(*team_orders) for insight_id in turn if insight_id is not None]+def load_scored_state(+ config: AnomalyScoringConfig,+ teams: dict[int, Team],+ insights: Collection[ActiveInsight],+ now: datetime.datetime,+ deadline: float | None,+) -> tuple[dict[int, dict[str, datetime.datetime]], set[int]]:+ """The scored state of the insights, and the teams whose state loaded.++ One query per team. The teams that waited longest load first. Loading stops at ``deadline``, a+ ``time.monotonic`` value, after at least one team, or when ClickHouse is full for several teams.+ A team whose query fails waits for a later tick.+ """+ windows: dict[int, dict[datetime.datetime, set[int]]] = {}+ for insight in insights:+ since = scored_state_since(config, insight.interval, now)+ windows.setdefault(insight.team_id, {}).setdefault(since, set()).add(insight.insight_id)+ state: dict[int, dict[str, datetime.datetime]] = {}+ loaded: set[int] = set()+ attempted: list[int] = []+ at_capacity = 0+ for team_id in _team_load_order(windows):+ if at_capacity >= _MAX_AT_CAPACITY_TEAMS or (+ attempted and deadline is not None and time.monotonic() >= deadline+ ):+ break+ attempted.append(team_id)+ try:+ state.update(scored_buckets(teams[team_id], windows[team_id], now))+ except _SCORED_BUCKETS_LIMIT_ERRORS as error:+ logger.warning("anomaly_scoring_scored_buckets_failed", team_id=team_id, error_class=type(error).__name__)+ if isinstance(error, ClickHouseAtCapacity):+ at_capacity += 1+ continue+ loaded.add(team_id)+ # A failed team also goes to the back, so a team whose query always fails does not take time from every plan.+ _mark_teams_loaded(attempted, now)+ if len(attempted) < len(windows):+ logger.info(+ "anomaly_scoring_plan_stopped_loading",+ teams_loaded=len(loaded),+ teams_skipped=len(windows) - len(loaded),+ at_capacity=at_capacity,+ )+ return state, loaded++def select_insights(- config: AnomalyScoringConfig, selection_config: SelectionConfig, now: datetime.datetime, limit: int | None = None+ config: AnomalyScoringConfig,+ selection_config: SelectionConfig,+ now: datetime.datetime,+ limit: int | None = None,+ deadline: float | None = None,) -> Selection:- """The picks of the tick. ``limit`` replaces the pick cap of each pass, for a manual run."""+ """The picks of the tick. ``limit`` replaces the pick cap of each pass, for a manual run.++ ``deadline`` is a ``time.monotonic`` value. After it, no more teams load, and the plan uses the teams it has.+ """teams = {team.id: team for team in eligible_teams(config)}insights = active_insights(list(teams), config.intervals, now, config.active_window_days)active = len(insights)active_reasons = reason_counts(insights)census = team_census(teams, insights)- state: dict[int, dict[str, datetime.datetime]] = {}- 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)+ teams_with_insights = {insight.team_id for insight in insights}+ state, loaded_teams = load_scored_state(config, teams, insights, now, deadline)# 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]+ insights = [insight for insight in insights if insight.team_id in loaded_teams]newest_buckets = {insight.insight_id: max(state[insight.insight_id].values()) if insight.insight_id in state else None@@ -679,6 +760,8 @@ def select_insights(active=active,active_reasons=active_reasons,census=census,+ teams_planned=len(loaded_teams),+ teams_skipped=len(teams_with_insights) - len(loaded_teams),enrolled_teams=len(teams),enrolled_organizations=len({team.organization_id for team in teams.values()}),)diff --git a/products/signals/backend/anomaly_scores/tick.py b/products/signals/backend/anomaly_scores/tick.pyindex 25f67d3a9385..d54f46600181 100644--- a/products/signals/backend/anomaly_scores/tick.py+++ b/products/signals/backend/anomaly_scores/tick.py@@ -17,6 +17,7 @@ from django.utils import timezoneimport structlogfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy+from temporalio.exceptions import ActivityError, ApplicationErrorfrom posthog.hogql.errors import QueryError, TableAccessDeniedError@@ -88,6 +89,9 @@ STATUS_ARTIFACT_UNAVAILABLE = "artifact_unavailable"STATUS_ERRORED = "errored"_PLAN_TIMEOUT = datetime.timedelta(minutes=2)+# No team starts to load after this time. The rest of the plan scales with the loaded teams, so it needs the other half.+# A timed-out attempt does not stop its thread, so a plan that ends in time also keeps its retry from overlapping it.+_PLAN_LOAD_BUDGET = _PLAN_TIMEOUT / 2# All the scoring queries of one insight stop within their budget. The rest is detection, the capture request,# and the failure classification. A query timeout must reach the classification, so that it gets the 1 day cooldown._INSIGHT_TIMEOUT = datetime.timedelta(seconds=SCORING_QUERY_BUDGET_SECONDS) + datetime.timedelta(seconds=90)@@ -124,6 +128,8 @@ class AnomalyScoringTickPlan:active_reasons: dict[str, int] | None = Noneenrolled_teams: int = 0enrolled_organizations: int = 0+ teams_planned: int = 0+ teams_skipped: int = 0@frozen@@ -174,6 +180,14 @@ class AnomalyScoringTickResult:active_reasons: dict[str, int] | None = Noneenrolled_teams: int = 0enrolled_organizations: int = 0+ # Time of the plan activity, its retry included. Compare it with the plan timeout.+ plan_ms: int = 0+ # Teams with active insights that the plan loaded, and the teams that wait for a later tick.+ teams_planned: int = 0+ teams_skipped: int = 0+ # The plan activity failed, and the tick scored nothing. `plan_error` is the error class.+ plan_failed: bool = False+ plan_error: str | None = Nonedef plan_tick(limit: int | None, now: datetime.datetime) -> AnomalyScoringTickPlan:@@ -182,7 +196,8 @@ def plan_tick(limit: int | None, now: datetime.datetime) -> AnomalyScoringTickPlconfig = read_config(payload)if not config.enabled:return AnomalyScoringTickPlan(enabled=False, picks=[], candidates=0, max_concurrency=config.max_concurrency)- selection = select_insights(config, parse_selection_config(payload), now, limit)+ deadline = time.monotonic() + _PLAN_LOAD_BUDGET.total_seconds()+ selection = select_insights(config, parse_selection_config(payload), now, limit, deadline=deadline)record_candidates(selection.candidates)capture_census(selection.census, now)return AnomalyScoringTickPlan(@@ -201,9 +216,19 @@ def plan_tick(limit: int | None, now: datetime.datetime) -> AnomalyScoringTickPlactive_reasons=selection.active_reasons,enrolled_teams=selection.enrolled_teams,enrolled_organizations=selection.enrolled_organizations,+ teams_planned=selection.teams_planned,+ teams_skipped=selection.teams_skipped,)+def plan_error_class(error: ActivityError) -> str:+ """The class of the error that failed the plan activity. An activity timeout is a Temporal `TimeoutError`."""+ cause = error.cause+ if isinstance(cause, ApplicationError) and cause.type:+ return cause.type+ return type(cause).__name__ if cause is not None else type(error).__name__++def failure_status(error: Exception) -> str | None:"""The status of a known failure, or None for any other failure."""if isinstance(error, UnsupportedInsightError):@@ -431,6 +456,11 @@ def capture_tick(result: AnomalyScoringTickResult) -> None:active_reasons=result.active_reasons,enrolled_teams=result.enrolled_teams,enrolled_organizations=result.enrolled_organizations,+ plan_ms=result.plan_ms,+ teams_planned=result.teams_planned,+ teams_skipped=result.teams_skipped,+ plan_failed=result.plan_failed,+ plan_error=result.plan_error,)ph_background_capture()(distinct_id=ANOMALY_SCORING_FLAG_DISTINCT_ID,@@ -458,6 +488,11 @@ def capture_tick(result: AnomalyScoringTickResult) -> None:**{f"active_{reason}": count for reason, count in (result.active_reasons or {}).items()},"enrolled_teams": result.enrolled_teams,"enrolled_organizations": result.enrolled_organizations,+ "plan_ms": result.plan_ms,+ "teams_planned": result.teams_planned,+ "teams_skipped": result.teams_skipped,+ "plan_failed": result.plan_failed,+ "plan_error": result.plan_error,},)@@ -489,12 +524,27 @@ class AnomalyScoringTickWorkflow:@workflow.runasync def run(self, inputs: AnomalyScoringTickInput) -> AnomalyScoringTickResult:started = workflow.now()- plan = await workflow.execute_activity(- plan_anomaly_scoring_tick_activity,- inputs,- start_to_close_timeout=_PLAN_TIMEOUT,- retry_policy=RetryPolicy(maximum_attempts=2),- )+ try:+ plan = await workflow.execute_activity(+ plan_anomaly_scoring_tick_activity,+ inputs,+ start_to_close_timeout=_PLAN_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ except ActivityError as error:+ # Without this event, a failed tick looks like a missing tick. The workflow still fails.+ plan_ms = round((workflow.now() - started).total_seconds() * 1000)+ await self._capture(+ AnomalyScoringTickResult(+ enabled=True,+ duration_ms=plan_ms,+ plan_ms=plan_ms,+ plan_failed=True,+ plan_error=plan_error_class(error),+ )+ )+ raise+ plan_ms = round((workflow.now() - started).total_seconds() * 1000)if not plan.enabled:return AnomalyScoringTickResult()@@ -557,11 +607,17 @@ class AnomalyScoringTickWorkflow:active_reasons=plan.active_reasons,enrolled_teams=plan.enrolled_teams,enrolled_organizations=plan.enrolled_organizations,+ plan_ms=plan_ms,+ teams_planned=plan.teams_planned,+ teams_skipped=plan.teams_skipped,)+ await self._capture(result)+ return result++ async def _capture(self, result: AnomalyScoringTickResult) -> None:await workflow.execute_activity(capture_anomaly_scoring_tick_activity,result,start_to_close_timeout=_CAPTURE_TIMEOUT,retry_policy=RetryPolicy(maximum_attempts=2),)- return resultdiff --git a/products/signals/backend/test/test_anomaly_scoring_tick.py b/products/signals/backend/test/test_anomaly_scoring_tick.pyindex 3b90a87820b8..9b0043303ca7 100644--- a/products/signals/backend/test/test_anomaly_scoring_tick.py+++ b/products/signals/backend/test/test_anomaly_scoring_tick.py@@ -16,6 +16,7 @@ from django.test import SimpleTestCaseimport numpy as npfrom parameterized import parameterizedfrom temporalio import activity+from temporalio.client import WorkflowFailureErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker@@ -52,6 +53,7 @@ from products.signals.backend.anomaly_scores.queue import (_cooldown_key,_fleet_budget_key,_project_budget_key,+ _team_loaded_key,active_insights,eligible_teams,is_due,@@ -929,11 +931,12 @@ class TestScoredBuckets(ClickhouseTestMixin, BaseTest):# Any member can capture these: one names an insight of another team, one a bucket in the future.score(11, "f", datetime(2026, 10, 21, tzinfo=UTC))score(8, "c", datetime(2027, 1, 1, tzinfo=UTC))+ # Inside the window of the other insights, but older than the window of its own interval.+ score(12, "g", datetime(2026, 9, 15, tzinfo=UTC))state = scored_buckets(self.team,- insight_ids={7, 8, 9, 10},- since=datetime(2026, 9, 1, tzinfo=UTC),+ {datetime(2026, 9, 1, tzinfo=UTC): {7, 8, 9, 10}, datetime(2026, 10, 1, tzinfo=UTC): {12}},now=datetime(2026, 10, 22, tzinfo=UTC),)@@ -1025,8 +1028,11 @@ class TestScoredBuckets(ClickhouseTestMixin, BaseTest):(small_team.id, 1, {"day": 1}),]+ @parameterized.expand([("query_timeout", ClickHouseQueryTimeOut), ("at_capacity", ClickHouseAtCapacity)])@time_machine.travel(NOW, tick=False)- def test_select_insights_skips_a_project_whose_scored_buckets_query_times_out(self) -> None:+ def test_select_insights_skips_a_project_whose_scored_buckets_query_fails(+ self, _name: str, error: type[Exception]+ ) -> 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 = {}@@ -1046,7 +1052,7 @@ class TestScoredBuckets(ClickhouseTestMixin, BaseTest):def buckets(team: Team, *args: Any) -> dict[int, dict[str, datetime]]:if team.id == slow_team.id:- raise ClickHouseQueryTimeOut()+ raise error()return scored_buckets(team, *args)with (@@ -1056,6 +1062,36 @@ class TestScoredBuckets(ClickhouseTestMixin, BaseTest):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]+ assert (selection.teams_planned, selection.teams_skipped) == (1, 1)++ @time_machine.travel(NOW, tick=False)+ def test_a_plan_past_its_deadline_loads_one_team_and_the_next_plan_starts_from_another(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other")+ insights = {}+ for team in (self.team, other_team):+ insight = Insight.objects.create(team=team, name=team.name, query=_trends(interval="day"))+ DashboardTile.objects.create(dashboard=Dashboard.objects.create(team=team, name="Main"), insight=insight)+ cache.delete_many([_cooldown_key(insight.id), _team_loaded_key(team.id)])+ insights[team.id] = insight.id+ config = AnomalyScoringConfig(+ enabled=True,+ organization_ids=(str(self.organization.id),),+ allow_team_ids=(self.team.id, other_team.id),+ )++ picked: list[list[int]] = []+ with patch("products.signals.backend.anomaly_scores.queue.list_limited_team_attributes", return_value=[]):+ for later in (NOW, NOW + timedelta(minutes=5)):+ cache.delete_many(+ [_fleet_budget_key(later), *(_project_budget_key(team_id, later) for team_id in insights)]+ )+ selection = select_insights(+ config, SelectionConfig(weighting=Weighting.UNIFORM), later, limit=10, deadline=0.0+ )+ assert (selection.teams_planned, selection.teams_skipped) == (1, 1)+ picked.append([pick.insight_id for pick in selection.picks])++ assert sorted(insight_id for picks in picked for insight_id in picks) == sorted(insights.values())@parameterized.expand([("cap_one", 1, ["most_overdue"]), ("cap_two", 2, ["most_overdue", "popular"])])@time_machine.travel(NOW, tick=False)@@ -1252,12 +1288,16 @@ class TestScoredBuckets(ClickhouseTestMixin, BaseTest):async def _run_tick(- plan: AnomalyScoringTickPlan, statuses: dict[int, str]+ plan: AnomalyScoringTickPlan | Exception,+ statuses: dict[int, str],+ captured: list[AnomalyScoringTickResult] | None = None,) -> tuple[AnomalyScoringTickResult, list[int]]:started: list[int] = []@activity.defn(name="plan_anomaly_scoring_tick_activity")async def fake_plan(input: AnomalyScoringTickInput) -> AnomalyScoringTickPlan:+ if isinstance(plan, Exception):+ raise planreturn plan@activity.defn(name="score_anomaly_insight_activity")@@ -1267,7 +1307,8 @@ async def _run_tick(@activity.defn(name="capture_anomaly_scoring_tick_activity")async def fake_capture(result: AnomalyScoringTickResult) -> None:- pass+ if captured is not None:+ captured.append(result)async with await WorkflowEnvironment.start_time_skipping() as env:async with Worker(@@ -1315,3 +1356,15 @@ async def test_the_tick_stops_starting_picks_when_clickhouse_is_at_capacity(3,stopped,)+++async def test_a_failed_plan_sends_a_tick_event_and_still_fails_the_workflow() -> None:+ captured: list[AnomalyScoringTickResult] = []++ with pytest.raises(WorkflowFailureError):+ await _run_tick(ClickHouseAtCapacity(), {}, captured)++ assert [(result.plan_failed, result.plan_error, result.picked) for result in captured] == [+ (True, "ClickHouseAtCapacity", 0)+ ]