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(alerts): format notification values and breakdown labels (#67981)

jake sciotto9fff5737e9ae
diff --git a/ee/hogai/context/insight/format/test/test_utils.py b/ee/hogai/context/insight/format/test/test_utils.py
index 3256e90f9f3d..05e93e0ca1fd 100644
--- a/ee/hogai/context/insight/format/test/test_utils.py
+++ b/ee/hogai/context/insight/format/test/test_utils.py
@@ -8,7 +8,6 @@ from ..utils import (
format_matrix,
format_number,
format_percentage,
- replace_breakdown_labels,
strip_datetime_seconds,
)
@@ -64,21 +63,6 @@ class TestFormatUtils(BaseTest):
self.assertEqual(format_percentage(0.1234), "12.34%")
self.assertEqual(format_percentage(0.12345), "12.35%") # Tests rounding
- def test_replace_breakdown_labels(self):
- # Test with breakdown other string
- self.assertEqual(
- replace_breakdown_labels("test $$_posthog_breakdown_other_$$"), "test Other (i.e. all remaining values)"
- )
- # Test with breakdown null string
- self.assertEqual(replace_breakdown_labels("test $$_posthog_breakdown_null_$$"), "test None (i.e. no value)")
- # Test with both
- self.assertEqual(
- replace_breakdown_labels("$$_posthog_breakdown_other_$$ and $$_posthog_breakdown_null_$$"),
- "Other (i.e. all remaining values) and None (i.e. no value)",
- )
- # Test with normal string
- self.assertEqual(replace_breakdown_labels("normal text"), "normal text")
-
def test_strip_datetime_seconds(self):
self.assertEqual(strip_datetime_seconds("2025-01-20"), "2025-01-20")
self.assertEqual(strip_datetime_seconds("2025-01-20 00:00:00"), "2025-01-20 00:00")
diff --git a/ee/hogai/context/insight/format/trends.py b/ee/hogai/context/insight/format/trends.py
index 347a11257cf7..0a7bb7337317 100644
--- a/ee/hogai/context/insight/format/trends.py
+++ b/ee/hogai/context/insight/format/trends.py
@@ -2,7 +2,9 @@ from typing import Any
from posthog.schema import AssistantTrendsQuery, Compare, TrendsQuery
-from .utils import format_matrix, format_number, replace_breakdown_labels, strip_datetime_seconds
+from posthog.hogql_queries.insights.utils.breakdowns import humanize_breakdown_label
+
+from .utils import format_matrix, format_number, strip_datetime_seconds
class TrendsResultsFormatter:
@@ -111,7 +113,7 @@ class TrendsResultsFormatter:
breakdown_label = str(series["breakdown_value"])
name += f" breakdown for the value `{breakdown_label}`"
- return replace_breakdown_labels(name)
+ return humanize_breakdown_label(name)
def _format_results(self, results: list[dict]) -> str:
# Get dates and series labels
diff --git a/ee/hogai/context/insight/format/utils.py b/ee/hogai/context/insight/format/utils.py
index a2db7b1bf23e..ddf6b85439c5 100644
--- a/ee/hogai/context/insight/format/utils.py
+++ b/ee/hogai/context/insight/format/utils.py
@@ -2,13 +2,6 @@ import datetime
from math import floor
from typing import Any, Optional, Union
-from posthog.hogql_queries.insights.utils.breakdowns import (
- BREAKDOWN_NULL_DISPLAY,
- BREAKDOWN_NULL_STRING_LABEL,
- BREAKDOWN_OTHER_DISPLAY,
- BREAKDOWN_OTHER_STRING_LABEL,
-)
-
def format_matrix(matrix: list[list[Any]]) -> str:
# Coerce cells: a None (or non-str) cell would make "|".join raise and crash the build.
@@ -108,9 +101,3 @@ def format_date(date: datetime.date) -> str:
def strip_datetime_seconds(date: str) -> str:
return datetime.datetime.fromisoformat(date).strftime("%Y-%m-%d %H:%M" if ":" in date else "%Y-%m-%d")
-
-
-def replace_breakdown_labels(name: str) -> str:
- return name.replace(BREAKDOWN_OTHER_STRING_LABEL, BREAKDOWN_OTHER_DISPLAY).replace(
- BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_NULL_DISPLAY
- )
diff --git a/posthog/hogql_queries/insights/utils/breakdowns.py b/posthog/hogql_queries/insights/utils/breakdowns.py
index 8fa6cd539368..ca7098063eae 100644
--- a/posthog/hogql_queries/insights/utils/breakdowns.py
+++ b/posthog/hogql_queries/insights/utils/breakdowns.py
@@ -14,6 +14,15 @@ ALL_USERS_COHORT_ID = 0
NOT_IN_COHORT_ID = 2**52
+def humanize_breakdown_label(label: str) -> str:
+ """Swap the internal breakdown sentinels for their display strings. The sentinels are globally
+ unique tokens, so a substring replace covers every label shape — standalone, action-prefixed
+ ("signed_up - <sentinel>"), and "::"-joined multi-breakdown values — without fragile splitting."""
+ return label.replace(BREAKDOWN_OTHER_STRING_LABEL, BREAKDOWN_OTHER_DISPLAY).replace(
+ BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_NULL_DISPLAY
+ )
+
+
class _AliasStripper(CloningVisitor):
def visit_alias(self, node: ast.Alias) -> ast.Expr:
return self.visit(node.expr)
diff --git a/posthog/hogql_queries/insights/utils/test/test_breakdowns.py b/posthog/hogql_queries/insights/utils/test/test_breakdowns.py
index e52b73f12f6d..b01744b8b428 100644
--- a/posthog/hogql_queries/insights/utils/test/test_breakdowns.py
+++ b/posthog/hogql_queries/insights/utils/test/test_breakdowns.py
@@ -6,6 +6,7 @@ from posthog.hogql_queries.insights.utils.breakdowns import (
has_breakdown_filter,
has_multi_breakdown,
has_single_breakdown,
+ humanize_breakdown_label,
)
@@ -44,3 +45,25 @@ def test_breakdown_presence_helpers(
assert has_breakdown_filter(breakdown_filter) is expected_has_breakdown
assert has_single_breakdown(breakdown_filter) is expected_has_single
assert has_multi_breakdown(breakdown_filter) is expected_has_multi
+
+
+ "label, expected",
+ [
+ ("$$_posthog_breakdown_other_$$", "Other (i.e. all remaining values)"),
+ ("$$_posthog_breakdown_null_$$", "None (i.e. no value)"),
+ # both sentinels in one label are each replaced
+ (
+ "$$_posthog_breakdown_other_$$ and $$_posthog_breakdown_null_$$",
+ "Other (i.e. all remaining values) and None (i.e. no value)",
+ ),
+ # compound label shapes survive: action-prefixed and "::"-joined multi-breakdown
+ ("signed_up - $$_posthog_breakdown_other_$$", "signed_up - Other (i.e. all remaining values)"),
+ ("$$_posthog_breakdown_other_$$::US", "Other (i.e. all remaining values)::US"),
+ ("Chrome", "Chrome"),
+ # a normal label containing " - " must pass through untouched (no fragile splitting)
+ ("Signed up - paid", "Signed up - paid"),
+ ],
+)
+def test_humanize_breakdown_label(label: str, expected: str) -> None:
+ assert humanize_breakdown_label(label) == expected
diff --git a/posthog/tasks/alerts/test/test_alert_evaluation.py b/posthog/tasks/alerts/test/test_alert_evaluation.py
index e5bf1d5d0a43..81186a7b3b09 100644
--- a/posthog/tasks/alerts/test/test_alert_evaluation.py
+++ b/posthog/tasks/alerts/test/test_alert_evaluation.py
@@ -100,7 +100,7 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
assert mock_send_notifications_for_breaches.call_count == 1
anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
- assert "The insight value ($pageview) for current interval (0) is less than lower threshold (1.0)" in anomalies
+ assert "The insight value ($pageview) for current interval (0) is less than lower threshold (1)" in anomalies
def test_alert_triggered_for_single_formula(
self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
@@ -125,7 +125,7 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
assert len(anomalies) == 1
assert (
- "The insight value (Double Pageviews) for current interval (2.0) is more than upper threshold (1.0)"
+ "The insight value (Double Pageviews) for current interval (2) is more than upper threshold (1)"
in anomalies[0]
)
@@ -148,7 +148,7 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
assert len(anomalies) == 1
assert (
- "The insight value (Formula (A*2)) for current interval (2.0) is more than upper threshold (1.0)"
+ "The insight value (Formula (A*2)) for current interval (2) is more than upper threshold (1)"
in anomalies[0]
)
@@ -171,7 +171,7 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
assert len(anomalies) == 1
assert (
- "The insight value (Formula (A*2)) for current interval (2.0) is more than upper threshold (1.0)"
+ "The insight value (Formula (A*2)) for current interval (2) is more than upper threshold (1)"
in anomalies[0]
)
@@ -200,6 +200,6 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
assert len(anomalies) == 1
assert (
- "The insight value (Double Pageviews) for current interval (2.0) is more than upper threshold (1.0)"
+ "The insight value (Double Pageviews) for current interval (2) is more than upper threshold (1)"
in anomalies[0]
)
diff --git a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
index caa9ded2ce8d..8aa6d36aedc1 100644
--- a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
@@ -9,6 +9,7 @@ import pytz
import dateutil
from posthog.schema import (
+ AggregationAxisFormat,
AlertCalculationInterval,
AlertState,
BaseMathType,
@@ -77,6 +78,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
self,
breakdown: Optional[BreakdownFilter] = None,
interval: IntervalType = IntervalType.WEEK,
+ trends_filter: Optional[TrendsFilter] = None,
) -> dict[str, Any]:
query_dict = TrendsQuery(
series=[
@@ -91,7 +93,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
),
],
breakdownFilter=breakdown,
- trendsFilter=TrendsFilter(display=ChartDisplayType.ACTIONS_LINE_GRAPH),
+ trendsFilter=trends_filter or TrendsFilter(display=ChartDisplayType.ACTIONS_LINE_GRAPH),
interval=interval,
dateRange=DateRange(date_from="-8w"),
).model_dump()
@@ -161,7 +163,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for previous week (0) is less than lower threshold (1.0)"],
+ ["The insight value (signed_up) for previous week (0) is less than lower threshold (1)"],
idempotency_key=ANY,
)
@@ -201,7 +203,33 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for previous week (2) is more than upper threshold (1.0)"],
+ ["The insight value (signed_up) for previous week (2) is more than upper threshold (1)"],
+ idempotency_key=ANY,
+ )
+
+ def test_trend_currency_value_formatted_in_breach(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock
+ ) -> None:
+ # A currency-formatted insight renders the breach value and threshold with the team's currency
+ # symbol (USD by default), mirroring the chart — not as a raw float.
+ insight = self.create_time_series_trend_insight(
+ trends_filter=TrendsFilter(
+ display=ChartDisplayType.ACTIONS_LINE_GRAPH,
+ aggregationAxisFormat=AggregationAxisFormat.CURRENCY,
+ )
+ )
+ alert = self.create_alert(insight, series_index=0, upper=1)
+
+ with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1)):
+ _create_event(team=self.team, event="signed_up", distinct_id="1")
+ _create_event(team=self.team, event="signed_up", distinct_id="2")
+ flush_persons_and_events()
+
+ run_alert_check(alert["id"])
+
+ mock_send_breaches.assert_called_once_with(
+ ANY,
+ ["The insight value (signed_up) for previous week ($2.00) is more than upper threshold ($1.00)"],
idempotency_key=ANY,
)
@@ -314,7 +342,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up - Chrome) for previous week (2.0) is more than upper threshold (1.0)"],
+ ["The insight value (signed_up - Chrome) for previous week (2) is more than upper threshold (1)"],
idempotency_key=ANY,
)
@@ -362,7 +390,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up - Firefox) for previous week (1.0) is less than lower threshold (2.0)"],
+ ["The insight value (signed_up - Firefox) for previous week (1) is less than lower threshold (2)"],
idempotency_key=ANY,
)
@@ -454,7 +482,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for current interval (3) is more than upper threshold (1.0)"],
+ ["The insight value (signed_up) for current interval (3) is more than upper threshold (1)"],
idempotency_key=ANY,
)
@@ -502,7 +530,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up - Chrome) for current interval (2) is more than upper threshold (1.0)"],
+ ["The insight value (signed_up - Chrome) for current interval (2) is more than upper threshold (1)"],
idempotency_key=ANY,
)
@@ -545,7 +573,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for current week (2) is more than upper threshold (1.0)"],
+ ["The insight value (signed_up) for current week (2) is more than upper threshold (1)"],
idempotency_key=ANY,
)
@@ -672,7 +700,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for previous week (0) is less than lower threshold (2.0)"],
+ ["The insight value (signed_up) for previous week (0) is less than lower threshold (2)"],
idempotency_key=ANY,
)
diff --git a/posthog/tasks/alerts/test/test_trends_relative_alerts.py b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
index a285017744a9..04449dd3df06 100644
--- a/posthog/tasks/alerts/test/test_trends_relative_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
@@ -194,7 +194,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for previous week (2) increased more than upper threshold (1.0)"],
+ ["The insight value (signed_up) for previous week (2) increased more than upper threshold (1)"],
idempotency_key=ANY,
)
@@ -369,7 +369,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for previous week (-1) increased less than lower threshold (2.0)"],
+ ["The insight value (signed_up) for previous week (-1) increased less than lower threshold (2)"],
idempotency_key=ANY,
)
@@ -567,7 +567,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for previous week (2) decreased more than upper threshold (1.0)"],
+ ["The insight value (signed_up) for previous week (2) decreased more than upper threshold (1)"],
idempotency_key=ANY,
)
@@ -668,7 +668,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for previous week (1) decreased less than lower threshold (2.0)"],
+ ["The insight value (signed_up) for previous week (1) decreased less than lower threshold (2)"],
idempotency_key=ANY,
)
@@ -994,7 +994,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
call(
ANY,
[
- "The insight value (signed_up - Chrome) for previous week (2.0) increased more than upper threshold (1.0)"
+ "The insight value (signed_up - Chrome) for previous week (2) increased more than upper threshold (1)"
],
idempotency_key=ANY,
),
@@ -1122,7 +1122,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
call(
ANY,
[
- "The insight value (signed_up - Firefox) for previous week (0.0) increased less than lower threshold (1.0)"
+ "The insight value (signed_up - Firefox) for previous week (0) increased less than lower threshold (1)"
],
idempotency_key=ANY,
),
@@ -1250,7 +1250,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
call(
ANY,
[
- "The insight value (signed_up - Chrome) for previous week (-2.0) decreased less than lower threshold (1.0)"
+ "The insight value (signed_up - Chrome) for previous week (-2) decreased less than lower threshold (1)"
],
idempotency_key=ANY,
),
@@ -1379,7 +1379,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
call(
ANY,
[
- "The insight value (signed_up - Chrome) for previous week (2.0) decreased more than upper threshold (1.0)"
+ "The insight value (signed_up - Chrome) for previous week (2) decreased more than upper threshold (1)"
],
idempotency_key=ANY,
),
@@ -1687,7 +1687,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for current week (2) increased more than upper threshold (1.0)"],
+ ["The insight value (signed_up) for current week (2) increased more than upper threshold (1)"],
idempotency_key=ANY,
)
@@ -1890,7 +1890,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# so logic fallback to previous week
mock_send_breaches.assert_called_once_with(
ANY,
- ["The insight value (signed_up) for previous week (2) increased more than upper threshold (1.0)"],
+ ["The insight value (signed_up) for previous week (2) increased more than upper threshold (1)"],
idempotency_key=ANY,
)
diff --git a/products/alerts/backend/evaluation/comparator.py b/products/alerts/backend/evaluation/comparator.py
index 01a3dd1d19a7..b3ca68427788 100644
--- a/products/alerts/backend/evaluation/comparator.py
+++ b/products/alerts/backend/evaluation/comparator.py
@@ -1,3 +1,5 @@
+from collections.abc import Callable
+
from posthog.schema import (
AlertCondition,
AlertConditionType,
@@ -29,13 +31,20 @@ def _breach_messages(
series: str | None = None,
is_current_interval: bool = False,
unit: str = "",
+ value_formatter: Callable[[float], str] | None = None,
) -> list[str]:
is_percentage = threshold_type == InsightThresholdType.PERCENTAGE
- # `unit` (e.g. "%" for funnel conversion rates, which are absolute 0–100 values) keeps the
- # notification consistent with the configure-time UI. PERCENTAGE thresholds already render their own %.
+ # PERCENTAGE thresholds render the relative-change ratio as their own % and take precedence.
+ # Otherwise a trends ``value_formatter`` mirrors the insight's axis format (currency, prefix,
+ # decimals). Falls back to raw value + ``unit`` (e.g. "%" for funnel conversion rates, which are
+ # absolute 0–100 values) to keep the notification consistent with the configure-time UI.
def _fmt(value: float) -> str:
- return f"{value:.2%}" if is_percentage else f"{value}{unit}"
+ if is_percentage:
+ return f"{value:.2%}"
+ if value_formatter is not None:
+ return value_formatter(value)
+ return f"{value}{unit}"
formatted_value = _fmt(calculated_value)
@@ -143,6 +152,7 @@ def evaluate_threshold(
series=s.label,
is_current_interval=s.is_current_interval,
unit=result.unit,
+ value_formatter=result.value_formatter,
)
if breaches:
if not result.aggregate_breaches:
diff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.py
index 3cab467337d8..41aebfc5690c 100644
--- a/products/alerts/backend/evaluation/contract.py
+++ b/products/alerts/backend/evaluation/contract.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Protocol
@@ -53,6 +54,10 @@ class ExtractionResult:
# alerts set this so a resolved label column surfaces, e.g. "(Burn rate 24h)". Breakdowns already
# name every row via ``is_breakdown``; this covers the one-series case where the name is meaningful.
include_series_label: bool = False
+ # Optional per-value display formatter mirroring the insight's axis format (currency, prefix/postfix,
+ # decimals, duration, %). None → the comparator falls back to raw ``f"{value}{unit}"``. Only the
+ # trends extractor sets it today; the PERCENTAGE-threshold path ignores it (relative % ratios).
+ value_formatter: Callable[[float], str] | None = None
def zero_sentinel_series() -> ComparableSeries:
diff --git a/products/alerts/backend/evaluation/formatting.py b/products/alerts/backend/evaluation/formatting.py
new file mode 100644
index 000000000000..bea7a096ee44
--- /dev/null
+++ b/products/alerts/backend/evaluation/formatting.py
@@ -0,0 +1,199 @@
+"""Format alert-breach values and breakdown labels the way the insight itself displays them.
+
+This is a backend port of the frontend `formatAggregationAxisValue`
+(`frontend/src/scenes/insights/aggregationAxisFormat.ts`): given a trends insight's axis config
+(`aggregationAxisFormat`, prefix/postfix, decimal places) plus the team's base currency, render a
+raw metric value as the user sees it on the chart — so notification messages read "($803.77)" and
+"(Other (i.e. all remaining values))" instead of "(803.7740196999998)" and a raw breakdown sentinel.
+"""
+
+import math
+from collections.abc import Callable
+
+from posthog.schema import AggregationAxisFormat, TrendsFilter
+
+from posthog.utils import compact_number
+
+DEFAULT_DECIMAL_PLACES = 2
+
+# en-US currency symbols for common currencies, mirroring the Intl.NumberFormat('en-US') output the
+# frontend's formatCurrency relies on. Unlisted currencies fall back to a "<CODE> " prefix, and a
+# missing currency falls back to "$" (matching the frontend humanFriendlyCurrency fallback).
+_CURRENCY_SYMBOLS: dict[str, str] = {
+ "USD": "$",
+ "EUR": "€",
+ "GBP": "£",
+ "JPY": "¥",
+ "CNY": "CN¥",
+ "INR": "₹",
+ "KRW": "₩",
+ "RUB": "₽",
+ "BRL": "R$",
+ "CAD": "CA$",
+ "AUD": "A$",
+ "NZD": "NZ$",
+ "HKD": "HK$",
+ "SGD": "S$",
+ "MXN": "MX$",
+ "TRY": "₺",
+ "THB": "฿",
+ "PHP": "₱",
+ "IDR": "Rp",
+ "ILS": "₪",
+ "ZAR": "R",
+ "CHF": "CHF ",
+ "SEK": "SEK ",
+ "NOK": "NOK ",
+ "DKK": "DKK ",
+ "PLN": "PLN ",
+ "AED": "AED ",
+ "SAR": "SAR ",
+}
+
+
+def make_trends_value_formatter(trends_filter: TrendsFilter | None, currency: str | None) -> Callable[[float], str]:
+ """Bind a trends insight's axis config into a one-arg value formatter for the comparator.
+
+ Tolerates ``trends_filter=None`` (a valid trends query state) by rendering a plain humanized number.
+ """
+ axis_format = trends_filter.aggregationAxisFormat if trends_filter else None
+ prefix = trends_filter.aggregationAxisPrefix if trends_filter else None
+ postfix = trends_filter.aggregationAxisPostfix if trends_filter else None
+ decimal_places = trends_filter.decimalPlaces if trends_filter else None
+ min_decimal_places = trends_filter.minDecimalPlaces if trends_filter else None
+
+ def _format(value: float) -> str:
+ return format_aggregation_value(
+ value,
+ axis_format=axis_format,
+ prefix=prefix,
+ postfix=postfix,
+ decimal_places=decimal_places,
+ min_decimal_places=min_decimal_places,
+ currency=currency,
+ )
+
+ return _format
+
+
+def format_aggregation_value(
+ value: float,
+ *,
+ axis_format: AggregationAxisFormat | None = None,
+ prefix: str | None = None,
+ postfix: str | None = None,
+ decimal_places: float | None = None,
+ min_decimal_places: float | None = None,
+ currency: str | None = None,
+) -> str:
+ """Render a single metric value per the insight's axis format, wrapped in its prefix/postfix."""
+ if not math.isfinite(value):
+ formatted = "∞" if value > 0 else "-∞" if value < 0 else "NaN"
+ return f"{prefix or ''}{formatted}{postfix or ''}"
+
+ match axis_format:
+ case AggregationAxisFormat.DURATION:
+ formatted = _format_duration_seconds(value)
+ case AggregationAxisFormat.DURATION_MS:
+ formatted = _format_duration_seconds(value / 1000, seconds_fixed=1)
+ case AggregationAxisFormat.PERCENTAGE:
+ formatted = _percentage(value / 100, decimal_places)
+ case AggregationAxisFormat.PERCENTAGE_SCALED:
+ formatted = _percentage(value, decimal_places)
+ case AggregationAxisFormat.CURRENCY:
+ formatted = _format_currency(value, currency)
+ case AggregationAxisFormat.SHORT:
+ formatted = compact_number(value)
+ case _: # NUMERIC or unset
+ formatted = _human_friendly_number(value, decimal_places, min_decimal_places)
+
+ return f"{prefix or ''}{formatted}{postfix or ''}"
+
+
+def _clamp_decimal_places(value: float | None, fallback: int) -> int:
+ """Mirror the frontend validateFractionDigits: only accept a whole number in [0, 100]."""
+ if value is None:
+ return fallback
+ as_int = int(value)
+ if as_int != value or as_int < 0 or as_int > 100:
+ return fallback
+ return as_int
+
+
+def _human_friendly_number(
+ value: float, max_decimal_places: float | None = None, min_decimal_places: float | None = None
+) -> str:
+ """Thousands-separated number, trimming trailing zeros down to min_decimal_places.
+
+ Port of the frontend humanFriendlyNumber (`(n).toLocaleString('en-US', {...})`).
+ """
+ max_dp = _clamp_decimal_places(max_decimal_places, DEFAULT_DECIMAL_PLACES)
+ min_dp = _clamp_decimal_places(min_decimal_places, 0)
+ if min_dp > max_dp:
+ min_dp = max_dp
+
+ formatted = f"{value:,.{max_dp}f}"
+ if "." not in formatted:
+ return formatted
+ integer_part, _, frac = formatted.partition(".")
+ frac = frac.rstrip("0")
+ if len(frac) < min_dp:
+ frac = frac.ljust(min_dp, "0")
+ return f"{integer_part}.{frac}" if frac else integer_part
+
+
+def _percentage(division: float, max_decimal_places: float | None = None) -> str:
+ """Render a fraction as a percentage, e.g. 0.5 -> "50%" (port of the frontend percentage())."""
+ if not math.isfinite(division):
+ return "∞%" if division > 0 else "-∞%" if division < 0 else "NaN%"
+ return f"{_human_friendly_number(division * 100, max_decimal_places, 0)}%"
+
+
+def _format_currency(value: float, currency: str | None) -> str:
+ """Prefix the humanized number (fixed 2 decimals, like the frontend formatCurrency) with the
+ currency symbol. Unknown currencies fall back to the code; a missing currency falls back to "$"."""
+ number = _human_friendly_number(value, DEFAULT_DECIMAL_PLACES, DEFAULT_DECIMAL_PLACES)
+ if not currency:
+ return f"${number}"
+ symbol = _CURRENCY_SYMBOLS.get(currency.upper())
+ if symbol is not None:
+ return f"{symbol}{number}"
+ return f"{currency.upper()} {number}"
+
+
+def _format_duration_seconds(value: float, *, seconds_fixed: int | None = None) -> str:
+ """Convert seconds to a human-readable duration ("45s", "2m 12s", "1h 4m", "850ms").
+
+ Port of the frontend humanFriendlyDuration; handles negative (relative differences) and zero.
+ """
+ if value < 0:
+ return f"-{_format_duration_seconds(-value, seconds_fixed=seconds_fixed)}"
+ if value == 0:
+ return "0s"
+ if value < 1:
+ return f"{round(value * 1000)}ms"
+ if value < 60:
+ return f"{_trim_float(f'{value:.{seconds_fixed or 0}f}')}s"
+
+ days = math.floor(value / 86400)
+ hours = math.floor((value % 86400) / 3600)
+ minutes = math.floor((value % 3600) / 60)
+ seconds = math.floor((value % 3600) % 60)
+
+ day_display = f"{days}d" if days > 0 else ""
+ hour_display = f"{hours}h" if hours > 0 else ""
+ minute_display = f"{minutes}m" if minutes > 0 else ""
+ second_display = f"{seconds}s" if seconds > 0 else ("" if (hour_display or minute_display) else "0s")
+
+ if days > 0:
+ units = [u for u in (day_display, hour_display) if u]
+ else:
+ units = [u for u in (hour_display, minute_display, second_display) if u]
+ return " ".join(units)
+
+
+def _trim_float(formatted: str) -> str:
+ """Strip trailing zeros (and a bare trailing dot) from a fixed-point string, like JS parseFloat."""
+ if "." in formatted:
+ formatted = formatted.rstrip("0").rstrip(".")
+ return formatted
diff --git a/products/alerts/backend/evaluation/test/test_comparator.py b/products/alerts/backend/evaluation/test/test_comparator.py
index ff158be48223..965f8c6bcbe4 100644
--- a/products/alerts/backend/evaluation/test/test_comparator.py
+++ b/products/alerts/backend/evaluation/test/test_comparator.py
@@ -213,3 +213,24 @@ def test_unframed_message_uses_subject_without_interval_framing():
assert result.breaches is not None
assert result.breaches[0] == "The SQL insight value (5.0) is less than lower threshold (10.0)"
assert "interval" not in result.breaches[0]
+
+
+def test_value_formatter_formats_both_value_and_bounds():
+ # A trends value_formatter renders the breach value AND the threshold bound (currency here).
+ series = [ComparableSeries(label="A", points=[SeriesPoint(None, 5.0)], current_index=0)]
+ result = ExtractionResult(series=series, value_formatter=lambda v: f"${v:,.2f}")
+ out = evaluate_threshold(result, ABSOLUTE, _threshold(lower=10))
+ assert out.breaches is not None
+ assert (
+ out.breaches[0] == "The insight value (A) for previous interval ($5.00) is less than lower threshold ($10.00)"
+ )
+
+
+def test_percentage_threshold_ignores_value_formatter():
+ # A relative % alert renders its change ratio as its own %, taking precedence over any formatter.
+ series = [ComparableSeries(label="A", points=[SeriesPoint(None, v) for v in (10.0, 20.0)], current_index=1)]
+ result = ExtractionResult(series=series, value_formatter=lambda v: f"${v:,.2f}")
+ out = evaluate_threshold(result, INCREASE, _threshold(type_=InsightThresholdType.PERCENTAGE, upper=0.5))
+ assert out.breaches is not None
+ assert "100.00%" in out.breaches[0]
+ assert "$" not in out.breaches[0]
diff --git a/products/alerts/backend/evaluation/test/test_formatting.py b/products/alerts/backend/evaluation/test/test_formatting.py
new file mode 100644
index 000000000000..644230fe2ed0
--- /dev/null
+++ b/products/alerts/backend/evaluation/test/test_formatting.py
@@ -0,0 +1,54 @@
+import pytest
+
+from posthog.schema import AggregationAxisFormat, TrendsFilter
+
+from products.alerts.backend.evaluation.formatting import format_aggregation_value, make_trends_value_formatter
+
+A = AggregationAxisFormat
+
+
+ "value,kwargs,expected",
+ [
+ # numeric: thousands separators + trailing-zero trimming (fixes the raw-float leak)
+ (803.7740196999998, {}, "803.77"),
+ (2.0, {}, "2"),
+ (1234.5, {}, "1,234.5"),
+ (1000.0, {}, "1,000"),
+ (803.77, {"decimal_places": 0}, "804"),
+ (5.0, {"min_decimal_places": 2}, "5.00"),
+ (float("inf"), {}, "∞"),
+ (float("-inf"), {}, "-∞"),
+ # currency: symbol + fixed 2 decimals; unknown code and missing currency both degrade safely
+ (803.7740196999998, {"axis_format": A.CURRENCY, "currency": "USD"}, "$803.77"),
+ (10.0, {"axis_format": A.CURRENCY, "currency": "USD"}, "$10.00"),
+ (1234.5, {"axis_format": A.CURRENCY, "currency": "EUR"}, "€1,234.50"),
+ (1234.5, {"axis_format": A.CURRENCY, "currency": "SEK"}, "SEK 1,234.50"),
+ (50.0, {"axis_format": A.CURRENCY, "currency": None}, "$50.00"),
+ # prefix/postfix wrap the formatted value verbatim (they carry their own spacing)
+ (1234.0, {"prefix": "$", "postfix": " reqs"}, "$1,234 reqs"),
+ # duration: seconds humanized; negative (relative differences) and zero handled
+ (72.0, {"axis_format": A.DURATION}, "1m 12s"),
+ (0.0, {"axis_format": A.DURATION}, "0s"),
+ (-72.0, {"axis_format": A.DURATION}, "-1m 12s"),
+ (3660.0, {"axis_format": A.DURATION}, "1h 1m"),
+ (1500.0, {"axis_format": A.DURATION_MS}, "1.5s"),
+ # percentage variants (axis %, distinct from a PERCENTAGE threshold's own rendering)
+ (50.0, {"axis_format": A.PERCENTAGE}, "50%"),
+ (0.5, {"axis_format": A.PERCENTAGE_SCALED}, "50%"),
+ # short / compact
+ (1234000.0, {"axis_format": A.SHORT}, "1.23M"),
+ ],
+)
+def test_format_aggregation_value(value: float, kwargs: dict, expected: str) -> None:
+ assert format_aggregation_value(value, **kwargs) == expected
+
+
+def test_make_trends_value_formatter_reads_filter_and_currency() -> None:
+ fmt = make_trends_value_formatter(TrendsFilter(aggregationAxisFormat=A.CURRENCY), "USD")
+ assert fmt(803.7740196999998) == "$803.77"
+
+
+def test_make_trends_value_formatter_handles_none_filter() -> None:
+ fmt = make_trends_value_formatter(None, None)
+ assert fmt(803.7740196999998) == "803.77"
diff --git a/products/alerts/backend/evaluation/trends.py b/products/alerts/backend/evaluation/trends.py
index d10d928cad86..33e196fc0699 100644
--- a/products/alerts/backend/evaluation/trends.py
+++ b/products/alerts/backend/evaluation/trends.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from typing import Any, cast
from posthog.schema import (
@@ -14,6 +15,7 @@ from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.caching.fetch_from_cache import InsightResult
from posthog.event_usage import EventSource
+from posthog.hogql_queries.insights.utils.breakdowns import humanize_breakdown_label
# These helpers also back the anomaly detector, so they remain in the tasks module for now.
from posthog.tasks.alerts.trends import (
@@ -30,6 +32,7 @@ from products.alerts.backend.evaluation.contract import (
lookback_intervals_for,
zero_sentinel_series,
)
+from products.alerts.backend.evaluation.formatting import make_trends_value_formatter
from products.alerts.backend.models.alert import AlertConfiguration
from products.product_analytics.backend.models.insight import Insight
@@ -62,6 +65,9 @@ class TrendsExtractor:
if threshold.bounds is None:
raise ValueError("TrendsExtractor requires threshold bounds — dispatcher invariant violated")
+ # Render breach values the way the insight displays them (currency, prefix/postfix, decimals).
+ value_formatter = make_trends_value_formatter(query.trendsFilter, alert.team.base_currency)
+
is_non_time_series = _is_non_time_series_trend(query)
has_breakdown = _has_breakdown(query)
check_current_interval = bool(config.check_ongoing_interval)
@@ -79,7 +85,11 @@ class TrendsExtractor:
else _date_range_override_for_intervals(query, last_x_intervals=lookback_intervals)
)
calculation_result = self._calculate(alert, insight, execution_mode, filters_override)
- if (empty := self._empty_result(calculation_result, alert, has_breakdown, interval_type)) is not None:
+ if (
+ empty := self._empty_result(
+ calculation_result, alert, has_breakdown, interval_type, value_formatter
+ )
+ ) is not None:
return empty
if check_current_interval and threshold.bounds.upper is None:
raise ValueError(
@@ -94,7 +104,11 @@ class TrendsExtractor:
# against the one before it, so we need the extra lookback interval.
filters_override = _date_range_override_for_intervals(query, last_x_intervals=lookback_intervals)
calculation_result = self._calculate(alert, insight, execution_mode, filters_override)
- if (empty := self._empty_result(calculation_result, alert, has_breakdown, interval_type)) is not None:
+ if (
+ empty := self._empty_result(
+ calculation_result, alert, has_breakdown, interval_type, value_formatter
+ )
+ ) is not None:
return empty
if check_current_interval and threshold.bounds.upper is None:
raise ValueError(
@@ -107,7 +121,11 @@ class TrendsExtractor:
raise ValueError("Relative alerts not supported for non time series trends")
filters_override = _date_range_override_for_intervals(query, last_x_intervals=lookback_intervals)
calculation_result = self._calculate(alert, insight, execution_mode, filters_override)
- if (empty := self._empty_result(calculation_result, alert, has_breakdown, interval_type)) is not None:
+ if (
+ empty := self._empty_result(
+ calculation_result, alert, has_breakdown, interval_type, value_formatter
+ )
+ ) is not None:
return empty
anchor_is_current = False
@@ -116,7 +134,12 @@ class TrendsExtractor:
series = self._to_series(config, calculation_result, has_breakdown, is_non_time_series, anchor_is_current)
# subject/framed use the ExtractionResult defaults ("The insight value", framed).
- return ExtractionResult(series=series, is_breakdown=has_breakdown, interval_type=interval_type)
+ return ExtractionResult(
+ series=series,
+ is_breakdown=has_breakdown,
+ interval_type=interval_type,
+ value_formatter=value_formatter,
+ )
def _calculate(
self,
@@ -142,6 +165,7 @@ class TrendsExtractor:
alert: AlertConfiguration,
has_breakdown: bool,
interval_type: IntervalType | None,
+ value_formatter: Callable[[float], str],
) -> ExtractionResult | None:
"""A ``None`` result means the query layer swallowed an error — raise to avoid a misfire.
An empty result means no data, treated as a 0 value compared against the threshold (this
@@ -154,6 +178,7 @@ class TrendsExtractor:
is_breakdown=has_breakdown,
interval_type=interval_type,
empty_query_result=True,
+ value_formatter=value_formatter,
)
return None
@@ -185,7 +210,7 @@ class TrendsExtractor:
current_index = len(points) - 1 if anchor_is_current else len(points) - 2
series.append(
ComparableSeries(
- label=result["label"],
+ label=humanize_breakdown_label(result["label"]),
points=points,
current_index=current_index,
is_current_interval=anchor_is_current,