Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/interpreter/runtimecost.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 "errors"
19 "math"
20
21 "github.com/google/cel-go/common"
22 "github.com/google/cel-go/common/overloads"
23 "github.com/google/cel-go/common/types"
24 "github.com/google/cel-go/common/types/ref"
25 "github.com/google/cel-go/common/types/traits"
26 )
27
28 // WARNING: Any changes to cost calculations in this file require a corresponding change in checker/cost.go
29
30 // ActualCostEstimator provides function call cost estimations at runtime
31 // CallCost returns an estimated cost for the function overload invocation with the given args, or nil if it has no
32 // estimate to provide. CEL attempts to provide reasonable estimates for its standard function library, so CallCost
33 // should typically not need to provide an estimate for CELs standard function.
34 type ActualCostEstimator interface {
35 CallCost(function, overloadID string, args []ref.Val, result ref.Val) *uint64
36 }
37
38 // costTrackPlanOption modifies the cost tracking factory associatied with the CostObserver
39 type costTrackPlanOption func(*costTrackerFactory) *costTrackerFactory
40
41 // CostTrackerFactory configures the factory method to generate a new cost-tracker per-evaluation.
42 func CostTrackerFactory(factory func() (*CostTracker, error)) costTrackPlanOption {
43 return func(fac *costTrackerFactory) *costTrackerFactory {
44 fac.factory = factory
45 return fac
46 }
47 }
48
49 // CostObserver provides an observer that tracks runtime cost.
50 func CostObserver(opts ...costTrackPlanOption) PlannerOption {
51 ct := &costTrackerFactory{}
52 for _, o := range opts {
53 ct = o(ct)
54 }
55 return func(p *planner) (*planner, error) {
56 if ct.factory == nil {
57 return nil, errors.New("cost tracker factory not configured")
58 }
59 p.observers = append(p.observers, ct)
60 p.decorators = append(p.decorators, decObserveEval(ct.Observe))
61 return p, nil
62 }
63 }
64
65 // costTrackerConverter identifies an object which is convertible to a CostTracker instance.
66 type costTrackerConverter interface {
67 asCostTracker() *CostTracker
68 }
69
70 // costTrackActivation hides state in the Activation in a manner not accessible to expressions.
71 type costTrackActivation struct {
72 vars Activation
73 costTracker *CostTracker
74 }
75
76 // ResolveName proxies variable lookups to the backing activation.
77 func (cta costTrackActivation) ResolveName(name string) (any, bool) {
78 return cta.vars.ResolveName(name)
79 }
80
81 // Parent proxies parent lookups to the backing activation.
82 func (cta costTrackActivation) Parent() Activation {
83 return cta.vars
84 }
85
86 // AsPartialActivation supports conversion to a partial activation in order to detect unknown attributes.
87 func (cta costTrackActivation) AsPartialActivation() (PartialActivation, bool) {
88 return AsPartialActivation(cta.vars)
89 }
90
91 // asCostTracker implements the costTrackerConverter method.
92 func (cta costTrackActivation) asCostTracker() *CostTracker {
93 return cta.costTracker
94 }
95
96 // asCostTracker walks the Activation hierarchy and returns the first cost tracker found, if present.
97 func asCostTracker(vars Activation) (*CostTracker, bool) {
98 if conv, ok := vars.(costTrackerConverter); ok {
99 return conv.asCostTracker(), true
100 }
101 if vars.Parent() != nil {
102 return asCostTracker(vars.Parent())
103 }
104 return nil, false
105 }
106
107 // costTrackerFactory holds a factory for producing new CostTracker instances on each Eval call.
108 type costTrackerFactory struct {
109 factory func() (*CostTracker, error)
110 }
111
112 // InitState produces a CostTracker and bundles it into an Activation in a way which is not visible
113 // to expression evaluation.
114 func (ct *costTrackerFactory) InitState(vars Activation) (Activation, error) {
115 tracker, err := ct.factory()
116 if err != nil {
117 return nil, err
118 }
119 return costTrackActivation{vars: vars, costTracker: tracker}, nil
120 }
121
122 // GetState extracts the CostTracker from the Activation.
123 func (ct *costTrackerFactory) GetState(vars Activation) any {
124 if tracker, found := asCostTracker(vars); found {
125 return tracker
126 }
127 return nil
128 }
129
130 // Observe computes the incremental cost of each step and records it into the CostTracker associated
131 // with the evaluation.
132 func (ct *costTrackerFactory) Observe(vars Activation, id int64, programStep any, val ref.Val) {
133 tracker, found := asCostTracker(vars)
134 if !found {
135 return
136 }
137 switch t := programStep.(type) {
138 case ConstantQualifier:
139 // TODO: Push identifiers on to the stack before observing constant qualifiers that apply to them
140 // and enable the below pop. Once enabled this can case can be collapsed into the Qualifier case.
141 tracker.cost++
142 case InterpretableConst:
143 // zero cost
144 case InterpretableAttribute:
145 switch a := t.Attr().(type) {
146 case *conditionalAttribute:
147 // Ternary has no direct cost. All cost is from the conditional and the true/false branch expressions.
148 tracker.stack.drop(a.falsy.ID(), a.truthy.ID(), a.expr.ID())
149 default:
150 tracker.stack.drop(t.Attr().ID())
151 tracker.cost += common.SelectAndIdentCost
152 }
153 if !tracker.presenceTestHasCost {
154 if _, isTestOnly := programStep.(*evalTestOnly); isTestOnly {
155 tracker.cost -= common.SelectAndIdentCost
156 }
157 }
158 case *evalExhaustiveConditional:
159 // Ternary has no direct cost. All cost is from the conditional and the true/false branch expressions.
160 tracker.stack.drop(t.attr.falsy.ID(), t.attr.truthy.ID(), t.attr.expr.ID())
161
162 // While the field names are identical, the boolean operation eval structs do not share an interface and so
163 // must be handled individually.
164 case *evalOr:
165 for _, term := range t.terms {
166 tracker.stack.drop(term.ID())
167 }
168 case *evalAnd:
169 for _, term := range t.terms {
170 tracker.stack.drop(term.ID())
171 }
172 case *evalExhaustiveOr:
173 for _, term := range t.terms {
174 tracker.stack.drop(term.ID())
175 }
176 case *evalExhaustiveAnd:
177 for _, term := range t.terms {
178 tracker.stack.drop(term.ID())
179 }
180 case *evalFold:
181 tracker.stack.drop(t.iterRange.ID())
182 case Qualifier:
183 tracker.cost++
184 case InterpretableCall:
185 if argVals, ok := tracker.stack.dropArgs(t.Args()); ok {
186 tracker.cost += tracker.costCall(t, argVals, val)
187 }
188 case InterpretableConstructor:
189 tracker.stack.dropArgs(t.InitVals())
190 switch t.Type() {
191 case types.ListType:
192 tracker.cost += common.ListCreateBaseCost
193 case types.MapType:
194 tracker.cost += common.MapCreateBaseCost
195 default:
196 tracker.cost += common.StructCreateBaseCost
197 }
198 }
199 tracker.stack.push(val, id)
200
201 if tracker.Limit != nil && tracker.cost > *tracker.Limit {
202 panic(EvalCancelledError{Cause: CostLimitExceeded, Message: "operation cancelled: actual cost limit exceeded"})
203 }
204 }
205
206 // CostTrackerOption configures the behavior of CostTracker objects.
207 type CostTrackerOption func(*CostTracker) error
208
209 // CostTrackerLimit sets the runtime limit on the evaluation cost during execution and will terminate the expression
210 // evaluation if the limit is exceeded.
211 func CostTrackerLimit(limit uint64) CostTrackerOption {
212 return func(tracker *CostTracker) error {
213 tracker.Limit = &limit
214 return nil
215 }
216 }
217
218 // PresenceTestHasCost determines whether presence testing has a cost of one or zero.
219 // Defaults to presence test has a cost of one.
220 func PresenceTestHasCost(hasCost bool) CostTrackerOption {
221 return func(tracker *CostTracker) error {
222 tracker.presenceTestHasCost = hasCost
223 return nil
224 }
225 }
226
227 // NewCostTracker creates a new CostTracker with a given estimator and a set of functional CostTrackerOption values.
228 func NewCostTracker(estimator ActualCostEstimator, opts ...CostTrackerOption) (*CostTracker, error) {
229 tracker := &CostTracker{
230 Estimator: estimator,
231 overloadTrackers: map[string]FunctionTracker{},
232 presenceTestHasCost: true,
233 }
234 for _, opt := range opts {
235 err := opt(tracker)
236 if err != nil {
237 return nil, err
238 }
239 }
240 return tracker, nil
241 }
242
243 // OverloadCostTracker binds an overload ID to a runtime FunctionTracker implementation.
244 //
245 // OverloadCostTracker instances augment or override ActualCostEstimator decisions, allowing for versioned and/or
246 // optional cost tracking changes.
247 func OverloadCostTracker(overloadID string, fnTracker FunctionTracker) CostTrackerOption {
248 return func(tracker *CostTracker) error {
249 tracker.overloadTrackers[overloadID] = fnTracker
250 return nil
251 }
252 }
253
254 // FunctionTracker computes the actual cost of evaluating the functions with the given arguments and result.
255 type FunctionTracker func(args []ref.Val, result ref.Val) *uint64
256
257 // CostTracker represents the information needed for tracking runtime cost.
258 type CostTracker struct {
259 Estimator ActualCostEstimator
260 overloadTrackers map[string]FunctionTracker
261 Limit *uint64
262 presenceTestHasCost bool
263
264 cost uint64
265 stack refValStack
266 }
267
268 // ActualCost returns the runtime cost
269 func (c *CostTracker) ActualCost() uint64 {
270 return c.cost
271 }
272
273 func (c *CostTracker) costCall(call InterpretableCall, args []ref.Val, result ref.Val) uint64 {
274 var cost uint64
275 if len(c.overloadTrackers) != 0 {
276 if tracker, found := c.overloadTrackers[call.OverloadID()]; found {
277 callCost := tracker(args, result)
278 if callCost != nil {
279 cost += *callCost
280 return cost
281 }
282 }
283 }
284 if c.Estimator != nil {
285 callCost := c.Estimator.CallCost(call.Function(), call.OverloadID(), args, result)
286 if callCost != nil {
287 cost += *callCost
288 return cost
289 }
290 }
291 // if user didn't specify, the default way of calculating runtime cost would be used.
292 // if user has their own implementation of ActualCostEstimator, make sure to cover the mapping between overloadId and cost calculation
293 switch call.OverloadID() {
294 // O(n) functions
295 case overloads.StartsWithString, overloads.EndsWithString, overloads.StringToBytes, overloads.BytesToString, overloads.ExtQuoteString, overloads.ExtFormatString:
296 cost += uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor))
297 case overloads.InList:
298 // If a list is composed entirely of constant values this is O(1), but we don't account for that here.
299 // We just assume all list containment checks are O(n).
300 cost += actualSize(args[1])
301 // O(min(m, n)) functions
302 case overloads.LessString, overloads.GreaterString, overloads.LessEqualsString, overloads.GreaterEqualsString,
303 overloads.LessBytes, overloads.GreaterBytes, overloads.LessEqualsBytes, overloads.GreaterEqualsBytes,
304 overloads.Equals, overloads.NotEquals:
305 // When we check the equality of 2 scalar values (e.g. 2 integers, 2 floating-point numbers, 2 booleans etc.),
306 // the CostTracker.ActualSize() function by definition returns 1 for each operand, resulting in an overall cost
307 // of 1.
308 lhsSize := actualSize(args[0])
309 rhsSize := actualSize(args[1])
310 minSize := lhsSize
311 if rhsSize < minSize {
312 minSize = rhsSize
313 }
314 cost += uint64(math.Ceil(float64(minSize) * common.StringTraversalCostFactor))
315 // O(m+n) functions
316 case overloads.AddString, overloads.AddBytes:
317 // In the worst case scenario, we would need to reallocate a new backing store and copy both operands over.
318 cost += uint64(math.Ceil(float64(actualSize(args[0])+actualSize(args[1])) * common.StringTraversalCostFactor))
319 // O(nm) functions
320 case overloads.MatchesString:
321 // https://swtch.com/~rsc/regexp/regexp1.html applies to RE2 implementation supported by CEL
322 // Add one to string length for purposes of cost calculation to prevent product of string and regex to be 0
323 // in case where string is empty but regex is still expensive.
324 strCost := uint64(math.Ceil((1.0 + float64(actualSize(args[0]))) * common.StringTraversalCostFactor))
325 // We don't know how many expressions are in the regex, just the string length (a huge
326 // improvement here would be to somehow get a count the number of expressions in the regex or
327 // how many states are in the regex state machine and use that to measure regex cost).
328 // For now, we're making a guess that each expression in a regex is typically at least 4 chars
329 // in length.
330 regexCost := uint64(math.Ceil(float64(actualSize(args[1])) * common.RegexStringLengthCostFactor))
331 cost += strCost * regexCost
332 case overloads.ContainsString:
333 strCost := uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor))
334 substrCost := uint64(math.Ceil(float64(actualSize(args[1])) * common.StringTraversalCostFactor))
335 cost += strCost * substrCost
336
337 default:
338 // The following operations are assumed to have O(1) complexity.
339 // - AddList due to the implementation. Index lookup can be O(c) the
340 // number of concatenated lists, but we don't track that is cost calculations.
341 // - Conversions, since none perform a traversal of a type of unbound length.
342 // - Computing the size of strings, byte sequences, lists and maps.
343 // - Logical operations and all operators on fixed width scalars (comparisons, equality)
344 // - Any functions that don't have a declared cost either here or in provided ActualCostEstimator.
345 cost++
346
347 }
348 return cost
349 }
350
351 // actualSize returns the size of the value for all traits.Sizer values, a fixed size for all proto-based
352 // objects, and a size of 1 for all other value types.
353 func actualSize(value ref.Val) uint64 {
354 if sz, ok := value.(traits.Sizer); ok {
355 return uint64(sz.Size().(types.Int))
356 }
357 if opt, ok := value.(*types.Optional); ok && opt.HasValue() {
358 return actualSize(opt.GetValue())
359 }
360 return 1
361 }
362
363 type stackVal struct {
364 Val ref.Val
365 ID int64
366 }
367
368 // refValStack keeps track of values of the stack for cost calculation purposes
369 type refValStack []stackVal
370
371 func (s *refValStack) push(val ref.Val, id int64) {
372 value := stackVal{Val: val, ID: id}
373 *s = append(*s, value)
374 }
375
376 // TODO: Allowing drop and dropArgs to remove stack items above the IDs they are provided is a workaround. drop and dropArgs
377 // should find and remove only the stack items matching the provided IDs once all attributes are properly pushed and popped from stack.
378
379 // drop searches the stack for each ID and removes the ID and all stack items above it.
380 // If none of the IDs are found, the stack is not modified.
381 // WARNING: It is possible for multiple expressions with the same ID to exist (due to how macros are implemented) so it's
382 // possible that a dropped ID will remain on the stack. They should be removed when IDs on the stack are popped.
383 func (s *refValStack) drop(ids ...int64) {
384 for _, id := range ids {
385 for idx := len(*s) - 1; idx >= 0; idx-- {
386 if (*s)[idx].ID == id {
387 *s = (*s)[:idx]
388 break
389 }
390 }
391 }
392 }
393
394 // dropArgs searches the stack for all the args by their IDs, accumulates their associated ref.Vals and drops any
395 // stack items above any of the arg IDs. If any of the IDs are not found the stack, false is returned.
396 // Args are assumed to be found in the stack in reverse order, i.e. the last arg is expected to be found highest in
397 // the stack.
398 // WARNING: It is possible for multiple expressions with the same ID to exist (due to how macros are implemented) so it's
399 // possible that a dropped ID will remain on the stack. They should be removed when IDs on the stack are popped.
400 func (s *refValStack) dropArgs(args []Interpretable) ([]ref.Val, bool) {
401 result := make([]ref.Val, len(args))
402 argloop:
403 for nIdx := len(args) - 1; nIdx >= 0; nIdx-- {
404 for idx := len(*s) - 1; idx >= 0; idx-- {
405 if (*s)[idx].ID == args[nIdx].ID() {
406 el := (*s)[idx]
407 *s = (*s)[:idx]
408 result[nIdx] = el.Val
409 continue argloop
410 }
411 }
412 return nil, false
413 }
414 return result, true
415 }