: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(metrics): accept exponent numbers in formulas (#116603)
Daniel Visca0d92be637905
diff --git a/products/metrics/backend/formula.py b/products/metrics/backend/formula.pyindex 47e86d660a5e..b207cec7b16a 100644--- a/products/metrics/backend/formula.py+++ b/products/metrics/backend/formula.py@@ -2,7 +2,7 @@A formula combines clause results by name — `(a - b) / a` — evaluatedpoint-by-point on the shared time grid. Parsing is a tiny recursive-descent-parser (numbers, clause identifiers, + - * /, unary minus, parentheses);+parser (numbers with an optional exponent, clause identifiers, + - * /, unary minus, parentheses);nothing is ever eval()'d."""@@ -12,7 +12,9 @@ import reimport mathfrom collections.abc import Mapping-_TOKEN_RE = re.compile(r"\s*(?:(?P<ident>[A-Za-z_][A-Za-z0-9_]*)|(?P<number>\d+(?:\.\d+)?)|(?P<op>[()+\-*/]))")+_TOKEN_RE = re.compile(+ r"\s*(?:(?P<ident>[A-Za-z_][A-Za-z0-9_]*)|(?P<number>\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|(?P<op>[()+\-*/]))"+)# (kind, value) tuples; kind is "ident" | "number" | "op"_Token = tuple[str, str]diff --git a/products/metrics/backend/tests/test_metric_query_runner_unit.py b/products/metrics/backend/tests/test_metric_query_runner_unit.pyindex b2c884a4bbcd..ef0f27e58b0a 100644--- a/products/metrics/backend/tests/test_metric_query_runner_unit.py+++ b/products/metrics/backend/tests/test_metric_query_runner_unit.py@@ -58,6 +58,8 @@ class TestFormulaParser:("unary_minus", "-a + 5", {"a": 2.0}, 3.0),("division_by_zero_yields_zero", "a / b", {"a": 5.0, "b": 0.0}, 0.0),("number_only_arithmetic", "a * 0 + 1.5", {"a": 9.0}, 1.5),+ ("exponent_literal", "a * 1e3", {"a": 2.0}, 2000.0),+ ("negative_exponent_literal", "a * 2.5E-2", {"a": 4.0}, 0.1),])def test_evaluate(self, _name, formula, values, expected):@@ -72,6 +74,7 @@ class TestFormulaParser:("empty", " ", frozenset({"a"})),("bad_char", "a ^ b", frozenset({"a", "b"})),("non_finite_literal", "9" * 400, frozenset({"a"})),+ ("non_finite_exponent_literal", "a * 1e400", frozenset({"a"})),("nesting_too_deep_parens", "(" * 40 + "a" + ")" * 40, frozenset({"a"})),("nesting_too_deep_unary", "-" * 40 + "a", frozenset({"a"})),]@@ -79,3 +82,7 @@ class TestFormulaParser:def test_rejects(self, _name, formula, names):with pytest.raises(ValueError):parse_formula(formula, names)++ def test_overflowing_exponent_asks_for_a_smaller_number(self):+ with pytest.raises(ValueError, match="too large"):+ parse_formula("a * 1e400", frozenset({"a"}))