absmartly-sdk 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +2 -1
  3. data/CHANGELOG.md +52 -1
  4. data/Gemfile +4 -0
  5. data/Gemfile.lock +5 -1
  6. data/README.md +463 -145
  7. data/lib/a_b_smartly.rb +118 -22
  8. data/lib/absmartly/version.rb +1 -1
  9. data/lib/absmartly.rb +4 -0
  10. data/lib/audience_matcher.rb +93 -1
  11. data/lib/client.rb +44 -12
  12. data/lib/client_config.rb +3 -1
  13. data/lib/context.rb +1288 -236
  14. data/lib/context_data_result.rb +27 -0
  15. data/lib/context_event_logger.rb +3 -0
  16. data/lib/context_event_logger_callback.rb +1 -1
  17. data/lib/context_publisher.rb +9 -0
  18. data/lib/default_audience_deserializer.rb +2 -2
  19. data/lib/default_context_data_deserializer.rb +3 -3
  20. data/lib/default_context_event_serializer.rb +2 -1
  21. data/lib/default_context_publisher.rb +9 -0
  22. data/lib/default_http_client.rb +26 -5
  23. data/lib/default_http_client_config.rb +6 -1
  24. data/lib/default_variable_parser.rb +1 -1
  25. data/lib/hashing.rb +39 -2
  26. data/lib/json/context_data.rb +26 -3
  27. data/lib/json/experiment.rb +36 -10
  28. data/lib/json/exposure.rb +8 -4
  29. data/lib/json_expr/expr_evaluator.rb +7 -9
  30. data/lib/json_expr/json_expr.rb +23 -17
  31. data/lib/json_expr/operators/and_combinator.rb +2 -1
  32. data/lib/json_expr/operators/in_operator.rb +3 -1
  33. data/lib/json_expr/operators/match_operator.rb +9 -5
  34. data/lib/json_expr/operators/or_combinator.rb +4 -2
  35. data/lib/json_expr/operators/semver_operator.rb +17 -0
  36. data/lib/json_expr/operators/semver_operators.rb +50 -0
  37. data/lib/json_expr/semver_comparator.rb +98 -0
  38. data/lib/publish_error.rb +11 -0
  39. data/lib/scheduled_thread_pool_executor.rb +8 -0
  40. data/lib/type_utils.rb +59 -0
  41. data/lib/variant_assigner.rb +1 -1
  42. metadata +10 -4
  43. data/absmartly.gemspec +0 -45
  44. data/example/example.rb +0 -85
data/lib/context.rb CHANGED
@@ -1,7 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # Fiber.current and Fiber#alive? before Ruby 3.1.
4
+ require "fiber"
3
5
  require_relative "hashing"
6
+ require_relative "type_utils"
4
7
  require_relative "variant_assigner"
8
+ require_relative "audience_matcher"
9
+ require_relative "default_audience_deserializer"
5
10
  require_relative "context_event_logger"
6
11
  require_relative "json/unit"
7
12
  require_relative "json/attribute"
@@ -10,47 +15,48 @@ require_relative "json/publish_event"
10
15
  require_relative "json/goal_achievement"
11
16
 
12
17
  class Context
13
- attr_reader :data, :pending_count
18
+ # Immutable-by-convention snapshot swapped in with a single assignment so
19
+ # readers see either the complete old or the complete new state.
20
+ State = Struct.new(:data, :index, :index_variables, :custom_fields)
21
+ NO_RULES = ""
22
+ SEAL_FLUSH_PASSES = 2
23
+ private_constant :SEAL_FLUSH_PASSES
24
+ class EventsQueuedWhileClosing < StandardError; end
25
+ private_constant :EventsQueuedWhileClosing
26
+ NO_HOLDOUTS = {}.freeze
27
+ private_constant :NO_HOLDOUTS
28
+ # After this many overtaken walks a read returns the default, exposing nothing.
29
+ VARIABLE_WALK_ATTEMPTS = 3
30
+ private_constant :VARIABLE_WALK_ATTEMPTS
31
+
32
+ attr_reader :pending_count
14
33
 
15
34
  def self.create(clock, config, data_future, data_provider,
16
- event_handler, event_logger, variable_parser, audience_matcher)
35
+ event_handler, event_logger, variable_parser, audience_matcher,
36
+ application: nil, environment: nil)
17
37
  Context.new(clock, config, data_future, data_provider,
18
- event_handler, event_logger, variable_parser, audience_matcher)
38
+ event_handler, event_logger, variable_parser, audience_matcher,
39
+ application: application, environment: environment)
40
+ end
41
+
42
+ def self.create_async(clock, config, data_provider,
43
+ event_handler, event_logger, variable_parser, audience_matcher,
44
+ application: nil, environment: nil)
45
+ context = Context.allocate
46
+ context.send(:initialize_async, clock, config, data_provider,
47
+ event_handler, event_logger, variable_parser, audience_matcher,
48
+ application: application, environment: environment)
49
+ context
19
50
  end
20
51
 
21
52
  def initialize(clock, config, data_future, data_provider,
22
- event_handler, event_logger, variable_parser, audience_matcher)
23
- @index = []
24
- @context_custom_fields = {}
25
- @achievements = []
26
- @assignment_cache = {}
27
- @assignments = {}
28
- @clock = clock.is_a?(String) ? Time.iso8601(clock) : clock
29
- @publish_delay = config.publish_delay
30
- @refresh_interval = config.refresh_interval
31
- @event_handler = event_handler
32
- @event_logger = !config.event_logger.nil? ? config.event_logger : event_logger
33
- @data_provider = data_provider
34
- @variable_parser = variable_parser
35
- @audience_matcher = audience_matcher
36
- @closed = false
37
-
38
- @units = {}
39
- @attributes = []
40
- @overrides = {}
41
- @cassignments = {}
42
- @assigners = {}
43
- @hashed_units = {}
44
- @pending_count = 0
45
- @exposures ||= []
46
- @attrs_seq = 0
53
+ event_handler, event_logger, variable_parser, audience_matcher,
54
+ application: nil, environment: nil)
55
+ init_common(clock, config, data_provider, event_handler, event_logger,
56
+ variable_parser, audience_matcher, application, environment)
47
57
 
48
- set_units(config.units) if config.units
49
- set_attributes(config.attributes) if config.attributes
50
- set_overrides(config.overrides) if config.overrides
51
- set_custom_assignments(config.custom_assignments) if config.custom_assignments
52
58
  if data_future.success?
53
- assign_data(data_future.data_future)
59
+ @state = build_state(data_future.data_future)
54
60
  log_event(ContextEventLogger::EVENT_TYPE::READY, data_future.data_future)
55
61
  else
56
62
  set_data_failed(data_future.exception)
@@ -58,8 +64,58 @@ class Context
58
64
  end
59
65
  end
60
66
 
67
+ def set_data(data_future)
68
+ ready_data = nil
69
+ failure = nil
70
+ # Skip building a payload a refresh has already superseded; ready? is
71
+ # rechecked under the lock before a built snapshot is installed.
72
+ state = data_future.success? && !ready? ? build_state(data_future.data_future) : nil
73
+ @ready_mutex.synchronize do
74
+ # A refresh may already have installed data while the initial fetch was
75
+ # in flight: keep it, so a late success doesn't replace newer data and
76
+ # a late failure is only logged.
77
+ if ready?
78
+ failure = data_future.exception unless data_future.success?
79
+ elsif state
80
+ @state = state
81
+ else
82
+ failure = data_future.exception
83
+ set_data_failed(failure)
84
+ end
85
+ ready_data = @state.data unless @failed
86
+ @ready_condvar.broadcast
87
+ end
88
+
89
+ # User callbacks run outside the readiness lock so they may call
90
+ # wait_until_ready.
91
+ log_error(failure) unless failure.nil?
92
+ log_event(ContextEventLogger::EVENT_TYPE::READY, ready_data) unless ready_data.nil?
93
+ end
94
+
95
+ def wait_until_ready(timeout = nil)
96
+ # Called from a variable parser while this thread builds the data that
97
+ # would make the context ready: waiting here could never finish.
98
+ return self if building?
99
+
100
+ @ready_mutex.synchronize do
101
+ unless ready? || failed?
102
+ if timeout
103
+ deadline = Time.now + timeout
104
+ until ready? || failed?
105
+ remaining = deadline - Time.now
106
+ break if remaining <= 0
107
+ @ready_condvar.wait(@ready_mutex, remaining)
108
+ end
109
+ else
110
+ @ready_condvar.wait(@ready_mutex) until ready? || failed?
111
+ end
112
+ end
113
+ end
114
+ self
115
+ end
116
+
61
117
  def ready?
62
- !@data.nil?
118
+ !@state.data.nil?
63
119
  end
64
120
 
65
121
  def failed?
@@ -70,20 +126,51 @@ class Context
70
126
  @closed
71
127
  end
72
128
 
129
+ def finalized?
130
+ closed?
131
+ end
132
+
133
+ def finalizing?
134
+ !@closed && @sealing.positive?
135
+ end
136
+
137
+ attr_reader :ready_error
138
+
139
+ def get_unit(unit_type)
140
+ @units[unit_type.to_sym]
141
+ end
142
+
143
+ def get_units
144
+ @units.dup
145
+ end
146
+
147
+ def get_attribute(name)
148
+ result = nil
149
+ @attributes.each do |attr|
150
+ result = attr.value if attr.name == name
151
+ end
152
+ result
153
+ end
154
+
155
+ def get_attributes
156
+ user_attributes
157
+ end
158
+
73
159
  def experiments
74
- check_ready?(true)
160
+ check_ready?(false)
161
+ check_not_closed_by_close?
75
162
 
76
- @data.experiments.map(&:name)
163
+ @state.data.experiments.map(&:name)
77
164
  end
78
165
 
79
166
  def set_override(experiment_name, variant)
80
- check_not_closed?
167
+ check_not_closed_by_close?
81
168
 
82
169
  @overrides[experiment_name.to_s.to_sym] = variant
83
170
  end
84
171
 
85
172
  def set_overrides(overrides)
86
- check_not_closed?
173
+ check_not_closed_by_close?
87
174
 
88
175
  @overrides.merge!(overrides.transform_keys(&:to_sym))
89
176
  end
@@ -115,17 +202,30 @@ class Context
115
202
  def set_unit(unit_type, uid)
116
203
  check_not_closed?
117
204
 
205
+ if Absmartly::TypeUtils.numeric?(uid)
206
+ trimmed = uid
207
+ else
208
+ # Like v1.3.0, any other value (Symbol, session id, UUID object) is
209
+ # stored as its to_s text.
210
+ uid = uid.respond_to?(:to_str) ? uid.to_str : uid.to_s
211
+ trimmed = uid.strip
212
+ end
213
+
118
214
  previous = @units[unit_type.to_sym]
119
- if !previous.nil? && previous != uid
215
+ # Compared as text, so 123456 and "123456" are the same unit, as in v1.3.0.
216
+ if !previous.nil? && previous.to_s != trimmed.to_s
120
217
  raise IllegalStateException.new("Unit '#{unit_type}' already set.")
121
218
  end
122
219
 
123
- trimmed = uid.to_s.strip
124
- if trimmed.empty?
220
+ if trimmed.is_a?(String) && trimmed.empty?
125
221
  raise IllegalStateException.new("Unit '#{unit_type}' UID must not be blank.")
126
222
  end
127
223
 
128
- @units[unit_type] = trimmed
224
+ if previous.nil?
225
+ @units[unit_type.to_sym] = trimmed
226
+ invalidate_assignments_missing_unit(unit_type.to_s)
227
+ end
228
+ trimmed.to_s
129
229
  end
130
230
 
131
231
  def set_units(units)
@@ -149,35 +249,23 @@ class Context
149
249
 
150
250
  def treatment(experiment_name)
151
251
  check_ready?(true)
152
- assignment = assignment(experiment_name)
153
- unless assignment.exposed
154
- queue_exposure(assignment)
155
- end
156
252
 
157
- assignment.variant
253
+ while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path
254
+ assignment = assignment(experiment_name)
255
+ # set_unit may evict it between the lookup and the exposure claim:
256
+ # then it is resolved again, so the variant served is the one exposed.
257
+ return assignment.variant unless claim_and_queue_exposure(assignment, experiment_name) == :evicted
258
+ end
158
259
  end
159
260
 
261
+ # A held-out experiment publishes no exposure of its own, unless an override
262
+ # or rule chose its variant. The holdouts covering it then expose once each,
263
+ # in id order, from the arms pinned when the assignment was made, so a
264
+ # refresh in between can't publish another holdout epoch (as in JS).
160
265
  def queue_exposure(assignment)
161
- unless assignment.exposed
162
- assignment.exposed = true
163
-
164
- exposure = Exposure.new
165
- exposure.id = assignment.id || 0
166
- exposure.name = assignment.name
167
- exposure.unit = assignment.unit_type
168
- exposure.variant = assignment.variant
169
- exposure.exposed_at = @clock.to_i
170
- exposure.assigned = assignment.assigned
171
- exposure.eligible = assignment.eligible
172
- exposure.overridden = assignment.overridden
173
- exposure.full_on = assignment.full_on
174
- exposure.custom = assignment.custom
175
- exposure.audience_mismatch = assignment.audience_mismatch
176
-
177
- @pending_count += 1
178
- @exposures.push(exposure)
179
- log_event(ContextEventLogger::EVENT_TYPE::EXPOSURE, exposure)
180
- end
266
+ result = nil
267
+ claim_and_queue_exposure(assignment) { |logged| result = logged }
268
+ result
181
269
  end
182
270
 
183
271
  def peek_treatment(experiment_name)
@@ -188,31 +276,40 @@ class Context
188
276
 
189
277
  alias peek peek_treatment
190
278
 
279
+ # Maps each variable key to one experiment name, as in v1.3.0: the
280
+ # lowest-id experiment defining it, which is not necessarily the one whose
281
+ # value variable_value returns (see variable_keys_list).
191
282
  def variable_keys
192
283
  check_ready?(true)
193
284
 
194
285
  hsh = {}
195
- @index_variables.each { |key, value| hsh[key] = value.data.name }
286
+ @state.index_variables.each { |key, values| hsh[key] = values.first.data.name }
196
287
  hsh
197
288
  end
198
289
 
199
- def variable_value(key, default_value)
290
+ # Maps each variable key to the names of every experiment that defines it.
291
+ def variable_keys_list
200
292
  check_ready?(true)
201
293
 
202
- assignment = variable_assignment(key)
203
- unless assignment.nil? || assignment.variables.nil?
204
- queue_exposure(assignment) unless assignment.exposed
205
- return assignment.variables[key.to_s.to_sym] if assignment.variables.key?(key.to_s.to_sym)
294
+ hsh = {}
295
+ @state.index_variables.each do |key, values|
296
+ hsh[key] = values.map { |v| v.data.name }
206
297
  end
298
+ hsh
299
+ end
300
+
301
+ def variable_value(key, default_value)
302
+ check_ready?(true)
207
303
 
208
- default_value
304
+ resolve_variable_value(key, default_value, true)
209
305
  end
210
306
 
211
307
  def custom_field_keys
212
308
  check_ready?(true)
309
+
213
310
  keys = []
214
311
 
215
- @data.experiments.each do |experiment|
312
+ @state.data.experiments.each do |experiment|
216
313
  custom_field_values = experiment.custom_field_values
217
314
  if custom_field_values != nil
218
315
  custom_field_values.each do |custom_field|
@@ -221,60 +318,54 @@ class Context
221
318
  end
222
319
  end
223
320
 
224
- return keys.sort.uniq
321
+ keys.sort.uniq
225
322
  end
226
323
 
227
324
  def custom_field_value(experimentName, key)
228
- check_ready?(true)
229
-
230
- experiment_custom_fields = @context_custom_fields[experimentName]
231
-
232
- if experiment_custom_fields != nil
233
- field = experiment_custom_fields[key]
234
- if field != nil
235
- return field.value
236
- end
237
- end
325
+ custom_field(experimentName, key)&.value
326
+ end
238
327
 
239
- return nil
328
+ def custom_field_value_type(experimentName, key)
329
+ custom_field(experimentName, key)&.type
240
330
  end
241
331
 
242
332
  def custom_field_type(experimentName, key)
243
- check_ready?(true)
244
-
245
- experiment_custom_fields = @context_custom_fields[experimentName]
246
-
247
- if experiment_custom_fields != nil
248
- field = experiment_custom_fields[key]
249
- if field != nil
250
- return field.type
251
- end
252
- end
253
-
254
- return nil
333
+ custom_field_value_type(experimentName, key)
255
334
  end
256
335
 
257
336
  def peek_variable_value(key, default_value)
258
337
  check_ready?(true)
259
338
 
260
- assignment = variable_assignment(key)
261
- return assignment.variables[key.to_s.to_sym] if !assignment.nil? &&
262
- !assignment.variables.nil? &&
263
- assignment.variables.key?(key.to_s.to_sym)
264
-
265
- default_value
339
+ resolve_variable_value(key, default_value, false)
266
340
  end
267
341
 
268
- def track(goal_name, properties)
342
+ def track(goal_name, properties = nil)
269
343
  check_not_closed?
344
+ # Hash-like objects such as ActionController::Parameters are accepted
345
+ # through to_unsafe_h or to_h, as v1.3.0 accepted any properties object.
346
+ # to_unsafe_h comes first because Parameters#to_h raises unless permitted.
347
+ if !properties.nil? && !Absmartly::TypeUtils.object?(properties) && !properties.is_a?(Array)
348
+ if properties.respond_to?(:to_unsafe_h)
349
+ properties = properties.to_unsafe_h
350
+ elsif properties.respond_to?(:to_h)
351
+ properties = properties.to_h
352
+ end
353
+ end
354
+ unless properties.nil? || Absmartly::TypeUtils.object?(properties)
355
+ raise ArgumentError, "Goal '#{goal_name}' properties must be of type object."
356
+ end
270
357
 
271
358
  achievement = GoalAchievement.new
272
359
  achievement.achieved_at = @clock.to_i
273
360
  achievement.name = goal_name
274
- achievement.properties = properties
361
+ achievement.properties = properties.nil? ? nil : properties.dup
362
+
363
+ @queue_mutex.synchronize do
364
+ check_not_closed?
275
365
 
276
- @pending_count += 1
277
- @achievements.push(achievement)
366
+ @pending_count += 1
367
+ @achievements.push(achievement)
368
+ end
278
369
  log_event(ContextEventLogger::EVENT_TYPE::GOAL, achievement)
279
370
  end
280
371
 
@@ -286,75 +377,420 @@ class Context
286
377
 
287
378
  def refresh
288
379
  check_not_closed?
380
+ return nil if @failed
289
381
 
290
- unless @failed
291
- data_future = @data_provider.context_data
292
- if data_future.success?
293
- assign_data(data_future.data_future)
294
- log_event(ContextEventLogger::EVENT_TYPE::REFRESH, data_future.data_future)
295
- else
296
- set_data_failed(data_future.exception)
297
- log_error(data_future.exception)
382
+ data_future = @data_provider.context_data
383
+ if data_future.success?
384
+ state = build_state(data_future.data_future)
385
+ # Committed under the readiness lock, so a waiter on a context created
386
+ # asynchronously wakes, and an initial fetch that failed while this
387
+ # refresh was in flight no longer leaves the context failed.
388
+ Thread.handle_interrupt(Object => :never) do
389
+ @ready_mutex.synchronize do
390
+ @state = state
391
+ @failed = false
392
+ @data_failed = nil
393
+ @ready_error = nil
394
+ @ready_condvar.broadcast
395
+ end
298
396
  end
397
+ log_event(ContextEventLogger::EVENT_TYPE::REFRESH, data_future.data_future)
398
+ else
399
+ log_error(data_future.exception)
299
400
  end
300
401
  end
301
402
 
403
+ # Publishes pending events, then seals the context and logs "close", as in
404
+ # v1.3.0: a publish the collector rejects is logged as an error and the
405
+ # context is still sealed. A publisher that raises propagates the error and
406
+ # leaves the context open with the events queued.
302
407
  def close
303
- unless @closed
304
- if @pending_count > 0
305
- flush
306
- end
307
- @closed = true
308
- log_event(ContextEventLogger::EVENT_TYPE::CLOSE, nil)
309
- end
408
+ seal(ContextEventLogger::EVENT_TYPE::CLOSE)
409
+ end
410
+
411
+ # Like close, but as the JavaScript SDK does: if the final publish fails, the
412
+ # failure is raised and the context stays open with the events queued, so
413
+ # finalize can be retried. Logs "finalize" once sealed, and set_override,
414
+ # set_overrides and experiments keep working afterwards.
415
+ def finalize
416
+ seal(ContextEventLogger::EVENT_TYPE::FINALIZE)
310
417
  end
311
418
 
312
419
  def data
313
420
  check_ready?(true)
314
421
 
315
- @data
422
+ @state.data
423
+ end
424
+
425
+ def inspect
426
+ "#<Context ready=#{ready?} closed=#{closed?}>"
316
427
  end
317
428
 
318
429
  private
319
- def flush
320
- if !@failed
321
- if @pending_count > 0
322
- exposures = nil
323
- achievements = nil
324
- event_count = @pending_count
325
-
326
- if event_count > 0
327
- unless @exposures.empty?
328
- exposures = @exposures
329
- @exposures = []
430
+ # SDK reads check the cache under the assignment lock; a direct
431
+ # queue_exposure call has nothing to check and may already hold it (from a
432
+ # custom matcher), so it skips it.
433
+ def with_assignment_lock_if(locked, &block)
434
+ locked ? @assignment_mutex.synchronize(&block) : yield
435
+ end
436
+
437
+ # Claims and queues assignment's exposure. With experiment_name, the claim
438
+ # is taken only while the assignment is still the cached one for that
439
+ # experiment (checked under the assignment lock, which set_unit also
440
+ # takes to evict), and a no-unit split assignment whose unit has since
441
+ # been set counts as stale; then nothing is queued and :evicted is
442
+ # returned so the caller resolves it again. Returns nil otherwise, never
443
+ # the logger's result (that is passed to the block).
444
+ def claim_and_queue_exposure(assignment, experiment_name = nil)
445
+ return if assignment.exposed
446
+
447
+ claimed = false
448
+ begin
449
+ loop do
450
+ status = nil
451
+ # Waiting for the assignment lock stays interruptible; only the claim
452
+ # bookkeeping under it is masked.
453
+ with_assignment_lock_if(experiment_name) do
454
+ Thread.handle_interrupt(Object => :never) do
455
+ @queue_mutex.synchronize do
456
+ check_not_closed?
457
+ owner = @exposing[assignment]
458
+ status =
459
+ if owner
460
+ # Another thread's exposure is in flight; this thread's own
461
+ # (a reentrant read from its clock) uses the outer one.
462
+ owner.equal?(Thread.current) ? :reentered : :waiting
463
+ elsif assignment.exposed
464
+ :exposed
465
+ # On the SDK's read paths (experiment_name given), a no-unit
466
+ # split assignment whose unit has since been set is stale too
467
+ # (a failed exposure left it cached): resolved again. A
468
+ # direct queue_exposure call queues what it is given.
469
+ elsif experiment_name.nil? ||
470
+ (@assignment_cache[experiment_name.to_s].equal?(assignment) && !unit_now_set?(assignment))
471
+ @exposing[assignment] = Thread.current
472
+ claimed = true
473
+ :claimed
474
+ else
475
+ :evicted
476
+ end
477
+ end
478
+ end
479
+ end
480
+ return :evicted if status == :evicted
481
+ break unless status == :waiting
482
+
483
+ @queue_mutex.synchronize do
484
+ owner = @exposing[assignment]
485
+ @exposure_condvar.wait(@queue_mutex) if owner && !owner.equal?(Thread.current)
486
+ end
487
+ end
488
+ return unless claimed
489
+
490
+ # Only this assignment is claimed, without holding a lock over the
491
+ # supplied clock; distinct nested or concurrent exposures can proceed.
492
+ exposed_at = @clock.to_i
493
+ exposure = nil
494
+ holdout_exposures = nil
495
+ @queue_mutex.synchronize do
496
+ # Checked under the queue lock so an exposure cannot slip in after close
497
+ # sealed the queue and be stranded.
498
+ check_not_closed?
499
+
500
+ unless assignment.exposed
501
+ assignment.exposed = true
502
+
503
+ # A held-out experiment publishes no exposure of its own, unless an
504
+ # override or rule chose its variant. The holdouts covering it then
505
+ # expose once each, in id order, from the arms pinned when the
506
+ # assignment was made (as in JS).
507
+ if !assignment.suppressed || assignment.overridden || assignment.rule_override
508
+ exposure = enqueue_exposure(assignment.name, assignment, exposed_at)
330
509
  end
510
+ assignment.holdout_assignments&.each_with_index do |holdout_assignment, i|
511
+ next if holdout_assignment.nil? || holdout_assignment.exposed
331
512
 
332
- unless @achievements.empty?
333
- achievements = @achievements
334
- @achievements = []
513
+ holdout_assignment.exposed = true
514
+ (holdout_exposures ||= []) << enqueue_exposure(assignment.holdouts[i].name, holdout_assignment, exposed_at)
515
+ end
516
+ end
517
+ end
518
+ ensure
519
+ # Only the claim is released here (no assignment lock, so an unwinding
520
+ # timeout is not held up). A no-unit assignment left unexposed after its
521
+ # unit was set is rebuilt by the next read (see cached_or_new_assignment).
522
+ if claimed
523
+ Thread.handle_interrupt(Object => :never) do
524
+ @queue_mutex.synchronize do
525
+ @exposing.delete(assignment)
526
+ @exposure_condvar.broadcast
335
527
  end
528
+ end
529
+ end
530
+ end
531
+ # User callbacks run outside the lock so they can call publish/track.
532
+ logged = log_event(ContextEventLogger::EVENT_TYPE::EXPOSURE, exposure) unless exposure.nil?
533
+ holdout_exposures&.each { |e| log_event(ContextEventLogger::EVENT_TYPE::EXPOSURE, e) }
534
+ yield logged if block_given? && !exposure.nil?
535
+ nil
536
+ end
336
537
 
337
- @pending_count = 0
538
+ def seal(event_type)
539
+ return nil if @closed
540
+
541
+ # Called from a logger callback while a publish is in flight: defer so the
542
+ # events queued by the callback are still sent before finalizing. A seal
543
+ # that is already running does not claim it, so the request survives if
544
+ # that seal fails or gives up.
545
+ if @publish_mutex.owned?
546
+ @deferred_mutex.synchronize do
547
+ @close_pending = event_type
548
+ @close_requests += 1
549
+ end
550
+ return nil
551
+ end
552
+
553
+ close = event_type == ContextEventLogger::EVENT_TYPE::CLOSE
554
+ registered = false
555
+ begin
556
+ Thread.handle_interrupt(Object => :never) do
557
+ @queue_mutex.synchronize { @sealing += 1 }
558
+ registered = true
559
+ end
560
+ # One extra pass sends events a logger callback queued during the
561
+ # first publish; after that raise with the remaining events queued,
562
+ # so a callback can't keep close publishing forever or lose events.
563
+ SEAL_FLUSH_PASSES.times do |pass|
564
+ # close drops a batch the collector rejected, as in v1.3.0, but only
565
+ # that batch; anything queued meanwhile is still sent or kept.
566
+ result = flush(sealing: true, drop_rejected: close)
567
+ last_pass = pass == SEAL_FLUSH_PASSES - 1
568
+ raise_publish_failure(result) if !close && publish_failed?(result)
569
+
570
+ sealed = @queue_mutex.synchronize do
571
+ next :done if @closed
572
+
573
+ unless @exposures.empty? && @achievements.empty?
574
+ raise EventsQueuedWhileClosing.new("Events queued while closing; retry close or finalize") if last_pass
575
+
576
+ next :retry
577
+ end
338
578
 
339
- event = PublishEvent.new
340
- event.hashed = true
341
- event.published_at = @clock.to_i
342
- event.units = @units.map do |key, value|
343
- Unit.new(key.to_s, unit_hash(key, value))
579
+ Thread.handle_interrupt(Object => :never) do
580
+ @sealed_by = event_type
581
+ @closed = true
344
582
  end
345
- event.exposures = exposures
346
- event.attributes = @attributes unless @attributes.empty?
347
- event.goals = achievements unless achievements.nil?
583
+ :sealed
584
+ end
585
+ return nil if sealed == :done
586
+ next if sealed == :retry
587
+
588
+ logged = log_event(event_type, nil)
589
+ return close ? logged : nil
590
+ end
591
+ nil
592
+ ensure
593
+ if registered
594
+ Thread.handle_interrupt(Object => :never) do
595
+ @queue_mutex.synchronize { @sealing -= 1 }
596
+ end
597
+ end
598
+ end
599
+ end
600
+
601
+ # sealing: this flush is a seal's own pass, so it neither starts another
602
+ # seal nor claims a deferred one. Any other publish (on any thread) may.
603
+ def flush(sealing: false, drop_rejected: false)
604
+ dropped, failure = @failed ? @ready_mutex.synchronize { drop_if_failed(sealing) } : [false, nil]
605
+ return failure if dropped
606
+
607
+ # Serialize publishes so a queued event is part of at most one in-flight
608
+ # request; on failure the events stay queued for the next attempt.
609
+ # A logger callback that calls publish from inside a publish must not
610
+ # deadlock or re-send the in-flight snapshot; the outer call owns it.
611
+ return nil if @publish_mutex.owned?
612
+
613
+ claimed = nil
614
+ begin
615
+ result = @publish_mutex.synchronize do
616
+ exposures = achievements = nil
617
+ sent = nil
618
+ event_count = 0
619
+ # Failure installation and recovery both take this lock. Keep the
620
+ # decision and snapshot together, but never hold it across publishing.
621
+ dropped, failure = @ready_mutex.synchronize do
622
+ failed_result = drop_if_failed(sealing)
623
+ unless failed_result.first
624
+ @queue_mutex.synchronize do
625
+ exposures = @exposures.dup
626
+ achievements = @achievements.dup
627
+ event_count = exposures.size + achievements.size
628
+ # Which arrays were sent and how much of each: the queues only
629
+ # grow by appending or are replaced whole, so a handler that
630
+ # mutates its payload can't change what is removed.
631
+ sent = [@exposures, exposures.size, @achievements, achievements.size]
632
+ end
633
+ end
634
+ failed_result
635
+ end
636
+ next failure if dropped
637
+
638
+ if event_count.zero?
639
+ # Assigned under the mask, so an interrupt can't land between
640
+ # clearing the request and recording that this publish holds it.
641
+ Thread.handle_interrupt(Object => :never) { claimed = take_close_pending } unless sealing
642
+ next nil
643
+ end
644
+
645
+ event = PublishEvent.new
646
+ event.hashed = true
647
+ event.published_at = @clock.to_i
648
+ event.units = @units.map do |key, value|
649
+ Unit.new(key.to_s, unit_hash(key, value))
650
+ end
651
+ event.exposures = exposures unless exposures.empty?
652
+ event.attributes = @attributes unless @attributes.empty?
653
+ event.goals = achievements unless achievements.empty?
654
+ # Like the JavaScript SDK, the publish event is logged once the batch is
655
+ # delivered; a failed delivery logs an error event instead.
656
+ begin
657
+ response = @event_handler.publish(self, event)
658
+ rescue StandardError => e
659
+ log_error(e)
660
+ raise
661
+ end
662
+
663
+ if publish_failed?(response)
664
+ if response.is_a?(Exception)
665
+ log_error(response)
666
+ elsif response.respond_to?(:exception) && response.exception
667
+ log_error(response.exception)
668
+ else
669
+ log_error(StandardError.new("Publish failed (status=#{response.respond_to?(:status) ? response.status : 'unknown'})"))
670
+ end
671
+ remove_published(sent) if drop_rejected
672
+ response
673
+ else
348
674
  log_event(ContextEventLogger::EVENT_TYPE::PUBLISH, event)
349
- @event_handler.publish(self, event)
675
+ remove_published(sent)
676
+ # Claim a deferred close while still holding the lock, so only this
677
+ # successful publish can carry it out; a request made by another
678
+ # thread after a rejected publish waits for its own success.
679
+ # Assigned under the mask, so an interrupt can't land between
680
+ # clearing the request and recording that this publish holds it.
681
+ Thread.handle_interrupt(Object => :never) { claimed = take_close_pending } unless sealing
682
+ response
350
683
  end
351
684
  end
352
- else
685
+
686
+ if claimed
687
+ claimed = nil if run_deferred_seal(claimed)
688
+ end
689
+ result
690
+ ensure
691
+ # A deferred seal claimed by this publish that did not finish stays
692
+ # pending for the next successful publish: one not started (an
693
+ # interrupt landed after the claim), one that left events queued, or
694
+ # one whose own publish was rejected, raised or was interrupted (a
695
+ # Timeout or Thread#kill). Any error still propagates.
696
+ restore_close_pending(claimed) if claimed
697
+ end
698
+ end
699
+
700
+ # A failed context drops its queued events. Called under the readiness
701
+ # lock, which a recovering refresh also holds while it clears @failed, so
702
+ # goals tracked after recovery are never dropped by a publish that saw the
703
+ # context failed. publish gets the load error, as in v1.3.0; a seal's own
704
+ # pass gets nil, since dropping them is not a publish failure.
705
+ def drop_if_failed(sealing)
706
+ return [false, nil] unless @failed
707
+
708
+ @queue_mutex.synchronize do
353
709
  @exposures = []
354
710
  @achievements = []
355
711
  @pending_count = 0
356
- @data_failed
357
712
  end
713
+ [true, sealing ? nil : @data_failed]
714
+ end
715
+
716
+ # Removes the sent prefix of each queue, unless a failed-context publish
717
+ # replaced that queue while the request was in flight (then the batch is
718
+ # already gone and the new queue holds only newer events).
719
+ def remove_published((exposures, exposure_count, achievements, achievement_count))
720
+ @queue_mutex.synchronize do
721
+ @exposures.shift(exposure_count) if @exposures.equal?(exposures)
722
+ @achievements.shift(achievement_count) if @achievements.equal?(achievements)
723
+ @pending_count = @exposures.size + @achievements.size
724
+ end
725
+ end
726
+
727
+ def take_close_pending
728
+ @deferred_mutex.synchronize do
729
+ next nil unless @close_pending
730
+
731
+ claimed = [@close_pending, @close_requests]
732
+ @close_pending = false
733
+ claimed
734
+ end
735
+ end
736
+
737
+ # True once the seal finished; false when events were still queued.
738
+ def run_deferred_seal(claimed)
739
+ seal(claimed.first)
740
+ true
741
+ rescue EventsQueuedWhileClosing
742
+ false
743
+ end
744
+
745
+ # Unless the context sealed or a newer request was made meanwhile (even
746
+ # one another publish has already claimed).
747
+ def restore_close_pending((event_type, request))
748
+ Thread.handle_interrupt(Object => :never) do
749
+ @deferred_mutex.synchronize do
750
+ @close_pending = event_type unless @closed || @close_requests != request
751
+ end
752
+ end
753
+ end
754
+
755
+ def publish_failed?(result)
756
+ result.is_a?(Exception) ||
757
+ (result.respond_to?(:exception) && result.exception) ||
758
+ (result.respond_to?(:success?) && !result.success?)
759
+ end
760
+
761
+ def raise_publish_failure(result)
762
+ if result.is_a?(StandardError)
763
+ raise result
764
+ elsif result.is_a?(Exception)
765
+ raise StandardError.new(result.message), cause: result
766
+ elsif result.respond_to?(:exception) && result.exception
767
+ raise_publish_failure(result.exception)
768
+ else
769
+ status = result.respond_to?(:status) ? result.status : "unknown"
770
+ raise StandardError.new("Publish failed (status=#{status})")
771
+ end
772
+ end
773
+
774
+ # Called under the queue lock; exposed_at is read before taking it, since a
775
+ # supplied clock may call back into the context.
776
+ def enqueue_exposure(name, assignment, exposed_at)
777
+ exposure = Exposure.new
778
+ exposure.id = assignment.id || 0
779
+ exposure.name = name
780
+ exposure.unit = assignment.unit_type
781
+ exposure.variant = assignment.variant
782
+ exposure.exposed_at = exposed_at
783
+ exposure.assigned = assignment.assigned
784
+ exposure.eligible = assignment.eligible
785
+ exposure.overridden = assignment.overridden
786
+ exposure.full_on = assignment.full_on
787
+ exposure.custom = assignment.custom
788
+ exposure.audience_mismatch = assignment.audience_mismatch
789
+ exposure.rule_override = assignment.rule_override
790
+
791
+ @pending_count += 1
792
+ @exposures.push(exposure)
793
+ exposure
358
794
  end
359
795
 
360
796
  def check_not_closed?
@@ -363,6 +799,11 @@ class Context
363
799
  end
364
800
  end
365
801
 
802
+ # After finalize these still work, as in the JavaScript SDK.
803
+ def check_not_closed_by_close?
804
+ check_not_closed? if @sealed_by == ContextEventLogger::EVENT_TYPE::CLOSE
805
+ end
806
+
366
807
  def check_ready?(expect_not_closed)
367
808
  if !ready?
368
809
  raise IllegalStateException.new("ABSmartly Context is not yet ready")
@@ -371,6 +812,11 @@ class Context
371
812
  end
372
813
  end
373
814
 
815
+ def custom_field(experiment_name, key)
816
+ check_ready?(true)
817
+ @state.custom_fields.dig(experiment_name, key)
818
+ end
819
+
374
820
  def experiment_matches(experiment, assignment)
375
821
  experiment.id == assignment.id &&
376
822
  experiment.unit_type == assignment.unit_type &&
@@ -379,96 +825,348 @@ class Context
379
825
  experiment.traffic_split == assignment.traffic_split
380
826
  end
381
827
 
382
- def audience_matches(experiment, assignment)
383
- if !experiment.audience.nil? && experiment.audience.size > 0
384
- if @attrs_seq > (assignment.attrs_seq || 0)
385
- attrs = @attributes.inject({}) do |hash, attr|
386
- hash[attr.name] = attr.value
387
- hash
388
- end
389
- match = @audience_matcher.evaluate(experiment.audience, attrs)
390
- new_audience_mismatch = match && !match.result
828
+ # System values go in first, then user-set attributes overlay them, so a
829
+ # user attribute always wins over the system value for the same name, even
830
+ # when set after the context was created (the @attrs_seq bump re-evaluates
831
+ # the cached assignment). Empty system values were skipped at init, so a
832
+ # missing config leaves the key out rather than matching on "".
833
+ # The latest value per name, keyed as the caller set it. Private so an
834
+ # override of the public get_attributes doesn't change matcher inputs.
835
+ def user_attributes
836
+ result = {}
837
+ @attributes.each { |attr| result[attr.name] = attr.value }
838
+ result
839
+ end
391
840
 
392
- if new_audience_mismatch != assignment.audience_mismatch
393
- return false
394
- end
841
+ def attributes_map
842
+ # User attributes keep the caller's key, as v1.3.0 passed them to custom
843
+ # matchers. A system entry is added only when no user attribute has that
844
+ # name as a String or Symbol, the forms audience conditions can read.
845
+ user = user_attributes
846
+ attrs = {}
847
+ @system_attributes.each do |name, value|
848
+ attrs[name] = value unless user.key?(name) || user.key?(name.to_sym)
849
+ end
850
+ attrs.merge!(user)
851
+ end
852
+
853
+ # The built-in evaluator reads a name as a String or a Symbol, so it gets
854
+ # one entry per name: the latest value set under either spelling.
855
+ def evaluator_attributes
856
+ attrs = {}
857
+ @system_attributes.each { |name, value| attrs[name] = value }
858
+ @attributes.each { |attr| attrs[attr.name.to_s] = attr.value }
859
+ attrs
860
+ end
861
+
862
+ # Custom matchers get the caller's keys (as in v1.3.0); the built-in one
863
+ # gets the latest value per name.
864
+ def matcher_attributes(matcher)
865
+ matcher.instance_of?(AudienceMatcher) ? evaluator_attributes : attributes_map
866
+ end
867
+
868
+ # A built-in audience matcher is also the rule matcher, and the evaluator
869
+ # never changes its input, so the map built for the rules is reused.
870
+ def audience_attributes(rule_attrs)
871
+ return rule_attrs if !rule_attrs.nil? && @audience_matcher.instance_of?(AudienceMatcher)
872
+
873
+ matcher_attributes(@audience_matcher)
874
+ end
395
875
 
396
- assignment.attrs_seq = @attrs_seq
876
+ # A split rule or a holdout resolved while its unit was missing gave the
877
+ # no-unit result; once the unit is set, unexposed ones are rebuilt. Exposed ones
878
+ # stay, so the user never switches variant or gets a second exposure.
879
+ # One being exposed right now (its clock is running) is kept: it is
880
+ # about to be queued with its variant, so evicting it would serve one
881
+ # variant and expose two. If that exposure fails, the next read or claim
882
+ # finds it stale and resolves it again.
883
+ def invalidate_assignments_missing_unit(unit_type)
884
+ @assignment_mutex.synchronize do
885
+ exposing = @queue_mutex.synchronize { @exposing.dup }
886
+ @assignment_cache.delete_if do |_name, assignment|
887
+ assignment.unit_type.to_s == unit_type && !assignment.exposed && missing_unit?(assignment) &&
888
+ !exposing.key?(assignment)
397
889
  end
398
890
  end
891
+ end
892
+
893
+ # A no-unit split assignment whose unit has since been set, that is not
894
+ # exposed and not being exposed: set_unit skipped evicting it because its
895
+ # exposure was in progress, and that exposure did not complete.
896
+ def stale_missing_unit?(assignment)
897
+ return false unless unit_now_set?(assignment)
898
+
899
+ !exposed_or_exposing?(assignment)
900
+ end
901
+
902
+ # Read together under the queue lock: an exposure completing sets exposed
903
+ # and releases its claim under that lock, so a reader can't see neither.
904
+ def exposed_or_exposing?(assignment)
905
+ # exposed only moves false -> true: the positive result is stable.
906
+ return true if assignment.exposed
907
+
908
+ @queue_mutex.synchronize { assignment.exposed || @exposing.key?(assignment) }
909
+ end
910
+
911
+ # Resolved while its unit was missing: a no-unit split rule, or a holdout
912
+ # whose arm could not be computed yet.
913
+ def missing_unit?(assignment)
914
+ assignment.rule_missing_unit || (!assignment.holdout_assignments.nil? && assignment.holdout_assignments.include?(nil))
915
+ end
916
+
917
+ def unit_now_set?(assignment)
918
+ missing_unit?(assignment) && !assignment.unit_type.nil? && !@units[assignment.unit_type.to_sym].nil?
919
+ end
920
+
921
+ # Arm 0 always holds the unit out. In a 3-arm holdout arm 1 is "full-on
922
+ # only", so it holds out experiments that are not full-on. The arm count
923
+ # comes from the split, never from holdoutType.
924
+ def held_out_by?(variant, arm_count, full_on_variant)
925
+ return true if variant == 0
926
+
927
+ arm_count == 3 && variant == 1 && full_on_variant == 0
928
+ end
929
+
930
+ # Only (id, iteration) per holdout: a same-iteration seed or split edit
931
+ # must not rebuild an exposed assignment and expose it again.
932
+ def holdout_set_matches(entry, assignment)
933
+ fresh = entry.holdouts
934
+ pinned = assignment.holdouts
935
+ return true if fresh.equal?(pinned) || (!fresh.nil? && fresh.equal?(assignment.matched_holdouts))
936
+ return false if fresh.nil? || pinned.nil?
937
+ return false unless fresh.length == pinned.length
938
+
939
+ matches = fresh.each_with_index.all? do |holdout, i|
940
+ holdout_id(holdout.id) == holdout_id(pinned[i].id) && holdout.iteration == pinned[i].iteration
941
+ end
942
+ # The pinned list still names the exposures, so an equivalent list from a
943
+ # refresh is remembered apart and later reads compare it by identity.
944
+ assignment.matched_holdouts = fresh if matches
945
+ matches
946
+ end
947
+
948
+ # The arm is computed with the covered experiment's unit type, cached per
949
+ # (holdout id, unit type) and kept while the holdout's iteration is
950
+ # unchanged, together with the arm count it was computed against. nil
951
+ # means the unit is not set yet; it is never cached.
952
+ def holdout_assignment(holdout, unit_type)
953
+ id = holdout_id(holdout.id)
954
+ key = [id, unit_type]
955
+ cached = @holdout_assignments&.[](key)
956
+ return cached if cached && cached.iteration == holdout.iteration
957
+
958
+ uid = @units[unit_type.to_sym]
959
+ return nil if uid.nil?
960
+
961
+ assignment = Assignment.new
962
+ assignment.id = id
963
+ assignment.iteration = holdout.iteration
964
+ assignment.unit_type = unit_type
965
+ assignment.variant = variant_assigner(unit_type, uid).assign(holdout.split, holdout.seed_hi || 0,
966
+ holdout.seed_lo || 0)
967
+ assignment.assigned = true
968
+ assignment.holdout_arm_count = holdout.split.length
969
+ (@holdout_assignments ||= {})[key] = assignment
970
+ end
971
+
972
+ def audience_matches(entry, assignment)
973
+ experiment = entry.data
974
+ key = entry.rule_key
975
+ cached_key = assignment.rule_key || NO_RULES
976
+ # The environment is fixed per context, so the rules text alone
977
+ # identifies them. Equal text from a refresh is acknowledged by
978
+ # adopting the new object, so later reads compare by identity.
979
+ key_changed = !key.equal?(cached_key)
980
+ if key_changed && key == cached_key
981
+ assignment.rule_key = key
982
+ key_changed = false
983
+ end
984
+
985
+ return false if key_changed && key.empty? && assignment.rule_override
986
+
987
+ if @attrs_seq > (assignment.attrs_seq || 0) || key_changed
988
+ rule_attrs = nil
989
+ unless key.empty?
990
+ # Exposed, or being exposed right now (its clock may set the unit):
991
+ # the no-unit variant stays, so a unit arriving can't switch it.
992
+ pinned_missing = assignment.rule_missing_unit && exposed_or_exposing?(assignment)
993
+ rule_attrs = matcher_attributes(rule_matcher)
994
+ rule = resolve_rule(entry, rule_attrs, pinned_missing)
995
+ return false if rule&.first != assignment.rule_variant
996
+
997
+ assignment.rule_missing_unit = rule ? rule.last : false
998
+ end
999
+
1000
+ # A held-out unit skipped the audience when assigned, so it is not
1001
+ # evaluated here either; only a rule can take it out of suppression.
1002
+ if !assignment.rule_override && !assignment.suppressed &&
1003
+ !experiment.audience.nil? && experiment.audience.size > 0
1004
+ match = @audience_matcher.evaluate(experiment.audience, audience_attributes(rule_attrs))
1005
+ # An indeterminate result (no filter, bad JSON) keeps the cached flag.
1006
+ new_audience_mismatch = match.nil? ? assignment.audience_mismatch : !match.result
1007
+
1008
+ return false if new_audience_mismatch != assignment.audience_mismatch
1009
+ end
1010
+
1011
+ assignment.rule_key = key
1012
+ assignment.attrs_seq = @attrs_seq
1013
+ end
399
1014
  true
400
1015
  end
401
1016
 
1017
+ # A custom audience matcher written for v1.3.0 only implements
1018
+ # evaluate(audience, attributes); rules then use the default engine.
1019
+ def rule_matcher
1020
+ @rule_matcher ||= begin
1021
+ rule_capable = @audience_matcher.respond_to?(:parse_rules) &&
1022
+ @audience_matcher.respond_to?(:evaluate_parsed_rules)
1023
+ rule_capable ? @audience_matcher : AudienceMatcher.new(DefaultAudienceDeserializer.new)
1024
+ end
1025
+ end
1026
+
1027
+ # Returns [variant, missing_unit], or nil to fall back to normal
1028
+ # assignment (as JS and Java do for an out-of-range variant or a split
1029
+ # without one percentage per variant).
1030
+ def resolve_rule(entry, attrs, unit_pinned_missing)
1031
+ experiment = entry.data
1032
+ return nil if entry.rules.nil?
1033
+
1034
+ action = rule_matcher.evaluate_parsed_rules(entry.rules, @environment, attrs)
1035
+ return nil if action.nil?
1036
+
1037
+ variant_count = experiment.variants.length
1038
+ unless action.split?
1039
+ return action.variant >= 0 && action.variant < variant_count ? [action.variant, false] : nil
1040
+ end
1041
+ return nil if action.split.length != variant_count
1042
+
1043
+ unit_type = experiment.unit_type
1044
+ uid = unit_type.nil? || unit_pinned_missing ? nil : @units[unit_type.to_sym]
1045
+ return [experiment.full_on_variant || 0, true] if uid.nil?
1046
+
1047
+ assigner = variant_assigner(unit_type, uid)
1048
+ [assigner.assign(action.split, experiment.seed_hi, experiment.seed_lo), false]
1049
+ end
1050
+
1051
+ # The state is read under the lock, so each holder sees data at least as
1052
+ # new as the previous one: a read that started before a refresh can't
1053
+ # overwrite assignments (or holdout arms) already built from newer data,
1054
+ # which would reset their exposed flag and expose them again.
402
1055
  def assignment(experiment_name)
1056
+ @assignment_mutex.synchronize { cached_or_new_assignment(experiment_name, @state) }
1057
+ end
1058
+
1059
+ def cached_or_new_assignment(experiment_name, state)
403
1060
  assignment = @assignment_cache[experiment_name.to_s]
1061
+ exp_key = experiment_name.to_s.to_sym
1062
+ custom = @cassignments[exp_key]
1063
+ override = @overrides[exp_key]
1064
+ experiment = experiment(experiment_name.to_s, state)
1065
+
1066
+ # Built from the empty snapshot of a failed context that a refresh has
1067
+ # since recovered with the experiment: resolved again against the
1068
+ # recovered data. The marker stays on the old assignment, so a rebuild
1069
+ # that raises leaves it ineligible for reuse.
1070
+ # (The failed snapshot has no experiments, so a read on it never matches.)
1071
+ if @failed_marked && !assignment.nil? && !experiment.nil? &&
1072
+ assignment.instance_variable_get(:@failed_snapshot)
1073
+ assignment = nil
1074
+ end
1075
+ # Inline guard: only an unexposed no-unit result can be stale, and the
1076
+ # check itself takes the queue lock.
1077
+ if !assignment.nil? && !assignment.exposed &&
1078
+ (assignment.rule_missing_unit || assignment.holdout_assignments&.include?(nil)) &&
1079
+ stale_missing_unit?(assignment)
1080
+ assignment = nil
1081
+ end
404
1082
 
405
1083
  if !assignment.nil?
406
- custom = @cassignments.transform_keys(&:to_sym)[experiment_name.to_s.to_sym]
407
- override = @overrides.transform_keys(&:to_sym)[experiment_name.to_s.to_sym]
408
- experiment = experiment(experiment_name.to_s)
409
1084
  if !override.nil?
410
- if assignment.overridden && assignment.variant == override
1085
+ if assignment.overridden && assignment.variant == override &&
1086
+ (experiment.nil? || holdout_set_matches(experiment, assignment))
411
1087
  return assignment
412
1088
  end
413
1089
  elsif experiment.nil?
414
- if !assignment.assigned
415
- return assignment
416
- end
417
- elsif custom.nil? || custom == assignment.variant
418
- if experiment_matches(experiment.data, assignment) && audience_matches(experiment.data, assignment)
419
- return assignment
420
- end
1090
+ # A rule-won assignment came from the experiment's rules, so it is
1091
+ # rebuilt once the experiment is gone.
1092
+ return assignment if !assignment.assigned && !assignment.rule_override && !assignment.overridden
1093
+ elsif (custom.nil? || assignment.rule_override || assignment.suppressed ||
1094
+ (custom == assignment.variant && (assignment.custom || assignment.exposed))) &&
1095
+ experiment_matches(experiment.data, assignment) &&
1096
+ # Inline nil check: a method call here costs ~4% on the no-holdout path.
1097
+ (experiment.holdouts.nil? ? assignment.holdouts.nil? : holdout_set_matches(experiment, assignment)) &&
1098
+ ((experiment.unconditional && assignment.rule_key.equal?(NO_RULES)) ||
1099
+ audience_matches(experiment, assignment))
1100
+ # A rule wins over a custom assignment, and a held-out unit never
1101
+ # takes one. An unexposed assignment that merely equals a new custom
1102
+ # variant is rebuilt to flag it custom.
1103
+ return assignment
421
1104
  end
422
1105
  end
423
1106
 
424
- custom = @cassignments.transform_keys(&:to_sym)[experiment_name.to_s.to_sym]
425
- override = @overrides.transform_keys(&:to_sym)[experiment_name.to_s.to_sym]
426
- experiment = experiment(experiment_name.to_s)
427
-
428
1107
  assignment = Assignment.new
429
1108
  assignment.name = experiment_name
430
1109
  assignment.eligible = true
431
1110
 
1111
+ if !experiment.nil? && !experiment.holdouts.nil?
1112
+ data = experiment.data
1113
+ unit_type = data.unit_type
1114
+ assignment.holdouts = experiment.holdouts
1115
+ assignment.holdout_assignments = experiment.holdouts.map do |holdout|
1116
+ unit_type.nil? ? nil : holdout_assignment(holdout, unit_type)
1117
+ end
1118
+ assignment.suppressed = assignment.holdout_assignments.any? do |holdout_assignment|
1119
+ !holdout_assignment.nil? &&
1120
+ held_out_by?(holdout_assignment.variant, holdout_assignment.holdout_arm_count, data.full_on_variant)
1121
+ end
1122
+ end
1123
+
432
1124
  if !override.nil?
433
1125
  unless experiment.nil?
434
1126
  assignment.id = experiment.data.id
435
1127
  assignment.unit_type = experiment.data.unit_type
436
1128
  end
437
-
438
1129
  assignment.overridden = true
439
1130
  assignment.variant = override
440
- else
441
- unless experiment.nil?
442
- unit_type = experiment.data.unit_type
443
-
444
- if !experiment.data.audience.nil? && experiment.data.audience.size > 0
445
- attrs = @attributes.inject({}) do |hash, attr|
446
- hash[attr.name] = attr.value
447
- hash
448
- end
449
- match = @audience_matcher.evaluate(experiment.data.audience, attrs)
450
- if match && !match.result
451
- assignment.audience_mismatch = true
452
- end
1131
+ elsif !experiment.nil?
1132
+ data = experiment.data
1133
+ assignment.unit_type = data.unit_type
1134
+ assignment.id = data.id
1135
+ assignment.iteration = data.iteration
1136
+ assignment.traffic_split = data.traffic_split
1137
+ assignment.full_on_variant = data.full_on_variant
1138
+ assignment.rule_key = experiment.rule_key
1139
+ rule_attrs = assignment.rule_key.empty? ? nil : matcher_attributes(rule_matcher)
1140
+ rule = rule_attrs.nil? ? nil : resolve_rule(experiment, rule_attrs, false)
1141
+ assignment.rule_variant = rule&.first
1142
+ assignment.rule_missing_unit = rule ? rule.last : false
1143
+
1144
+ # A matching rule wins over holdout suppression, as an override does;
1145
+ # suppression skips the audience, full-on, traffic and custom paths.
1146
+ if rule
1147
+ assignment.rule_override = true
1148
+ assignment.variant = rule.first
1149
+ elsif assignment.suppressed
1150
+ assignment.variant = 0
1151
+ else
1152
+ if !data.audience.nil? && data.audience.size > 0
1153
+ match = @audience_matcher.evaluate(data.audience, audience_attributes(rule_attrs))
1154
+ assignment.audience_mismatch = true if match && !match.result
453
1155
  end
454
1156
 
455
- if experiment.data.audience_strict && assignment.audience_mismatch
1157
+ if data.audience_strict && assignment.audience_mismatch
456
1158
  assignment.variant = 0
457
- elsif experiment.data.full_on_variant == 0
458
- uid = @units.transform_keys(&:to_sym)[experiment.data.unit_type.to_sym]
1159
+ elsif data.full_on_variant == 0
1160
+ uid = @units[data.unit_type.to_sym]
459
1161
  unless uid.nil?
460
1162
  assigner = VariantAssigner.new(uid)
461
- eligible = assigner.assign(experiment.data.traffic_split,
462
- experiment.data.traffic_seed_hi,
463
- experiment.data.traffic_seed_lo) == 1
1163
+ eligible = assigner.assign(data.traffic_split, data.traffic_seed_hi, data.traffic_seed_lo) == 1
464
1164
  if eligible
465
1165
  if !custom.nil?
466
1166
  assignment.variant = custom
467
1167
  assignment.custom = true
468
1168
  else
469
- assignment.variant = assigner.assign(experiment.data.split,
470
- experiment.data.seed_hi,
471
- experiment.data.seed_lo)
1169
+ assignment.variant = assigner.assign(data.split, data.seed_hi, data.seed_lo)
472
1170
  end
473
1171
  else
474
1172
  assignment.eligible = false
@@ -478,39 +1176,179 @@ class Context
478
1176
  end
479
1177
  else
480
1178
  assignment.assigned = true
481
- assignment.variant = experiment.data.full_on_variant
1179
+ assignment.variant = data.full_on_variant
482
1180
  assignment.full_on = true
483
1181
  end
484
-
485
- assignment.unit_type = unit_type
486
- assignment.id = experiment.data.id
487
- assignment.iteration = experiment.data.iteration
488
- assignment.traffic_split = experiment.data.traffic_split
489
- assignment.full_on_variant = experiment.data.full_on_variant
490
- assignment.attrs_seq = @attrs_seq
491
1182
  end
1183
+ assignment.attrs_seq = @attrs_seq
492
1184
  end
493
1185
 
494
1186
  if !experiment.nil? && assignment.variant >= 0 && assignment.variant < experiment.data.variants.length
495
1187
  assignment.variables = experiment.variables[assignment.variant] || {}
496
1188
  end
497
1189
 
1190
+ failed_built = state.equal?(@failed_state)
1191
+ # A read that finishes after a refresh recovered the context must not
1192
+ # replace what was resolved against the recovered data, unless that
1193
+ # data lacks the experiment too and would resolve it the same way.
1194
+ if failed_built && !@state.equal?(@failed_state) && !experiment(experiment_name.to_s).nil?
1195
+ return assignment
1196
+ end
1197
+
1198
+ # Provenance belongs to the new assignment before the single cache
1199
+ # write. An interrupted replacement leaves the old assignment marked;
1200
+ # a marker on an uncached replacement has no effect on later reads.
1201
+ if failed_built
1202
+ assignment.instance_variable_set(:@failed_snapshot, true)
1203
+ @failed_marked = true
1204
+ end
498
1205
  @assignment_cache[experiment_name.to_s] = assignment
499
1206
  assignment
500
1207
  end
501
1208
 
502
- def variable_assignment(key)
503
- experiment = variable_experiment(key)
1209
+ # As java-sdk Context.getVariableAssignment resolves a key shared by
1210
+ # several experiments: the first one, in experiment id order, that the
1211
+ # unit is assigned to, overridden in or rule-assigned in wins, and only
1212
+ # that one is exposed. A winner whose variant lacks the key gives the
1213
+ # default; the walk never moves past it. When none wins, a held-out unit
1214
+ # reads the first held-out experiment (control, or the default if its
1215
+ # control lacks the key). A non-peek read still exposes the holdouts of
1216
+ # each candidate it visits, as java-sdk does.
1217
+ def resolve_variable_value(key, default_value, expose)
1218
+ key = key.to_s.to_sym
1219
+ winner = nil
1220
+ attempts = 0
1221
+ while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path
1222
+ return default_value if attempts >= VARIABLE_WALK_ATTEMPTS
1223
+
1224
+ attempts += 1
1225
+ state = @state
1226
+ winner = variable_assignment(key, expose, state)
1227
+ visited = nil
1228
+ winner, visited = winner if winner.is_a?(Array)
1229
+ # A refresh, even one from a holdout's logger, restarts the walk.
1230
+ next unless @state.equal?(state)
1231
+
1232
+ unless visited.nil?
1233
+ i = 0
1234
+ while i < visited.length && @state.equal?(state)
1235
+ queue_holdout_exposures(visited[i])
1236
+ i += 1
1237
+ end
1238
+ next unless @state.equal?(state)
1239
+ end
1240
+ break if winner.nil? || !expose || winner.exposed
1241
+ # The unit was set in between, so the walk may now pick another
1242
+ # candidate: it starts again, as java-sdk's settleExposure does.
1243
+ break unless claim_and_queue_exposure(winner, winner.name) == :evicted
1244
+ end
1245
+ return default_value if winner.nil? || winner.variables.nil? || !winner.variables.key?(key)
1246
+
1247
+ winner.variables[key]
1248
+ end
1249
+
1250
+ # Returns the winner, or, when exposing and a visited candidate still has
1251
+ # a holdout to expose, [winner, those candidates] (only then allocated);
1252
+ # the caller exposes them once the walk stands.
1253
+ def variable_assignment(key, expose, state = @state)
1254
+ candidates = state.index_variables[key]
1255
+ return nil if candidates.nil?
1256
+
1257
+ visited = nil
1258
+ suppressed_fallback = nil
1259
+ i = 0
1260
+ # An index loop, not each: no block frame per candidate on the read path.
1261
+ while i < candidates.length
1262
+ # Resolved from the state current under the assignment lock, so a read
1263
+ # that a refresh overtook can't reinstall an old assignment.
1264
+ assignment = assignment(candidates[i].data.name)
1265
+ # As in java-sdk, visited candidates' holdouts precede the winner's exposure.
1266
+ if expose && !assignment.holdout_assignments.nil? &&
1267
+ (!assignment.exposed || assignment.overridden) && holdouts_pending?(assignment)
1268
+ (visited ||= []) << assignment
1269
+ end
1270
+ if assignment.assigned || assignment.overridden || assignment.rule_override
1271
+ return visited ? [assignment, visited] : assignment
1272
+ end
504
1273
 
505
- assignment(experiment.data.name) unless experiment.nil?
1274
+ suppressed_fallback ||= assignment if assignment.suppressed
1275
+ i += 1
1276
+ end
1277
+ visited ? [suppressed_fallback, visited] : suppressed_fallback
506
1278
  end
507
1279
 
508
- def experiment(experiment)
509
- @index.transform_keys(&:to_sym)[experiment.to_s.to_sym]
1280
+ # Whether a candidate has a holdout arm still to expose (or, for an
1281
+ # override, one still to resolve). A warm read past an exposed loser then
1282
+ # collects nothing.
1283
+ def holdouts_pending?(assignment)
1284
+ arms = assignment.holdout_assignments
1285
+ i = 0
1286
+ while i < arms.length
1287
+ arm = arms[i]
1288
+ if arm.nil?
1289
+ unit_type = assignment.unit_type
1290
+ return true if assignment.overridden && !unit_type.nil? && !@units[unit_type.to_sym].nil?
1291
+ elsif !arm.exposed
1292
+ return true
1293
+ end
1294
+
1295
+ i += 1
1296
+ end
1297
+ false
510
1298
  end
511
1299
 
512
- def variable_experiment(key)
513
- @index_variables.transform_keys(&:to_sym)[key.to_s.to_sym]
1300
+ # Replaces the arms of an override still missing them, once its unit is
1301
+ # set; the holdout arm cache is written under the assignment lock.
1302
+ def resolve_late_holdout_arms(assignment)
1303
+ arms = assignment.holdout_assignments
1304
+ return unless unit_now_set?(assignment) && arms.include?(nil)
1305
+
1306
+ @assignment_mutex.synchronize do
1307
+ arms = assignment.holdout_assignments
1308
+ # The live holdouts (a refresh's equivalent list, if any): the arms are
1309
+ # decided now, so they and their exposures' names come from those, as
1310
+ # java-sdk resolves an override's holdouts against the installed data.
1311
+ holdouts = assignment.matched_holdouts || assignment.holdouts
1312
+ if arms.include?(nil)
1313
+ assignment.holdout_assignments = arms.each_with_index.map do |arm, i|
1314
+ arm || holdout_assignment(holdouts[i], assignment.unit_type)
1315
+ end
1316
+ assignment.holdouts = holdouts
1317
+ end
1318
+ end
1319
+ end
1320
+
1321
+ # Exposes the holdouts covering a visited candidate, from the arms pinned
1322
+ # in its assignment, without exposing the candidate itself.
1323
+ def queue_holdout_exposures(assignment)
1324
+ return if assignment.exposed && !assignment.overridden
1325
+
1326
+ # As java-sdk resolves an override's holdouts live on each visit, an
1327
+ # arm an override could not get before its unit was set is resolved
1328
+ # once the unit is, so its holdout is exposed even after the override.
1329
+ resolve_late_holdout_arms(assignment) if assignment.overridden
1330
+ holdout_assignments = assignment.holdout_assignments
1331
+ return if holdout_assignments.nil?
1332
+
1333
+ # Checked again under the lock; this keeps warm reads off the clock and lock.
1334
+ return if holdout_assignments.all? { |holdout_assignment| holdout_assignment.nil? || holdout_assignment.exposed }
1335
+
1336
+ exposed_at = @clock.to_i
1337
+ holdout_exposures = nil
1338
+ @queue_mutex.synchronize do
1339
+ check_not_closed?
1340
+ holdout_assignments.each_with_index do |holdout_assignment, i|
1341
+ next if holdout_assignment.nil? || holdout_assignment.exposed
1342
+
1343
+ holdout_assignment.exposed = true
1344
+ (holdout_exposures ||= []) << enqueue_exposure(assignment.holdouts[i].name, holdout_assignment, exposed_at)
1345
+ end
1346
+ end
1347
+ holdout_exposures&.each { |e| log_event(ContextEventLogger::EVENT_TYPE::EXPOSURE, e) }
1348
+ end
1349
+
1350
+ def experiment(experiment, state = @state)
1351
+ state.index[experiment.to_s.to_sym]
514
1352
  end
515
1353
 
516
1354
  def unit_hash(unit_type, unit_uid)
@@ -521,23 +1359,138 @@ class Context
521
1359
  @assigners[unit_type] ||= VariantAssigner.new(unit_hash)
522
1360
  end
523
1361
 
524
- def assign_data(data)
525
- @data = data
526
- @index = {}
527
- @index_variables = {}
1362
+ # Builds the snapshot for data, calling the variable parser; callers run
1363
+ # it outside the readiness lock so a parser may call wait_until_ready.
1364
+ # The membership bookkeeping defers asynchronous interrupts (Timeout,
1365
+ # Thread#raise), so one landing while it waits for the lock can't leave
1366
+ # this thread registered or unbalanced. The parsing keeps the caller's
1367
+ # interrupt mask: interruptible by default, deferred if the caller masked.
1368
+ # Ruby can't run the parse under the caller's mask inside a masked
1369
+ # cleanup, so an interrupt landing as the cleanup starts can skip it; a
1370
+ # registration only counts while the thread is inside build_state (see
1371
+ # building?), and the next build or wait drops one left behind.
1372
+ def build_state(data)
1373
+ thread = Thread.current
1374
+ nested = build_state_on_stack?(1)
1375
+ registered = false
1376
+ begin
1377
+ Thread.handle_interrupt(Object => :never) do
1378
+ @ready_mutex.synchronize do
1379
+ # [count, fiber that registered first]. A count left by an
1380
+ # interrupted cleanup in this fiber, with no build of it still
1381
+ # running further up the stack, is dropped first.
1382
+ entry = @building_threads[thread]
1383
+ # (The stack is checked above, before entering these blocks.)
1384
+ entry = nil if entry && (entry[1].equal?(Fiber.current) ? !nested : !entry[1].alive?)
1385
+ @building_threads[thread] = entry ? [entry[0] + 1, entry[1]] : [1, Fiber.current]
1386
+ end
1387
+ registered = true
1388
+ end
1389
+ build_state_maps(data)
1390
+ ensure
1391
+ if registered
1392
+ Thread.handle_interrupt(Object => :never) do
1393
+ @ready_mutex.synchronize do
1394
+ entry = @building_threads[thread]
1395
+ if entry && entry[0] > 1
1396
+ @building_threads[thread] = [entry[0] - 1, entry[1]]
1397
+ elsif entry
1398
+ @building_threads.delete(thread)
1399
+ end
1400
+ end
1401
+ end
1402
+ end
1403
+ end
1404
+ end
1405
+
1406
+ # True while this thread is building a snapshot (a variable parser calling
1407
+ # back). A registration whose build has unwound without its cleanup is
1408
+ # dropped here, so the thread waits like any other.
1409
+ def building?
1410
+ thread = Thread.current
1411
+ entry = @ready_mutex.synchronize { @building_threads[thread] }
1412
+ return false if entry.nil?
1413
+ return true unless stale_build_entry?(entry)
1414
+
1415
+ Thread.handle_interrupt(Object => :never) do
1416
+ @ready_mutex.synchronize { @building_threads.delete(thread) if @building_threads[thread].equal?(entry) }
1417
+ end
1418
+ false
1419
+ end
1420
+
1421
+ # A backtrace covers only the current fiber, so the stack is checked only
1422
+ # from the fiber that registered; a parser that waits from a nested fiber
1423
+ # still counts as building. A registering fiber that has ended is stale.
1424
+ def stale_build_entry?(entry)
1425
+ fiber = entry[1]
1426
+ return !build_state_on_stack?(0) if fiber.equal?(Fiber.current)
1427
+ return true unless fiber.alive?
1428
+ # Ruby 3.0+ can read the registering fiber's stack from a fiber it
1429
+ # resumed; 2.7 cannot, so there a live registering fiber still counts.
1430
+ return false unless fiber.respond_to?(:backtrace_locations)
1431
+
1432
+ !build_state_on_stack?(0, fiber.backtrace_locations || [])
1433
+ end
1434
+
1435
+ # Whether more than skip build_state frames are on this thread's stack.
1436
+ # Called only outside build_state's blocks, so each frame is one build.
1437
+ def build_state_on_stack?(skip, locations = caller_locations)
1438
+ locations.count { |location| location.path == __FILE__ && location.base_label == "build_state" } > skip
1439
+ end
1440
+
1441
+ def build_state_maps(data)
1442
+ index = {}
1443
+ index_variables = {}
1444
+ custom_fields = {}
1445
+ holdouts_by_id = NO_HOLDOUTS
1446
+
1447
+ # Only holdouts with a numeric split and seeds can assign a unit; the
1448
+ # others are ignored, and so are holdoutIds that name none of them.
1449
+ # A custom deserializer's data may predate holdouts, so they are optional.
1450
+ holdouts = data.holdouts if data.respond_to?(:holdouts)
1451
+ holdouts.each do |holdout|
1452
+ next unless holdout.is_a?(Experiment)
1453
+
1454
+ id = holdout_id(holdout.id)
1455
+ split = holdout.split
1456
+ next if id.nil? || !split.is_a?(Array) || split.empty? || !split.all?(Numeric)
1457
+ next unless [holdout.seed_hi, holdout.seed_lo].all? { |seed| seed.nil? || seed.is_a?(Integer) }
1458
+
1459
+ holdouts_by_id = {} if holdouts_by_id.frozen?
1460
+ holdouts_by_id[id] = holdout
1461
+ end if holdouts.is_a?(Array)
528
1462
 
529
1463
  if data && !data.experiments.nil? && !data.experiments.empty?
530
1464
  data.experiments.each do |experiment|
531
- @experimentCustomFieldValues = {}
1465
+ experiment_custom_field_values = {}
532
1466
 
533
1467
  experiment_variables = ExperimentVariables.new
534
1468
  experiment_variables.data = experiment
1469
+ rules = experiment.assignment_rules
1470
+ if rules.is_a?(String) && !rules.empty?
1471
+ experiment_variables.rule_key = rules
1472
+ experiment_variables.rules = rule_matcher.parse_rules(rules)
1473
+ else
1474
+ experiment_variables.rule_key = NO_RULES
1475
+ end
1476
+ experiment_variables.unconditional = experiment_variables.rule_key.equal?(NO_RULES) &&
1477
+ (experiment.audience.nil? || experiment.audience.empty?)
1478
+ holdout_ids = experiment.holdout_ids unless holdouts_by_id.empty? || !experiment.respond_to?(:holdout_ids)
1479
+ if holdout_ids.is_a?(Array) && !holdout_ids.empty?
1480
+ holdouts = holdout_ids.filter_map { |id| holdouts_by_id[holdout_id(id)] }.uniq.sort_by { |h| holdout_id(h.id) }
1481
+ experiment_variables.holdouts = holdouts unless holdouts.empty?
1482
+ end
535
1483
  experiment_variables.variables ||= []
536
1484
  experiment.variants.each do |variant|
537
1485
  if !variant.config.nil? && !variant.config.empty?
538
1486
  variables = @variable_parser.parse(self, experiment.name, variant.name,
539
- variant.config)
540
- variables.keys.each { |key| @index_variables[key] = experiment_variables }
1487
+ variant.config) || {}
1488
+ variables.keys.each do |key|
1489
+ # Kept sorted and unique by experiment id, as the JavaScript SDK does.
1490
+ list = (index_variables[key] ||= [])
1491
+ at = list.bsearch_index { |other| other.data.id >= experiment.id } || list.length
1492
+ list.insert(at, experiment_variables) unless list[at]&.data&.id == experiment.id
1493
+ end
541
1494
  experiment_variables.variables.push(variables)
542
1495
  else
543
1496
  experiment_variables.variables.push({})
@@ -551,38 +1504,49 @@ class Context
551
1504
 
552
1505
  if !custom_field_value.value.nil?
553
1506
  custom_value = custom_field_value.value
1507
+ type = custom_field_value.type.to_s
554
1508
 
555
- if custom_field_value.type.start_with?("json")
1509
+ if type.start_with?("json")
556
1510
  value.value = @variable_parser.parse(self, experiment.name, custom_field_value.name, custom_value)
557
1511
 
558
- elsif custom_field_value.type.start_with?("boolean")
1512
+ elsif type.start_with?("boolean")
559
1513
  value.value = custom_value == "true"
560
1514
 
561
- elsif custom_field_value.type.start_with?("number")
1515
+ elsif type.start_with?("number")
562
1516
  value.value = custom_value.to_i
563
1517
 
564
1518
  else
565
1519
  value.value = custom_field_value.value
566
1520
  end
567
1521
 
568
- @experimentCustomFieldValues[custom_field_value.name] = value
1522
+ experiment_custom_field_values[custom_field_value.name] = value
569
1523
 
570
1524
  end
571
-
572
1525
  end
573
1526
  end
574
1527
 
575
- @index[experiment.name] = experiment_variables
576
- @context_custom_fields[experiment.name] = @experimentCustomFieldValues
1528
+ index[experiment.name.to_sym] = experiment_variables
1529
+ custom_fields[experiment.name] = experiment_custom_field_values
577
1530
  end
578
1531
  end
1532
+
1533
+ State.new(data, index, index_variables, custom_fields)
1534
+ end
1535
+
1536
+ # Collector IDs are integers; integral floats and canonical decimal text
1537
+ # are accepted too. Other text is ignored, even when identical on both sides.
1538
+ def holdout_id(id)
1539
+ case id
1540
+ when Integer then id
1541
+ when Float then id.to_i if id.finite? && id == id.floor
1542
+ when String then Integer(id, 10) if id.match?(/\A(?:0|-?[1-9]\d*)\z/)
1543
+ end
579
1544
  end
580
1545
 
581
1546
  def set_data_failed(exception)
582
1547
  @data_failed = exception
583
- @index = {}
584
- @index_variables = {}
585
- @data = ContextData.new
1548
+ @ready_error = exception
1549
+ @state = @failed_state = State.new(ContextData.new, {}, {}, {})
586
1550
  @failed = true
587
1551
  end
588
1552
 
@@ -590,12 +1554,80 @@ class Context
590
1554
  unless @event_logger.nil?
591
1555
  @event_logger.handle_event(event, data)
592
1556
  end
1557
+ rescue StandardError
1558
+ nil
593
1559
  end
594
1560
 
595
1561
  def log_error(error)
596
1562
  unless @event_logger.nil?
597
1563
  @event_logger.handle_event(ContextEventLogger::EVENT_TYPE::ERROR, error.message)
598
1564
  end
1565
+ rescue StandardError
1566
+ nil
1567
+ end
1568
+
1569
+ def init_common(clock, config, data_provider, event_handler, event_logger,
1570
+ variable_parser, audience_matcher, application = nil, environment = nil)
1571
+ @state = State.new(nil, {}, {}, {})
1572
+ @achievements = []
1573
+ @assignment_cache = {}
1574
+ @holdout_assignments = nil
1575
+ @assignment_mutex = Mutex.new
1576
+ @failed_marked = false
1577
+ @exposing = {}.compare_by_identity
1578
+ @exposure_condvar = ConditionVariable.new
1579
+ @assignments = {}
1580
+ @clock = clock.is_a?(String) ? Time.iso8601(clock) : clock
1581
+ @publish_delay = config.publish_delay
1582
+ @refresh_interval = config.refresh_interval
1583
+ @event_handler = event_handler
1584
+ @event_logger = !config.event_logger.nil? ? config.event_logger : event_logger
1585
+ @data_provider = data_provider
1586
+ @variable_parser = variable_parser
1587
+ @audience_matcher = audience_matcher
1588
+ @environment = environment
1589
+ @closed = false
1590
+ @sealing = 0
1591
+ @failed = false
1592
+ @ready_error = nil
1593
+ @sealed_by = nil
1594
+ @building_threads = {}
1595
+
1596
+ # System attributes (application/environment names from the client
1597
+ # config) seed the audience evaluation map. The collector already
1598
+ # attaches both server-side, so they are never added to the publish
1599
+ # payload; empty values are skipped so a missing key stays absent.
1600
+ @system_attributes = {}
1601
+ @system_attributes["application"] = application if application.is_a?(String) && !application.empty?
1602
+ @system_attributes["environment"] = environment if environment.is_a?(String) && !environment.empty?
1603
+
1604
+ @units = {}
1605
+ @attributes = []
1606
+ @overrides = {}
1607
+ @cassignments = {}
1608
+ @assigners = {}
1609
+ @hashed_units = {}
1610
+ @pending_count = 0
1611
+ @exposures = []
1612
+ @attrs_seq = 0
1613
+ @ready_mutex = Mutex.new
1614
+ @ready_condvar = ConditionVariable.new
1615
+ @queue_mutex = Mutex.new
1616
+ @publish_mutex = Mutex.new
1617
+ @deferred_mutex = Mutex.new
1618
+ @close_pending = false
1619
+ @close_requests = 0
1620
+
1621
+ set_units(config.units) if config.units
1622
+ set_attributes(config.attributes) if config.attributes
1623
+ set_overrides(config.overrides) if config.overrides
1624
+ set_custom_assignments(config.custom_assignments) if config.custom_assignments
1625
+ end
1626
+
1627
+ def initialize_async(clock, config, data_provider, event_handler, event_logger,
1628
+ variable_parser, audience_matcher, application: nil, environment: nil)
1629
+ init_common(clock, config, data_provider, event_handler, event_logger,
1630
+ variable_parser, audience_matcher, application, environment)
599
1631
  end
600
1632
 
601
1633
  attr_accessor :clock,
@@ -630,7 +1662,9 @@ end
630
1662
  class Assignment
631
1663
  attr_accessor :id, :iteration, :full_on_variant, :name, :unit_type,
632
1664
  :traffic_split, :variant, :assigned, :overridden, :eligible,
633
- :full_on, :custom, :audience_mismatch, :variables, :exposed, :attrs_seq
1665
+ :full_on, :custom, :audience_mismatch, :variables, :exposed, :attrs_seq,
1666
+ :rule_override, :rule_variant, :rule_missing_unit, :rule_key,
1667
+ :suppressed, :holdouts, :matched_holdouts, :holdout_assignments, :holdout_arm_count
634
1668
 
635
1669
  def initialize
636
1670
  @variant = 0
@@ -643,12 +1677,30 @@ class Assignment
643
1677
  @full_on = false
644
1678
  @custom = false
645
1679
  @audience_mismatch = false
1680
+ @rule_override = false
1681
+ @rule_missing_unit = false
646
1682
  @attrs_seq = 0
1683
+ @holdouts = nil
1684
+ @matched_holdouts = nil
1685
+ # Private: set by the context on an assignment built from a failed load's
1686
+ # empty snapshot. Initialized so every assignment keeps one layout.
1687
+ @failed_snapshot = false
647
1688
  end
648
1689
  end
649
1690
 
650
1691
  class ExperimentVariables
651
- attr_accessor :data, :variables
1692
+ attr_accessor :data, :variables, :rules, :rule_key, :unconditional, :holdouts
1693
+
1694
+ # Every field is set up front so all instances share one object shape and
1695
+ # the cached read path's attribute reads stay monomorphic.
1696
+ def initialize
1697
+ @data = nil
1698
+ @variables = nil
1699
+ @rules = nil
1700
+ @rule_key = nil
1701
+ @unconditional = nil
1702
+ @holdouts = nil
1703
+ end
652
1704
  end
653
1705
 
654
1706
  class ContextCustomFieldValues