From e04da7c474c1b168ef13234c202b39ee59b66f88 Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Wed, 25 Nov 2026 12:09:17 +0100 Subject: [PATCH 1/5] Compare predicate collections by structure predicateCombination matched collections by String(), which prints some different trees the same: a BuiltinNode's Map field, a folded (-2) left of **, and folded float or NaN constants. Compare the trees field by field instead. --- optimizer/optimizer_test.go | 33 ++++++++++++ optimizer/predicate_combination.go | 86 +++++++++++++++++++++++++++++- 2 files changed, 118 insertions(+), 1 deletion(-) diff --git a/optimizer/optimizer_test.go b/optimizer/optimizer_test.go index 9c5cd68ec..fce742ee8 100644 --- a/optimizer/optimizer_test.go +++ b/optimizer/optimizer_test.go @@ -497,3 +497,36 @@ func TestOptimize_predicate_combination_with_non_json_float(t *testing.T) { require.NoError(t, err, code) } } + +func TestOptimize_predicate_combination_same_string(t *testing.T) { + // predicateCombination must merge only calls on the same collection. + // These collections differ but print the same via String(). + env := map[string]any{"a": []int{1, 2, 3}, "n": 2, "NaN": 7} + for _, code := range []string{ + // filterMap sets BuiltinNode.Map, which String() does not print. + `all(map(filter(a, # > 0), # * 10), # > 5) && all(filter(a, # > 0), # < 5)`, + `not (any(map(filter(a, # > 0), # * 10), # == 1) || any(filter(a, # > 0), # == 30))`, + // Folded (-2) prints as -2, so (-2) ** n printed as -2 ** n. + `all([(-2) ** n], # > 0) && all([-2 ** n], # < 0)`, + `all([(-2.0) ** n], # > 0) && all([-2.0 ** n], # < 0)`, + // Folded constants print 2.0 as 2, and NaN like an identifier. + `all([2.0], type(#) == "float") && all([2], type(#) == "int")`, + `all([0/0], # != #) && all([NaN], # == 7)`, + // 0.0 and -0.0 are equal, but they are not the same constant. + `all([-0.0], 1 / # < 0) && all([0.0], 1 / # > 0)`, + } { + t.Run(code, func(t *testing.T) { + unoptimized, err := expr.Compile(code, expr.Env(env), expr.Optimize(false)) + require.NoError(t, err) + want, err := expr.Run(unoptimized, env) + require.NoError(t, err) + require.Equal(t, true, want) + + optimized, err := expr.Compile(code, expr.Env(env)) + require.NoError(t, err) + got, err := expr.Run(optimized, env) + require.NoError(t, err) + assert.Equal(t, want, got) + }) + } +} diff --git a/optimizer/predicate_combination.go b/optimizer/predicate_combination.go index 65f88e348..339255d39 100644 --- a/optimizer/predicate_combination.go +++ b/optimizer/predicate_combination.go @@ -1,6 +1,9 @@ package optimizer import ( + "math" + "reflect" + . "github.com/expr-lang/expr/ast" "github.com/expr-lang/expr/parser/operator" ) @@ -20,7 +23,7 @@ func (v *predicateCombination) Visit(node *Node) { if left, ok := op.Left.(*BuiltinNode); ok { if combinedOp, ok := combinedOperator(left.Name, op.Operator); ok { if right, ok := op.Right.(*BuiltinNode); ok && right.Name == left.Name { - if left.Arguments[0].Type() == right.Arguments[0].Type() && left.Arguments[0].String() == right.Arguments[0].String() { + if left.Arguments[0].Type() == right.Arguments[0].Type() && sameNode(left.Arguments[0], right.Arguments[0]) { predicate := &PredicateNode{ Node: &BinaryNode{ Operator: combinedOp, @@ -59,3 +62,84 @@ func combinedOperator(fn, op string) (string, bool) { } return "", false } + +// sameNode reports whether a and b are the same expression. It compares the +// trees field by field instead of comparing String() output, because different +// trees can print the same: a BuiltinNode's Map field is not printed, and a +// folded ConstantNode prints 2.0 as 2. +func sameNode(a, b Node) bool { + return sameValue(reflect.ValueOf(a), reflect.ValueOf(b), false) +} + +var constantNodeType = reflect.TypeOf(ConstantNode{}) + +// sameValue compares a and b by type and value. In nodes it skips unexported +// fields, which hold the location and type and differ between two copies of +// one expression. Inside a constant it compares every field. Floats compare +// by bits, so 0.0 and -0.0 differ. Values it cannot compare are never same. +func sameValue(a, b reflect.Value, constant bool) bool { + if !a.IsValid() || !b.IsValid() { + return a.IsValid() == b.IsValid() + } + if a.Type() != b.Type() { + return false + } + switch a.Kind() { + case reflect.Interface, reflect.Ptr: + if a.IsNil() || b.IsNil() { + return a.IsNil() == b.IsNil() + } + return sameValue(a.Elem(), b.Elem(), constant) + case reflect.Struct: + if a.Type() == constantNodeType { + constant = true + } + for i := 0; i < a.NumField(); i++ { + if !constant && !a.Type().Field(i).IsExported() { + continue + } + if !sameValue(a.Field(i), b.Field(i), constant) { + return false + } + } + return true + case reflect.Slice, reflect.Array: + if a.Len() != b.Len() { + return false + } + for i := 0; i < a.Len(); i++ { + if !sameValue(a.Index(i), b.Index(i), constant) { + return false + } + } + return true + case reflect.Map: + if a.IsNil() != b.IsNil() || a.Len() != b.Len() { + return false + } + iter := a.MapRange() + for iter.Next() { + bv := b.MapIndex(iter.Key()) + if !bv.IsValid() || !sameValue(iter.Value(), bv, constant) { + return false + } + } + return true + case reflect.Bool: + return a.Bool() == b.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() == b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() == b.Uint() + case reflect.Float32, reflect.Float64: + return math.Float64bits(a.Float()) == math.Float64bits(b.Float()) + case reflect.Complex64, reflect.Complex128: + ac, bc := a.Complex(), b.Complex() + return math.Float64bits(real(ac)) == math.Float64bits(real(bc)) && + math.Float64bits(imag(ac)) == math.Float64bits(imag(bc)) + case reflect.String: + return a.String() == b.String() + default: + return false + } +} From 78a2064e74dddbd6266305dd954f6d72dc2cf3a7 Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Wed, 25 Nov 2026 13:51:03 +0100 Subject: [PATCH 2/5] Merge predicates on the same constant collection Compare only a ConstantNode's value, not its location and type, so identical constant collections still merge. Bound the depth of the constant walk so a self-referential value cannot overflow the stack. --- optimizer/optimizer_test.go | 36 ++++++++++++++++++++++++++++ optimizer/predicate_combination.go | 38 ++++++++++++++++++++---------- 2 files changed, 61 insertions(+), 13 deletions(-) diff --git a/optimizer/optimizer_test.go b/optimizer/optimizer_test.go index fce742ee8..db8d86bb5 100644 --- a/optimizer/optimizer_test.go +++ b/optimizer/optimizer_test.go @@ -530,3 +530,39 @@ func TestOptimize_predicate_combination_same_string(t *testing.T) { }) } } + +func TestOptimize_predicate_combination_same_constant(t *testing.T) { + // Collections holding folded constants still merge when they are the same. + env := map[string]any{"a": []int{1, 2, 3}} + for _, code := range []string{ + `all([1, 2, 3], # > 0) && all([1, 2, 3], # < 5)`, + `all(filter(a, # in [1, 2]), # > 0) && all(filter(a, # in [1, 2]), # < 5)`, + `all([0/0], # != #) && all([0/0], # != 0)`, + } { + t.Run(code, func(t *testing.T) { + tree, err := parser.Parse(code) + require.NoError(t, err) + config := conf.New(env) + _, err = checker.Check(tree, config) + require.NoError(t, err) + err = optimizer.Optimize(&tree.Node, config) + require.NoError(t, err) + + builtin, ok := tree.Node.(*ast.BuiltinNode) + require.True(t, ok, "not merged: %s", tree.Node) + assert.Equal(t, "all", builtin.Name) + }) + } +} + +func TestOptimize_predicate_combination_self_referential_constant(t *testing.T) { + self := map[string]any{} + self["self"] = self + env := map[string]any{"c": func() any { return self }} + code := `all([c()], # != nil) && all([c()], # != nil)` + program, err := expr.Compile(code, expr.Env(env), expr.ConstExpr("c")) + require.NoError(t, err) + out, err := expr.Run(program, env) + require.NoError(t, err) + assert.Equal(t, true, out) +} diff --git a/optimizer/predicate_combination.go b/optimizer/predicate_combination.go index 339255d39..7d938a919 100644 --- a/optimizer/predicate_combination.go +++ b/optimizer/predicate_combination.go @@ -68,16 +68,28 @@ func combinedOperator(fn, op string) (string, bool) { // trees can print the same: a BuiltinNode's Map field is not printed, and a // folded ConstantNode prints 2.0 as 2. func sameNode(a, b Node) bool { - return sameValue(reflect.ValueOf(a), reflect.ValueOf(b), false) + return sameValue(reflect.ValueOf(a), reflect.ValueOf(b), -1) } var constantNodeType = reflect.TypeOf(ConstantNode{}) -// sameValue compares a and b by type and value. In nodes it skips unexported -// fields, which hold the location and type and differ between two copies of -// one expression. Inside a constant it compares every field. Floats compare -// by bits, so 0.0 and -0.0 differ. Values it cannot compare are never same. -func sameValue(a, b reflect.Value, constant bool) bool { +// maxConstantDepth bounds how deep sameValue walks into a constant's value, +// so a value that refers to itself cannot recurse forever. +const maxConstantDepth = 100 + +// sameValue compares a and b by type and value. depth is -1 while walking +// nodes, where it skips unexported fields: they hold the location and type, +// which differ between two copies of one expression. Inside a constant's +// value, depth counts the nesting, and every field is compared. Floats +// compare by bits, so 0.0 and -0.0 differ. Values it cannot compare, and +// constants nested deeper than maxConstantDepth, are never the same. +func sameValue(a, b reflect.Value, depth int) bool { + if depth >= 0 { + depth++ + if depth > maxConstantDepth { + return false + } + } if !a.IsValid() || !b.IsValid() { return a.IsValid() == b.IsValid() } @@ -89,16 +101,16 @@ func sameValue(a, b reflect.Value, constant bool) bool { if a.IsNil() || b.IsNil() { return a.IsNil() == b.IsNil() } - return sameValue(a.Elem(), b.Elem(), constant) + return sameValue(a.Elem(), b.Elem(), depth) case reflect.Struct: - if a.Type() == constantNodeType { - constant = true + if depth < 0 && a.Type() == constantNodeType { + return sameValue(a.FieldByName("Value"), b.FieldByName("Value"), 0) } for i := 0; i < a.NumField(); i++ { - if !constant && !a.Type().Field(i).IsExported() { + if depth < 0 && !a.Type().Field(i).IsExported() { continue } - if !sameValue(a.Field(i), b.Field(i), constant) { + if !sameValue(a.Field(i), b.Field(i), depth) { return false } } @@ -108,7 +120,7 @@ func sameValue(a, b reflect.Value, constant bool) bool { return false } for i := 0; i < a.Len(); i++ { - if !sameValue(a.Index(i), b.Index(i), constant) { + if !sameValue(a.Index(i), b.Index(i), depth) { return false } } @@ -120,7 +132,7 @@ func sameValue(a, b reflect.Value, constant bool) bool { iter := a.MapRange() for iter.Next() { bv := b.MapIndex(iter.Key()) - if !bv.IsValid() || !sameValue(iter.Value(), bv, constant) { + if !bv.IsValid() || !sameValue(iter.Value(), bv, depth) { return false } } From 1fd33961a9e28963ecf7bb2410c3bd4ea1f4b52c Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Wed, 25 Nov 2026 13:54:27 +0100 Subject: [PATCH 3/5] Bound the constant comparison for shared values Remember visited pointer pairs, like reflect.DeepEqual, so constants that reuse a value in many places or refer to themselves compare in linear time. Match map keys that == does not compare exactly, such as 0.0 and -0.0, by searching. --- optimizer/optimizer_test.go | 62 +++++++++++++++--- optimizer/predicate_combination.go | 101 ++++++++++++++++++++++++----- 2 files changed, 135 insertions(+), 28 deletions(-) diff --git a/optimizer/optimizer_test.go b/optimizer/optimizer_test.go index db8d86bb5..0c526f0d7 100644 --- a/optimizer/optimizer_test.go +++ b/optimizer/optimizer_test.go @@ -2,8 +2,10 @@ package optimizer_test import ( "fmt" + "math" "strings" "testing" + "time" "github.com/expr-lang/expr/internal/testify/assert" "github.com/expr-lang/expr/internal/testify/require" @@ -555,14 +557,54 @@ func TestOptimize_predicate_combination_same_constant(t *testing.T) { } } -func TestOptimize_predicate_combination_self_referential_constant(t *testing.T) { - self := map[string]any{} - self["self"] = self - env := map[string]any{"c": func() any { return self }} - code := `all([c()], # != nil) && all([c()], # != nil)` - program, err := expr.Compile(code, expr.Env(env), expr.ConstExpr("c")) - require.NoError(t, err) - out, err := expr.Run(program, env) - require.NoError(t, err) - assert.Equal(t, true, out) +func TestOptimize_predicate_combination_shared_constant(t *testing.T) { + // Constant values that refer to themselves, or reuse one value in many + // places, must compare in bounded time and still merge. + cycle := map[string]any{} + cycle["a"] = cycle + cycle["b"] = cycle + var shared any = 1 + for i := 0; i < 40; i++ { + shared = []any{shared, shared} + } + for name, value := range map[string]any{"cycle": cycle, "shared": shared} { + t.Run(name, func(t *testing.T) { + env := map[string]any{"c": func() any { return value }} + tree, err := parser.Parse(`all([c()], # != nil) && all([c()], # != 1)`) + require.NoError(t, err) + config := conf.New(env) + config.ConstExpr("c") + _, err = checker.Check(tree, config) + require.NoError(t, err) + + done := make(chan error, 1) + go func() { done <- optimizer.Optimize(&tree.Node, config) }() + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(5 * time.Second): + t.Fatal("optimizer did not finish") + } + + builtin, ok := tree.Node.(*ast.BuiltinNode) + require.True(t, ok, "not merged: %T", tree.Node) + assert.Equal(t, "all", builtin.Name) + }) + } +} + +func TestOptimize_predicate_combination_float_map_keys(t *testing.T) { + // Map keys 0.0 and -0.0 are equal under ==, but not the same constant. + env := map[string]any{ + "neg": func() any { return map[float64]int{math.Copysign(0, -1): 1} }, + "pos": func() any { return map[float64]int{0: 1} }, + } + code := `all(keys(neg()), 1 / # < 0) && all(keys(pos()), 1 / # > 0)` + for _, optimize := range []bool{false, true} { + program, err := expr.Compile(code, expr.Env(env), expr.ConstExpr("neg"), expr.ConstExpr("pos"), expr.Optimize(optimize)) + require.NoError(t, err) + out, err := expr.Run(program, env) + require.NoError(t, err) + assert.Equal(t, true, out, "optimize=%v", optimize) + } } diff --git a/optimizer/predicate_combination.go b/optimizer/predicate_combination.go index 7d938a919..a83ce34bc 100644 --- a/optimizer/predicate_combination.go +++ b/optimizer/predicate_combination.go @@ -68,22 +68,39 @@ func combinedOperator(fn, op string) (string, bool) { // trees can print the same: a BuiltinNode's Map field is not printed, and a // folded ConstantNode prints 2.0 as 2. func sameNode(a, b Node) bool { - return sameValue(reflect.ValueOf(a), reflect.ValueOf(b), -1) + c := comparer{visited: map[visit]bool{}} + return c.same(reflect.ValueOf(a), reflect.ValueOf(b), -1) } var constantNodeType = reflect.TypeOf(ConstantNode{}) -// maxConstantDepth bounds how deep sameValue walks into a constant's value, -// so a value that refers to itself cannot recurse forever. +// maxConstantDepth bounds how deep the comparison walks into a constant's +// value, so a deeply nested value cannot overflow the stack. const maxConstantDepth = 100 -// sameValue compares a and b by type and value. depth is -1 while walking -// nodes, where it skips unexported fields: they hold the location and type, -// which differ between two copies of one expression. Inside a constant's -// value, depth counts the nesting, and every field is compared. Floats -// compare by bits, so 0.0 and -0.0 differ. Values it cannot compare, and -// constants nested deeper than maxConstantDepth, are never the same. -func sameValue(a, b reflect.Value, depth int) bool { +// visit is a pair of pointers, with their type, that the comparison has +// already reached. +type visit struct { + a, b uintptr + t reflect.Type +} + +type comparer struct { + visited map[visit]bool +} + +// same compares a and b by type and value. depth is -1 while walking nodes, +// where it skips unexported fields: they hold the location and type, which +// differ between two copies of one expression. Inside a constant's value, +// depth counts the nesting, and every field is compared. Floats compare by +// bits, so 0.0 and -0.0 differ. Values it cannot compare, and constants +// nested deeper than maxConstantDepth, are never the same. +// +// Like reflect.DeepEqual, it remembers each pair of pointers it reaches and +// treats a pair it meets again as the same. Any difference stops the whole +// comparison, so this ends cycles and keeps values that share parts from +// being walked once per path. +func (c *comparer) same(a, b reflect.Value, depth int) bool { if depth >= 0 { depth++ if depth > maxConstantDepth { @@ -97,20 +114,36 @@ func sameValue(a, b reflect.Value, depth int) bool { return false } switch a.Kind() { - case reflect.Interface, reflect.Ptr: + case reflect.Ptr, reflect.Map, reflect.Slice: + if a.IsNil() || b.IsNil() { + return a.IsNil() == b.IsNil() + } + if a.Kind() == reflect.Slice && a.Len() != b.Len() { + return false + } + v := visit{a.Pointer(), b.Pointer(), a.Type()} + if c.visited[v] { + return true + } + c.visited[v] = true + } + switch a.Kind() { + case reflect.Interface: if a.IsNil() || b.IsNil() { return a.IsNil() == b.IsNil() } - return sameValue(a.Elem(), b.Elem(), depth) + return c.same(a.Elem(), b.Elem(), depth) + case reflect.Ptr: + return c.same(a.Elem(), b.Elem(), depth) case reflect.Struct: if depth < 0 && a.Type() == constantNodeType { - return sameValue(a.FieldByName("Value"), b.FieldByName("Value"), 0) + return c.same(a.FieldByName("Value"), b.FieldByName("Value"), 0) } for i := 0; i < a.NumField(); i++ { if depth < 0 && !a.Type().Field(i).IsExported() { continue } - if !sameValue(a.Field(i), b.Field(i), depth) { + if !c.same(a.Field(i), b.Field(i), depth) { return false } } @@ -120,19 +153,19 @@ func sameValue(a, b reflect.Value, depth int) bool { return false } for i := 0; i < a.Len(); i++ { - if !sameValue(a.Index(i), b.Index(i), depth) { + if !c.same(a.Index(i), b.Index(i), depth) { return false } } return true case reflect.Map: - if a.IsNil() != b.IsNil() || a.Len() != b.Len() { + if a.Len() != b.Len() { return false } iter := a.MapRange() for iter.Next() { - bv := b.MapIndex(iter.Key()) - if !bv.IsValid() || !sameValue(iter.Value(), bv, depth) { + bv, ok := c.mapIndex(b, iter.Key(), depth) + if !ok || !c.same(iter.Value(), bv, depth) { return false } } @@ -155,3 +188,35 @@ func sameValue(a, b reflect.Value, depth int) bool { return false } } + +// mapIndex finds the value for key in m. Go map lookup uses ==, which finds +// key 0.0 for -0.0, so keys that are not compared exactly by == are matched +// by searching m's keys with same. +func (c *comparer) mapIndex(m, key reflect.Value, depth int) (reflect.Value, bool) { + if exactKey(key) { + v := m.MapIndex(key) + return v, v.IsValid() + } + iter := m.MapRange() + for iter.Next() { + if c.same(key, iter.Key(), depth) { + return iter.Value(), true + } + } + return reflect.Value{}, false +} + +// exactKey reports whether == on key means the same value: true for bools, +// integers and strings, false for floats and anything that may hold one. +func exactKey(key reflect.Value) bool { + switch key.Kind() { + case reflect.Bool, reflect.String, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return true + case reflect.Interface: + return !key.IsNil() && exactKey(key.Elem()) + default: + return false + } +} From 4c53f111a73f2a4b6ede53651a4e52fcbbd763fd Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Wed, 25 Nov 2026 14:00:13 +0100 Subject: [PATCH 4/5] Compare only plain constant values, with a step budget Drop the visited set: a failed map key search left wrong entries in it, and it missed values shared through arrays. Constants now compare only when they hold plain data with exactly comparable map keys, and the whole comparison stops after a fixed number of steps. Anything else counts as different, which only skips the merge. --- optimizer/optimizer_test.go | 68 +++++++++++------- optimizer/predicate_combination.go | 112 +++++++++++------------------ 2 files changed, 84 insertions(+), 96 deletions(-) diff --git a/optimizer/optimizer_test.go b/optimizer/optimizer_test.go index 0c526f0d7..12adf1762 100644 --- a/optimizer/optimizer_test.go +++ b/optimizer/optimizer_test.go @@ -3,6 +3,7 @@ package optimizer_test import ( "fmt" "math" + "reflect" "strings" "testing" "time" @@ -557,17 +558,52 @@ func TestOptimize_predicate_combination_same_constant(t *testing.T) { } } -func TestOptimize_predicate_combination_shared_constant(t *testing.T) { - // Constant values that refer to themselves, or reuse one value in many - // places, must compare in bounded time and still merge. +func TestOptimize_predicate_combination_constant_values(t *testing.T) { + // Constants holding values that the comparison cannot check exactly must + // not be merged when they differ. The expression is true unless c2's + // predicate wrongly runs on c1's value. + code := `all([c1()], same(#, c1())) && all([c2()], same(#, c2()))` + x0, x5, y0, y5 := 0, 5, 0, 5 + for _, tt := range []struct { + name string + c1, c2 any + }{ + {"pointer keys", []any{map[*int]int{&x0: 1, &x5: 2}, &x0}, []any{map[*int]int{&y0: 1, &y5: 2}, &y5}}, + {"NaN keys", map[float64]int{math.NaN(): 1, math.NaN(): 1}, map[float64]int{math.NaN(): 1, math.NaN(): 2}}, + {"signed zero keys", map[float64]int{math.Copysign(0, -1): 1}, map[float64]int{0: 1}}, + } { + t.Run(tt.name, func(t *testing.T) { + env := map[string]any{ + "c1": func() any { return tt.c1 }, + "c2": func() any { return tt.c2 }, + // c1 and c2 return the same map or slice each time, so + // compare identity. + "same": func(a, b any) bool { + return reflect.ValueOf(a).Pointer() == reflect.ValueOf(b).Pointer() + }, + } + program, err := expr.Compile(code, expr.Env(env), expr.ConstExpr("c1"), expr.ConstExpr("c2")) + require.NoError(t, err) + out, err := expr.Run(program, env) + require.NoError(t, err) + assert.Equal(t, true, out) + }) + } +} + +func TestOptimize_predicate_combination_large_constant(t *testing.T) { + // Constants that refer to themselves, or reuse one value in many places, + // must not hang the optimizer. cycle := map[string]any{} cycle["a"] = cycle cycle["b"] = cycle - var shared any = 1 + var slices any = 1 + var arrays any = 1 for i := 0; i < 40; i++ { - shared = []any{shared, shared} + slices = []any{slices, slices} + arrays = [2]any{arrays, arrays} } - for name, value := range map[string]any{"cycle": cycle, "shared": shared} { + for name, value := range map[string]any{"cycle": cycle, "shared slices": slices, "shared arrays": arrays} { t.Run(name, func(t *testing.T) { env := map[string]any{"c": func() any { return value }} tree, err := parser.Parse(`all([c()], # != nil) && all([c()], # != 1)`) @@ -585,26 +621,6 @@ func TestOptimize_predicate_combination_shared_constant(t *testing.T) { case <-time.After(5 * time.Second): t.Fatal("optimizer did not finish") } - - builtin, ok := tree.Node.(*ast.BuiltinNode) - require.True(t, ok, "not merged: %T", tree.Node) - assert.Equal(t, "all", builtin.Name) }) } } - -func TestOptimize_predicate_combination_float_map_keys(t *testing.T) { - // Map keys 0.0 and -0.0 are equal under ==, but not the same constant. - env := map[string]any{ - "neg": func() any { return map[float64]int{math.Copysign(0, -1): 1} }, - "pos": func() any { return map[float64]int{0: 1} }, - } - code := `all(keys(neg()), 1 / # < 0) && all(keys(pos()), 1 / # > 0)` - for _, optimize := range []bool{false, true} { - program, err := expr.Compile(code, expr.Env(env), expr.ConstExpr("neg"), expr.ConstExpr("pos"), expr.Optimize(optimize)) - require.NoError(t, err) - out, err := expr.Run(program, env) - require.NoError(t, err) - assert.Equal(t, true, out, "optimize=%v", optimize) - } -} diff --git a/optimizer/predicate_combination.go b/optimizer/predicate_combination.go index a83ce34bc..9f5933ab9 100644 --- a/optimizer/predicate_combination.go +++ b/optimizer/predicate_combination.go @@ -67,45 +67,35 @@ func combinedOperator(fn, op string) (string, bool) { // trees field by field instead of comparing String() output, because different // trees can print the same: a BuiltinNode's Map field is not printed, and a // folded ConstantNode prints 2.0 as 2. +// +// A false result only skips an optimization, so the comparison is +// conservative: anything it cannot compare simply and quickly is different. func sameNode(a, b Node) bool { - c := comparer{visited: map[visit]bool{}} - return c.same(reflect.ValueOf(a), reflect.ValueOf(b), -1) + c := comparer{steps: maxCompareSteps} + return c.same(reflect.ValueOf(a), reflect.ValueOf(b), false) } var constantNodeType = reflect.TypeOf(ConstantNode{}) -// maxConstantDepth bounds how deep the comparison walks into a constant's -// value, so a deeply nested value cannot overflow the stack. -const maxConstantDepth = 100 - -// visit is a pair of pointers, with their type, that the comparison has -// already reached. -type visit struct { - a, b uintptr - t reflect.Type -} +// maxCompareSteps bounds the work of one comparison. Constant values can +// refer to themselves or reuse one value in many places, and walking them +// could otherwise take forever. +const maxCompareSteps = 100_000 type comparer struct { - visited map[visit]bool + steps int } -// same compares a and b by type and value. depth is -1 while walking nodes, -// where it skips unexported fields: they hold the location and type, which -// differ between two copies of one expression. Inside a constant's value, -// depth counts the nesting, and every field is compared. Floats compare by -// bits, so 0.0 and -0.0 differ. Values it cannot compare, and constants -// nested deeper than maxConstantDepth, are never the same. -// -// Like reflect.DeepEqual, it remembers each pair of pointers it reaches and -// treats a pair it meets again as the same. Any difference stops the whole -// comparison, so this ends cycles and keeps values that share parts from -// being walked once per path. -func (c *comparer) same(a, b reflect.Value, depth int) bool { - if depth >= 0 { - depth++ - if depth > maxConstantDepth { - return false - } +// same compares a and b by type and value. While walking nodes, it skips +// unexported fields: they hold the location and type, which differ between +// two copies of one expression. Inside a constant's value it compares every +// field, and allows only plain data: no pointers, funcs or channels, and only +// map keys that == compares exactly. Floats compare by bits, so 0.0 and -0.0 +// differ. +func (c *comparer) same(a, b reflect.Value, constant bool) bool { + c.steps-- + if c.steps < 0 { + return false } if !a.IsValid() || !b.IsValid() { return a.IsValid() == b.IsValid() @@ -114,58 +104,56 @@ func (c *comparer) same(a, b reflect.Value, depth int) bool { return false } switch a.Kind() { - case reflect.Ptr, reflect.Map, reflect.Slice: + case reflect.Interface: if a.IsNil() || b.IsNil() { return a.IsNil() == b.IsNil() } - if a.Kind() == reflect.Slice && a.Len() != b.Len() { + return c.same(a.Elem(), b.Elem(), constant) + case reflect.Ptr: + if constant { return false } - v := visit{a.Pointer(), b.Pointer(), a.Type()} - if c.visited[v] { - return true - } - c.visited[v] = true - } - switch a.Kind() { - case reflect.Interface: if a.IsNil() || b.IsNil() { return a.IsNil() == b.IsNil() } - return c.same(a.Elem(), b.Elem(), depth) - case reflect.Ptr: - return c.same(a.Elem(), b.Elem(), depth) + return c.same(a.Elem(), b.Elem(), constant) case reflect.Struct: - if depth < 0 && a.Type() == constantNodeType { - return c.same(a.FieldByName("Value"), b.FieldByName("Value"), 0) + if !constant && a.Type() == constantNodeType { + return c.same(a.FieldByName("Value"), b.FieldByName("Value"), true) } for i := 0; i < a.NumField(); i++ { - if depth < 0 && !a.Type().Field(i).IsExported() { + if !constant && !a.Type().Field(i).IsExported() { continue } - if !c.same(a.Field(i), b.Field(i), depth) { + if !c.same(a.Field(i), b.Field(i), constant) { return false } } return true case reflect.Slice, reflect.Array: + if a.Kind() == reflect.Slice && a.IsNil() != b.IsNil() { + return false + } if a.Len() != b.Len() { return false } for i := 0; i < a.Len(); i++ { - if !c.same(a.Index(i), b.Index(i), depth) { + if !c.same(a.Index(i), b.Index(i), constant) { return false } } return true case reflect.Map: - if a.Len() != b.Len() { + if a.IsNil() != b.IsNil() || a.Len() != b.Len() { return false } iter := a.MapRange() for iter.Next() { - bv, ok := c.mapIndex(b, iter.Key(), depth) - if !ok || !c.same(iter.Value(), bv, depth) { + if !exactKey(iter.Key()) { + return false + } + bv := b.MapIndex(iter.Key()) + if !bv.IsValid() || !c.same(iter.Value(), bv, constant) { return false } } @@ -189,25 +177,9 @@ func (c *comparer) same(a, b reflect.Value, depth int) bool { } } -// mapIndex finds the value for key in m. Go map lookup uses ==, which finds -// key 0.0 for -0.0, so keys that are not compared exactly by == are matched -// by searching m's keys with same. -func (c *comparer) mapIndex(m, key reflect.Value, depth int) (reflect.Value, bool) { - if exactKey(key) { - v := m.MapIndex(key) - return v, v.IsValid() - } - iter := m.MapRange() - for iter.Next() { - if c.same(key, iter.Key(), depth) { - return iter.Value(), true - } - } - return reflect.Value{}, false -} - -// exactKey reports whether == on key means the same value: true for bools, -// integers and strings, false for floats and anything that may hold one. +// exactKey reports whether == on a map key means the same value: true for +// bools, integers and strings, false for floats, pointers and anything else. +// With exact keys, the same key in two maps is found by a plain lookup. func exactKey(key reflect.Value) bool { switch key.Kind() { case reflect.Bool, reflect.String, From 089c2b4fdf51e9df8768e90618b5352683346d33 Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Wed, 25 Nov 2026 14:03:55 +0100 Subject: [PATCH 5/5] Merge constants holding the same pointer Treat the very same pointer, map or slice in two constants as the same value, so a cached ConstExpr result like []*User still merges. Build the large-constant test values twice so the comparison walks them. --- optimizer/optimizer_test.go | 62 +++++++++++++++++++++++------- optimizer/predicate_combination.go | 13 ++++++- 2 files changed, 61 insertions(+), 14 deletions(-) diff --git a/optimizer/optimizer_test.go b/optimizer/optimizer_test.go index 12adf1762..5fb6d1d5e 100644 --- a/optimizer/optimizer_test.go +++ b/optimizer/optimizer_test.go @@ -591,25 +591,61 @@ func TestOptimize_predicate_combination_constant_values(t *testing.T) { } } +func TestOptimize_predicate_combination_same_pointer(t *testing.T) { + // A constant holding pointers merges when both sides hold the same data. + type user struct{ Age int } + users := []*user{{Age: 20}, {Age: 30}} + env := map[string]any{"users": func() any { return users }} + tree, err := parser.Parse(`all(users(), .Age > 18) && all(users(), .Age < 40)`) + require.NoError(t, err) + config := conf.New(env) + config.ConstExpr("users") + _, err = checker.Check(tree, config) + require.NoError(t, err) + err = optimizer.Optimize(&tree.Node, config) + require.NoError(t, err) + + builtin, ok := tree.Node.(*ast.BuiltinNode) + require.True(t, ok, "not merged: %T", tree.Node) + assert.Equal(t, "all", builtin.Name) +} + func TestOptimize_predicate_combination_large_constant(t *testing.T) { // Constants that refer to themselves, or reuse one value in many places, - // must not hang the optimizer. - cycle := map[string]any{} - cycle["a"] = cycle - cycle["b"] = cycle - var slices any = 1 - var arrays any = 1 - for i := 0; i < 40; i++ { - slices = []any{slices, slices} - arrays = [2]any{arrays, arrays} + // must not hang the optimizer. Each case builds two equal values that do + // not share data, so the comparison has to walk them. + cycle := func() any { + m := map[string]any{} + m["a"] = m + m["b"] = m + return m + } + slices := func() any { + var v any = 1 + for i := 0; i < 40; i++ { + v = []any{v, v} + } + return v } - for name, value := range map[string]any{"cycle": cycle, "shared slices": slices, "shared arrays": arrays} { + arrays := func() any { + var v any = 1 + for i := 0; i < 40; i++ { + v = [2]any{v, v} + } + return v + } + for name, build := range map[string]func() any{"cycle": cycle, "shared slices": slices, "shared arrays": arrays} { + c1, c2 := build(), build() t.Run(name, func(t *testing.T) { - env := map[string]any{"c": func() any { return value }} - tree, err := parser.Parse(`all([c()], # != nil) && all([c()], # != 1)`) + env := map[string]any{ + "c1": func() any { return c1 }, + "c2": func() any { return c2 }, + } + tree, err := parser.Parse(`all([c1()], # != nil) && all([c2()], # != 1)`) require.NoError(t, err) config := conf.New(env) - config.ConstExpr("c") + config.ConstExpr("c1") + config.ConstExpr("c2") _, err = checker.Check(tree, config) require.NoError(t, err) diff --git a/optimizer/predicate_combination.go b/optimizer/predicate_combination.go index 9f5933ab9..19778b360 100644 --- a/optimizer/predicate_combination.go +++ b/optimizer/predicate_combination.go @@ -90,7 +90,8 @@ type comparer struct { // unexported fields: they hold the location and type, which differ between // two copies of one expression. Inside a constant's value it compares every // field, and allows only plain data: no pointers, funcs or channels, and only -// map keys that == compares exactly. Floats compare by bits, so 0.0 and -0.0 +// map keys that == compares exactly. The exception is the very same pointer, +// map or slice on both sides, which is always the same value. Floats compare by bits, so 0.0 and -0.0 // differ. func (c *comparer) same(a, b reflect.Value, constant bool) bool { c.steps-- @@ -103,6 +104,16 @@ func (c *comparer) same(a, b reflect.Value, constant bool) bool { if a.Type() != b.Type() { return false } + if constant { + switch a.Kind() { + case reflect.Ptr, reflect.Map, reflect.Slice: + // The very same data is the same value, even where its parts + // could not be compared. + if a.Pointer() == b.Pointer() && (a.Kind() != reflect.Slice || a.Len() == b.Len()) { + return true + } + } + } switch a.Kind() { case reflect.Interface: if a.IsNil() || b.IsNil() {