Class: Statsig::Evaluator

Inherits:
Object
  • Object
show all
Defined in:
lib/evaluator.rb

Constant Summary collapse

EXPOSURE_LOGGING_CONDITION_TYPES =
[
  Const::CND_PASS_GATE,
  Const::CND_FAIL_GATE,
  Const::CND_EXPERIMENT_GROUP
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(store, options, persistent_storage_utils, logger = nil) ⇒ Evaluator

Returns a new instance of Evaluator.



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/evaluator.rb', line 35

def initialize(store, options, persistent_storage_utils, logger = nil)
  UAParser.initialize_async
  CountryLookup.initialize_async

  @spec_store = store
  @gate_overrides = {}
  @config_overrides = {}
  @experiment_overrides = {}
  @options = options
  @persistent_storage_utils = persistent_storage_utils
  @logger = logger
end

Instance Attribute Details

#config_overridesObject

Returns the value of attribute config_overrides.



27
28
29
# File 'lib/evaluator.rb', line 27

def config_overrides
  @config_overrides
end

#experiment_overridesObject

Returns the value of attribute experiment_overrides.



29
30
31
# File 'lib/evaluator.rb', line 29

def experiment_overrides
  @experiment_overrides
end

#gate_overridesObject

Returns the value of attribute gate_overrides.



25
26
27
# File 'lib/evaluator.rb', line 25

def gate_overrides
  @gate_overrides
end

#optionsObject

Returns the value of attribute options.



31
32
33
# File 'lib/evaluator.rb', line 31

def options
  @options
end

#persistent_storage_utilsObject

Returns the value of attribute persistent_storage_utils.



33
34
35
# File 'lib/evaluator.rb', line 33

def persistent_storage_utils
  @persistent_storage_utils
end

#spec_storeObject

Returns the value of attribute spec_store.



23
24
25
# File 'lib/evaluator.rb', line 23

def spec_store
  @spec_store
end

Instance Method Details

#apply_cmab_best_group(cmab, cmab_config, user, end_result) ⇒ Object



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/evaluator.rb', line 319

def apply_cmab_best_group(cmab, cmab_config, user, end_result)
  higher_better = cmab[:higherIsBetter]
  best_score = higher_better ? -1_000_000_000 : 1_000_000_000
  has_score = false
  best_group = nil
  cmab[:groups].each do |group|
    group_id = group[:id]
    config = cmab_config[group_id.to_sym]
    next if config.nil?

    weights_numerical = config[:weightsNumerical]
    weights_categorical = config[:weightsCategorical]

    next if weights_numerical.length.zero? && weights_categorical.length.zero?

    score = 0
    score += config[:alpha] + config[:intercept]

    weights_categorical.each do |key, weights|
      value = get_value_from_user(user, key.to_s)
      next if value.nil?

      if weights.key?(value.to_sym)
        score += weights[value.to_sym]
      end
    end

    weights_numerical.each do |key, weight|
      value = get_value_from_user(user, key.to_s)
      if value.is_a?(Numeric)
        score += weight * value
      end
    end
    if !has_score || (higher_better && score > best_score) || (!higher_better && score < best_score)
      best_score = score
      best_group = group
    end
    has_score = true
  end
  if best_group.nil?
    best_group = cmab[:groups][Random.rand(cmab[:groups].length)]
  end
  end_result.json_value = best_group[:parameterValues]
  end_result.rule_id = best_group[:id]
  end_result.group_name = best_group[:name]
  end_result.is_experiment_group = true
end

#apply_cmab_sampling(cmab, cmab_config, end_result) ⇒ Object



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/evaluator.rb', line 367

def apply_cmab_sampling(cmab, cmab_config, end_result)
  total_records = 0.0
  cmab[:groups].each do |group|
    group_id = group[:id]
    config = cmab_config[group_id.to_sym]
    cur_count = 1.0
    unless config.nil?
      cur_count += config[:records]
    end
    total_records += 1.0 / cur_count
  end

  sum = 0.0
  value = Random.rand
  cmab[:groups].each do |group|
    group_id = group[:id]
    config = cmab_config[group_id.to_sym]
    cur_count = 1.0
    unless config.nil?
      cur_count += config[:records]
    end
    sum += 1.0 / cur_count / total_records
    next unless value < sum

    end_result.json_value = group[:parameterValues]
    end_result.rule_id = group[:id] + Const::EXPLORE
    end_result.group_name = group[:name]
    end_result.is_experiment_group = true
    return true
  end
  false
end

#check_gate(user, gate_name, end_result, ignore_local_overrides: false, is_nested: false) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/evaluator.rb', line 143

def check_gate(user, gate_name, end_result, ignore_local_overrides: false, is_nested: false)
  unless ignore_local_overrides
    local_override = lookup_gate_override(gate_name)
    unless local_override.nil?
      end_result.gate_value = local_override.gate_value
      end_result.rule_id = local_override.rule_id
      unless end_result.disable_evaluation_details
        end_result.evaluation_details = local_override.evaluation_details
      end
      return
    end
  end

  if @spec_store.init_reason == EvaluationReason::UNINITIALIZED
    end_result.gate_value = false
    unless end_result.disable_evaluation_details
      end_result.evaluation_details = EvaluationDetails.uninitialized
    end
    return
  end

  unless @spec_store.has_gate?(gate_name)
    if try_apply_config_mapping(gate_name, user, end_result, Const::TYPE_FEATURE_GATE, Const::EMPTY_STR)
      return
    end

    unsupported_or_unrecognized(gate_name, end_result)
    return
  end

  spec = @spec_store.get_gate(gate_name)
  if try_apply_config_mapping(gate_name, user, end_result, spec[:entity], spec[:salt])
    return
  end

  eval_spec(gate_name, user, spec, end_result, is_nested: is_nested)
end

#clear_config_overridesObject



543
544
545
# File 'lib/evaluator.rb', line 543

def clear_config_overrides
  @config_overrides.clear
end

#clear_experiment_overridesObject



574
575
576
# File 'lib/evaluator.rb', line 574

def clear_experiment_overrides
  @experiment_overrides.clear
end

#clear_gate_overridesObject



531
532
533
# File 'lib/evaluator.rb', line 531

def clear_gate_overrides
  @gate_overrides.clear
end

#eval_cmab(config_name, user, end_result) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/evaluator.rb', line 257

def eval_cmab(config_name, user, end_result)
  return false unless @spec_store.has_cmab_config?(config_name)

  cmab = @spec_store.get_cmab_config(config_name)

  if !cmab[:enabled] || cmab[:groups].length.zero?
    end_result.rule_id = Const::PRESTART
    end_result.json_value = cmab[:defaultValue]
    finalize_cmab_eval_result(cmab, end_result, did_pass: false)
    return true
  end

  targeting_gate = cmab[:targetingGateName]
  unless targeting_gate.nil?
    check_gate(user, targeting_gate, end_result, is_nested: true)

    gate_value = end_result.gate_value

    unless end_result.disable_exposures
      new_exposure = {
        gate: targeting_gate,
        gateValue: gate_value ? Const::TRUE : Const::FALSE,
        ruleID: end_result.rule_id
      }
      end_result.secondary_exposures.append(new_exposure)
    end

    if gate_value == false
      end_result.rule_id = Const::FAILS_TARGETING
      end_result.json_value = cmab[:defaultValue]
      finalize_cmab_eval_result(cmab, end_result, did_pass: false)
      return true
    end
  end

  cmab_config = cmab[:config]
  unit_id = user.get_unit_id(cmab[:idType]) || Const::EMPTY_STR
  salt = cmab[:salt] || config_name
  hash = compute_user_hash("#{salt}.#{unit_id}")

  # If there is no config assign the user to a random group
  if cmab_config.nil?
    group_size = 10_000.0 / cmab[:groups].length
    group = cmab[:groups][(hash % 10_000) / group_size]
    end_result.json_value = group[:parameterValues]
    end_result.rule_id = group[:id] + Const::EXPLORE
    end_result.group_name = group[:name]
    end_result.is_experiment_group = true
    finalize_cmab_eval_result(cmab, end_result, did_pass: true)
    return true
  end

  should_sample = (hash % 10_000) < cmab[:sampleRate] * 10_000
  if should_sample && apply_cmab_sampling(cmab, cmab_config, end_result)
    finalize_cmab_eval_result(cmab, end_result, did_pass: true)
    return true
  end
  apply_cmab_best_group(cmab, cmab_config, user, end_result)
  finalize_cmab_eval_result(cmab, end_result, did_pass: true)
  true
end

#eval_spec(config_name, user, config, end_result, is_nested: false) ⇒ Object



582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# File 'lib/evaluator.rb', line 582

def eval_spec(config_name, user, config, end_result, is_nested: false)
  config[:rules].each do |rule|
    end_result.sampling_rate = rule[:samplingRate]
    eval_rule(user, rule, end_result)

    if end_result.gate_value
      if eval_delegate(config_name, user, rule, end_result)
        finalize_secondary_exposures(end_result)
        return
      end

      pass = eval_pass_percent(user, rule, config[:salt])
      finalize_eval_result(config, end_result, did_pass: pass, rule: rule, is_nested: is_nested)
      return
    end
  end

  finalize_eval_result(config, end_result, did_pass: false, rule: nil, is_nested: is_nested)
end

#get_client_initialize_response(user, hash_algo, client_sdk_key, include_local_overrides) ⇒ Object



462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/evaluator.rb', line 462

def get_client_initialize_response(user, hash_algo, client_sdk_key, include_local_overrides)
  if @spec_store.is_ready_for_checks == false
    return nil
  end
  if @spec_store.last_config_sync_time == 0
    return nil
  end

  evaluated_keys = {}
  if user.user_id.nil? == false
    evaluated_keys[:userID] = user.user_id
  end

  if user.custom_ids.nil? == false
    evaluated_keys[:customIDs] = user.custom_ids
  end
  meta = Statsig.
  {
    feature_gates: Statsig::ResponseFormatter
                     .get_responses(@spec_store.gates, self, user, client_sdk_key, hash_algo, include_local_overrides: include_local_overrides),
    dynamic_configs: Statsig::ResponseFormatter
                       .get_responses(@spec_store.configs, self, user, client_sdk_key, hash_algo, include_local_overrides: include_local_overrides),
    layer_configs: Statsig::ResponseFormatter
                     .get_responses(@spec_store.layers, self, user, client_sdk_key, hash_algo, include_local_overrides: include_local_overrides),
    sdkParams: {},
    has_updates: true,
    generator: Const::STATSIG_RUBY_SDK,
    evaluated_keys: evaluated_keys,
    time: @spec_store.last_config_sync_time,
    hash_used: hash_algo,
    user: user.serialize(true),
    sdkInfo: {sdkType: meta["sdkType"], sdkVersion: meta["sdkVersion"]},
  }
end

#get_config(user, config_name, end_result, user_persisted_values: nil, ignore_local_overrides: false) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/evaluator.rb', line 181

def get_config(user, config_name, end_result, user_persisted_values: nil, ignore_local_overrides: false)
  unless ignore_local_overrides
    local_override = lookup_config_override(config_name)
    unless local_override.nil?
      end_result.id_type = local_override.id_type
      end_result.rule_id = local_override.rule_id
      end_result.json_value = local_override.json_value
      end_result.group_name = local_override.group_name
      end_result.is_experiment_group = local_override.is_experiment_group
      unless end_result.disable_evaluation_details
        end_result.evaluation_details = local_override.evaluation_details
      end
      return
    end
  end

  if @spec_store.init_reason == EvaluationReason::UNINITIALIZED
    unless end_result.disable_evaluation_details
      end_result.evaluation_details = EvaluationDetails.uninitialized
    end
    return
  end

  if eval_cmab(config_name, user, end_result)
    return
  end

  unless @spec_store.has_config?(config_name)
    if try_apply_config_mapping(config_name, user, end_result, Const::TYPE_DYNAMIC_CONFIG, Const::EMPTY_STR)
      return
    end

    unsupported_or_unrecognized(config_name, end_result)
    return
  end

  config = @spec_store.get_config(config_name)

  if try_apply_config_mapping(config_name, user, end_result, config[:entity], config[:salt])
    return
  end

  # If persisted values is provided and the experiment is active, return sticky values if exists.
  if !user_persisted_values.nil? && config[:isActive] == true
    sticky_values = user_persisted_values[config_name]
    unless sticky_values.nil?
      end_result.gate_value = sticky_values[Statsig::Const::GATE_VALUE]
      end_result.json_value = sticky_values[Statsig::Const::JSON_VALUE]
      end_result.rule_id = sticky_values[Statsig::Const::RULE_ID]
      end_result.secondary_exposures = sticky_values[Statsig::Const::SECONDARY_EXPOSURES]
      end_result.group_name = sticky_values[Statsig::Const::GROUP_NAME]
      end_result.id_type = sticky_values[Statsig::Const::ID_TYPE]
      end_result.target_app_ids = sticky_values[Statsig::Const::TARGET_APP_IDS]
      unless end_result.disable_evaluation_details
        end_result.evaluation_details = EvaluationDetails.persisted(
          sticky_values[Statsig::Const::CONFIG_SYNC_TIME],
          sticky_values[Statsig::Const::INIT_TIME]
        )
      end
      return
    end

    # If it doesn't exist, then save to persisted storage if the user was assigned to an experiment group.
    eval_spec(config_name, user, config, end_result)
    if end_result.is_experiment_group
      @persistent_storage_utils.add_evaluation_to_user_persisted_values(user_persisted_values, config_name,
                                                                        end_result)
      @persistent_storage_utils.save_to_storage(user, config[:idType], user_persisted_values)
    end
    # Otherwise, remove from persisted storage
  else
    @persistent_storage_utils.remove_experiment_from_storage(user, config[:idType], config_name)
    eval_spec(config_name, user, config, end_result)
  end
end

#get_layer(user, layer_name, end_result) ⇒ Object



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/evaluator.rb', line 400

def get_layer(user, layer_name, end_result)
  if @spec_store.init_reason == EvaluationReason::UNINITIALIZED
    unless end_result.disable_evaluation_details
      end_result.evaluation_details = EvaluationDetails.uninitialized
    end
    return
  end

  unless @spec_store.has_layer?(layer_name)
    if try_apply_config_mapping(layer_name, user, end_result, Const::LAYER, Const::EMPTY_STR)
      return
    end

    unsupported_or_unrecognized(layer_name, end_result)
    return
  end

  layer = @spec_store.get_layer(layer_name)
  if try_apply_config_mapping(layer_name, user, end_result, layer[:entity], layer[:salt])
    return
  end

  eval_spec(layer_name, user, layer, end_result)
end

#list_autotunesObject



449
450
451
452
453
454
455
456
# File 'lib/evaluator.rb', line 449

def list_autotunes
keys = []
@spec_store.configs.each do |key, value|
  if value[:entity] == Const::TYPE_AUTOTUNE
    keys << key.to_s
  end
end
keys    end

#list_configsObject



429
430
431
432
433
434
435
436
437
# File 'lib/evaluator.rb', line 429

def list_configs
  keys = []
  @spec_store.configs.each do |key, value|
    if value[:entity] == Const::TYPE_DYNAMIC_CONFIG
      keys << key.to_s
    end
  end
  keys
end

#list_experimentsObject



439
440
441
442
443
444
445
446
447
# File 'lib/evaluator.rb', line 439

def list_experiments
  keys = []
  @spec_store.configs.each do |key, value|
    if value[:entity] == Const::TYPE_EXPERIMENT
      keys << key.to_s
    end
  end
  keys
end

#list_gatesObject



425
426
427
# File 'lib/evaluator.rb', line 425

def list_gates
  @spec_store.gates.keys.map(&:to_s)
end

#list_layersObject



458
459
460
# File 'lib/evaluator.rb', line 458

def list_layers
  @spec_store.layers.keys.map(&:to_s)
end

#lookup_config_override(config_name) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/evaluator.rb', line 69

def lookup_config_override(config_name)
  config_name_sym = config_name.to_sym
  if @experiment_overrides.key?(config_name_sym)
    override = @experiment_overrides[config_name_sym]
    return ConfigResult.new(
      name: config_name,
      json_value: override[:value],
      group_name: override[:group_name],
      rule_id: override[:rule_id],
      evaluation_details: EvaluationDetails.local_override(
        @spec_store.last_config_sync_time,
        @spec_store.initial_config_sync_time
      )
    )
  end
  if @config_overrides.key?(config_name_sym)
    override = @config_overrides[config_name_sym]
    return ConfigResult.new(
      name: config_name,
      json_value: override,
      rule_id: Const::OVERRIDE,
      evaluation_details: EvaluationDetails.local_override(
        @spec_store.last_config_sync_time,
        @spec_store.initial_config_sync_time
      )
    )
  end
  nil
end

#lookup_gate_override(gate_name) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/evaluator.rb', line 52

def lookup_gate_override(gate_name)
  gate_name_sym = gate_name.to_sym
  if @gate_overrides.key?(gate_name_sym)
    return ConfigResult.new(
      name: gate_name,
      gate_value: @gate_overrides[gate_name_sym],
      rule_id: Const::OVERRIDE,
      id_type: @spec_store.has_gate?(gate_name) ? @spec_store.get_gate(gate_name)[:idType] : Const::EMPTY_STR,
      evaluation_details: EvaluationDetails.local_override(
        @spec_store.last_config_sync_time,
        @spec_store.initial_config_sync_time
      )
    )
  end
  return nil
end

#maybe_restart_background_threadsObject



48
49
50
# File 'lib/evaluator.rb', line 48

def maybe_restart_background_threads
  @spec_store.maybe_restart_background_threads
end

#override_config(config, value) ⇒ Object



535
536
537
# File 'lib/evaluator.rb', line 535

def override_config(config, value)
  @config_overrides[config.to_sym] = value
end

#override_experiment_by_group_name(experiment_name, group_name) ⇒ Object



547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# File 'lib/evaluator.rb', line 547

def override_experiment_by_group_name(experiment_name, group_name)
  return unless @spec_store.has_config?(experiment_name)

  config = @spec_store.get_config(experiment_name)
  return unless config[:entity] == Const::TYPE_EXPERIMENT

  config[:rules].each do |rule|
    if rule[:groupName] == group_name
      @experiment_overrides[experiment_name.to_sym] = {
        value: rule[:returnValue],
        group_name: rule[:groupName],
        rule_id: rule[:id],
        evaluation_details: EvaluationDetails.local_override(@spec_store.last_config_sync_time, @spec_store.initial_config_sync_time)
      }
      return
    end
  end

  # If no matching rule is found, create a default override with empty value
  @experiment_overrides[experiment_name.to_sym] = {
    value: {},
    group_name: group_name,
    rule_id: "#{experiment_name}:override",
    evaluation_details: EvaluationDetails.local_override(@spec_store.last_config_sync_time, @spec_store.initial_config_sync_time)
  }
end

#override_gate(gate, value) ⇒ Object



523
524
525
# File 'lib/evaluator.rb', line 523

def override_gate(gate, value)
  @gate_overrides[gate.to_sym] = value
end

#remove_config_override(config) ⇒ Object



539
540
541
# File 'lib/evaluator.rb', line 539

def remove_config_override(config)
  @config_overrides.delete(config.to_sym)
end

#remove_experiment_override(experiment_name) ⇒ Object



578
579
580
# File 'lib/evaluator.rb', line 578

def remove_experiment_override(experiment_name)
  @experiment_overrides.delete(experiment_name.to_sym)
end

#remove_gate_override(gate) ⇒ Object



527
528
529
# File 'lib/evaluator.rb', line 527

def remove_gate_override(gate)
  @gate_overrides.delete(gate.to_sym)
end

#shutdownObject



497
498
499
# File 'lib/evaluator.rb', line 497

def shutdown
  @spec_store.shutdown
end

#try_apply_config_mapping(gate_name, user, end_result, type, salt) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/evaluator.rb', line 99

def try_apply_config_mapping(gate_name, user, end_result, type, salt)
  gate_name_sym = gate_name.to_sym
  return false unless @spec_store.overrides.key?(gate_name_sym)

  mapping_list = @spec_store.overrides[gate_name_sym]
  mapping_list.each do |mapping|
    rules = mapping[:rules]
    rules.each do |rule|
      start_time = rule[:start_time]
      if !start_time.nil? && start_time > (Time.now.to_i * 1000)
        next
      end

      rule_name = rule[:rule_name].to_sym
      next unless @spec_store.override_rules.key?(rule_name)

      override_rule = @spec_store.override_rules[rule_name]
      eval_rule(user, override_rule, end_result)
      unless end_result.gate_value
        next
      end

      pass = eval_pass_percent(user, override_rule, salt)
      unless pass
        next
      end

      new_config_name = mapping[:new_config_name]
      end_result.override_config_name = new_config_name
      if type == Const::TYPE_FEATURE_GATE
        check_gate(user, new_config_name, end_result)
      end
      if [Const::TYPE_EXPERIMENT, Const::TYPE_DYNAMIC_CONFIG, Const::TYPE_AUTOTUNE].include?(type)
        get_config(user, new_config_name, end_result)
      end
      if type == Const::TYPE_LAYER
        get_layer(user, new_config_name, end_result)
      end
      return true
    end
  end
  false
end

#unsupported_or_unrecognized(config_name, end_result) ⇒ Object



501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/evaluator.rb', line 501

def unsupported_or_unrecognized(config_name, end_result)
  end_result.rule_id = Const::EMPTY_STR
  end_result.gate_value = false

  if end_result.disable_evaluation_details
    return
  end

  if @spec_store.unsupported_configs.include?(config_name)
    end_result.evaluation_details = EvaluationDetails.unsupported(
      @spec_store.last_config_sync_time,
      @spec_store.initial_config_sync_time
    )
    return
  end

  end_result.evaluation_details = EvaluationDetails.unrecognized(
    @spec_store.last_config_sync_time,
    @spec_store.initial_config_sync_time
  )
end