: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(alerts): key, scope and mute grouped insight alerts per breakdown value (#118167)
Jimmy Zhu83452f561219
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex f85b14b9d8fc..6c14454a83f3 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -1461,7 +1461,7 @@4 posthog/temporal/proxy_service/monitor.py4 posthog/temporal/salesforce_enrichment/conversations_slack_workflow.py4 posthog/temporal/salesforce_enrichment/usage_workflow.py-4 products/alerts/backend/evaluation/contract.py+3 products/alerts/backend/evaluation/contract.py4 products/approvals/backend/services.py4 products/batch_exports/backend/temporal/destinations/file_download_batch_export.py4 products/conversations/backend/temporal/coordinator.pydiff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.pyindex 7c5ed53af390..2da532f7e79c 100644--- a/products/alerts/backend/evaluation/contract.py+++ b/products/alerts/backend/evaluation/contract.py@@ -19,12 +19,16 @@ class SeriesPoint:value: float | None # None = missing data point this interval-@dataclass+@frozenclass ComparableSeries:label: str # series / breakdown label, used in breach messagespoints: list[SeriesPoint] # chronologically ascending; extractor guarantees ordercurrent_index: int # comparison anchor; previous = current_index - 1is_current_interval: bool = False # anchor is the ongoing (incomplete) interval — affects breach wording+ # The raw identity a caller keys per-series state on. Labels are formatted for display and two+ # series can render the same one, such as multi-breakdown values ["a::b", "c"] and ["a", "b::c"].+ # None when the label is the only identity the extractor has.+ identity: str | None = None@frozen@@ -68,6 +72,9 @@ class ExtractionResult:# trends extractor sets it today; the PERCENTAGE-threshold path ignores it (relative % ratios).value_formatter: Callable[[float], str] | None = Noneevaluated_interval: EvaluatedInterval | None = None+ # The query folded breakdown values past its limit into one "Other" series, so a value missing+ # from ``series`` may still exist and breach.+ truncated: bool = Falsedef zero_sentinel_series() -> ComparableSeries:diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.pyindex 06d8ee3edc08..99397c94b770 100644--- a/products/alerts/backend/evaluation/dispatcher.py+++ b/products/alerts/backend/evaluation/dispatcher.py@@ -214,13 +214,20 @@ def _one_series(result: ExtractionResult, series: ComparableSeries) -> Extractio@frozenclass SeriesEvaluation:+ # What per-series state is keyed on. `label` is for display, and two series can share one.+ identity: strlabel: strresult: AlertEvaluationResult-def check_alert_per_series(- alert: AlertConfiguration,-) -> tuple[SeriesEvaluation, ...] | AlertEvaluationResult:+@frozen+class PerSeriesEvaluation:+ series: tuple[SeriesEvaluation, ...]+ # The breakdown limit folded some values into "Other", so a value not in `series` may still breach.+ truncated: bool = False+++def check_alert_per_series(alert: AlertConfiguration) -> PerSeriesEvaluation | AlertEvaluationResult:"""Each series' own verdict for a threshold alert, rather than one verdict for the insight.`check_alert_for_insight` stops at the first series that breaches, because one alert holds one@@ -236,16 +243,25 @@ def check_alert_per_series(except DelayedEvaluationUnavailable as err:return AlertEvaluationResult(value=None, breaches=[], skipped_reason=str(err))if extracted is None:- return ()- return tuple(- SeriesEvaluation(- label=series.label,- result=describe_delayed_evaluation(- evaluate_threshold(_one_series(extracted.result, series), extracted.condition, extracted.threshold),- extracted.result,- ),- )- for series in extracted.result.series+ return PerSeriesEvaluation(series=())+ result = extracted.result+ if result.is_breakdown and result.empty_query_result:+ # The extractor stands in a zero series for a query with no rows. A breakdown with no rows+ # has no values, so that series is not a breakdown value and must not become a group.+ return PerSeriesEvaluation(series=())+ return PerSeriesEvaluation(+ series=tuple(+ SeriesEvaluation(+ identity=series.identity or series.label,+ label=series.label,+ result=describe_delayed_evaluation(+ evaluate_threshold(_one_series(result, series), extracted.condition, extracted.threshold),+ result,+ ),+ )+ for series in result.series+ ),+ truncated=result.truncated,)diff --git a/products/alerts/backend/evaluation/test/test_dispatcher.py b/products/alerts/backend/evaluation/test/test_dispatcher.pyindex 569a6f0c012b..80740b239515 100644--- a/products/alerts/backend/evaluation/test/test_dispatcher.py+++ b/products/alerts/backend/evaluation/test/test_dispatcher.py@@ -10,6 +10,7 @@ from rest_framework.exceptions import ValidationError as DRFValidationErrorfrom posthog.schema import NodeKindfrom posthog.api.services.query import ExecutionMode+from posthog.caching.insight_result import InsightResultfrom posthog.errors import CHQueryErrorNoCommonType, CHQueryErrorS3FileChangedDuringReadfrom posthog.hogql_queries.query_failure_handling import build_failure_exceptionfrom posthog.query_cache.failures import QueryFailureRecord@@ -20,7 +21,12 @@ from products.alerts.backend.evaluation.contract import (ExtractionResult,SeriesPoint,)-from products.alerts.backend.evaluation.dispatcher import EXTRACTORS, check_alert_per_series, run_extractor+from products.alerts.backend.evaluation.dispatcher import (+ EXTRACTORS,+ PerSeriesEvaluation,+ check_alert_per_series,+ run_extractor,+)IF_STALE = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE@@ -120,9 +126,64 @@ def test_per_series_judges_every_breakdown_value_where_the_alert_stops_at_the_fi):evaluated = check_alert_per_series(alert)- assert isinstance(evaluated, tuple)- assert [(s.label, s.result.value, bool(s.result.breaches)) for s in evaluated] == [+ assert isinstance(evaluated, PerSeriesEvaluation)+ assert [(s.label, s.result.value, bool(s.result.breaches)) for s in evaluated.series] == [("Chrome", 150.0, True),("Safari", 40.0, False),("Firefox", 120.0, True),]+++def _breakdown_row(breakdown_value: list[str], label: str) -> dict[str, Any]:+ return {+ "data": [150.0, 150.0],+ "days": ["2026-09-15", "2026-09-16"],+ "label": label,+ "breakdown_value": breakdown_value,+ "order": 0,+ }+++ "rows, has_more, expected_identities, truncated",+ [+ (+ [_breakdown_row(["a::b", "c"], "a::b::c"), _breakdown_row(["a", "b::c"], "a::b::c")],+ False,+ ['[0,["a::b","c"]]', '[0,["a","b::c"]]'],+ False,+ ),+ ([_breakdown_row(["a", "c"], "a::c")], True, ['[0,["a","c"]]'], True),+ ([], False, [], False),+ ],+ ids=["labels_that_render_alike", "past_the_breakdown_limit", "no_rows"],+)+def test_per_series_keys_trends_breakdowns_on_their_raw_values(+ rows: list[dict[str, Any]], has_more: bool, expected_identities: list[str], truncated: bool+) -> None:+ alert = MagicMock(+ detector_config=None,+ evaluation_delay_intervals=0,+ config={"type": "TrendsAlertConfig", "series_index": 0},+ threshold=MagicMock(configuration={"type": "absolute", "bounds": {"lower": 200}}),+ condition={"type": "absolute_value"},+ team=MagicMock(base_currency="USD", timezone="UTC"),+ )+ alert.insight.query = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ "interval": "day",+ "breakdownFilter": {"breakdowns": [{"property": "a"}, {"property": "b"}]},+ }+ calculated = InsightResult(+ result=rows, has_more=has_more, columns=[], timezone="UTC", last_refresh=None, cache_key="", is_cached=False+ )+ with (+ patch("products.alerts.backend.evaluation.trends.calculate_for_query_based_insight", return_value=calculated),+ patch("products.alerts.backend.evaluation.dispatcher.upgrade_insight", return_value=nullcontext()),+ ):+ evaluated = check_alert_per_series(alert)++ assert isinstance(evaluated, PerSeriesEvaluation)+ assert [series.identity for series in evaluated.series] == expected_identities+ assert evaluated.truncated is truncateddiff --git a/products/alerts/backend/evaluation/trends.py b/products/alerts/backend/evaluation/trends.pyindex fec3980b2732..8878c3296e24 100644--- a/products/alerts/backend/evaluation/trends.py+++ b/products/alerts/backend/evaluation/trends.py@@ -1,3 +1,4 @@+import jsonfrom collections.abc import Callablefrom typing import Any, cast@@ -159,6 +160,7 @@ class TrendsExtractor:is_breakdown=has_breakdown,interval_type=interval_type,value_formatter=value_formatter,+ truncated=has_breakdown and bool(calculation_result.has_more),),delay=delay,minimum_points=1 if condition.type == AlertConditionType.ABSOLUTE_VALUE else 2,@@ -243,6 +245,14 @@ class TrendsExtractor:points=points,current_index=current_index,is_current_interval=is_current_interval,+ identity=_breakdown_identity(result) if has_breakdown else None,))return series+++def _breakdown_identity(result: dict[str, Any]) -> str:+ """The series and the raw breakdown value, which the formatted label can merge across rows."""+ return json.dumps(+ [result.get("order"), result.get("breakdown_value")], separators=(",", ":"), ensure_ascii=False, default=str+ )diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.pyindex dcffb107f1fd..5218102ebde1 100644--- a/products/alerts/backend/platform_source_cycle.py+++ b/products/alerts/backend/platform_source_cycle.py@@ -35,7 +35,7 @@ from posthog.temporal.alerts.admission import admit_evaluation_slots, release_evfrom products.alerts.backend.evaluation import check_alert_for_insightfrom products.alerts.backend.evaluation.contract import AlertExtractionError-from products.alerts.backend.evaluation.dispatcher import check_alert_per_series+from products.alerts.backend.evaluation.dispatcher import PerSeriesEvaluation, check_alert_per_seriesfrom products.alerts.backend.insight_alert_state_machine import INSIGHT_ALERT_POLICY, insight_snapshotfrom products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_IDfrom products.alerts.backend.models.alert import AlertConfiguration@@ -56,7 +56,7 @@ from products.alerts_platform.backend.facade.grouping import (bounded_grouping_key,decide_groups,delivery_parts,- is_hashed_grouping_key,+ not_breaching,)from products.alerts_platform.backend.facade.lifecycle import (NOTIFICATION_EVENT_KINDS,@@ -236,12 +236,18 @@ def _legacy_alert(check: PlatformAlertCheckInput) -> AlertConfiguration | None:)-def _snapshot(check: PlatformAlertCheckInput, instance: InstanceCheckState | None = None) -> AlertSnapshot:+def _snapshot(+ check: PlatformAlertCheckInput,+ instance: InstanceCheckState | None = None,+ *,+ snooze_until: datetime | None = None,+) -> AlertSnapshot:instance = instance or check.instance()return insight_snapshot(AlertState(instance.state),last_notified_at=instance.last_notified_at,firing_started_at=instance.firing_started_at,+ snooze_until=snooze_until,)@@ -365,13 +371,20 @@ _FAILED_CHECKS: Final = frozenset({SkipReason.QUERY_FAILED, SkipReason.BROKEN_CO# The one label a grouped insight alert splits on: each breakdown value is a group.BREAKDOWN_GROUPING_KEY = "breakdown"+# A breakdown value can be muted on its own, which production cannot express, so the platform's+# mute applies: the value is still judged and only its announcement is held. A snooze of the+# production alert never reaches here, because `_decide` records that check without a query.+GROUPED_INSIGHT_ALERT_POLICY: Final = replace(INSIGHT_ALERT_POLICY, mute_gates_notification_only=True)+def _decide_grouped(check: PlatformAlertCheckInput, snapshot: AlertSnapshot, alert: AlertConfiguration, *, now: datetime) -> PlatformAlertOutcome:"""One check of a breakdown alert, judged per breakdown value through the platform's decision.- An open value the query no longer returns is judged as not breaching, so it can resolve.+ An open value the query no longer returns is judged as not breaching, so it can resolve. When+ the breakdown limit folded values into "Other", a missing value may still breach, so an open+ value the query did not return is left as it is."""if tuple(check.grouping.keys) != (BREAKDOWN_GROUPING_KEY,):return _broken(check, snapshot, now=now, message=f"An insight alert can only group by {BREAKDOWN_GROUPING_KEY}")@@ -382,7 +395,7 @@ def _decide_grouped(return _broken(check, snapshot, now=now, message=str(error))except Exception as error:return _query_failed(check, snapshot, error, now=now)- if not isinstance(evaluated, tuple):+ if not isinstance(evaluated, PerSeriesEvaluation):return _skipped(check, snapshot, now=now)duration_ms = int((time.monotonic() - started_at) * 1000)@@ -390,21 +403,17 @@ def _decide_grouped(check,[GroupObservation(- grouping_key=bounded_grouping_key(series.label),+ grouping_key=bounded_grouping_key(series.identity),current_breached=bool(series.result.breaches),value=series.result.value,labels={BREAKDOWN_GROUPING_KEY: series.label},)- for series in evaluated+ for series in evaluated.series],- snapshot_of=lambda instance, _prior: _snapshot(check, instance),- policy=INSIGHT_ALERT_POLICY,+ snapshot_of=lambda instance, _prior: _snapshot(check, instance, snooze_until=instance.snooze_until),+ policy=GROUPED_INSIGHT_ALERT_POLICY,now=now,- absent=lambda key: GroupObservation(- grouping_key=key,- current_breached=False,- labels={} if is_hashed_grouping_key(key) else {BREAKDOWN_GROUPING_KEY: key},- ),+ absent=(lambda _key: None) if evaluated.truncated else not_breaching,)for verdict in decision.verdicts:_record_metrics(verdict.outcome.notification, verdict.snapshot.state.value, verdict.group.new_state)diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.pyindex ef59b4f1b3b2..b475c5070221 100644--- a/products/alerts/backend/test/test_platform_source_cycle.py+++ b/products/alerts/backend/test/test_platform_source_cycle.py@@ -18,7 +18,7 @@ from posthog.schema_enums import AlertCalculationIntervalfrom posthog.tasks.alerts.utils import AlertEvaluationResultfrom products.alerts.backend.evaluation.contract import AlertExtractionError-from products.alerts.backend.evaluation.dispatcher import SeriesEvaluation+from products.alerts.backend.evaluation.dispatcher import PerSeriesEvaluation, SeriesEvaluationfrom products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_IDfrom products.alerts.backend.models.alert import AlertCheck, AlertConfigurationfrom products.alerts.backend.platform_source_cycle import (@@ -74,16 +74,22 @@ class TestPlatformInsightEvaluation(APIBaseTest):)def _evaluate_per_series(- self, configuration: PlatformConfigurationSnapshot, values: dict[str, float]+ self, configuration: PlatformConfigurationSnapshot, values: dict[str, float], *, truncated: bool = False) -> PlatformAlertOutcome:slot = slot_of(configuration.next_check_at, CUTOFF)expires_at = time.time() + 3600assert plan_insight_batch(self.team.id, slot, CUTOFF, expires_at=expires_at) == (str(configuration.id),)- evaluated = tuple(- SeriesEvaluation(- label=label, result=AlertEvaluationResult(value=value, breaches=["above 100"] if value > 100 else [])- )- for label, value in values.items()+ # One label for every series, so a key taken from the label instead of the identity merges them.+ evaluated = PerSeriesEvaluation(+ series=tuple(+ SeriesEvaluation(+ identity=identity,+ label="browser",+ result=AlertEvaluationResult(value=value, breaches=["above 100"] if value > 100 else []),+ )+ for identity, value in values.items()+ ),+ truncated=truncated,)with patch(f"{_MODULE}.check_alert_per_series", return_value=evaluated):evaluation = evaluate_insight_check(@@ -93,7 +99,10 @@ class TestPlatformInsightEvaluation(APIBaseTest):(outcome,) = evaluation.outcomesreturn outcome- def test_each_breakdown_value_fires_and_resolves_on_its_own(self) -> None:+ @parameterized.expand([("complete", False, "not_firing"), ("past_the_breakdown_limit", True, None)])+ def test_each_breakdown_value_fires_and_resolves_on_its_own(+ self, _name: str, truncated: bool, missing_state: str | None+ ) -> None:grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("breakdown",))configuration = self._copy(self._alert(), grouping=grouping.to_stored())@@ -106,12 +115,22 @@ class TestPlatformInsightEvaluation(APIBaseTest):with team_scope(self.team.id):platform_testing.set_due_at(configuration.id, CUTOFF - timedelta(minutes=1))- resolved = self._evaluate_per_series(configuration, {"Chrome": 150.0})+ resolved = self._evaluate_per_series(configuration, {"Chrome": 150.0}, truncated=truncated)- assert {group.grouping_key: group.new_state for group in resolved.groups} == {- "Chrome": "firing",- "Firefox": "not_firing",- }+ expected = {"Chrome": "firing"} | ({"Firefox": missing_state} if missing_state else {})+ assert {group.grouping_key: group.new_state for group in resolved.groups} == expected++ def test_a_muted_breakdown_value_tracks_its_firing_without_announcing_it(self) -> None:+ grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("breakdown",))+ configuration = self._copy(+ self._alert(), grouping=grouping.to_stored(), snooze_until=CUTOFF + timedelta(hours=1)+ )++ outcome = self._evaluate_per_series(configuration, {"Chrome": 150.0})++ assert [(group.kind, group.new_state, group.muted_notification) for group in outcome.groups] == [+ (AlertEventKind.CHECK, "firing", "fire")+ ]def _evaluate(self, configuration: PlatformConfigurationSnapshot, *, result: Any = Nonediff --git a/products/alerts_platform/backend/facade/grouping.py b/products/alerts_platform/backend/facade/grouping.pyindex 1c4945caf6e5..bd4544b98d34 100644--- a/products/alerts_platform/backend/facade/grouping.py+++ b/products/alerts_platform/backend/facade/grouping.py@@ -41,18 +41,35 @@ MAX_GROUPING_KEY_LENGTH: Final = 255_HASHED_PREFIX: Final = "sha256:"-def bounded_grouping_key(key: str) -> str:- """A key that fits the column. Stable across checks, so a group keeps its row."""- if len(key) <= MAX_GROUPING_KEY_LENGTH:- return key- return f"{_HASHED_PREFIX}{hashlib.sha256(key.encode()).hexdigest()}"--def is_hashed_grouping_key(key: str) -> bool:"""Whether `bounded_grouping_key` hashed this key, so the value it came from is gone."""return key.startswith(_HASHED_PREFIX)+def _storable(key: str) -> bool:+ # A PostgreSQL text column rejects NUL, and UTF-8 cannot encode a lone surrogate. Either one+ # aborts the transaction that records the whole batch.+ if "\x00" in key:+ return False+ try:+ key.encode()+ except UnicodeEncodeError:+ return False+ return True+++def bounded_grouping_key(key: str) -> str:+ """A key the column can store. Stable across checks, so a group keeps its row.++ A key stays as it is only when it fits, PostgreSQL can store it, and it cannot read as a hash.+ Every other key is hashed. A literal key in the hash namespace is hashed too, because otherwise+ it would share a row with the long key whose digest it spells.+ """+ if len(key) <= MAX_GROUPING_KEY_LENGTH and not is_hashed_grouping_key(key) and _storable(key):+ return key+ return f"{_HASHED_PREFIX}{hashlib.sha256(key.encode('utf-8', 'surrogatepass')).hexdigest()}"++# A label value can come from ingested data, such as a service name, so its size is the sender's# choice. Every group's labels cross Temporal on the outcome, and a cap on the count and on each# encoded size keeps a check's outcome inside `MAX_BATCH_PAYLOAD_BYTES` at `MAX_INSTANCES_CEILING`.@@ -157,7 +174,7 @@ def muted_value(outcome: Outcome) -> str:return "" if muted == NotificationAction.NONE else muted.value-def _not_breaching(grouping_key: str) -> GroupObservation:+def not_breaching(grouping_key: str) -> GroupObservation:return GroupObservation(grouping_key=grouping_key, current_breached=False)@@ -177,7 +194,7 @@ def decide_groups(policy: AlertPolicy,now: datetime,muted: bool = False,- absent: Callable[[str], GroupObservation | None] = _not_breaching,+ absent: Callable[[str], GroupObservation | None] = not_breaching,) -> GroupDecision:"""Each observed group run through the machine against its own instance.diff --git a/products/alerts_platform/backend/tests/test_grouping.py b/products/alerts_platform/backend/tests/test_grouping.pynew file mode 100644index 000000000000..e430476db6ff--- /dev/null+++ b/products/alerts_platform/backend/tests/test_grouping.py@@ -0,0 +1,36 @@+import hashlib++import pytest++from products.alerts_platform.backend.facade.grouping import bounded_grouping_key, is_hashed_grouping_key++_LONG = "x" * 300+_LONG_DIGEST = f"sha256:{hashlib.sha256(_LONG.encode()).hexdigest()}"+++ "key, kept",+ [+ ("Chrome", True),+ ('{"service_name":"api"}', True),+ ("x" * 255, True),+ (_LONG, False),+ (_LONG_DIGEST, False),+ ("sha256:", False),+ ("Chr\x00me", False),+ ("Chr\ud800me", False),+ ],+ ids=["plain", "json", "at_limit", "too_long", "literal_digest", "literal_prefix", "nul", "lone_surrogate"],+)+def test_a_key_is_kept_only_when_the_column_can_store_it_and_it_cannot_read_as_a_hash(key: str, kept: bool) -> None:+ bounded = bounded_grouping_key(key)++ assert (bounded == key) is kept+ assert is_hashed_grouping_key(bounded) is not kept+ assert len(bounded) <= 255 and "\x00" not in bounded+ bounded.encode()+++def test_a_literal_digest_does_not_share_a_row_with_the_long_key_it_spells() -> None:+ assert bounded_grouping_key(_LONG) == _LONG_DIGEST+ assert bounded_grouping_key(_LONG_DIGEST) != _LONG_DIGEST