Debian Codegraph @

checker/cost.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 checker
16
17 import (
18 "math"
19
20 "github.com/google/cel-go/common"
21 "github.com/google/cel-go/common/ast"
22 "github.com/google/cel-go/common/overloads"
23 "github.com/google/cel-go/common/types"
24 "github.com/google/cel-go/parser"
25 )
26
27 // WARNING: Any changes to cost calculations in this file require a corresponding change in interpreter/runtimecost.go
28
29 // CostEstimator estimates the sizes of variable length input data and the costs of functions.
30 type CostEstimator interface {
31 // EstimateSize returns a SizeEstimate for the given AstNode, or nil if the estimator has no
32 // estimate to provide.
33 //
34 // The size is equivalent to the result of the CEL `size()` function:
35 // * Number of unicode characters in a string
36 // * Number of bytes in a sequence
37 // * Number of map entries or number of list items.
38 //
39 // EstimateSize is only called for AstNodes where CEL does not know the size; EstimateSize is not
40 // called for values defined inline in CEL where the size is already obvious to CEL.
41 EstimateSize(element AstNode) *SizeEstimate
42
43 // EstimateCallCost returns the estimated cost of an invocation, or nil if the estimator has no
44 // estimate to provide.
45 EstimateCallCost(function, overloadID string, target *AstNode, args []AstNode) *CallEstimate
46 }
47
48 // CallEstimate includes a CostEstimate for the call, and an optional estimate of the result object size.
49 // The ResultSize should only be provided if the call results in a map, list, string or bytes.
50 type CallEstimate struct {
51 CostEstimate
52
53 ResultSize *SizeEstimate
54 }
55
56 // AstNode represents an AST node for the purpose of cost estimations.
57 type AstNode interface {
58 // Path returns a field path through the provided type declarations to the type of the AstNode, or nil if the AstNode does not
59 // represent type directly reachable from the provided type declarations.
60 // The first path element is a variable. All subsequent path elements are one of: field name, '@items', '@keys', '@values'.
61 Path() []string
62
63 // Type returns the deduced type of the AstNode.
64 Type() *types.Type
65
66 // Expr returns the expression of the AstNode.
67 Expr() ast.Expr
68
69 // ComputedSize returns a size estimate of the AstNode derived from information available in the CEL expression.
70 // For constants and inline list and map declarations, the exact size is returned. For concatenated list, strings
71 // and bytes, the size is derived from the size estimates of the operands. nil is returned if there is no
72 // computed size available.
73 ComputedSize() *SizeEstimate
74 }
75
76 type astNode struct {
77 path []string
78 t *types.Type
79 expr ast.Expr
80 derivedSize *SizeEstimate
81 }
82
83 func (e astNode) Path() []string {
84 return e.path
85 }
86
87 func (e astNode) Type() *types.Type {
88 return e.t
89 }
90
91 func (e astNode) Expr() ast.Expr {
92 return e.expr
93 }
94
95 func (e astNode) ComputedSize() *SizeEstimate {
96 return e.derivedSize
97 }
98
99 // SizeEstimate represents an estimated size of a variable length string, bytes, map or list.
100 type SizeEstimate struct {
101 Min, Max uint64
102 }
103
104 // UnknownSizeEstimate returns a size between 0 and max uint
105 func UnknownSizeEstimate() SizeEstimate {
106 return unknownSizeEstimate
107 }
108
109 // FixedSizeEstimate returns a size estimate with a fixed min and max range.
110 func FixedSizeEstimate(size uint64) SizeEstimate {
111 return SizeEstimate{Min: size, Max: size}
112 }
113
114 // Add adds to another SizeEstimate and returns the sum.
115 // If add would result in an uint64 overflow, the result is math.MaxUint64.
116 func (se SizeEstimate) Add(sizeEstimate SizeEstimate) SizeEstimate {
117 return SizeEstimate{
118 addUint64NoOverflow(se.Min, sizeEstimate.Min),
119 addUint64NoOverflow(se.Max, sizeEstimate.Max),
120 }
121 }
122
123 // Multiply multiplies by another SizeEstimate and returns the product.
124 // If multiply would result in an uint64 overflow, the result is math.MaxUint64.
125 func (se SizeEstimate) Multiply(sizeEstimate SizeEstimate) SizeEstimate {
126 return SizeEstimate{
127 multiplyUint64NoOverflow(se.Min, sizeEstimate.Min),
128 multiplyUint64NoOverflow(se.Max, sizeEstimate.Max),
129 }
130 }
131
132 // MultiplyByCostFactor multiplies a SizeEstimate by a cost factor and returns the CostEstimate with the
133 // nearest integer of the result, rounded up.
134 func (se SizeEstimate) MultiplyByCostFactor(costPerUnit float64) CostEstimate {
135 return CostEstimate{
136 multiplyByCostFactor(se.Min, costPerUnit),
137 multiplyByCostFactor(se.Max, costPerUnit),
138 }
139 }
140
141 // MultiplyByCost multiplies by the cost and returns the product.
142 // If multiply would result in an uint64 overflow, the result is math.MaxUint64.
143 func (se SizeEstimate) MultiplyByCost(cost CostEstimate) CostEstimate {
144 return CostEstimate{
145 multiplyUint64NoOverflow(se.Min, cost.Min),
146 multiplyUint64NoOverflow(se.Max, cost.Max),
147 }
148 }
149
150 // Union returns a SizeEstimate that encompasses both input the SizeEstimate.
151 func (se SizeEstimate) Union(size SizeEstimate) SizeEstimate {
152 result := se
153 if size.Min < result.Min {
154 result.Min = size.Min
155 }
156 if size.Max > result.Max {
157 result.Max = size.Max
158 }
159 return result
160 }
161
162 // CostEstimate represents an estimated cost range and provides add and multiply operations
163 // that do not overflow.
164 type CostEstimate struct {
165 Min, Max uint64
166 }
167
168 // UnknownCostEstimate returns a cost with an unknown impact.
169 func UnknownCostEstimate() CostEstimate {
170 return unknownCostEstimate
171 }
172
173 // FixedCostEstimate returns a cost with a fixed min and max range.
174 func FixedCostEstimate(cost uint64) CostEstimate {
175 return CostEstimate{Min: cost, Max: cost}
176 }
177
178 // Add adds the costs and returns the sum.
179 // If add would result in an uint64 overflow for the min or max, the value is set to math.MaxUint64.
180 func (ce CostEstimate) Add(cost CostEstimate) CostEstimate {
181 return CostEstimate{
182 Min: addUint64NoOverflow(ce.Min, cost.Min),
183 Max: addUint64NoOverflow(ce.Max, cost.Max),
184 }
185 }
186
187 // Multiply multiplies by the cost and returns the product.
188 // If multiply would result in an uint64 overflow, the result is math.MaxUint64.
189 func (ce CostEstimate) Multiply(cost CostEstimate) CostEstimate {
190 return CostEstimate{
191 Min: multiplyUint64NoOverflow(ce.Min, cost.Min),
192 Max: multiplyUint64NoOverflow(ce.Max, cost.Max),
193 }
194 }
195
196 // MultiplyByCostFactor multiplies a CostEstimate by a cost factor and returns the CostEstimate with the
197 // nearest integer of the result, rounded up.
198 func (ce CostEstimate) MultiplyByCostFactor(costPerUnit float64) CostEstimate {
199 return CostEstimate{
200 Min: multiplyByCostFactor(ce.Min, costPerUnit),
201 Max: multiplyByCostFactor(ce.Max, costPerUnit),
202 }
203 }
204
205 // Union returns a CostEstimate that encompasses both input the CostEstimates.
206 func (ce CostEstimate) Union(size CostEstimate) CostEstimate {
207 result := ce
208 if size.Min < result.Min {
209 result.Min = size.Min
210 }
211 if size.Max > result.Max {
212 result.Max = size.Max
213 }
214 return result
215 }
216
217 // addUint64NoOverflow adds non-negative ints. If the result is exceeds math.MaxUint64, math.MaxUint64
218 // is returned.
219 func addUint64NoOverflow(x, y uint64) uint64 {
220 if y > 0 && x > math.MaxUint64-y {
221 return math.MaxUint64
222 }
223 return x + y
224 }
225
226 // multiplyUint64NoOverflow multiplies non-negative ints. If the result is exceeds math.MaxUint64, math.MaxUint64
227 // is returned.
228 func multiplyUint64NoOverflow(x, y uint64) uint64 {
229 if y != 0 && x > math.MaxUint64/y {
230 return math.MaxUint64
231 }
232 return x * y
233 }
234
235 // multiplyByFactor multiplies an integer by a cost factor float and returns the nearest integer value, rounded up.
236 func multiplyByCostFactor(x uint64, y float64) uint64 {
237 xFloat := float64(x)
238 if xFloat > 0 && y > 0 && xFloat > math.MaxUint64/y {
239 return math.MaxUint64
240 }
241 ceil := math.Ceil(xFloat * y)
242 if ceil >= doubleTwoTo64 {
243 return math.MaxUint64
244 }
245 return uint64(ceil)
246 }
247
248 // CostOption configures flags which affect cost computations.
249 type CostOption func(*coster) error
250
251 // PresenceTestHasCost determines whether presence testing has a cost of one or zero.
252 //
253 // Defaults to presence test has a cost of one.
254 func PresenceTestHasCost(hasCost bool) CostOption {
255 return func(c *coster) error {
256 if hasCost {
257 c.presenceTestCost = selectAndIdentCost
258 return nil
259 }
260 c.presenceTestCost = FixedCostEstimate(0)
261 return nil
262 }
263 }
264
265 // FunctionEstimator provides a CallEstimate given the target and arguments for a specific function, overload pair.
266 type FunctionEstimator func(estimator CostEstimator, target *AstNode, args []AstNode) *CallEstimate
267
268 // OverloadCostEstimate binds a FunctionCoster to a specific function overload ID.
269 //
270 // When a OverloadCostEstimate is provided, it will override the cost calculation of the CostEstimator provided to
271 // the Cost() call.
272 func OverloadCostEstimate(overloadID string, functionCoster FunctionEstimator) CostOption {
273 return func(c *coster) error {
274 c.overloadEstimators[overloadID] = functionCoster
275 return nil
276 }
277 }
278
279 // Cost estimates the cost of the parsed and type checked CEL expression.
280 func Cost(checked *ast.AST, estimator CostEstimator, opts ...CostOption) (CostEstimate, error) {
281 c := &coster{
282 checkedAST: checked,
283 estimator: estimator,
284 overloadEstimators: map[string]FunctionEstimator{},
285 exprPaths: map[int64][]string{},
286 localVars: make(scopes),
287 computedSizes: map[int64]SizeEstimate{},
288 computedEntrySizes: map[int64]entrySizeEstimate{},
289 presenceTestCost: FixedCostEstimate(1),
290 }
291 for _, opt := range opts {
292 err := opt(c)
293 if err != nil {
294 return CostEstimate{}, err
295 }
296 }
297 return c.cost(checked.Expr()), nil
298 }
299
300 type coster struct {
301 // exprPaths maps from Expr Id to field path.
302 exprPaths map[int64][]string
303 // localVars tracks the local and iteration variables assigned during evaluation.
304 localVars scopes
305 // computedSizes tracks the computed sizes of call results.
306 computedSizes map[int64]SizeEstimate
307 // computedEntrySizes tracks the size of list and map entries
308 computedEntrySizes map[int64]entrySizeEstimate
309
310 checkedAST *ast.AST
311 estimator CostEstimator
312 overloadEstimators map[string]FunctionEstimator
313 // presenceTestCost will either be a zero or one based on whether has() macros count against cost computations.
314 presenceTestCost CostEstimate
315 }
316
317 // entrySizeEstimate captures the container kind and associated key/index and value SizeEstimate values.
318 //
319 // An entrySizeEstimate only exists if both the key/index and the value have SizeEstimate values, otherwise
320 // a nil entrySizeEstimate should be used.
321 type entrySizeEstimate struct {
322 containerKind types.Kind
323 key SizeEstimate
324 val SizeEstimate
325 }
326
327 // container returns the container kind (list or map) of the entry.
328 func (s *entrySizeEstimate) container() types.Kind {
329 if s == nil {
330 return types.UnknownKind
331 }
332 return s.containerKind
333 }
334
335 // keySize returns the SizeEstimate for the key if one exists.
336 func (s *entrySizeEstimate) keySize() *SizeEstimate {
337 if s == nil {
338 return nil
339 }
340 return &s.key
341 }
342
343 // valSize returns the SizeEstimate for the value if one exists.
344 func (s *entrySizeEstimate) valSize() *SizeEstimate {
345 if s == nil {
346 return nil
347 }
348 return &s.val
349 }
350
351 func (s *entrySizeEstimate) union(other *entrySizeEstimate) *entrySizeEstimate {
352 if s == nil || other == nil {
353 return nil
354 }
355 sk := s.key.Union(other.key)
356 sv := s.val.Union(other.val)
357 return &entrySizeEstimate{
358 containerKind: s.containerKind,
359 key: sk,
360 val: sv,
361 }
362 }
363
364 // localVar captures the local variable size and entrySize estimates if they exist for variables
365 type localVar struct {
366 exprID int64
367 path []string
368 size *SizeEstimate
369 entrySize *entrySizeEstimate
370 }
371
372 // scopes is a stack of variable name to integer id stack to handle scopes created by cel.bind() like macros
373 type scopes map[string][]*localVar
374
375 func (s scopes) push(varName string, expr ast.Expr, path []string, size *SizeEstimate, entrySize *entrySizeEstimate) {
376 s[varName] = append(s[varName], &localVar{
377 exprID: expr.ID(),
378 path: path,
379 size: size,
380 entrySize: entrySize,
381 })
382 }
383
384 func (s scopes) pop(varName string) {
385 varStack := s[varName]
386 s[varName] = varStack[:len(varStack)-1]
387 }
388
389 func (s scopes) peek(varName string) (*localVar, bool) {
390 varStack := s[varName]
391 if len(varStack) > 0 {
392 return varStack[len(varStack)-1], true
393 }
394 return nil, false
395 }
396
397 func (c *coster) pushIterKey(varName string, rangeExpr ast.Expr) {
398 entrySize := c.computeEntrySize(rangeExpr)
399 size := entrySize.keySize()
400 path := c.getPath(rangeExpr)
401 container := entrySize.container()
402 if container == types.UnknownKind {
403 container = c.getType(rangeExpr).Kind()
404 }
405 subpath := "@keys"
406 if container == types.ListKind {
407 subpath = "@indices"
408 }
409 c.localVars.push(varName, rangeExpr, append(path, subpath), size, nil)
410 }
411
412 func (c *coster) pushIterValue(varName string, rangeExpr ast.Expr) {
413 entrySize := c.computeEntrySize(rangeExpr)
414 size := entrySize.valSize()
415 path := c.getPath(rangeExpr)
416 container := entrySize.container()
417 if container == types.UnknownKind {
418 container = c.getType(rangeExpr).Kind()
419 }
420 subpath := "@values"
421 if container == types.ListKind {
422 subpath = "@items"
423 }
424 c.localVars.push(varName, rangeExpr, append(path, subpath), size, nil)
425 }
426
427 func (c *coster) pushIterSingle(varName string, rangeExpr ast.Expr) {
428 entrySize := c.computeEntrySize(rangeExpr)
429 size := entrySize.keySize()
430 subpath := "@keys"
431 container := entrySize.container()
432 if container == types.UnknownKind {
433 container = c.getType(rangeExpr).Kind()
434 }
435 if container == types.ListKind {
436 size = entrySize.valSize()
437 subpath = "@items"
438 }
439 path := c.getPath(rangeExpr)
440 c.localVars.push(varName, rangeExpr, append(path, subpath), size, nil)
441 }
442
443 func (c *coster) pushLocalVar(varName string, e ast.Expr) {
444 path := c.getPath(e)
445 // note: retrieve the entry size for the local variable based on the size of the binding expression
446 // since the binding expression could be a list or map, the entry size should also be propagated
447 entrySize := c.computeEntrySize(e)
448 c.localVars.push(varName, e, path, c.computeSize(e), entrySize)
449 }
450
451 func (c *coster) peekLocalVar(varName string) (*localVar, bool) {
452 return c.localVars.peek(varName)
453 }
454
455 func (c *coster) popLocalVar(varName string) {
456 c.localVars.pop(varName)
457 }
458
459 func (c *coster) cost(e ast.Expr) CostEstimate {
460 if e == nil {
461 return CostEstimate{}
462 }
463 var cost CostEstimate
464 switch e.Kind() {
465 case ast.LiteralKind:
466 cost = constCost
467 case ast.IdentKind:
468 cost = c.costIdent(e)
469 case ast.SelectKind:
470 cost = c.costSelect(e)
471 case ast.CallKind:
472 cost = c.costCall(e)
473 case ast.ListKind:
474 cost = c.costCreateList(e)
475 case ast.MapKind:
476 cost = c.costCreateMap(e)
477 case ast.StructKind:
478 cost = c.costCreateStruct(e)
479 case ast.ComprehensionKind:
480 if c.isBind(e) {
481 cost = c.costBind(e)
482 } else {
483 cost = c.costComprehension(e)
484 }
485 default:
486 return CostEstimate{}
487 }
488 return cost
489 }
490
491 func (c *coster) costIdent(e ast.Expr) CostEstimate {
492 identName := e.AsIdent()
493 // build and track the field path
494 if v, ok := c.peekLocalVar(identName); ok {
495 c.addPath(e, v.path)
496 } else {
497 c.addPath(e, []string{identName})
498 }
499 return selectAndIdentCost
500 }
501
502 func (c *coster) costSelect(e ast.Expr) CostEstimate {
503 sel := e.AsSelect()
504 var sum CostEstimate
505 if sel.IsTestOnly() {
506 // recurse, but do not add any cost
507 // this is equivalent to how evalTestOnly increments the runtime cost counter
508 // but does not add any additional cost for the qualifier, except here we do
509 // the reverse (ident adds cost)
510 sum = sum.Add(c.presenceTestCost)
511 sum = sum.Add(c.cost(sel.Operand()))
512 return sum
513 }
514 sum = sum.Add(c.cost(sel.Operand()))
515 targetType := c.getType(sel.Operand())
516 switch targetType.Kind() {
517 case types.MapKind, types.StructKind, types.TypeParamKind:
518 sum = sum.Add(selectAndIdentCost)
519 }
520
521 // build and track the field path
522 c.addPath(e, append(c.getPath(sel.Operand()), sel.FieldName()))
523 return sum
524 }
525
526 func (c *coster) costCall(e ast.Expr) CostEstimate {
527 // Dyn is just a way to disable type-checking, so return the cost of 1 with the cost of the argument
528 if dynEstimate := c.maybeUnwrapDynCall(e); dynEstimate != nil {
529 return *dynEstimate
530 }
531
532 // Continue estimating the cost of all other calls.
533 call := e.AsCall()
534 args := call.Args()
535 var sum CostEstimate
536
537 argTypes := make([]AstNode, len(args))
538 argCosts := make([]CostEstimate, len(args))
539 for i, arg := range args {
540 argCosts[i] = c.cost(arg)
541 argTypes[i] = c.newAstNode(arg)
542 }
543
544 overloadIDs := c.checkedAST.GetOverloadIDs(e.ID())
545 if len(overloadIDs) == 0 {
546 return CostEstimate{}
547 }
548 var targetType *AstNode
549 if call.IsMemberFunction() {
550 sum = sum.Add(c.cost(call.Target()))
551 var t AstNode = c.newAstNode(call.Target())
552 targetType = &t
553 }
554 // Pick a cost estimate range that covers all the overload cost estimation ranges
555 fnCost := CostEstimate{Min: uint64(math.MaxUint64), Max: 0}
556 var resultSize *SizeEstimate
557 for _, overload := range overloadIDs {
558 overloadCost := c.functionCost(e, call.FunctionName(), overload, targetType, argTypes, argCosts)
559 fnCost = fnCost.Union(overloadCost.CostEstimate)
560 if overloadCost.ResultSize != nil {
561 if resultSize == nil {
562 resultSize = overloadCost.ResultSize
563 } else {
564 size := resultSize.Union(*overloadCost.ResultSize)
565 resultSize = &size
566 }
567 }
568 // build and track the field path for index operations
569 switch overload {
570 case overloads.IndexList:
571 if len(args) > 0 {
572 // note: assigning resultSize here could be redundant with the path-based lookup later
573 resultSize = c.computeEntrySize(args[0]).valSize()
574 c.addPath(e, append(c.getPath(args[0]), "@items"))
575 }
576 case overloads.IndexMap:
577 if len(args) > 0 {
578 resultSize = c.computeEntrySize(args[0]).valSize()
579 c.addPath(e, append(c.getPath(args[0]), "@values"))
580 }
581 }
582 if resultSize == nil {
583 resultSize = c.computeSize(e)
584 }
585 }
586 c.setSize(e, resultSize)
587 return sum.Add(fnCost)
588 }
589
590 func (c *coster) maybeUnwrapDynCall(e ast.Expr) *CostEstimate {
591 call := e.AsCall()
592 if call.FunctionName() != "dyn" {
593 return nil
594 }
595 arg := call.Args()[0]
596 argCost := c.cost(arg)
597 c.copySizeEstimates(e, arg)
598 callCost := FixedCostEstimate(1).Add(argCost)
599 return &callCost
600 }
601
602 func (c *coster) costCreateList(e ast.Expr) CostEstimate {
603 create := e.AsList()
604 var sum CostEstimate
605 itemSize := SizeEstimate{Min: math.MaxUint64, Max: 0}
606 if create.Size() == 0 {
607 itemSize.Min = 0
608 }
609 for _, e := range create.Elements() {
610 sum = sum.Add(c.cost(e))
611 is := c.sizeOrUnknown(e)
612 itemSize = itemSize.Union(is)
613 }
614 c.setEntrySize(e, &entrySizeEstimate{containerKind: types.ListKind, key: FixedSizeEstimate(1), val: itemSize})
615 return sum.Add(createListBaseCost)
616 }
617
618 func (c *coster) costCreateMap(e ast.Expr) CostEstimate {
619 mapVal := e.AsMap()
620 var sum CostEstimate
621 keySize := SizeEstimate{Min: math.MaxUint64, Max: 0}
622 valSize := SizeEstimate{Min: math.MaxUint64, Max: 0}
623 if mapVal.Size() == 0 {
624 valSize.Min = 0
625 keySize.Min = 0
626 }
627 for _, ent := range mapVal.Entries() {
628 entry := ent.AsMapEntry()
629 sum = sum.Add(c.cost(entry.Key()))
630 sum = sum.Add(c.cost(entry.Value()))
631 // Compute the key size range
632 ks := c.sizeOrUnknown(entry.Key())
633 keySize = keySize.Union(ks)
634 // Compute the value size range
635 vs := c.sizeOrUnknown(entry.Value())
636 valSize = valSize.Union(vs)
637 }
638 c.setEntrySize(e, &entrySizeEstimate{containerKind: types.MapKind, key: keySize, val: valSize})
639 return sum.Add(createMapBaseCost)
640 }
641
642 func (c *coster) costCreateStruct(e ast.Expr) CostEstimate {
643 msgVal := e.AsStruct()
644 var sum CostEstimate
645 for _, ent := range msgVal.Fields() {
646 field := ent.AsStructField()
647 sum = sum.Add(c.cost(field.Value()))
648 }
649 return sum.Add(createMessageBaseCost)
650 }
651
652 func (c *coster) costComprehension(e ast.Expr) CostEstimate {
653 comp := e.AsComprehension()
654 var sum CostEstimate
655 sum = sum.Add(c.cost(comp.IterRange()))
656 sum = sum.Add(c.cost(comp.AccuInit()))
657 c.pushLocalVar(comp.AccuVar(), comp.AccuInit())
658
659 // Track the iterRange of each IterVar and AccuVar for field path construction
660 if comp.HasIterVar2() {
661 c.pushIterKey(comp.IterVar(), comp.IterRange())
662 c.pushIterValue(comp.IterVar2(), comp.IterRange())
663 } else {
664 c.pushIterSingle(comp.IterVar(), comp.IterRange())
665 }
666
667 // Determine the cost for each element in the loop
668 loopCost := c.cost(comp.LoopCondition())
669 stepCost := c.cost(comp.LoopStep())
670
671 // Clear the intermediate variable tracking.
672 c.popLocalVar(comp.IterVar())
673 if comp.HasIterVar2() {
674 c.popLocalVar(comp.IterVar2())
675 }
676
677 // Determine the result cost.
678 sum = sum.Add(c.cost(comp.Result()))
679 c.localVars.pop(comp.AccuVar())
680
681 // Estimate the cost of the loop.
682 rangeCnt := c.sizeOrUnknown(comp.IterRange())
683 rangeCost := rangeCnt.MultiplyByCost(stepCost.Add(loopCost))
684 sum = sum.Add(rangeCost)
685
686 switch k := comp.AccuInit().Kind(); k {
687 case ast.LiteralKind:
688 c.setSize(e, c.computeSize(comp.AccuInit()))
689 case ast.ListKind, ast.MapKind:
690 c.setSize(e, &rangeCnt)
691 // For a step which produces a container value, it will have an entry size associated
692 // with its expression id.
693 if stepEntrySize := c.computeEntrySize(comp.LoopStep()); stepEntrySize != nil {
694 c.setEntrySize(e, stepEntrySize)
695 break
696 }
697 }
698 return sum
699 }
700
701 func (c *coster) isBind(e ast.Expr) bool {
702 comp := e.AsComprehension()
703 iterRange := comp.IterRange()
704 loopCond := comp.LoopCondition()
705 return iterRange.Kind() == ast.ListKind && iterRange.AsList().Size() == 0 &&
706 loopCond.Kind() == ast.LiteralKind && loopCond.AsLiteral() == types.False &&
707 comp.AccuVar() != parser.AccumulatorName
708 }
709
710 func (c *coster) costBind(e ast.Expr) CostEstimate {
711 comp := e.AsComprehension()
712 var sum CostEstimate
713 // Binds are lazily initialized, so we retain the cost of an empty iteration range.
714 sum = sum.Add(c.cost(comp.IterRange()))
715 sum = sum.Add(c.cost(comp.AccuInit()))
716
717 c.pushLocalVar(comp.AccuVar(), comp.AccuInit())
718 sum = sum.Add(c.cost(comp.Result()))
719 c.popLocalVar(comp.AccuVar())
720
721 // Associate the bind output size with the result size.
722 c.copySizeEstimates(e, comp.Result())
723 return sum
724 }
725
726 func (c *coster) functionCost(e ast.Expr, function, overloadID string, target *AstNode, args []AstNode, argCosts []CostEstimate) CallEstimate {
727 argCostSum := func() CostEstimate {
728 var sum CostEstimate
729 for _, a := range argCosts {
730 sum = sum.Add(a)
731 }
732 return sum
733 }
734 if len(c.overloadEstimators) != 0 {
735 if estimator, found := c.overloadEstimators[overloadID]; found {
736 if est := estimator(c.estimator, target, args); est != nil {
737 callEst := *est
738 return CallEstimate{CostEstimate: callEst.Add(argCostSum()), ResultSize: est.ResultSize}
739 }
740 }
741 }
742 if est := c.estimator.EstimateCallCost(function, overloadID, target, args); est != nil {
743 callEst := *est
744 return CallEstimate{CostEstimate: callEst.Add(argCostSum()), ResultSize: est.ResultSize}
745 }
746 switch overloadID {
747 // O(n) functions
748 case overloads.ExtFormatString:
749 if target != nil {
750 // ResultSize not calculated because we can't bound the max size.
751 return CallEstimate{
752 CostEstimate: c.sizeOrUnknown(*target).MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum())}
753 }
754 case overloads.StringToBytes:
755 if len(args) == 1 {
756 sz := c.sizeOrUnknown(args[0])
757 // ResultSize max is when each char converts to 4 bytes.
758 return CallEstimate{
759 CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()),
760 ResultSize: &SizeEstimate{Min: sz.Min, Max: sz.Max * 4}}
761 }
762 case overloads.BytesToString:
763 if len(args) == 1 {
764 sz := c.sizeOrUnknown(args[0])
765 // ResultSize min is when 4 bytes convert to 1 char.
766 return CallEstimate{
767 CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()),
768 ResultSize: &SizeEstimate{Min: sz.Min / 4, Max: sz.Max}}
769 }
770 case overloads.ExtQuoteString:
771 if len(args) == 1 {
772 sz := c.sizeOrUnknown(args[0])
773 // ResultSize max is when each char is escaped. 2 quote chars always added.
774 return CallEstimate{
775 CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()),
776 ResultSize: &SizeEstimate{Min: sz.Min + 2, Max: sz.Max*2 + 2}}
777 }
778 case overloads.StartsWithString, overloads.EndsWithString:
779 if len(args) == 1 {
780 return CallEstimate{CostEstimate: c.sizeOrUnknown(args[0]).MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum())}
781 }
782 case overloads.InList:
783 // If a list is composed entirely of constant values this is O(1), but we don't account for that here.
784 // We just assume all list containment checks are O(n).
785 if len(args) == 2 {
786 return CallEstimate{CostEstimate: c.sizeOrUnknown(args[1]).MultiplyByCostFactor(1).Add(argCostSum())}
787 }
788 // O(nm) functions
789 case overloads.MatchesString:
790 // https://swtch.com/~rsc/regexp/regexp1.html applies to RE2 implementation supported by CEL
791 if target != nil && len(args) == 1 {
792 // Add one to string length for purposes of cost calculation to prevent product of string and regex to be 0
793 // in case where string is empty but regex is still expensive.
794 strCost := c.sizeOrUnknown(*target).Add(SizeEstimate{Min: 1, Max: 1}).MultiplyByCostFactor(common.StringTraversalCostFactor)
795 // We don't know how many expressions are in the regex, just the string length (a huge
796 // improvement here would be to somehow get a count the number of expressions in the regex or
797 // how many states are in the regex state machine and use that to measure regex cost).
798 // For now, we're making a guess that each expression in a regex is typically at least 4 chars
799 // in length.
800 regexCost := c.sizeOrUnknown(args[0]).MultiplyByCostFactor(common.RegexStringLengthCostFactor)
801 return CallEstimate{CostEstimate: strCost.Multiply(regexCost).Add(argCostSum())}
802 }
803 case overloads.ContainsString:
804 if target != nil && len(args) == 1 {
805 strCost := c.sizeOrUnknown(*target).MultiplyByCostFactor(common.StringTraversalCostFactor)
806 substrCost := c.sizeOrUnknown(args[0]).MultiplyByCostFactor(common.StringTraversalCostFactor)
807 return CallEstimate{CostEstimate: strCost.Multiply(substrCost).Add(argCostSum())}
808 }
809 case overloads.LogicalOr, overloads.LogicalAnd:
810 lhs := argCosts[0]
811 rhs := argCosts[1]
812 // min cost is min of LHS for short circuited && or ||
813 argCost := CostEstimate{Min: lhs.Min, Max: lhs.Add(rhs).Max}
814 return CallEstimate{CostEstimate: argCost}
815 case overloads.Conditional:
816 size := c.sizeOrUnknown(args[1]).Union(c.sizeOrUnknown(args[2]))
817 resultEntrySize := c.computeEntrySize(args[1].Expr()).union(c.computeEntrySize(args[2].Expr()))
818 c.setEntrySize(e, resultEntrySize)
819 conditionalCost := argCosts[0]
820 ifTrueCost := argCosts[1]
821 ifFalseCost := argCosts[2]
822 argCost := conditionalCost.Add(ifTrueCost.Union(ifFalseCost))
823 return CallEstimate{CostEstimate: argCost, ResultSize: &size}
824 case overloads.AddString, overloads.AddBytes, overloads.AddList:
825 if len(args) == 2 {
826 lhsSize := c.sizeOrUnknown(args[0])
827 rhsSize := c.sizeOrUnknown(args[1])
828 resultSize := lhsSize.Add(rhsSize)
829 rhsEntrySize := c.computeEntrySize(args[0].Expr())
830 lhsEntrySize := c.computeEntrySize(args[1].Expr())
831 resultEntrySize := rhsEntrySize.union(lhsEntrySize)
832 if resultEntrySize != nil {
833 c.setEntrySize(e, resultEntrySize)
834 }
835 switch overloadID {
836 case overloads.AddList:
837 // list concatenation is O(1), but we handle it here to track size
838 return CallEstimate{CostEstimate: FixedCostEstimate(1).Add(argCostSum()), ResultSize: &resultSize}
839 default:
840 return CallEstimate{CostEstimate: resultSize.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), ResultSize: &resultSize}
841 }
842 }
843 case overloads.LessString, overloads.GreaterString, overloads.LessEqualsString, overloads.GreaterEqualsString,
844 overloads.LessBytes, overloads.GreaterBytes, overloads.LessEqualsBytes, overloads.GreaterEqualsBytes,
845 overloads.Equals, overloads.NotEquals:
846 lhsCost := c.sizeOrUnknown(args[0])
847 rhsCost := c.sizeOrUnknown(args[1])
848 min := uint64(0)
849 smallestMax := lhsCost.Max
850 if rhsCost.Max < smallestMax {
851 smallestMax = rhsCost.Max
852 }
853 if smallestMax > 0 {
854 min = 1
855 }
856 // equality of 2 scalar values results in a cost of 1
857 return CallEstimate{
858 CostEstimate: CostEstimate{Min: min, Max: smallestMax}.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()),
859 }
860 }
861 // O(1) functions
862 // See CostTracker.costCall for more details about O(1) cost calculations
863
864 // Benchmarks suggest that most of the other operations take +/- 50% of a base cost unit
865 // which on an Intel xeon 2.20GHz CPU is 50ns.
866 return CallEstimate{CostEstimate: FixedCostEstimate(1).Add(argCostSum())}
867 }
868
869 func (c *coster) getType(e ast.Expr) *types.Type {
870 return c.checkedAST.GetType(e.ID())
871 }
872
873 func (c *coster) getPath(e ast.Expr) []string {
874 if e.Kind() == ast.IdentKind {
875 if v, found := c.peekLocalVar(e.AsIdent()); found {
876 return v.path[:]
877 }
878 }
879 return c.exprPaths[e.ID()][:]
880 }
881
882 func (c *coster) addPath(e ast.Expr, path []string) {
883 c.exprPaths[e.ID()] = path
884 }
885
886 func isAccumulatorVar(name string) bool {
887 return name == parser.AccumulatorName || name == parser.HiddenAccumulatorName
888 }
889
890 func (c *coster) newAstNode(e ast.Expr) *astNode {
891 path := c.getPath(e)
892 if len(path) > 0 && isAccumulatorVar(path[0]) {
893 // only provide paths to root vars; omit accumulator vars
894 path = nil
895 }
896 return &astNode{
897 path: path,
898 t: c.getType(e),
899 expr: e,
900 derivedSize: c.computeSize(e)}
901 }
902
903 func (c *coster) setSize(e ast.Expr, size *SizeEstimate) {
904 if size == nil {
905 return
906 }
907 // Store the computed size with the expression
908 c.computedSizes[e.ID()] = *size
909 }
910
911 func (c *coster) sizeOrUnknown(node any) SizeEstimate {
912 switch v := node.(type) {
913 case ast.Expr:
914 if sz := c.computeSize(v); sz != nil {
915 return *sz
916 }
917 case AstNode:
918 if sz := v.ComputedSize(); sz != nil {
919 return *sz
920 }
921 }
922 return UnknownSizeEstimate()
923 }
924
925 func (c *coster) copySizeEstimates(dst, src ast.Expr) {
926 c.setSize(dst, c.computeSize(src))
927 c.setEntrySize(dst, c.computeEntrySize(src))
928 }
929
930 func (c *coster) computeSize(e ast.Expr) *SizeEstimate {
931 if size, ok := c.computedSizes[e.ID()]; ok {
932 return &size
933 }
934 if size := computeExprSize(e); size != nil {
935 return size
936 }
937 // Ensure size estimates are computed first as users may choose to override the costs that
938 // CEL would otherwise ascribe to the type.
939 node := astNode{expr: e, path: c.getPath(e), t: c.getType(e)}
940 if size := c.estimator.EstimateSize(node); size != nil {
941 // storing the computed size should reduce calls to EstimateSize()
942 c.computedSizes[e.ID()] = *size
943 return size
944 }
945 if size := computeTypeSize(c.getType(e)); size != nil {
946 return size
947 }
948 if e.Kind() == ast.IdentKind {
949 varName := e.AsIdent()
950 if v, ok := c.peekLocalVar(varName); ok && v.size != nil {
951 return v.size
952 }
953 }
954 return nil
955 }
956
957 func (c *coster) setEntrySize(e ast.Expr, size *entrySizeEstimate) {
958 if size == nil {
959 return
960 }
961 c.computedEntrySizes[e.ID()] = *size
962 }
963
964 func (c *coster) computeEntrySize(e ast.Expr) *entrySizeEstimate {
965 if sz, found := c.computedEntrySizes[e.ID()]; found {
966 return &sz
967 }
968 if e.Kind() == ast.IdentKind {
969 varName := e.AsIdent()
970 if v, ok := c.peekLocalVar(varName); ok && v.entrySize != nil {
971 return v.entrySize
972 }
973 }
974 return nil
975 }
976
977 func computeExprSize(expr ast.Expr) *SizeEstimate {
978 var v uint64
979 switch expr.Kind() {
980 case ast.LiteralKind:
981 switch ck := expr.AsLiteral().(type) {
982 case types.String:
983 // converting to runes here is an O(n) operation, but
984 // this is consistent with how size is computed at runtime,
985 // and how the language definition defines string size
986 v = uint64(len([]rune(ck)))
987 case types.Bytes:
988 v = uint64(len(ck))
989 case types.Bool, types.Double, types.Duration,
990 types.Int, types.Timestamp, types.Uint,
991 types.Null:
992 v = uint64(1)
993 default:
994 return nil
995 }
996 case ast.ListKind:
997 v = uint64(expr.AsList().Size())
998 case ast.MapKind:
999 v = uint64(expr.AsMap().Size())
1000 default:
1001 return nil
1002 }
1003 cost := FixedSizeEstimate(v)
1004 return &cost
1005 }
1006
1007 func computeTypeSize(t *types.Type) *SizeEstimate {
1008 if isScalar(t) {
1009 cost := FixedSizeEstimate(1)
1010 return &cost
1011 }
1012 return nil
1013 }
1014
1015 // isScalar returns true if the given type is known to be of a constant size at
1016 // compile time. isScalar will return false for strings (they are variable-width)
1017 // in addition to protobuf.Any and protobuf.Value (their size is not knowable at compile time).
1018 func isScalar(t *types.Type) bool {
1019 switch t.Kind() {
1020 case types.BoolKind, types.DoubleKind, types.DurationKind, types.IntKind, types.TimestampKind, types.UintKind:
1021 return true
1022 case types.OpaqueKind:
1023 if t.TypeName() == "optional_type" {
1024 return isScalar(t.Parameters()[0])
1025 }
1026 }
1027 return false
1028 }
1029
1030 var (
1031 doubleTwoTo64 = math.Ldexp(1.0, 64)
1032
1033 unknownSizeEstimate = SizeEstimate{Min: 0, Max: math.MaxUint64}
1034 unknownCostEstimate = unknownSizeEstimate.MultiplyByCostFactor(1)
1035
1036 selectAndIdentCost = FixedCostEstimate(common.SelectAndIdentCost)
1037 constCost = FixedCostEstimate(common.ConstCost)
1038
1039 createListBaseCost = FixedCostEstimate(common.ListCreateBaseCost)
1040 createMapBaseCost = FixedCostEstimate(common.MapCreateBaseCost)
1041 createMessageBaseCost = FixedCostEstimate(common.StructCreateBaseCost)
1042 )