Repository navigation
Description
Compiling nested calls of a builtin that has several overloads, like replace, join or sort, takes exponential time in the nesting depth. 20 nested replace calls take about 1 second to compile, and 42 never finish. We hit this in production, where one user's expression kept a server compiling until it ran out of memory. Compiling can't be cancelled, so a timeout around it doesn't help.
The same nesting with a function registered through expr.Function, with the same two overloads, stays at about 50 µs:
package main
import (
"fmt"
"strings"
"time"
"github.com/expr-lang/expr"
)
func main() {
// Same two overloads as the builtin, but registered as a function.
replace2 := expr.Function("replace2",
func(params ...any) (any, error) { return params[0], nil },
new(func(string, string) string),
new(func(string, string, string) string),
)
for _, depth := range []int{10, 14, 18, 20} {
builtin := strings.Repeat("replace(", depth) + `"a"` + strings.Repeat(`, "a", "b")`, depth)
function := strings.Repeat("replace2(", depth) + `"a"` + strings.Repeat(`, "a", "b")`, depth)
start := time.Now()
if _, err := expr.Compile(builtin); err != nil {
panic(err)
}
tBuiltin := time.Since(start)
start = time.Now()
if _, err := expr.Compile(function, replace2); err != nil {
panic(err)
}
tFunction := time.Since(start)
fmt.Printf("depth %d: replace %v, replace2 %v\n", depth, tBuiltin.Round(time.Microsecond), tFunction.Round(time.Microsecond))
}
}depth 10: replace 695µs, replace2 27µs
depth 14: replace 8.202ms, replace2 48µs
depth 18: replace 155.439ms, replace2 53µs
depth 20: replace 993.25ms, replace2 53µs
This is with v1.17.7, and v1.18.0 behaves the same.
The cause looks like checkFunction in checker/checker.go. For a builtin with several Types, it calls checkArguments once per overload until one matches. Each call visits every argument again, and it does so even when the number of arguments doesn't match, since the wrong-count branch also visits them. So a call checks its argument subtree once per overload it tries, and that multiplies at every level of nesting. callNode doesn't have the problem, because it returns early when the node already has a type. builtinNode has no such check.
Visiting each argument once before the loop over Types, and reusing the result for every overload, would make this linear. Skipping overloads with the wrong number of arguments before visiting would also help, but wouldn't cover overloads that fail on their types.
Activity
antonmedv commentedon Nov 22, 2026
Thanks for the detailed report and the analysis of the cause! This is fixed in v1.18.1 by #1010: compile time now grows linearly with nesting depth (42 nested
replacecalls compile in about 75 µs). Since it lets untrusted expressions exhaust CPU and memory, we published it as GHSA-6h63-3f9q-wq5h, with you credited as reporter. A CVE has been requested.checker: check nested overloaded calls in linear time (expr-lang#1010)