[PATCH v2 02/36] perf pmu-events: Fix Simplify() and Equals() bugs in metric.py

From: Ian Rogers

Date: Wed Dec 02 2026 - 13:41:01 EST


Fix constant folding and equality bugs in metric.py:
- Operator.Simplify(): evaluate constant expressions using Decimal
matching perf's expr.y semantics instead of ast.literal_eval(), which
raises ValueError on *, /, %, <, >, &, |, and ^, and check
isinstance(lhs, Constant) on the simplified lhs rather than self.lhs.
- Function.Simplify(): add the missing return on d_ratio constant
folding and evaluate d_ratio/min/max directly instead of calling
ast.literal_eval().
- Function.Equals(): handle one-sided rhs is None instead of returning
True or raising AttributeError.
- Constant.__init__(): normalize -0 to 0.

Add unit tests covering these cases and aggr_nr() parsing.

Fixes: 40769665b63d ("perf jevents: Parse metrics during conversion")
Fixes: 3241cd11d9a0 ("perf jevents metric: Correct Function equality")
Signed-off-by: Ian Rogers <irogers@xxxxxxxxxx>
---
tools/perf/pmu-events/metric.py | 50 ++++++++++++++++++++++------
tools/perf/pmu-events/metric_test.py | 40 ++++++++++++++++++++++
2 files changed, 80 insertions(+), 10 deletions(-)

diff --git a/tools/perf/pmu-events/metric.py b/tools/perf/pmu-events/metric.py
index f5d81eccd5c3..04bb29ce7722 100644
--- a/tools/perf/pmu-events/metric.py
+++ b/tools/perf/pmu-events/metric.py
@@ -273,9 +273,32 @@ class Operator(Expression):
lhs = self.lhs.Simplify()
rhs = self.rhs.Simplify()
if isinstance(lhs, Constant) and isinstance(rhs, Constant):
- return Constant(ast.literal_eval(lhs.value + self.operator + rhs.value))
-
- if isinstance(self.lhs, Constant):
+ l = decimal.Decimal(lhs.value)
+ r = decimal.Decimal(rhs.value)
+ if self.operator == '|':
+ return Constant(0 if l == 0 and r == 0 else 1)
+ if self.operator == '&':
+ return Constant(1 if l != 0 and r != 0 else 0)
+ if self.operator == '^':
+ return Constant(1 if (l == 0) != (r == 0) else 0)
+ if self.operator == '<':
+ return Constant(1 if l < r else 0)
+ if self.operator == '>':
+ return Constant(1 if l > r else 0)
+ if self.operator == '+':
+ return Constant(l + r)
+ if self.operator == '-':
+ return Constant(l - r)
+ if self.operator == '*':
+ return Constant(l * r)
+ if self.operator == '/' and r != 0:
+ return Constant(l / r)
+ if self.operator == '%' and int(r) != 0:
+ li, ri = int(l), int(r)
+ # Match C integer remainder (truncating toward zero) used by perf's expr.y.
+ return Constant(li - int(li / ri) * ri)
+
+ if isinstance(lhs, Constant):
if self.operator in ('+', '|') and lhs.value == '0':
return rhs

@@ -395,11 +418,16 @@ class Function(Expression):
lhs = self.lhs.Simplify()
rhs = self.rhs.Simplify() if self.rhs else None
if isinstance(lhs, Constant) and isinstance(rhs, Constant):
+ l = decimal.Decimal(lhs.value)
+ r = decimal.Decimal(rhs.value)
if self.fn == 'd_ratio':
- if rhs.value == '0':
+ if r == 0:
return Constant(0)
- Constant(ast.literal_eval(f'{lhs} / {rhs}'))
- return Constant(ast.literal_eval(f'{self.fn}({lhs}, {rhs})'))
+ return Constant(l / r)
+ if self.fn == 'min':
+ return lhs if l <= r else rhs
+ if self.fn == 'max':
+ return lhs if l >= r else rhs

return Function(self.fn, lhs, rhs)

@@ -410,9 +438,9 @@ class Function(Expression):
def Equals(self, other: Expression) -> bool:
if isinstance(other, Function):
result = self.fn == other.fn and self.lhs.Equals(other.lhs)
- if self.rhs:
- result = result and self.rhs.Equals(other.rhs)
- return result
+ if self.rhs is None or other.rhs is None:
+ return result and self.rhs is other.rhs
+ return result and self.rhs.Equals(other.rhs)
return False

def Substitute(self, name: str, expression: Expression) -> Expression:
@@ -494,10 +522,12 @@ class MetricRef(Expression):
class Constant(Expression):
"""A constant within the expression tree."""

- def __init__(self, value: Union[float, str]):
+ def __init__(self, value: Union[float, str, decimal.Decimal]):
ctx = decimal.Context()
ctx.prec = 20
dec = ctx.create_decimal(repr(value) if isinstance(value, float) else value)
+ if dec == 0:
+ dec = decimal.Decimal(0)
self.value = dec.normalize().to_eng_string()
self.value = self.value.replace('+', '')
self.value = self.value.replace('E', 'e')
diff --git a/tools/perf/pmu-events/metric_test.py b/tools/perf/pmu-events/metric_test.py
index 8acfe4652b55..0221ac746ec2 100755
--- a/tools/perf/pmu-events/metric_test.py
+++ b/tools/perf/pmu-events/metric_test.py
@@ -4,6 +4,7 @@ import unittest
from metric import Constant
from metric import Event
from metric import Expression
+from metric import Function
from metric import ParsePerfJson
from metric import RewriteMetricsInTermsOfOthers

@@ -65,6 +66,16 @@ class TestMetricExpressions(unittest.TestCase):
after = before
self.assertEqual(ParsePerfJson(before).ToPerfJson(), after)

+ def test_ParseAggrNr(self):
+ before = 'aggr_nr(UNC_CHA_CLOCKTICKS)'
+ self.assertEqual(ParsePerfJson(before).ToPerfJson(), before)
+
+ before = 'a / pcu_0@UNC_P_CLOCKTICKS@ * aggr_nr(pcu_0@UNC_P_CLOCKTICKS@)'
+ self.assertEqual(ParsePerfJson(before).ToPerfJson(), before)
+
+ before = 'a / (b / aggr_nr(c))'
+ self.assertEqual(ParsePerfJson(before).ToPerfJson(), before)
+
def test_IfElseTests(self):
# if-else needs rewriting to Select and back.
before = r'Event1 if #smt_on else Event2'
@@ -160,6 +171,35 @@ class TestMetricExpressions(unittest.TestCase):
after = '0 * SLOTS'
self.assertEqual(ParsePerfJson(before).Simplify().ToPerfJson(), after)

+ # Constant folding for non-add/sub operators and simplified lhs.
+ self.assertEqual((Constant(2) * Constant(3)).Simplify().ToPerfJson(), '6')
+ self.assertEqual((Constant(6) / Constant(4)).Simplify().ToPerfJson(), '1.5')
+ self.assertEqual((Constant(7) % Constant(4)).Simplify().ToPerfJson(), '3')
+ self.assertEqual((Constant(1) < Constant(2)).Simplify().ToPerfJson(), '1')
+ self.assertEqual((Constant(1) > Constant(2)).Simplify().ToPerfJson(), '0')
+ self.assertEqual((Constant(2) & Constant(3)).Simplify().ToPerfJson(), '1')
+ self.assertEqual((Constant(2) & Constant(0)).Simplify().ToPerfJson(), '0')
+ self.assertEqual((Constant(0) | Constant(5)).Simplify().ToPerfJson(), '1')
+ self.assertEqual((Constant(2) ^ Constant(3)).Simplify().ToPerfJson(), '0')
+ self.assertEqual((Constant(2) ^ Constant(0)).Simplify().ToPerfJson(), '1')
+ self.assertEqual((Constant(1) / Constant(0)).Simplify().ToPerfJson(), '1 / 0')
+ self.assertEqual(ParsePerfJson('(0 if 1 else b) + a').Simplify().ToPerfJson(), 'a')
+ self.assertEqual(ParsePerfJson('(1 if 1 else b) * a').Simplify().ToPerfJson(), 'a')
+
+ # Constant folding in Function.Simplify().
+ self.assertEqual(ParsePerfJson('d_ratio(6, 4)').Simplify().ToPerfJson(), '1.5')
+ self.assertEqual(ParsePerfJson('d_ratio(6, 0)').Simplify().ToPerfJson(), '0')
+ self.assertEqual(ParsePerfJson('min(3, 5)').Simplify().ToPerfJson(), '3')
+ self.assertEqual(ParsePerfJson('max(3, 5)').Simplify().ToPerfJson(), '5')
+
+ def test_FunctionEquals(self):
+ f1 = Function('f', Event('a'))
+ f2 = Function('f', Event('a'), Event('b'))
+ self.assertFalse(f1.Equals(f2))
+ self.assertFalse(f2.Equals(f1))
+ self.assertTrue(f1.Equals(Function('f', Event('a'))))
+ self.assertTrue(f2.Equals(Function('f', Event('a'), Event('b'))))
+
def test_RewriteMetricsInTermsOfOthers(self):
Expression.__eq__ = lambda e1, e2: e1.Equals(e2)
before = [('cpu', 'm1', ParsePerfJson('a + b + c + d')),
--
2.56.1.915.g69d5ec7298-goog