Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/interpreter/runtimecost_test.go

raw symbols SCIP
1 // Copyright 2022 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package interpreter
16
17 import (
18 "fmt"
19 "math"
20 "math/rand"
21 "reflect"
22 "strings"
23 "testing"
24 "time"
25
26 "github.com/google/cel-go/checker"
27 "github.com/google/cel-go/common"
28 "github.com/google/cel-go/common/containers"
29 "github.com/google/cel-go/common/decls"
30 "github.com/google/cel-go/common/overloads"
31 "github.com/google/cel-go/common/types"
32 "github.com/google/cel-go/common/types/ref"
33 "github.com/google/cel-go/parser"
34
35 proto3pb "github.com/google/cel-go/test/proto3pb"
36 )
37
38 func TestTrackCostAdvanced(t *testing.T) {
39 var equalCases = []struct {
40 in any
41 lhsExpr string
42 rhsExpr string
43 }{
44 {
45 lhsExpr: `1`,
46 rhsExpr: `2`,
47 },
48 {
49 lhsExpr: `"abc".contains("d")`,
50 rhsExpr: `"def".contains("d")`,
51 },
52 {
53 lhsExpr: `1 in [4, 5, 6]`,
54 rhsExpr: `2 in [15, 17, 16]`,
55 },
56 }
57 for _, tc := range equalCases {
58 t.Run(tc.lhsExpr+" vs "+tc.rhsExpr, func(t *testing.T) {
59 ctx := constructActivation(t, tc.in)
60 lhsCost, _, err := computeCost(t, tc.lhsExpr, nil, ctx, nil)
61 if err != nil {
62 t.Fatalf("Interpreter.Eval(activation Activation) failed to eval expression due: %v", err)
63 }
64 rhsCost, _, err := computeCost(t, tc.rhsExpr, nil, ctx, nil)
65 if err != nil {
66 t.Fatalf("Interpreter.Eval(activation Activation) failed to eval expression due: %v", err)
67 }
68 if lhsCost != rhsCost {
69 t.Errorf(`Interpreter.Eval(activation Activation) failed return a cost for %s of %d equal to a cost for %s of %d`,
70 tc.lhsExpr, lhsCost, tc.rhsExpr, rhsCost)
71 }
72 })
73
74 }
75 var smallerCases = []struct {
76 in any
77 lhsExpr string
78 rhsExpr string
79 }{
80 {
81 lhsExpr: `1`,
82 rhsExpr: `1 + 2`,
83 },
84 {
85 lhsExpr: `"abc".contains("d")`,
86 rhsExpr: `"abcdhdflsfiehfieubdkwjbdwgxvuyagwsdwdnw qdbgquyidvbwqi".contains("e")`,
87 },
88 {
89 lhsExpr: `1 in [4, 5, 6]`,
90 rhsExpr: `1 in [4, 5, 6, 7, 8, 9]`,
91 },
92 }
93 for _, tc := range smallerCases {
94 t.Run(tc.lhsExpr+" vs "+tc.rhsExpr, func(t *testing.T) {
95 ctx := constructActivation(t, tc.in)
96 lhsCost, _, err := computeCost(t, tc.lhsExpr, nil, ctx, nil)
97 if err != nil {
98 t.Fatalf("Interpreter.Eval(activation Activation) failed to eval expression due: %v", err)
99 }
100 rhsCost, _, err := computeCost(t, tc.rhsExpr, nil, ctx, nil)
101 if err != nil {
102 t.Fatalf("Interpreter.Eval(activation Activation) failed to eval expression due: %v", err)
103 }
104 if lhsCost >= rhsCost {
105 t.Errorf(`Interpreter.Eval(activation Activation) failed return a cost for %s of %d less than the cost for %s of %d`,
106 tc.lhsExpr, lhsCost, tc.rhsExpr, rhsCost)
107 }
108 })
109 }
110 }
111
112 func computeCost(t *testing.T, expr string, vars []*decls.VariableDecl, ctx Activation, options []CostTrackerOption) (cost uint64, est checker.CostEstimate, err error) {
113 t.Helper()
114
115 s := common.NewTextSource(expr)
116 p, err := parser.NewParser(parser.Macros(parser.AllMacros...))
117 if err != nil {
118 t.Fatalf("Failed to initialize parser: %v", err)
119 }
120 parsed, errs := p.Parse(s)
121 if len(errs.GetErrors()) != 0 {
122 t.Fatalf(`Failed to Parse expression "%s", error: %v`, expr, errs.GetErrors())
123 }
124
125 cont := containers.DefaultContainer
126 reg := newTestRegistry(t, &proto3pb.TestAllTypes{})
127 attrs := NewAttributeFactory(cont, reg, reg)
128 env := newTestEnv(t, cont, reg)
129 err = env.AddIdents(vars...)
130 if err != nil {
131 t.Fatalf("Failed to initialize env: %v", err)
132 }
133 costTracker, err := NewCostTracker(&testRuntimeCostEstimator{}, options...)
134 if err != nil {
135 t.Fatalf("NewCostTracker() failed: %v", err)
136 }
137 checked, errs := checker.Check(parsed, s, env)
138 if len(errs.GetErrors()) != 0 {
139 t.Fatalf(`Failed to check expression "%s", error: %v`, expr, errs.GetErrors())
140 }
141 est, err = checker.Cost(checked, testCostEstimator{}, checker.PresenceTestHasCost(costTracker.presenceTestHasCost))
142 if err != nil {
143 t.Fatalf("checker.Cost() failed: %v", err)
144 }
145 interp := newStandardInterpreter(t, cont, reg, reg, attrs)
146 prg, err := interp.NewInterpretable(checked,
147 CostObserver(CostTrackerFactory(func() (*CostTracker, error) {
148 return costTracker, nil
149 })))
150 if err != nil {
151 t.Fatalf(`Failed to check expression "%s", error: %v`, expr, errs.GetErrors())
152 }
153
154 defer func() {
155 if r := recover(); r != nil {
156 switch t := r.(type) {
157 case EvalCancelledError:
158 err = t
159 default:
160 err = fmt.Errorf("internal error: %v", r)
161 }
162 }
163 }()
164 prg.Eval(ctx)
165 // TODO: enable this once all attributes are properly pushed and popped from stack.
166 //if len(costTracker.stack) != 1 {
167 // t.Fatalf(`Expected resulting stack size to be 1 but got %d: %#+v`, len(costTracker.stack), costTracker.stack)
168 //}
169 return costTracker.cost, est, err
170 }
171
172 func constructActivation(t *testing.T, in any) Activation {
173 t.Helper()
174 if in == nil {
175 return EmptyActivation()
176 }
177 a, err := NewActivation(in)
178 if err != nil {
179 t.Fatalf("NewActivation(%v) failed: %v", in, err)
180 }
181 return a
182 }
183
184 const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
185
186 func randSeq(n int) []byte {
187 b := make([]byte, n)
188 for i := range b {
189 b[i] = letterBytes[rand.Intn(len(letterBytes))]
190 }
191 return b
192 }
193
194 type testRuntimeCostEstimator struct {
195 }
196
197 var timeToYearCost uint64 = 7
198
199 func (e testRuntimeCostEstimator) CallCost(function, overloadID string, args []ref.Val, result ref.Val) *uint64 {
200 argsSize := make([]uint64, len(args))
201 for i, arg := range args {
202 reflectV := reflect.ValueOf(arg.Value())
203 switch reflectV.Kind() {
204 // Note that the CEL bytes type is implemented with Go byte slices, therefore also supported by the following
205 // code.
206 case reflect.String, reflect.Array, reflect.Slice, reflect.Map:
207 argsSize[i] = uint64(reflectV.Len())
208 default:
209 argsSize[i] = 1
210 }
211 }
212
213 switch overloadID {
214 case overloads.TimestampToYear:
215 return &timeToYearCost
216 default:
217 return nil
218 }
219 }
220
221 type testCostEstimator struct {
222 hints map[string]int64
223 }
224
225 func (tc testCostEstimator) EstimateSize(element checker.AstNode) *checker.SizeEstimate {
226 if l, ok := tc.hints[strings.Join(element.Path(), ".")]; ok {
227 return &checker.SizeEstimate{Min: 0, Max: uint64(l)}
228 }
229 return nil
230 }
231
232 func (tc testCostEstimator) EstimateCallCost(function, overloadID string, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {
233 switch overloadID {
234 case overloads.TimestampToYear:
235 return &checker.CallEstimate{CostEstimate: checker.FixedCostEstimate(7)}
236 }
237 return nil
238 }
239
240 func TestRuntimeCost(t *testing.T) {
241 allTypes := types.NewObjectType("google.expr.proto3.test.TestAllTypes")
242 allList := types.NewListType(allTypes)
243 intList := types.NewListType(types.IntType)
244 nestedList := types.NewListType(allList)
245
246 allMap := types.NewMapType(types.StringType, allTypes)
247 nestedMap := types.NewMapType(types.StringType, allMap)
248 cases := []struct {
249 name string
250 expr string
251 vars []*decls.VariableDecl
252 want uint64
253 in any
254 testFuncCost bool
255 limit uint64
256 options []CostTrackerOption
257
258 expectExceedsLimit bool
259 }{
260 {
261 name: "const",
262 expr: `"Hello World!"`,
263 want: 0,
264 },
265 {
266 name: "identity",
267 expr: `input`,
268 vars: []*decls.VariableDecl{decls.NewVariable("input", intList)},
269 want: 1,
270 in: map[string]any{"input": []int{1, 2}},
271 },
272 {
273 name: "select: map",
274 expr: `input['key']`,
275 vars: []*decls.VariableDecl{decls.NewVariable("input", types.NewMapType(types.StringType, types.StringType))},
276 want: 2,
277 in: map[string]any{"input": map[string]string{"key": "v"}},
278 },
279 {
280 name: "select: array index",
281 expr: `input[0]`,
282 vars: []*decls.VariableDecl{decls.NewVariable("input", types.NewListType(types.StringType))},
283 want: 2,
284 in: map[string]any{"input": []string{"v"}},
285 },
286 {
287 name: "select: field",
288 expr: `input.single_int32`,
289 vars: []*decls.VariableDecl{decls.NewVariable("input", allTypes)},
290 want: 2,
291 in: map[string]any{
292 "input": &proto3pb.TestAllTypes{
293 RepeatedBool: []bool{false},
294 MapInt64NestedType: map[int64]*proto3pb.NestedTestAllTypes{
295 1: {},
296 },
297 MapStringString: map[string]string{},
298 },
299 },
300 },
301 {
302 name: "expr select: map",
303 expr: `input['ke' + 'y']`,
304 vars: []*decls.VariableDecl{decls.NewVariable("input", types.NewMapType(types.StringType, types.StringType))},
305 want: 3,
306 in: map[string]any{"input": map[string]string{"key": "v"}},
307 },
308 {
309 name: "expr select: array index",
310 expr: `input[3-3]`,
311 vars: []*decls.VariableDecl{decls.NewVariable("input", types.NewListType(types.StringType))},
312 want: 3,
313 in: map[string]any{"input": []string{"v"}},
314 },
315 {
316 name: "select: field test only no has() cost",
317 expr: `has(input.single_int32)`,
318 vars: []*decls.VariableDecl{decls.NewVariable("input", types.NewObjectType("google.expr.proto3.test.TestAllTypes"))},
319 want: 1,
320 options: []CostTrackerOption{PresenceTestHasCost(false)},
321 in: map[string]any{
322 "input": &proto3pb.TestAllTypes{
323 RepeatedBool: []bool{false},
324 MapInt64NestedType: map[int64]*proto3pb.NestedTestAllTypes{
325 1: {},
326 },
327 MapStringString: map[string]string{},
328 },
329 },
330 },
331 {
332 name: "select: field test only",
333 expr: `has(input.single_int32)`,
334 vars: []*decls.VariableDecl{decls.NewVariable("input", types.NewObjectType("google.expr.proto3.test.TestAllTypes"))},
335 want: 2,
336 in: map[string]any{
337 "input": &proto3pb.TestAllTypes{
338 RepeatedBool: []bool{false},
339 MapInt64NestedType: map[int64]*proto3pb.NestedTestAllTypes{
340 1: {},
341 },
342 MapStringString: map[string]string{},
343 },
344 },
345 },
346 {
347 name: "select: non-proto field test has() cost",
348 expr: `has(input.testAttr.nestedAttr)`,
349 vars: []*decls.VariableDecl{decls.NewVariable("input", nestedMap)},
350 want: 3,
351 options: []CostTrackerOption{PresenceTestHasCost(true)},
352 in: map[string]any{
353 "input": map[string]any{
354 "testAttr": map[string]any{
355 "nestedAttr": "0",
356 },
357 },
358 },
359 },
360 {
361 name: "select: non-proto field test no has() cost",
362 expr: `has(input.testAttr.nestedAttr)`,
363 vars: []*decls.VariableDecl{decls.NewVariable("input", nestedMap)},
364 want: 2,
365 options: []CostTrackerOption{PresenceTestHasCost(false)},
366 in: map[string]any{
367 "input": map[string]any{
368 "testAttr": map[string]any{
369 "nestedAttr": "0",
370 },
371 },
372 },
373 },
374 {
375 name: "select: non-proto field test",
376 expr: `has(input.testAttr.nestedAttr)`,
377 vars: []*decls.VariableDecl{decls.NewVariable("input", nestedMap)},
378 want: 3,
379 in: map[string]any{
380 "input": map[string]any{
381 "testAttr": map[string]any{
382 "nestedAttr": "0",
383 },
384 },
385 },
386 },
387 {
388 name: "estimated function call",
389 expr: `input.getFullYear()`,
390 vars: []*decls.VariableDecl{decls.NewVariable("input", types.TimestampType)},
391 want: 8,
392 in: map[string]any{"input": time.Now()},
393 testFuncCost: true,
394 },
395 {
396 name: "create list",
397 expr: `[1, 2, 3]`,
398 want: 10,
399 },
400 {
401 name: "create struct",
402 expr: `google.expr.proto3.test.TestAllTypes{single_int32: 1, single_float: 3.14, single_string: 'str'}`,
403 want: 40,
404 },
405 {
406 name: "create map",
407 expr: `{"a": 1, "b": 2, "c": 3}`,
408 want: 30,
409 },
410 {
411 name: "all comprehension",
412 vars: []*decls.VariableDecl{decls.NewVariable("input", allList)},
413 expr: `input.all(x, true)`,
414 want: 2,
415 in: map[string]any{
416 "input": []*proto3pb.TestAllTypes{},
417 },
418 },
419 {
420 name: "nested all comprehension",
421 vars: []*decls.VariableDecl{decls.NewVariable("input", nestedList)},
422 expr: `input.all(x, x.all(y, true))`,
423 want: 2,
424 in: map[string]any{
425 "input": []*proto3pb.TestAllTypes{},
426 },
427 },
428 {
429 name: "all comprehension on literal",
430 expr: `[1, 2, 3].all(x, true)`,
431 want: 20,
432 },
433 {
434 name: "variable cost function",
435 vars: []*decls.VariableDecl{decls.NewVariable("input", types.StringType)},
436 expr: `input.matches('[0-9]')`,
437 want: 103,
438 in: map[string]any{"input": string(randSeq(500))},
439 },
440 {
441 name: "variable cost function with constant",
442 expr: `'123'.matches('[0-9]')`,
443 want: 2,
444 },
445 {
446 name: "or",
447 expr: `false || false`,
448 want: 0,
449 },
450 {
451 name: "or short-circuit",
452 expr: `true || false`,
453 want: 0,
454 },
455
456 {
457 name: "or accumulated branch cost",
458 expr: `a || b || c || d`,
459 vars: []*decls.VariableDecl{
460 decls.NewVariable("a", types.BoolType),
461 decls.NewVariable("b", types.BoolType),
462 decls.NewVariable("c", types.BoolType),
463 decls.NewVariable("d", types.BoolType),
464 },
465 in: map[string]any{
466 "a": false,
467 "b": false,
468 "c": false,
469 "d": false,
470 },
471 want: 4,
472 },
473 {
474 name: "and",
475 expr: `true && false`,
476 want: 0,
477 },
478 {
479 name: "and short-circuit",
480 expr: `false && true`,
481 want: 0,
482 },
483 {
484 name: "and accumulated branch cost",
485 expr: `a && b && c && d`,
486 vars: []*decls.VariableDecl{
487 decls.NewVariable("a", types.BoolType),
488 decls.NewVariable("b", types.BoolType),
489 decls.NewVariable("c", types.BoolType),
490 decls.NewVariable("d", types.BoolType),
491 },
492 in: map[string]any{
493 "a": true,
494 "b": true,
495 "c": true,
496 "d": true,
497 },
498 want: 4,
499 },
500 {
501 name: "lt",
502 expr: `1 < 2`,
503 want: 1,
504 },
505 {
506 name: "lte",
507 expr: `1 <= 2`,
508 want: 1,
509 },
510 {
511 name: "eq",
512 expr: `1 == 2`,
513 want: 1,
514 },
515 {
516 name: "gt",
517 expr: `2 > 1`,
518 want: 1,
519 },
520 {
521 name: "gte",
522 expr: `2 >= 1`,
523 want: 1,
524 },
525 {
526 name: "in",
527 expr: `2 in [1, 2, 3]`,
528 want: 13,
529 },
530 {
531 name: "plus",
532 expr: `1 + 1`,
533 want: 1,
534 },
535 {
536 name: "minus",
537 expr: `1 - 1`,
538 want: 1,
539 },
540 {
541 name: "/",
542 expr: `1 / 1`,
543 want: 1,
544 },
545 {
546 name: "/",
547 expr: `1 * 1`,
548 want: 1,
549 },
550 {
551 name: "%",
552 expr: `1 % 1`,
553 want: 1,
554 },
555 {
556 name: "ternary",
557 expr: `true ? 1 : 2`,
558 want: 0,
559 },
560 {
561 name: "string size",
562 expr: `size("123")`,
563 want: 1,
564 },
565 {
566 name: "str eq str",
567 expr: `'12345678901234567890' == '123456789012345678901234567890'`,
568 want: 2,
569 },
570 {
571 name: "bytes to string conversion",
572 vars: []*decls.VariableDecl{decls.NewVariable("input", types.BytesType)},
573 expr: `string(input)`,
574 want: 51,
575 in: map[string]any{"input": randSeq(500)},
576 },
577 {
578 name: "string to bytes conversion",
579 vars: []*decls.VariableDecl{decls.NewVariable("input", types.StringType)},
580 expr: `bytes(input)`,
581 want: 51,
582 in: map[string]any{"input": string(randSeq(500))},
583 },
584 {
585 name: "int to string conversion",
586 expr: `string(1)`,
587 want: 1,
588 },
589 {
590 name: "contains",
591 expr: `input.contains(arg1)`,
592 vars: []*decls.VariableDecl{
593 decls.NewVariable("input", types.StringType),
594 decls.NewVariable("arg1", types.StringType),
595 },
596 want: 2502,
597 in: map[string]any{"input": string(randSeq(500)), "arg1": string(randSeq(500))},
598 },
599 {
600 name: "matches",
601 expr: `input.matches('\\d+a\\d+b')`,
602 vars: []*decls.VariableDecl{
603 decls.NewVariable("input", types.StringType),
604 },
605 want: 103,
606 in: map[string]any{"input": string(randSeq(500)), "arg1": string(randSeq(500))},
607 },
608 {
609 name: "startsWith",
610 expr: `input.startsWith(arg1)`,
611 vars: []*decls.VariableDecl{
612 decls.NewVariable("input", types.StringType),
613 decls.NewVariable("arg1", types.StringType),
614 },
615 want: 3,
616 in: map[string]any{"input": "idc", "arg1": string(randSeq(500))},
617 },
618 {
619 name: "endsWith",
620 expr: `input.endsWith(arg1)`,
621 vars: []*decls.VariableDecl{
622 decls.NewVariable("input", types.StringType),
623 decls.NewVariable("arg1", types.StringType),
624 },
625 want: 3,
626 in: map[string]any{"input": "idc", "arg1": string(randSeq(500))},
627 },
628 {
629 name: "size receiver",
630 expr: `input.size()`,
631 vars: []*decls.VariableDecl{
632 decls.NewVariable("input", types.StringType),
633 },
634 want: 2,
635 in: map[string]any{"input": "500", "arg1": "500"},
636 },
637 {
638 name: "size",
639 expr: `size(input)`,
640 vars: []*decls.VariableDecl{
641 decls.NewVariable("input", types.StringType),
642 },
643 want: 2,
644 in: map[string]any{"input": "500", "arg1": "500"},
645 },
646 {
647 name: "ternary eval",
648 expr: `(x > 2 ? input1 : input2).all(y, true)`,
649 vars: []*decls.VariableDecl{
650 decls.NewVariable("x", types.IntType),
651 decls.NewVariable("input1", allList),
652 decls.NewVariable("input2", allList),
653 },
654 want: 6,
655 in: map[string]any{"input1": []*proto3pb.TestAllTypes{{}}, "input2": []*proto3pb.TestAllTypes{{}}, "x": 1},
656 },
657 {
658 name: "ternary eval trivial, true",
659 expr: `true ? false : 1 > 3`,
660 want: 0,
661 in: map[string]any{},
662 },
663 {
664 name: "ternary eval trivial, false",
665 expr: `false ? false : 1 > 3`,
666 want: 1,
667 in: map[string]any{},
668 },
669 {
670 name: "comprehension over map",
671 expr: `input.all(k, input[k].single_int32 > 3)`,
672 vars: []*decls.VariableDecl{
673 decls.NewVariable("input", allMap),
674 },
675 want: 9,
676 in: map[string]any{"input": map[string]any{"val": &proto3pb.TestAllTypes{}}},
677 },
678 {
679 name: "comprehension over nested map of maps",
680 expr: `input.all(k, input[k].all(x, true))`,
681 vars: []*decls.VariableDecl{
682 decls.NewVariable("input", nestedMap),
683 },
684 want: 2,
685 in: map[string]any{"input": map[string]any{}},
686 },
687 {
688 name: "string size of map keys",
689 expr: `input.all(k, k.contains(k))`,
690 vars: []*decls.VariableDecl{
691 decls.NewVariable("input", nestedMap),
692 },
693 want: 2,
694 in: map[string]any{"input": map[string]any{}},
695 },
696 {
697 name: "comprehension variable shadowing",
698 expr: `input.all(k, input[k].all(k, true) && k.contains(k))`,
699 vars: []*decls.VariableDecl{
700 decls.NewVariable("input", nestedMap),
701 },
702 want: 2,
703 in: map[string]any{"input": map[string]any{}},
704 },
705 {
706 name: "comprehension variable shadowing",
707 expr: `input.all(k, input[k].all(k, true) && k.contains(k))`,
708 vars: []*decls.VariableDecl{
709 decls.NewVariable("input", nestedMap),
710 },
711 want: 2,
712 in: map[string]any{"input": map[string]any{}},
713 },
714 {
715 name: "list concat",
716 expr: `(list1 + list2).all(x, true)`,
717 vars: []*decls.VariableDecl{
718 decls.NewVariable("list1", types.NewListType(types.IntType)),
719 decls.NewVariable("list2", types.NewListType(types.IntType)),
720 },
721 want: 4,
722 in: map[string]any{"list1": []int{}, "list2": []int{}},
723 },
724 {
725 name: "str concat",
726 expr: `"abcdefg".contains(str1 + str2)`,
727 vars: []*decls.VariableDecl{
728 decls.NewVariable("str1", types.StringType),
729 decls.NewVariable("str2", types.StringType),
730 },
731 want: 6,
732 in: map[string]any{"str1": "val1", "str2": "val2222222"},
733 },
734 {
735 name: "str concat custom cost tracker",
736 expr: `"abcdefg".contains(str1 + str2)`,
737 vars: []*decls.VariableDecl{
738 decls.NewVariable("str1", types.StringType),
739 decls.NewVariable("str2", types.StringType),
740 },
741 options: []CostTrackerOption{
742 OverloadCostTracker(overloads.ContainsString,
743 func(args []ref.Val, result ref.Val) *uint64 {
744 strCost := uint64(math.Ceil(float64(actualSize(args[0])) * 0.2))
745 substrCost := uint64(math.Ceil(float64(actualSize(args[1])) * 0.2))
746 cost := strCost * substrCost
747 return &cost
748 }),
749 },
750 want: 10,
751 in: map[string]any{"str1": "val1", "str2": "val2222222"},
752 },
753 {
754 name: "at limit",
755 expr: `"abcdefg".contains(str1 + str2)`,
756 vars: []*decls.VariableDecl{
757 decls.NewVariable("str1", types.StringType),
758 decls.NewVariable("str2", types.StringType),
759 },
760 in: map[string]any{"str1": "val1", "str2": "val2222222"},
761 limit: 6,
762 want: 6,
763 },
764 {
765 name: "above limit",
766 expr: `"abcdefg".contains(str1 + str2)`,
767 vars: []*decls.VariableDecl{
768 decls.NewVariable("str1", types.StringType),
769 decls.NewVariable("str2", types.StringType),
770 },
771 in: map[string]any{"str1": "val1", "str2": "val2222222"},
772 limit: 5,
773 expectExceedsLimit: true,
774 },
775 {
776 name: "ternary as operand",
777 expr: `(1 > 2 ? 5 : 3) > 1`,
778 vars: []*decls.VariableDecl{},
779 in: map[string]any{},
780 want: 2,
781 },
782 {
783 name: "ternary as operand",
784 expr: `(1 > 2 || 2 > 1) == true`,
785 vars: []*decls.VariableDecl{},
786 in: map[string]any{},
787 want: 3,
788 },
789 {
790 name: "list map literal",
791 expr: `[{'k1': 1}, {'k2': 2}].all(x, true)`,
792 vars: []*decls.VariableDecl{},
793 in: map[string]any{},
794 want: 77,
795 },
796 {
797 name: "list map literal",
798 expr: `[{'k1': 1}, {'k2': 2}].all(x, true)`,
799 vars: []*decls.VariableDecl{},
800 in: map[string]any{},
801 want: 77,
802 },
803 {
804 name: ".filter list literal",
805 expr: `[1,2,3,4,5].filter(x, x % 2 == 0)`,
806 vars: []*decls.VariableDecl{},
807 in: map[string]any{},
808 want: 62,
809 },
810 {
811 name: ".map list literal",
812 expr: `[1,2,3,4,5].map(x, x)`,
813 vars: []*decls.VariableDecl{},
814 in: map[string]any{},
815 want: 86,
816 },
817 {
818 name: ".map.filter list literal",
819 expr: `[1,2,3,4,5].map(x, x).filter(x, x % 2 == 0)`,
820 vars: []*decls.VariableDecl{},
821 in: map[string]any{},
822 want: 138,
823 },
824 {
825 name: ".map.exists list literal",
826 expr: `[1,2,3,4,5].map(x, x).exists(x, x == 5) == true`,
827 vars: []*decls.VariableDecl{},
828 in: map[string]any{},
829 want: 118,
830 },
831 {
832 name: ".map.map list literal",
833 expr: `[1,2,3,4,5].map(x, x).map(x, x)`,
834 vars: []*decls.VariableDecl{},
835 in: map[string]any{},
836 want: 162,
837 },
838 {
839 name: ".map.map list literal",
840 expr: `[1,2,3,4,5].map(x, [x, x]).filter(z, z.size() == 2)`,
841 vars: []*decls.VariableDecl{},
842 in: map[string]any{},
843 want: 232,
844 },
845 {
846 name: "comprehension on nested list",
847 expr: `[1,2,3,4,5].map(x, [x, x]).all(y, y.all(y, y == 1))`,
848 want: 171,
849 },
850 {
851 name: "comprehension size",
852 expr: `[1,2,3,4,5].map(x, x).map(x, x) + [1]`,
853 want: 173,
854 },
855 {
856 name: "nested comprehension",
857 expr: `[1,2,3].all(i, i in [1,2,3].map(j, j + j))`,
858 want: 86,
859 },
860 }
861
862 for _, tc := range cases {
863 t.Run(tc.name, func(t *testing.T) {
864 ctx := constructActivation(t, tc.in)
865 var costLimit *uint64
866 if tc.limit > 0 {
867 costLimit = &tc.limit
868 }
869 options := tc.options
870 if costLimit != nil {
871 options = append(options, CostTrackerLimit(*costLimit))
872 }
873 actualCost, est, err := computeCost(t, tc.expr, tc.vars, ctx, options)
874 if err != nil {
875 if tc.expectExceedsLimit {
876 return
877 }
878 t.Fatalf("Interpreter.Eval(activation Activation) failed due to: %v", err)
879 }
880 if tc.expectExceedsLimit {
881 t.Fatalf("Interpreter.Eval(activation Activation) failed to return a cost exceeded error for limit %d, got cost %d", tc.limit, actualCost)
882 }
883 if actualCost != tc.want {
884 t.Fatalf("Interpreter.Eval(activation Activation) failed to return expected runtime cost %d, got %d", tc.want, actualCost)
885 }
886 if est.Min > actualCost || est.Max < actualCost {
887 t.Fatalf("Interpreter.Eval(activation Activation) failed to return cost in range of estimate cost [%d, %d], got %d",
888 est.Min, est.Max, actualCost)
889 }
890 })
891 }
892 }